chore: file generation cleanup (#1736)

This PR does too many things :( 

1. Major refactoring of the dev/scripts and dev/code-generation folders. 

Primarily this was removing duplicate code and cleaning up some poorly written code snippets as well as making them more idempotent so then can be re-run over and over again but still maintain the same results. This is working on my machine, but I've been having problems in CI and comparing diffs so running generators in CI will have to wait. 

2. Re-Implement using the generated api routes for testing

This was a _huge_ refactor that touched damn near every test file but now we have auto-generated typed routes with inline hints and it's used for nearly every test excluding a few that use classes for better parameterization. This should greatly reduce errors when writing new tests. 

3. Minor Perf improvements for the All Recipes endpoint

  A. Removed redundant loops
  B. Uses orjson to do the encoding directly and returns a byte response instead of relying on the default 
       jsonable_encoder.

4. Fix some TS type errors that cropped up for seemingly no reason half way through the PR.

See this issue https://github.com/phillipdupuis/pydantic-to-typescript/issues/28

Basically, the generated TS type is not-correct since Pydantic will automatically fill in null fields. The resulting TS type is generated with a ? to indicate it can be null even though we _know_ that i can't be.
This commit is contained in:
Hayden 2022-10-18 14:49:41 -08:00 committed by GitHub
parent a8f0fb14a7
commit 9ecef4c25f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
107 changed files with 2520 additions and 1948 deletions

1
.gitignore vendored
View file

@ -158,3 +158,4 @@ dev/code-generation/generated/openapi.json
dev/code-generation/generated/test_routes.py
mealie/services/parser_services/crfpp/model.crfmodel
lcov.info
dev/code-generation/openapi.json

View file

@ -1,26 +0,0 @@
from pathlib import Path
CWD = Path(__file__).parent
PROJECT_DIR = Path(__file__).parent.parent.parent
class Directories:
out_dir = CWD / "generated"
class CodeTemplates:
interface = CWD / "templates" / "interface.js"
pytest_routes = CWD / "templates" / "test_routes.py.j2"
class CodeDest:
interface = CWD / "generated" / "interface.js"
pytest_routes = CWD / "generated" / "test_routes.py"
use_locales = PROJECT_DIR / "frontend" / "composables" / "use-locales" / "available-locales.ts"
class CodeKeys:
"""Hard coded comment IDs that are used to generate code"""
nuxt_local_messages = "MESSAGE_LOCALES"
nuxt_local_dates = "DATE_LOCALES"

View file

@ -1,8 +1,8 @@
from dataclasses import dataclass
from pathlib import Path
from _gen_utils import log, render_python_template
from slugify import slugify
from utils import render_python_template
CWD = Path(__file__).parent
@ -25,9 +25,7 @@ class TestDataPath:
# Remove any file extension
var = var.split(".")[0]
var = var.replace("'", "")
var = slugify(var, separator="_")
return cls(var, rel_path)
@ -97,8 +95,6 @@ def rename_non_compliant_paths():
def main():
log.info("Starting Template Generation")
rename_non_compliant_paths()
GENERATED.mkdir(exist_ok=True)
@ -115,8 +111,6 @@ def main():
{"children": all_children},
)
log.info("Finished Template Generation")
if __name__ == "__main__":
main()

View file

@ -0,0 +1,84 @@
import json
from pathlib import Path
from fastapi import FastAPI
from jinja2 import Template
from pydantic import BaseModel
from utils import PROJECT_DIR, CodeTemplates, HTTPRequest, RouteObject
CWD = Path(__file__).parent
OUTFILE = PROJECT_DIR / "tests" / "utils" / "api_routes" / "__init__.py"
class PathObject(BaseModel):
route_object: RouteObject
http_verbs: list[HTTPRequest]
class Config:
arbitrary_types_allowed = True
def get_path_objects(app: FastAPI):
paths = []
for key, value in app.openapi().items():
if key == "paths":
for key, value in value.items():
paths.append(
PathObject(
route_object=RouteObject(key),
http_verbs=[HTTPRequest(request_type=k, **v) for k, v in value.items()],
)
)
return paths
def dump_open_api(app: FastAPI):
"""Writes the Open API as JSON to a json file"""
OPEN_API_FILE = CWD / "openapi.json"
with open(OPEN_API_FILE, "w") as f:
f.write(json.dumps(app.openapi()))
def read_template(file: Path):
with open(file) as f:
return f.read()
def generate_python_templates(static_paths: list[PathObject], function_paths: list[PathObject]):
template = Template(read_template(CodeTemplates.pytest_routes))
content = template.render(
paths={
"prefix": "/api",
"static_paths": static_paths,
"function_paths": function_paths,
}
)
with open(OUTFILE, "w") as f:
f.write(content)
return
def main():
from mealie.app import app
dump_open_api(app)
paths = get_path_objects(app)
static_paths = [x.route_object for x in paths if not x.route_object.is_function]
function_paths = [x.route_object for x in paths if x.route_object.is_function]
static_paths.sort(key=lambda x: x.router_slug)
function_paths.sort(key=lambda x: x.router_slug)
generate_python_templates(static_paths, function_paths)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,102 @@
import pathlib
import re
from dataclasses import dataclass, field
from utils import PROJECT_DIR, log, render_python_template
template = """# This file is auto-generated by gen_schema_exports.py
{% for file in data.module.files %}{{ file.import_str() }}
{% endfor %}
__all__ = [
{% for file in data.module.files %}
{%- for class in file.classes -%}
"{{ class }}",
{%- endfor -%}
{%- endfor %}
]
"""
SCHEMA_PATH = PROJECT_DIR / "mealie" / "schema"
SKIP = {"static", "__pycache__"}
class PyFile:
import_path: str
"""The import path of the file"""
classes: list[str]
"""A list of classes in the file"""
def __init__(self, path: pathlib.Path):
self.import_path = path.stem
self.classes = []
self.classes = PyFile.extract_classes(path)
self.classes.sort()
def import_str(self) -> str:
"""Returns a string that can be used to import the file"""
return f"from .{self.import_path} import {', '.join(self.classes)}"
@staticmethod
def extract_classes(file_path: pathlib.Path) -> list[str]:
name = file_path.stem
if name == "__init__" or name.startswith("_"):
return []
classes = re.findall(r"(?m)^class\s(\w+)", file_path.read_text())
return classes
@dataclass
class Modules:
directory: pathlib.Path
"""The directory to search for modules"""
files: list[PyFile] = field(default_factory=list)
"""A list of files in the directory"""
def __post_init__(self):
for file in self.directory.glob("*.py"):
if file.name.startswith("_"):
continue
pfile = PyFile(file)
if len(pfile.classes) > 0:
self.files.append(pfile)
else:
log.debug(f"Skipping {file.name} as it has no classes")
def find_modules(root: pathlib.Path) -> list[Modules]:
"""Finds all the top level modules in the provided folder"""
modules: list[Modules] = []
for file in root.iterdir():
if file.is_dir() and file.name not in SKIP:
modules.append(Modules(directory=file))
return modules
def main():
modules = find_modules(SCHEMA_PATH)
for module in modules:
log.debug(f"Module: {module.directory.name}")
for file in module.files:
log.debug(f" File: {file.import_path}")
log.debug(f" Classes: [{', '.join(file.classes)}]")
render_python_template(template, module.directory / "__init__.py", {"module": module})
if __name__ == "__main__":
main()

View file

@ -1,53 +0,0 @@
import json
from typing import Any
from _gen_utils import render_python_template
from _open_api_parser import OpenAPIParser
from _static import CodeDest, CodeTemplates
from rich.console import Console
from mealie.app import app
"""
This code is used for generating route objects for each route in the OpenAPI Specification.
Currently, they are NOT automatically injected into the test suite. As such, you'll need to copy
the relevant contents of the generated file into the test suite where applicable. I am slowly
migrating the test suite to use this new generated file and this process will be "automated" in the
future.
"""
console = Console()
def write_dict_to_file(file_name: str, data: dict[str, Any]):
with open(file_name, "w") as f:
f.write(json.dumps(data, indent=4))
def main():
print("Starting...")
open_api = OpenAPIParser(app)
modules = open_api.get_by_module()
mods = []
for mod, value in modules.items():
routes = []
existings = set()
# Reduce routes by unique py_route attribute
for route in value:
if route.py_route not in existings:
existings.add(route.py_route)
routes.append(route)
module = {"name": mod, "routes": routes}
mods.append(module)
render_python_template(CodeTemplates.pytest_routes, CodeDest.pytest_routes, {"mods": mods})
print("Finished...")
if __name__ == "__main__":
main()

View file

@ -1,34 +0,0 @@
from _gen_utils import log, render_python_template
from _static import PROJECT_DIR
template = """# GENERATED CODE - DO NOT MODIFY BY HAND
{% for file in data.files %}from .{{ file }} import *
{% endfor %}
"""
SCHEMA_PATH = PROJECT_DIR / "mealie" / "schema"
def generate_init_files() -> None:
for schema in SCHEMA_PATH.iterdir():
if not schema.is_dir():
log.info(f"Skipping {schema}")
continue
log.info(f"Generating {schema}")
init_file = schema.joinpath("__init__.py")
module_files = [
f.stem for f in schema.iterdir() if f.is_file() and f.suffix == ".py" and not f.stem.startswith("_")
]
render_python_template(template, init_file, {"files": module_files})
def main():
log.info("Starting...")
generate_init_files()
log.info("Finished...")
if __name__ == "__main__":
main()

View file

@ -1,11 +1,12 @@
import pathlib
from pathlib import Path
import _static
import dotenv
import requests
from _gen_utils import log
from jinja2 import Template
from pydantic import Extra
from requests import Response
from utils import CodeDest, CodeKeys, inject_inline, log
from mealie.schema._mealie import MealieModel
@ -13,9 +14,6 @@ BASE = pathlib.Path(__file__).parent.parent.parent
API_KEY = dotenv.get_key(BASE / ".env", "CROWDIN_API_KEY")
if API_KEY is None or API_KEY == "":
log.info("CROWDIN_API_KEY is not set")
exit(1)
NAMES = {
"en-US": "American English",
@ -71,6 +69,9 @@ class TargetLanguage(MealieModel):
twoLettersCode: str
progress: float = 0.0
class Config:
extra = Extra.allow
class CrowdinApi:
project_name = "Mealie"
@ -127,11 +128,6 @@ class CrowdinApi:
return response.json()
from pathlib import Path
from _gen_utils import inject_inline
from _static import CodeKeys
PROJECT_DIR = Path(__file__).parent.parent.parent
@ -156,7 +152,7 @@ def inject_nuxt_values():
lang_string = f'{{ code: "{match.stem}", file: "{match.name}" }},'
all_langs.append(lang_string)
log.info(f"injecting locales into nuxt config -> {nuxt_config}")
log.debug(f"injecting locales into nuxt config -> {nuxt_config}")
inject_inline(nuxt_config, CodeKeys.nuxt_local_messages, all_langs)
inject_inline(nuxt_config, CodeKeys.nuxt_local_dates, all_date_locales)
@ -167,18 +163,19 @@ def generate_locales_ts_file():
tmpl = Template(LOCALE_TEMPLATE)
rendered = tmpl.render(locales=models)
log.info(f"generating locales ts file -> {_static.CodeDest.use_locales}")
with open(_static.CodeDest.use_locales, "w") as f:
log.debug(f"generating locales ts file -> {CodeDest.use_locales}")
with open(CodeDest.use_locales, "w") as f:
f.write(rendered) # type:ignore
def main():
if API_KEY is None or API_KEY == "":
log.error("CROWDIN_API_KEY is not set")
return
generate_locales_ts_file()
inject_nuxt_values()
log.info("finished code generation")
if __name__ == "__main__":
main()

View file

@ -1,29 +1,29 @@
from pathlib import Path
from _gen_utils import log
from jinja2 import Template
from pydantic2ts import generate_typescript_defs
from utils import log
# ============================================================
# Global Compoenents Generator
template = """// This Code is auto generated by gen_global_components.py
{% for name in global %} import {{ name }} from "@/components/global/{{ name }}.vue";
{% for name in global %}import {{ name }} from "@/components/global/{{ name }}.vue";
{% endfor %}{% for name in layout %}import {{ name }} from "@/components/layout/{{ name }}.vue";
{% endfor %}
{% for name in layout %} import {{ name }} from "@/components/layout/{{ name }}.vue";
{% endfor %}
declare module "vue" {
export interface GlobalComponents {
// Global Components
{% for name in global %} {{ name }}: typeof {{ name }};
{% endfor %} // Layout Components
{% for name in layout %} {{ name }}: typeof {{ name }};
{% endfor %}
}
{% for name in global -%}
{{ " " }}{{ name }}: typeof {{ name }};
{% endfor -%}
{{ " " }}// Layout Components
{% for name in layout -%}
{{ " " }}{{ name }}: typeof {{ name }};
{% endfor -%}{{ " }"}}
}
export {};
"""
CWD = Path(__file__).parent
@ -46,6 +46,7 @@ def generate_global_components_types() -> None:
data = {}
for name, path in component_paths.items():
components = [component.stem for component in path.glob("*.vue")]
components.sort()
data[name] = components
return data
@ -101,22 +102,27 @@ def generate_typescript_types() -> None:
failed_modules.append(module)
log.error(f"Module Error: {e}")
log.info("\n📁 Skipped Directories:")
log.debug("\n📁 Skipped Directories:")
for skipped_dir in skipped_dirs:
log.info(f" 📁 {skipped_dir.name}")
log.debug(f" 📁 {skipped_dir.name}")
log.info("📄 Skipped Files:")
log.debug("📄 Skipped Files:")
for f in skipped_files:
log.info(f" 📄 {f.name}")
log.debug(f" 📄 {f.name}")
log.error("❌ Failed Modules:")
for f in failed_modules:
log.error(f"{f.name}")
if len(failed_modules) > 0:
log.error("❌ Failed Modules:")
for f in failed_modules:
log.error(f"{f.name}")
def main():
log.debug("\n-- Starting Global Components Generator --")
generate_global_components_types()
log.debug("\n-- Starting Pydantic To Typescript Generator --")
generate_typescript_types()
if __name__ == "__main__":
log.info("\n-- Starting Global Components Generator --")
generate_global_components_types()
log.info("\n-- Starting Pydantic To Typescript Generator --")
generate_typescript_types()
main()

View file

@ -0,0 +1,28 @@
from pathlib import Path
import gen_py_pytest_data_paths
import gen_py_pytest_routes
import gen_py_schema_exports
import gen_ts_locales
import gen_ts_types
from utils import log
CWD = Path(__file__).parent
def main():
items = [
(gen_py_schema_exports.main, "schema exports"),
(gen_ts_types.main, "frontend types"),
(gen_ts_locales.main, "locales"),
(gen_py_pytest_data_paths.main, "test data paths"),
(gen_py_pytest_routes.main, "pytest routes"),
]
for func, name in items:
log.info(f"Generating {name}...")
func()
if __name__ == "__main__":
main()

View file

@ -1,9 +1,11 @@
{% for mod in mods %}
class {{mod.name}}Routes:{% for route in mod.routes %}{% if not route.path_is_func %}
{{route.name_snake}} = "{{ route.py_route }}"{% endif %}{% endfor %}{% for route in mod.routes %}
{% if route.path_is_func %}
@staticmethod
def {{route.name_snake}}({{ route.path_vars|join(", ") }}):
return f"{{route.py_route}}"
{% endif %}{% endfor %}
{% endfor %}
# This Content is Auto Generated for Pytest
prefix = "{{paths.prefix}}"
{% for path in paths.static_paths %}
{{ path.router_slug }} = "{{path.prefix}}{{ path.route }}"
"""`{{path.prefix}}{{ path.route }}`"""{% endfor %}
{% for path in paths.function_paths %}
def {{path.router_slug}}({{path.var|join(", ")}}):
"""`{{ paths.prefix }}{{ path.route }}`"""
return f"{prefix}{{ path.route }}"
{% endfor %}

View file

@ -0,0 +1,25 @@
from .open_api_parser import OpenAPIParser
from .route import HTTPRequest, ParameterIn, RequestBody, RequestType, RouteObject, RouterParameter
from .static import PROJECT_DIR, CodeDest, CodeKeys, CodeTemplates, Directories
from .template import CodeSlicer, find_start_end, get_indentation_of_string, inject_inline, log, render_python_template
__all__ = [
"CodeDest",
"CodeKeys",
"CodeSlicer",
"CodeTemplates",
"Directories",
"find_start_end",
"get_indentation_of_string",
"HTTPRequest",
"inject_inline",
"log",
"OpenAPIParser",
"ParameterIn",
"PROJECT_DIR",
"render_python_template",
"RequestBody",
"RequestType",
"RouteObject",
"RouterParameter",
]

View file

@ -3,11 +3,12 @@ import re
from pathlib import Path
from typing import Any
from _static import Directories
from fastapi import FastAPI
from humps import camelize
from slugify import slugify
from .static import Directories
def get_openapi_spec_by_ref(app, type_reference: str) -> dict:
if not type_reference:

View file

@ -3,7 +3,7 @@ from enum import Enum
from typing import Optional
from humps import camelize
from pydantic import BaseModel, Field
from pydantic import BaseModel, Extra, Field
from slugify import slugify
@ -30,6 +30,7 @@ class RequestType(str, Enum):
class ParameterIn(str, Enum):
query = "query"
path = "path"
header = "header"
class RouterParameter(BaseModel):
@ -37,10 +38,16 @@ class RouterParameter(BaseModel):
name: str
location: ParameterIn = Field(..., alias="in")
class Config:
extra = Extra.allow
class RequestBody(BaseModel):
required: bool = False
class Config:
extra = Extra.allow
class HTTPRequest(BaseModel):
request_type: RequestType
@ -49,7 +56,10 @@ class HTTPRequest(BaseModel):
requestBody: Optional[RequestBody]
parameters: list[RouterParameter] = []
tags: list[str]
tags: list[str] | None = []
class Config:
extra = Extra.allow
def list_as_js_object_string(self, parameters, braces=True):
if len(parameters) == 0:

View file

@ -0,0 +1,26 @@
from pathlib import Path
PARENT = Path(__file__).parent.parent
PROJECT_DIR = Path(__file__).parent.parent.parent.parent
class Directories:
out_dir = PARENT / "generated"
class CodeTemplates:
interface = PARENT / "templates" / "interface.js"
pytest_routes = PARENT / "templates" / "test_routes.py.j2"
class CodeDest:
interface = PARENT / "generated" / "interface.js"
pytest_routes = PARENT / "generated" / "test_routes.py"
use_locales = PROJECT_DIR / "frontend" / "composables" / "use-locales" / "available-locales.ts"
class CodeKeys:
"""Hard coded comment IDs that are used to generate code"""
nuxt_local_messages = "MESSAGE_LOCALES"
nuxt_local_dates = "DATE_LOCALES"

View file

@ -22,7 +22,9 @@ def render_python_template(template_file: Path | str, dest: Path, data: dict):
tplt = Template(template_file)
text = tplt.render(data=data)
text = black.format_str(text, mode=black.FileMode())
dest.write_text(text)
isort.file(dest)
@ -52,7 +54,7 @@ def get_indentation_of_string(line: str, comment_char: str = "//") -> str:
return re.sub(rf"{comment_char}.*", "", line).removesuffix("\n")
def find_start_end(file_text: list[str], gen_id: str) -> tuple[int, int]:
def find_start_end(file_text: list[str], gen_id: str) -> tuple[int, int, str]:
start = None
end = None
indentation = None
@ -90,7 +92,7 @@ def inject_inline(file_path: Path, key: str, code: list[str]) -> None:
"""
with open(file_path, "r") as f:
with open(file_path) as f:
file_text = f.readlines()
start, end, indentation = find_start_end(file_text, key)

View file

@ -2,8 +2,13 @@ import json
import random
import string
import time
from dataclasses import dataclass
import requests
from rich.console import Console
from rich.table import Table
console = Console()
def random_string(length: int) -> str:
@ -14,6 +19,218 @@ def payload_factory() -> dict:
return {"name": random_string(15)}
def recipe_data(name: str, slug: str, id: str, userId: str, groupId: str) -> dict:
return {
"id": id,
"userId": userId,
"groupId": groupId,
"name": name,
"slug": slug,
"image": "tNRG",
"recipeYield": "9 servings",
"totalTime": "33 Minutes",
"prepTime": "20 Minutes",
"cookTime": None,
"performTime": "13 Minutes",
"description": "These Levain Bakery-Style Peanut Butter Cookies are the ULTIMATE for serious PB lovers! Supremely thick and chewy with gooey centers and a soft texture, they're packed with peanut butter flavor and Reese's Pieces for the most amazing cookie ever!",
"recipeCategory": [],
"tags": [],
"tools": [],
"rating": None,
"orgURL": "https://thedomesticrebel.com/2021/04/28/levain-bakery-style-ultimate-peanut-butter-cookies/",
"recipeIngredient": [
{
"title": None,
"note": "1 cup unsalted butter, cut into cubes",
"unit": None,
"food": None,
"disableAmount": True,
"quantity": 1,
"originalText": None,
"referenceId": "ea3b6702-9532-4fbc-a40b-f99917831c26",
},
{
"title": None,
"note": "1 cup light brown sugar",
"unit": None,
"food": None,
"disableAmount": True,
"quantity": 1,
"originalText": None,
"referenceId": "c5bbfefb-1e23-4ffd-af88-c0363a0fae82",
},
{
"title": None,
"note": "1/2 cup granulated white sugar",
"unit": None,
"food": None,
"disableAmount": True,
"quantity": 1,
"originalText": None,
"referenceId": "034f481b-c426-4a17-b983-5aea9be4974b",
},
{
"title": None,
"note": "2 large eggs",
"unit": None,
"food": None,
"disableAmount": True,
"quantity": 1,
"originalText": None,
"referenceId": "37c1f796-3bdb-4856-859f-dbec90bc27e4",
},
{
"title": None,
"note": "2 tsp vanilla extract",
"unit": None,
"food": None,
"disableAmount": True,
"quantity": 1,
"originalText": None,
"referenceId": "85561ace-f249-401d-834c-e600a2f6280e",
},
{
"title": None,
"note": "1/2 cup creamy peanut butter",
"unit": None,
"food": None,
"disableAmount": True,
"quantity": 1,
"originalText": None,
"referenceId": "ac91bda0-e8a8-491a-976a-ae4e72418cfd",
},
{
"title": None,
"note": "1 tsp cornstarch",
"unit": None,
"food": None,
"disableAmount": True,
"quantity": 1,
"originalText": None,
"referenceId": "4d1256b3-115e-4475-83cd-464fbc304cb0",
},
{
"title": None,
"note": "1 tsp baking soda",
"unit": None,
"food": None,
"disableAmount": True,
"quantity": 1,
"originalText": None,
"referenceId": "64627441-39f9-4ee3-8494-bafe36451d12",
},
{
"title": None,
"note": "1/2 tsp salt",
"unit": None,
"food": None,
"disableAmount": True,
"quantity": 1,
"originalText": None,
"referenceId": "7ae212d0-3cd1-44b0-899e-ec5bd91fd384",
},
{
"title": None,
"note": "1 cup cake flour",
"unit": None,
"food": None,
"disableAmount": True,
"quantity": 1,
"originalText": None,
"referenceId": "06967994-8548-4952-a8cc-16e8db228ebd",
},
{
"title": None,
"note": "2 cups all-purpose flour",
"unit": None,
"food": None,
"disableAmount": True,
"quantity": 1,
"originalText": None,
"referenceId": "bdb33b23-c767-4465-acf8-3b8e79eb5691",
},
{
"title": None,
"note": "2 cups peanut butter chips",
"unit": None,
"food": None,
"disableAmount": True,
"quantity": 1,
"originalText": None,
"referenceId": "12ba0af8-affd-4fb2-9cca-6f1b3e8d3aef",
},
{
"title": None,
"note": "1½ cups Reese's Pieces candies",
"unit": None,
"food": None,
"disableAmount": True,
"quantity": 1,
"originalText": None,
"referenceId": "4bdc0598-a3eb-41ee-8af0-4da9348fbfe2",
},
],
"dateAdded": "2022-09-03",
"dateUpdated": "2022-09-10T15:18:19.866085",
"createdAt": "2022-09-03T18:31:17.488118",
"updateAt": "2022-09-10T15:18:19.869630",
"recipeInstructions": [
{
"id": "60ae53a3-b3ff-40ee-bae3-89fea0b1c637",
"title": "",
"text": "Preheat oven to 410° degrees F. Line 2 baking sheets with parchment paper or silicone liners; set aside.",
"ingredientReferences": [],
},
{
"id": "4e1c30c2-2e96-4a0a-b750-23c9ea3640f8",
"title": "",
"text": "In the bowl of a stand mixer, cream together the cubed butter, brown sugar and granulated sugar with the paddle attachment for 30 seconds on low speed. Increase speed to medium and beat for another 30 seconds, then increase to medium-high speed and beat for another 30 seconds until mixture is creamy and smooth. Beat in the eggs, one at a time, followed by the vanilla extract and peanut butter, scraping down the sides and bottom of the bowl as needed.",
"ingredientReferences": [],
},
{
"id": "9fb8e2a2-d410-445c-bafc-c059203e6f4b",
"title": "",
"text": "Add in the cornstarch, baking soda, salt, cake flour, and all-purpose flour and mix on low speed until just combined. Fold in the peanut butter chips and Reese's Pieces candies by hand until fully incorporated. Chill the dough uncovered in the fridge for 15 minutes.",
"ingredientReferences": [],
},
{
"id": "1ceb9aa4-49f7-4d4a-996f-3c715eb74642",
"title": "",
"text": 'Using a digital kitchen scale for accuracy, weigh out 6 ounces of cookie dough in a loose, rough textured ball. I like to make my cookie dough balls kind of tall as well. You do not want the dough balls to be smooth and compacted. Place on the baking sheet. Repeat with remaining dough balls, staggering on the baking sheet at least 3" apart from one another, and only placing 4 dough balls per baking sheet.',
"ingredientReferences": [],
},
{
"id": "591993fc-72bb-4091-8a12-84640c523fc1",
"title": "",
"text": "Bake one baking sheet at a time in the center rack of the oven for 10-13 minutes or until the tops are light golden brown and the exterior is dry and dull looking. Centers will be slightly underdone and gooey; this is okay and the cookies will finish cooking some once removed from the oven. Let stand on the baking sheets for at least 30 minutes before serving; the cookies are very delicate and fragile once removed from the oven and need time to set before being moved. Keep remaining dough refrigerated while other cookies bake.",
"ingredientReferences": [],
},
],
"nutrition": {
"calories": None,
"fatContent": None,
"proteinContent": None,
"carbohydrateContent": None,
"fiberContent": None,
"sodiumContent": None,
"sugarContent": None,
},
"settings": {
"public": True,
"showNutrition": False,
"showAssets": False,
"landscapeView": False,
"disableComments": False,
"disableAmount": True,
"locked": False,
},
"assets": [],
"notes": [],
"extras": {},
"comments": [],
}
def login(username="changeme@email.com", password="MyPassword"):
payload = {"username": username, "password": password}
@ -30,32 +247,90 @@ def populate_data(token):
r = requests.post("http://localhost:9000/api/recipes", json=payload, headers=token)
if r.status_code != 201:
print(f"Error: {r.status_code}")
print(r.text)
console.print(f"Error: {r.status_code}")
console.print(r.text)
exit()
else:
print(f"Created recipe: {payload}")
recipe_json = requests.get(f"http://localhost:9000/api/recipes/{payload['name']}", headers=token)
if recipe_json.status_code != 200:
console.print(f"Error: {recipe_json.status_code}")
console.print(recipe_json.text)
exit()
recipe = json.loads(recipe_json.text)
update_data = recipe_data(recipe["name"], recipe["slug"], recipe["id"], recipe["userId"], recipe["groupId"])
r = requests.put(f"http://localhost:9000/api/recipes/{update_data['slug']}", json=update_data, headers=token)
if r.status_code != 200:
console.print(f"Error: {r.status_code}")
console.print(r.text)
exit()
def time_request(url, headers):
@dataclass(slots=True)
class Result:
recipes: int
time: float
def time_request(url, headers) -> Result:
start = time.time()
r = requests.get(url, headers=headers)
print(f"Total Recipes {len(r.json())}")
end = time.time()
print(end - start)
return Result(len(r.json()["items"]), end - start)
def main():
print("Starting...")
token = login()
# populate_data(token)
for _ in range(10):
time_request("http://localhost:9000/api/recipes", token)
results: list[Result] = []
print("Finished...")
for _ in range(10):
result = time_request("http://localhost:9000/api/recipes?perPage=-1&page=1&loadFood=true", token)
results.append(result)
min, max, average = 99, 0, 0
for result in results:
if result.time < min:
min = result.time
if result.time > max:
max = result.time
average += result.time
tbl1 = Table(title="Requests")
tbl1.add_column("Recipes", justify="right", style="cyan", no_wrap=True)
tbl1.add_column("Time", justify="right", style="magenta")
for result in results:
tbl1.add_row(
str(result.recipes),
str(result.time),
)
tbl2 = Table(title="Summary")
tbl2.add_column("Min", justify="right", style="green")
tbl2.add_column("Max", justify="right", style="green")
tbl2.add_column("Average", justify="right", style="green")
tbl2.add_row(
str(round(min * 1000)) + "ms",
str(round(max * 1000)) + "ms",
str(round((average / len(results)) * 1000)) + "ms",
)
console = Console()
console.print(tbl1)
console.print(tbl2)
# Best Time 289 / 405/ 247
if __name__ == "__main__":

View file

@ -1,214 +0,0 @@
import json
import re
from enum import Enum
from itertools import groupby
from pathlib import Path
from typing import Optional
from fastapi import FastAPI
from humps import camelize
from jinja2 import Template
from pydantic import BaseModel, Field
from slugify import slugify
from mealie.app import app
CWD = Path(__file__).parent
OUT_DIR = CWD / "output"
TEMPLATES_DIR = CWD / "templates"
JS_DIR = OUT_DIR / "javascriptAPI"
JS_DIR.mkdir(exist_ok=True, parents=True)
class RouteObject:
def __init__(self, route_string) -> None:
self.prefix = "/" + route_string.split("/")[1]
self.route = "/" + route_string.split("/", 2)[2]
self.js_route = self.route.replace("{", "${")
self.parts = route_string.split("/")[1:]
self.var = re.findall(r"\{(.*?)\}", route_string)
self.is_function = "{" in self.route
self.router_slug = slugify("_".join(self.parts[1:]), separator="_")
self.router_camel = camelize(self.router_slug)
class RequestType(str, Enum):
get = "get"
put = "put"
post = "post"
patch = "patch"
delete = "delete"
class ParameterIn(str, Enum):
query = "query"
path = "path"
class RouterParameter(BaseModel):
required: bool = False
name: str
location: ParameterIn = Field(..., alias="in")
class RequestBody(BaseModel):
required: bool = False
class HTTPRequest(BaseModel):
request_type: RequestType
description: str = ""
summary: str
requestBody: Optional[RequestBody]
parameters: list[RouterParameter] = []
tags: list[str]
def list_as_js_object_string(self, parameters, braces=True):
if len(parameters) == 0:
return ""
if braces:
return "{" + ", ".join(parameters) + "}"
else:
return ", ".join(parameters)
def payload(self):
return "payload" if self.requestBody else ""
def function_args(self):
all_params = [p.name for p in self.parameters]
if self.requestBody:
all_params.append("payload")
return self.list_as_js_object_string(all_params)
def query_params(self):
params = [param.name for param in self.parameters if param.location == ParameterIn.query]
return self.list_as_js_object_string(params)
def path_params(self):
params = [param.name for param in self.parameters if param.location == ParameterIn.path]
return self.list_as_js_object_string(parameters=params, braces=False)
@property
def summary_camel(self):
return camelize(slugify(self.summary))
@property
def js_docs(self):
return self.description.replace("\n", " \n * ")
class PathObject(BaseModel):
route_object: RouteObject
http_verbs: list[HTTPRequest]
class Config:
arbitrary_types_allowed = True
def get_path_objects(app: FastAPI):
paths = []
for key, value in app.openapi().items():
if key == "paths":
for key, value in value.items():
paths.append(
PathObject(
route_object=RouteObject(key),
http_verbs=[HTTPRequest(request_type=k, **v) for k, v in value.items()],
)
)
return paths
def dump_open_api(app: FastAPI):
"""Writes the Open API as JSON to a json file"""
OPEN_API_FILE = CWD / "openapi.json"
with open(OPEN_API_FILE, "w") as f:
f.write(json.dumps(app.openapi()))
def read_template(file: Path):
with open(file, "r") as f:
return f.read()
def generate_python_templates(static_paths: list[PathObject], function_paths: list[PathObject]):
PYTEST_TEMPLATE = TEMPLATES_DIR / "pytest_routes.j2"
PYTHON_OUT_FILE = OUT_DIR / "app_routes.py"
template = Template(read_template(PYTEST_TEMPLATE))
content = template.render(
paths={
"prefix": "/api",
"static_paths": static_paths,
"function_paths": function_paths,
}
)
with open(PYTHON_OUT_FILE, "w") as f:
f.write(content)
return
def generate_js_templates(paths: list[PathObject]):
# Template Path
JS_API_INTERFACE = TEMPLATES_DIR / "js_api_interface.j2"
JS_INDEX = TEMPLATES_DIR / "js_index.j2"
INTERFACES_DIR = JS_DIR / "interfaces"
INTERFACES_DIR.mkdir(exist_ok=True, parents=True)
all_tags = []
for tag, tag_paths in groupby(paths, lambda x: x.http_verbs[0].tags[0]):
file_name = slugify(tag, separator="-")
tag = camelize(tag)
tag_paths: list[PathObject] = list(tag_paths)
template = Template(read_template(JS_API_INTERFACE))
content = template.render(
paths={
"prefix": "/api",
"static_paths": [x.route_object for x in tag_paths if not x.route_object.is_function],
"function_paths": [x.route_object for x in tag_paths if x.route_object.is_function],
"all_paths": tag_paths,
"export_name": tag,
}
)
tag: dict = {"camel": camelize(tag), "slug": file_name}
all_tags.append(tag)
with open(INTERFACES_DIR.joinpath(file_name + ".ts"), "w") as f:
f.write(content)
template = Template(read_template(JS_INDEX))
content = template.render(files={"files": all_tags})
with open(JS_DIR.joinpath("index.js"), "w") as f:
f.write(content)
def generate_template(app):
dump_open_api(app)
paths = get_path_objects(app)
static_paths = [x.route_object for x in paths if not x.route_object.is_function]
function_paths = [x.route_object for x in paths if x.route_object.is_function]
static_paths.sort(key=lambda x: x.router_slug)
function_paths.sort(key=lambda x: x.router_slug)
generate_python_templates(static_paths, function_paths)
generate_js_templates(paths)
if __name__ == "__main__":
generate_template(app)

View file

@ -1,26 +0,0 @@
import json
from pathlib import Path
import requests
CWD = Path(__file__).parent
def login(username="changeme@email.com", password="MyPassword"):
payload = {"username": username, "password": password}
r = requests.post("http://localhost:9000/api/auth/token", payload)
# Bearer
token = json.loads(r.text).get("access_token")
return {"Authorization": f"Bearer {token}"}
def main():
print("Starting...")
print("Finished...")
if __name__ == "__main__":
main()

View file

@ -1,159 +0,0 @@
import json
import re
from dataclasses import dataclass
from pathlib import Path
from slugify import slugify
CWD = Path(__file__).parent
PROJECT_BASE = CWD.parent.parent
server_side_msgs = PROJECT_BASE / "mealie" / "utils" / "error_messages.py"
en_us_msgs = PROJECT_BASE / "frontend" / "lang" / "errors" / "en-US.json"
client_side_msgs = PROJECT_BASE / "frontend" / "utils" / "error-messages.ts"
GENERATE_MESSAGES = [
# User Related
"user",
"webhook",
"token",
# Group Related
"group",
"cookbook",
"mealplan",
# Recipe Related
"scraper",
"recipe",
"ingredient",
"food",
"unit",
# Admin Related
"backup",
"migration",
"event",
]
class ErrorMessage:
def __init__(self, prefix, verb) -> None:
self.message = f"{prefix.title()} {verb.title()} Failed"
self.snake = slugify(self.message, separator="_")
self.kabab = slugify(self.message, separator="-")
def factory(prefix) -> list["ErrorMessage"]:
verbs = ["Create", "Update", "Delete"]
return [ErrorMessage(prefix, verb) for verb in verbs]
@dataclass
class CodeGenLines:
start: int
end: int
indentation: str
text: list[str]
_next_line = None
def purge_lines(self) -> None:
start = self.start + 1
end = self.end
del self.text[start:end]
def push_line(self, string: str) -> None:
self._next_line = self._next_line or self.start + 1
self.text.insert(self._next_line, self.indentation + string)
self._next_line += 1
def find_start(file_text: list[str], gen_id: str):
for x, line in enumerate(file_text):
if "CODE_GEN_ID:" in line and gen_id in line:
return x, line
return None
def find_end(file_text: list[str], gen_id: str):
for x, line in enumerate(file_text):
if f"END {gen_id}" in line:
return x, line
return None
def get_indentation_of_string(line: str):
return re.sub(r"#.*", "", line).removesuffix("\n")
def get_messages(message_prefix: str) -> str:
prefix = message_prefix.lower()
return [
f'{prefix}_create_failure = "{prefix}-create-failure"\n',
f'{prefix}_update_failure = "{prefix}-update-failure"\n',
f'{prefix}_delete_failure = "{prefix}-delete-failure"\n',
]
def code_gen_factory(file_path: Path) -> CodeGenLines:
with open(file_path, "r") as file:
text = file.readlines()
start_num, line = find_start(text, "ERROR_MESSAGE_ENUMS")
indentation = get_indentation_of_string(line)
end_num, line = find_end(text, "ERROR_MESSAGE_ENUMS")
return CodeGenLines(
start=start_num,
end=end_num,
indentation=indentation,
text=text,
)
def write_to_locals(messages: list[ErrorMessage]) -> None:
with open(en_us_msgs, "r") as f:
existing_msg = json.loads(f.read())
for msg in messages:
if msg.kabab in existing_msg:
continue
existing_msg[msg.kabab] = msg.message
print(f"Added Key {msg.kabab} to 'en-US.json'")
with open(en_us_msgs, "w") as f:
f.write(json.dumps(existing_msg, indent=4))
def main():
print("Starting...")
GENERATE_MESSAGES.sort()
code_gen = code_gen_factory(server_side_msgs)
code_gen.purge_lines()
messages = []
for msg_type in GENERATE_MESSAGES:
messages += get_messages(msg_type)
messages.append("\n")
for msg in messages:
code_gen.push_line(msg)
with open(server_side_msgs, "w") as file:
file.writelines(code_gen.text)
# Locals
local_msgs = []
for msg_type in GENERATE_MESSAGES:
local_msgs += ErrorMessage.factory(msg_type)
write_to_locals(local_msgs)
print("Done!")
if __name__ == "__main__":
main()

View file

@ -1,32 +0,0 @@
import json
import requests
from pydantic import BaseModel
class GithubIssue(BaseModel):
url: str
number: int
title: str
def get_issues_by_label(label="fixed-pending-release") -> list[GithubIssue]:
issues_url = f"https://api.github.com/repos/hay-kot/mealie/issues?labels={label}"
response = requests.get(issues_url)
issues = json.loads(response.text)
return [GithubIssue(**issue) for issue in issues]
def format_markdown_list(issues: list[GithubIssue]) -> str:
return "\n".join(f"- [{issue.number}]({issue.url}) - {issue.title}" for issue in issues)
def main() -> None:
issues = get_issues_by_label()
print(format_markdown_list(issues))
if __name__ == "__main__":
main()

View file

@ -1,156 +0,0 @@
# This Content is Auto Generated for Pytest
class AppRoutes:
def __init__(self) -> None:
self.prefix = '/api'
self.about_events = "/api/about/events"
self.about_events_notifications = "/api/about/events/notifications"
self.about_events_notifications_test = "/api/about/events/notifications/test"
self.about_recipes_defaults = "/api/about/recipes/defaults"
self.auth_refresh = "/api/auth/refresh"
self.auth_token = "/api/auth/token"
self.auth_token_long = "/api/auth/token/long"
self.backups_available = "/api/backups/available"
self.backups_export_database = "/api/backups/export/database"
self.backups_upload = "/api/backups/upload"
self.categories = "/api/categories"
self.categories_empty = "/api/categories/empty"
self.debug = "/api/debug"
self.debug_last_recipe_json = "/api/debug/last-recipe-json"
self.debug_log = "/api/debug/log"
self.debug_statistics = "/api/debug/statistics"
self.debug_version = "/api/debug/version"
self.groups = "/api/groups"
self.groups_self = "/api/groups/self"
self.meal_plans_all = "/api/meal-plans/all"
self.meal_plans_create = "/api/meal-plans/create"
self.meal_plans_this_week = "/api/meal-plans/this-week"
self.meal_plans_today = "/api/meal-plans/today"
self.meal_plans_today_image = "/api/meal-plans/today/image"
self.migrations = "/api/migrations"
self.recipes = "/api/recipes"
self.recipes_category = "/api/recipes/category"
self.recipes_create = "/api/recipes/create"
self.recipes_create_from_zip = "/api/recipes/create-from-zip"
self.recipes_create_url = "/api/recipes/create-url"
self.recipes_summary_uncategorized = "/api/recipes/summary/uncategorized"
self.recipes_summary_untagged = "/api/recipes/summary/untagged"
self.recipes_tag = "/api/recipes/tag"
self.recipes_test_scrape_url = "/api/recipes/test-scrape-url"
self.shopping_lists = "/api/shopping-lists"
self.site_settings = "/api/site-settings"
self.site_settings_custom_pages = "/api/site-settings/custom-pages"
self.site_settings_webhooks_test = "/api/site-settings/webhooks/test"
self.tags = "/api/tags"
self.tags_empty = "/api/tags/empty"
self.themes = "/api/themes"
self.themes_create = "/api/themes/create"
self.users = "/api/users"
self.users_api_tokens = "/api/users/api-tokens"
self.users_self = "/api/users/self"
self.users_sign_ups = "/api/users/sign-ups"
self.utils_download = "/api/utils/download"
def about_events_id(self, id):
return f"{self.prefix}/about/events/{id}"
def about_events_notifications_id(self, id):
return f"{self.prefix}/about/events/notifications/{id}"
def backups_file_name_delete(self, file_name):
return f"{self.prefix}/backups/{file_name}/delete"
def backups_file_name_download(self, file_name):
return f"{self.prefix}/backups/{file_name}/download"
def backups_file_name_import(self, file_name):
return f"{self.prefix}/backups/{file_name}/import"
def categories_category(self, category):
return f"{self.prefix}/categories/{category}"
def debug_log_num(self, num):
return f"{self.prefix}/debug/log/{num}"
def groups_id(self, id):
return f"{self.prefix}/groups/{id}"
def meal_plans_id(self, id):
return f"{self.prefix}/meal-plans/{id}"
def meal_plans_id_shopping_list(self, id):
return f"{self.prefix}/meal-plans/{id}/shopping-list"
def meal_plans_plan_id(self, plan_id):
return f"{self.prefix}/meal-plans/{plan_id}"
def media_recipes_recipe_slug_assets_file_name(self, recipe_slug, file_name):
return f"{self.prefix}/media/recipes/{recipe_slug}/assets/{file_name}"
def media_recipes_recipe_slug_images_file_name(self, recipe_slug, file_name):
return f"{self.prefix}/media/recipes/{recipe_slug}/images/{file_name}"
def migrations_import_type_file_name_delete(self, import_type, file_name):
return f"{self.prefix}/migrations/{import_type}/{file_name}/delete"
def migrations_import_type_file_name_import(self, import_type, file_name):
return f"{self.prefix}/migrations/{import_type}/{file_name}/import"
def migrations_import_type_upload(self, import_type):
return f"{self.prefix}/migrations/{import_type}/upload"
def recipes_recipe_slug(self, recipe_slug):
return f"{self.prefix}/recipes/{recipe_slug}"
def recipes_recipe_slug_assets(self, recipe_slug):
return f"{self.prefix}/recipes/{recipe_slug}/assets"
def recipes_recipe_slug_image(self, recipe_slug):
return f"{self.prefix}/recipes/{recipe_slug}/image"
def recipes_recipe_slug_zip(self, recipe_slug):
return f"{self.prefix}/recipes/{recipe_slug}/zip"
def recipes_slug_comments(self, slug):
return f"{self.prefix}/recipes/{slug}/comments"
def recipes_slug_comments_id(self, slug, id):
return f"{self.prefix}/recipes/{slug}/comments/{id}"
def shopping_lists_id(self, id):
return f"{self.prefix}/shopping-lists/{id}"
def site_settings_custom_pages_id(self, id):
return f"{self.prefix}/site-settings/custom-pages/{id}"
def tags_tag(self, tag):
return f"{self.prefix}/tags/{tag}"
def themes_id(self, id):
return f"{self.prefix}/themes/{id}"
def users_api_tokens_token_id(self, token_id):
return f"{self.prefix}/users/api-tokens/{token_id}"
def users_id(self, id):
return f"{self.prefix}/users/{id}"
def users_id_favorites(self, id):
return f"{self.prefix}/users/{id}/favorites"
def users_id_favorites_slug(self, id, slug):
return f"{self.prefix}/users/{id}/favorites/{slug}"
def users_id_image(self, id):
return f"{self.prefix}/users/{id}/image"
def users_id_password(self, id):
return f"{self.prefix}/users/{id}/password"
def users_id_reset_password(self, id):
return f"{self.prefix}/users/{id}/reset-password"
def users_sign_ups_token(self, token):
return f"{self.prefix}/users/sign-ups/{token}"

View file

@ -1,11 +0,0 @@
git checkout dev
git merge --strategy=ours master # keep the content of this branch, but record a merge
git checkout master
git merge dev # fast-forward master up to the merge
## TODOs
# Create New Branch v0.x.x
# Push Branch Version to Github
# Create Pull Request

View file

@ -1,17 +0,0 @@
import { requests } from "../requests";
const prefix = '{{paths.prefix}}'
const routes = { {% for path in paths.static_paths %}
{{ path.router_camel }}: `${prefix}{{ path.route }}`,{% endfor %}
{% for path in paths.function_paths %}
{{path.router_camel}}: ({{path.var|join(", ")}}) => `${prefix}{{ path.js_route }}`,{% endfor %}
}
export const {{paths.export_name}}API = { {% for path in paths.all_paths %} {% for verb in path.http_verbs %}
{% if verb.js_docs %}/** {{ verb.js_docs }}
*/ {% endif %}
async {{ verb.summary_camel }}({{ verb.function_args() }}) {
return await requests.{{ verb.request_type.value }}(routes.{{ path.route_object.router_camel }}{% if path.route_object.is_function %}({{verb.path_params()}}){% endif %}, {{ verb.query_params() }} {{ verb.payload() }})
}, {% endfor %} {% endfor %}
}

View file

@ -1,7 +0,0 @@
{% for api in files.files %}
import { {{ api.camel }}API } from "./interfaces/{{ api.slug }}" {% endfor %}
export const api = {
{% for api in files.files %}
{{api.camel}}: {{api.camel}}API, {% endfor %}
}

View file

@ -1,12 +0,0 @@
# This Content is Auto Generated for Pytest
class AppRoutes:
def __init__(self) -> None:
self.prefix = '{{paths.prefix}}'
{% for path in paths.static_paths %}
self.{{ path.router_slug }} = "{{path.prefix}}{{ path.route }}"{% endfor %}
{% for path in paths.function_paths %}
def {{path.router_slug}}(self, {{path.var|join(", ")}}):
return f"{self.prefix}{{ path.route }}"
{% endfor %}

View file

@ -146,7 +146,7 @@ import { until } from "@vueuse/core";
import { invoke } from "@vueuse/shared";
import draggable from "vuedraggable";
import { useUserApi, useStaticRoutes } from "~/composables/api";
import { OcrTsvResponse } from "~/types/api-types/ocr";
import { OcrTsvResponse as NullableOcrTsvResponse } from "~/types/api-types/ocr";
import { validators } from "~/composables/use-validators";
import { Recipe, RecipeIngredient, RecipeStep } from "~/types/api-types/recipe";
import { Paths, Leaves, SelectedRecipeLeaves } from "~/types/ocr-types";
@ -159,6 +159,10 @@ import RecipeOcrEditorPageHelp from "~/components/Domain/Recipe/RecipeOcrEditorP
import { uuid4 } from "~/composables/use-utils";
import { NoUndefinedField } from "~/types/api";
// Temporary Shim until we have a better solution
// https://github.com/phillipdupuis/pydantic-to-typescript/issues/28
type OcrTsvResponse = NoUndefinedField<NullableOcrTsvResponse>;
export default defineComponent({
components: {
RecipeIngredientEditor,

View file

@ -41,9 +41,14 @@
<script lang="ts">
import { defineComponent, reactive, useContext, ref, toRefs, watch } from "@nuxtjs/composition-api";
import { onMounted } from "vue-demi";
import { OcrTsvResponse } from "~/types/api-types/ocr";
import { NoUndefinedField } from "~/types/api";
import { OcrTsvResponse as NullableOcrTsvResponse } from "~/types/api-types/ocr";
import { CanvasModes, SelectedTextSplitModes, ImagePosition, Mouse, CanvasRect, ToolbarIcons } from "~/types/ocr-types";
// Temporary Shim until we have a better solution
// https://github.com/phillipdupuis/pydantic-to-typescript/issues/28
type OcrTsvResponse = NoUndefinedField<NullableOcrTsvResponse>;
export default defineComponent({
props: {
image: {
@ -451,8 +456,10 @@ export default defineComponent({
correctedRect.startY - state.imagePosition.dy < element.top * state.imagePosition.scale &&
correctedRect.startX - state.imagePosition.dx < element.left * state.imagePosition.scale &&
correctedRect.startX + correctedRect.w >
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
(element.left + element.width) * state.imagePosition.scale + state.imagePosition.dx &&
correctedRect.startY + correctedRect.h >
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
(element.top + element.height) * state.imagePosition.scale + state.imagePosition.dy
)
.map((element, index, array) => {
@ -464,6 +471,7 @@ export default defineComponent({
) {
separator = "\n";
}
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
return element.text + separator;
})
.join("");

View file

@ -3,12 +3,12 @@ export const LOCALES = [
{
name: "繁體中文 (Chinese traditional)",
value: "zh-TW",
progress: 77,
progress: 68,
},
{
name: "简体中文 (Chinese simplified)",
value: "zh-CN",
progress: 64,
progress: 57,
},
{
name: "Tiếng Việt (Vietnamese)",
@ -23,32 +23,32 @@ export const LOCALES = [
{
name: "Türkçe (Turkish)",
value: "tr-TR",
progress: 5,
progress: 32,
},
{
name: "Svenska (Swedish)",
value: "sv-SE",
progress: 93,
progress: 91,
},
{
name: "српски (Serbian)",
value: "sr-SP",
progress: 12,
progress: 11,
},
{
name: "Slovenian",
value: "sl-SI",
progress: 100,
progress: 95,
},
{
name: "Slovak",
value: "sk-SK",
progress: 78,
progress: 86,
},
{
name: "Pусский (Russian)",
value: "ru-RU",
progress: 64,
progress: 57,
},
{
name: "Română (Romanian)",
@ -58,27 +58,27 @@ export const LOCALES = [
{
name: "Português (Portuguese)",
value: "pt-PT",
progress: 10,
progress: 9,
},
{
name: "Português do Brasil (Brazilian Portuguese)",
value: "pt-BR",
progress: 44,
progress: 39,
},
{
name: "Polski (Polish)",
value: "pl-PL",
progress: 99,
progress: 88,
},
{
name: "Norsk (Norwegian)",
value: "no-NO",
progress: 64,
progress: 80,
},
{
name: "Nederlands (Dutch)",
value: "nl-NL",
progress: 85,
progress: 91,
},
{
name: "Lithuanian",
@ -98,17 +98,17 @@ export const LOCALES = [
{
name: "Italiano (Italian)",
value: "it-IT",
progress: 93,
progress: 83,
},
{
name: "Magyar (Hungarian)",
value: "hu-HU",
progress: 88,
progress: 78,
},
{
name: "עברית (Hebrew)",
value: "he-IL",
progress: 0,
progress: 33,
},
{
name: "Français (French)",
@ -118,17 +118,17 @@ export const LOCALES = [
{
name: "French, Canada",
value: "fr-CA",
progress: 85,
progress: 84,
},
{
name: "Suomi (Finnish)",
value: "fi-FI",
progress: 0,
progress: 23,
},
{
name: "Español (Spanish)",
value: "es-ES",
progress: 64,
progress: 95,
},
{
name: "American English",
@ -138,17 +138,17 @@ export const LOCALES = [
{
name: "British English",
value: "en-GB",
progress: 35,
progress: 32,
},
{
name: "Ελληνικά (Greek)",
value: "el-GR",
progress: 79,
progress: 70,
},
{
name: "Deutsch (German)",
value: "de-DE",
progress: 99,
progress: 100,
},
{
name: "Dansk (Danish)",
@ -158,12 +158,12 @@ export const LOCALES = [
{
name: "Čeština (Czech)",
value: "cs-CZ",
progress: 55,
progress: 66,
},
{
name: "Català (Catalan)",
value: "ca-ES",
progress: 64,
progress: 95,
},
{
name: "Bulgarian",
@ -173,7 +173,7 @@ export const LOCALES = [
{
name: "العربية (Arabic)",
value: "ar-SA",
progress: 11,
progress: 24,
},
{
name: "Afrikaans (Afrikaans)",

View file

@ -133,6 +133,9 @@ export interface RecipeIngredient {
export interface IngredientUnit {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
fraction?: boolean;
abbreviation?: string;
useAbbreviation?: boolean;
@ -143,6 +146,9 @@ export interface IngredientUnit {
export interface CreateIngredientUnit {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
fraction?: boolean;
abbreviation?: string;
useAbbreviation?: boolean;
@ -150,6 +156,9 @@ export interface CreateIngredientUnit {
export interface IngredientFood {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
labelId?: string;
id: string;
label?: MultiPurposeLabelSummary;
@ -165,6 +174,9 @@ export interface MultiPurposeLabelSummary {
export interface CreateIngredientFood {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
labelId?: string;
}
export interface CustomPageImport {

View file

@ -5,11 +5,6 @@
/* Do not modify it by hand - just update the pydantic models and then re-run the script
*/
export interface CategoryBase {
name: string;
id: string;
slug: string;
}
export interface CreateCookBook {
name: string;
description?: string;
@ -23,6 +18,11 @@ export interface CreateCookBook {
requireAllTags?: boolean;
requireAllTools?: boolean;
}
export interface CategoryBase {
name: string;
id: string;
slug: string;
}
export interface TagBase {
name: string;
id: string;
@ -112,6 +112,9 @@ export interface RecipeIngredient {
export interface IngredientUnit {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
fraction?: boolean;
abbreviation?: string;
useAbbreviation?: boolean;
@ -122,6 +125,9 @@ export interface IngredientUnit {
export interface CreateIngredientUnit {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
fraction?: boolean;
abbreviation?: string;
useAbbreviation?: boolean;
@ -129,6 +135,9 @@ export interface CreateIngredientUnit {
export interface IngredientFood {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
labelId?: string;
id: string;
label?: MultiPurposeLabelSummary;
@ -144,6 +153,9 @@ export interface MultiPurposeLabelSummary {
export interface CreateIngredientFood {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
labelId?: string;
}
export interface SaveCookBook {

View file

@ -73,6 +73,8 @@ export interface GroupEventNotifierCreate {
* If you modify this, make sure to update the EventBusService as well.
*/
export interface GroupEventNotifierOptions {
testMessage?: boolean;
webhookTask?: boolean;
recipeCreated?: boolean;
recipeUpdated?: boolean;
recipeDeleted?: boolean;
@ -99,6 +101,8 @@ export interface GroupEventNotifierOptions {
* If you modify this, make sure to update the EventBusService as well.
*/
export interface GroupEventNotifierOptionsOut {
testMessage?: boolean;
webhookTask?: boolean;
recipeCreated?: boolean;
recipeUpdated?: boolean;
recipeDeleted?: boolean;
@ -126,6 +130,8 @@ export interface GroupEventNotifierOptionsOut {
* If you modify this, make sure to update the EventBusService as well.
*/
export interface GroupEventNotifierOptionsSave {
testMessage?: boolean;
webhookTask?: boolean;
recipeCreated?: boolean;
recipeUpdated?: boolean;
recipeDeleted?: boolean;
@ -191,31 +197,6 @@ export interface GroupStorage {
totalStorageBytes: number;
totalStorageStr: string;
}
export interface IngredientFood {
name: string;
description?: string;
labelId?: string;
id: string;
label?: MultiPurposeLabelSummary;
createdAt?: string;
updateAt?: string;
}
export interface MultiPurposeLabelSummary {
name: string;
color?: string;
groupId: string;
id: string;
}
export interface IngredientUnit {
name: string;
description?: string;
fraction?: boolean;
abbreviation?: string;
useAbbreviation?: boolean;
id: string;
createdAt?: string;
updateAt?: string;
}
export interface ReadGroupPreferences {
privateGroup?: boolean;
firstDayOfWeek?: number;
@ -242,6 +223,156 @@ export interface ReadWebhook {
groupId: string;
id: string;
}
export interface SaveInviteToken {
usesLeft: number;
groupId: string;
token: string;
}
export interface SaveWebhook {
enabled?: boolean;
name?: string;
url?: string;
webhookType?: WebhookType & string;
scheduledTime: string;
groupId: string;
}
export interface SeederConfig {
locale: string;
}
export interface SetPermissions {
userId: string;
canManage?: boolean;
canInvite?: boolean;
canOrganize?: boolean;
}
export interface ShoppingListCreate {
name?: string;
extras?: {
[k: string]: unknown;
};
createdAt?: string;
updateAt?: string;
}
export interface ShoppingListItemCreate {
shoppingListId: string;
checked?: boolean;
position?: number;
isFood?: boolean;
note?: string;
quantity?: number;
unitId?: string;
unit?: IngredientUnit;
foodId?: string;
food?: IngredientFood;
labelId?: string;
recipeReferences?: ShoppingListItemRecipeRef[];
extras?: {
[k: string]: unknown;
};
createdAt?: string;
updateAt?: string;
}
export interface IngredientUnit {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
fraction?: boolean;
abbreviation?: string;
useAbbreviation?: boolean;
id: string;
createdAt?: string;
updateAt?: string;
}
export interface IngredientFood {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
labelId?: string;
id: string;
label?: MultiPurposeLabelSummary;
createdAt?: string;
updateAt?: string;
}
export interface MultiPurposeLabelSummary {
name: string;
color?: string;
groupId: string;
id: string;
}
export interface ShoppingListItemRecipeRef {
recipeId: string;
recipeQuantity?: number;
}
export interface ShoppingListItemOut {
shoppingListId: string;
checked?: boolean;
position?: number;
isFood?: boolean;
note?: string;
quantity?: number;
unitId?: string;
unit?: IngredientUnit;
foodId?: string;
food?: IngredientFood;
labelId?: string;
recipeReferences?: (ShoppingListItemRecipeRef | ShoppingListItemRecipeRefOut)[];
extras?: {
[k: string]: unknown;
};
createdAt?: string;
updateAt?: string;
id: string;
label?: MultiPurposeLabelSummary;
}
export interface ShoppingListItemRecipeRefOut {
recipeId: string;
recipeQuantity?: number;
id: string;
shoppingListItemId: string;
}
export interface ShoppingListItemUpdate {
shoppingListId: string;
checked?: boolean;
position?: number;
isFood?: boolean;
note?: string;
quantity?: number;
unitId?: string;
unit?: IngredientUnit;
foodId?: string;
food?: IngredientFood;
labelId?: string;
recipeReferences?: ShoppingListItemRecipeRef[];
extras?: {
[k: string]: unknown;
};
createdAt?: string;
updateAt?: string;
id: string;
}
export interface ShoppingListOut {
name?: string;
extras?: {
[k: string]: unknown;
};
createdAt?: string;
updateAt?: string;
groupId: string;
id: string;
listItems?: ShoppingListItemOut[];
recipeReferences: ShoppingListRecipeRefOut[];
}
export interface ShoppingListRecipeRefOut {
id: string;
shoppingListId: string;
recipeId: string;
recipeQuantity: number;
recipe: RecipeSummary;
}
export interface RecipeSummary {
id?: string;
userId?: string;
@ -295,6 +426,9 @@ export interface RecipeIngredient {
export interface CreateIngredientUnit {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
fraction?: boolean;
abbreviation?: string;
useAbbreviation?: boolean;
@ -302,120 +436,25 @@ export interface CreateIngredientUnit {
export interface CreateIngredientFood {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
labelId?: string;
}
export interface SaveInviteToken {
usesLeft: number;
groupId: string;
token: string;
}
export interface SaveWebhook {
enabled?: boolean;
name?: string;
url?: string;
webhookType?: WebhookType & string;
scheduledTime: string;
groupId: string;
}
export interface SeederConfig {
locale: string;
}
export interface SetPermissions {
userId: string;
canManage?: boolean;
canInvite?: boolean;
canOrganize?: boolean;
}
export interface ShoppingListCreate {
name?: string;
createdAt?: string;
updateAt?: string;
}
export interface ShoppingListItemCreate {
shoppingListId: string;
checked?: boolean;
position?: number;
isFood?: boolean;
note?: string;
quantity?: number;
unitId?: string;
unit?: IngredientUnit;
foodId?: string;
food?: IngredientFood;
labelId?: string;
recipeReferences?: ShoppingListItemRecipeRef[];
createdAt?: string;
updateAt?: string;
}
export interface ShoppingListItemRecipeRef {
recipeId: string;
recipeQuantity: number;
}
export interface ShoppingListItemOut {
shoppingListId: string;
checked?: boolean;
position?: number;
isFood?: boolean;
note?: string;
quantity?: number;
unitId?: string;
unit?: IngredientUnit;
foodId?: string;
food?: IngredientFood;
labelId?: string;
recipeReferences?: (ShoppingListItemRecipeRef | ShoppingListItemRecipeRefOut)[];
createdAt?: string;
updateAt?: string;
id: string;
label?: MultiPurposeLabelSummary;
}
export interface ShoppingListItemRecipeRefOut {
recipeId: string;
recipeQuantity: number;
id: string;
shoppingListItemId: string;
}
export interface ShoppingListItemUpdate {
shoppingListId: string;
checked?: boolean;
position?: number;
isFood?: boolean;
note?: string;
quantity?: number;
unitId?: string;
unit?: IngredientUnit;
foodId?: string;
food?: IngredientFood;
labelId?: string;
recipeReferences?: ShoppingListItemRecipeRef[];
createdAt?: string;
updateAt?: string;
id: string;
}
export interface ShoppingListOut {
name?: string;
createdAt?: string;
updateAt?: string;
groupId: string;
id: string;
listItems?: ShoppingListItemOut[];
recipeReferences: ShoppingListRecipeRefOut[];
}
export interface ShoppingListRecipeRefOut {
id: string;
shoppingListId: string;
recipeId: string;
recipeQuantity: number;
recipe: RecipeSummary;
}
export interface ShoppingListSave {
name?: string;
extras?: {
[k: string]: unknown;
};
createdAt?: string;
updateAt?: string;
groupId: string;
}
export interface ShoppingListSummary {
name?: string;
extras?: {
[k: string]: unknown;
};
createdAt?: string;
updateAt?: string;
groupId: string;
@ -423,6 +462,9 @@ export interface ShoppingListSummary {
}
export interface ShoppingListUpdate {
name?: string;
extras?: {
[k: string]: unknown;
};
createdAt?: string;
updateAt?: string;
groupId: string;

View file

@ -148,6 +148,9 @@ export interface RecipeIngredient {
export interface IngredientUnit {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
fraction?: boolean;
abbreviation?: string;
useAbbreviation?: boolean;
@ -158,6 +161,9 @@ export interface IngredientUnit {
export interface CreateIngredientUnit {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
fraction?: boolean;
abbreviation?: string;
useAbbreviation?: boolean;
@ -165,6 +171,9 @@ export interface CreateIngredientUnit {
export interface IngredientFood {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
labelId?: string;
id: string;
label?: MultiPurposeLabelSummary;
@ -180,6 +189,9 @@ export interface MultiPurposeLabelSummary {
export interface CreateIngredientFood {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
labelId?: string;
}
export interface SavePlanEntry {

View file

@ -5,17 +5,21 @@
/* Do not modify it by hand - just update the pydantic models and then re-run the script
*/
export interface OcrTsvResponse {
level: number;
pageNum: number;
blockNum: number;
parNum: number;
lineNum: number;
wordNum: number;
left: number;
top: number;
width: number;
height: number;
conf: number;
text: string;
export interface OcrAssetReq {
recipeSlug: string;
assetName: string;
}
export interface OcrTsvResponse {
level?: number;
pageNum?: number;
blockNum?: number;
parNum?: number;
lineNum?: number;
wordNum?: number;
left?: number;
top?: number;
width?: number;
height?: number;
conf?: number;
text?: string;
}

View file

@ -56,11 +56,17 @@ export interface CategorySave {
export interface CreateIngredientFood {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
labelId?: string;
}
export interface CreateIngredientUnit {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
fraction?: boolean;
abbreviation?: string;
useAbbreviation?: boolean;
@ -107,6 +113,9 @@ export interface IngredientConfidence {
export interface IngredientFood {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
labelId?: string;
id: string;
label?: MultiPurposeLabelSummary;
@ -132,6 +141,9 @@ export interface IngredientRequest {
export interface IngredientUnit {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
fraction?: boolean;
abbreviation?: string;
useAbbreviation?: boolean;
@ -160,13 +172,6 @@ export interface Nutrition {
sodiumContent?: string;
sugarContent?: string;
}
export interface PaginationQuery {
page?: number;
perPage?: number;
orderBy?: string;
orderDirection?: OrderDirection & string;
queryFilter?: string;
}
export interface ParsedIngredient {
input?: string;
confidence?: IngredientConfidence;
@ -213,8 +218,8 @@ export interface Recipe {
extras?: {
[k: string]: unknown;
};
comments?: RecipeCommentOut[];
isOcrRecipe?: boolean;
comments?: RecipeCommentOut[];
}
export interface RecipeTool {
id: string;
@ -335,16 +340,16 @@ export interface RecipeTagResponse {
slug: string;
recipes?: RecipeSummary[];
}
export interface RecipeTool1 {
export interface RecipeToolCreate {
name: string;
onHand?: boolean;
}
export interface RecipeToolOut {
name: string;
onHand?: boolean;
id: string;
slug: string;
}
export interface RecipeToolCreate {
name: string;
onHand?: boolean;
}
export interface RecipeToolResponse {
name: string;
onHand?: boolean;
@ -363,12 +368,18 @@ export interface RecipeZipTokenResponse {
export interface SaveIngredientFood {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
labelId?: string;
groupId: string;
}
export interface SaveIngredientUnit {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
fraction?: boolean;
abbreviation?: string;
useAbbreviation?: boolean;
@ -398,7 +409,17 @@ export interface TagSave {
export interface UnitFoodBase {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
}
export interface UpdateImageResponse {
image: string;
}
export interface PaginationQuery {
page?: number;
perPage?: number;
orderBy?: string;
orderDirection?: OrderDirection & string;
queryFilter?: string;
}

View file

@ -5,6 +5,8 @@
/* Do not modify it by hand - just update the pydantic models and then re-run the script
*/
export type OrderDirection = "asc" | "desc";
export interface ErrorResponse {
message: string;
error?: boolean;
@ -13,6 +15,13 @@ export interface ErrorResponse {
export interface FileTokenResponse {
fileToken: string;
}
export interface PaginationQuery {
page?: number;
perPage?: number;
orderBy?: string;
orderDirection?: OrderDirection & string;
queryFilter?: string;
}
export interface SuccessResponse {
message: string;
error?: boolean;

View file

@ -5,17 +5,13 @@
/* Do not modify it by hand - just update the pydantic models and then re-run the script
*/
export interface CategoryBase {
name: string;
id: string;
slug: string;
}
export interface ChangePassword {
currentPassword: string;
newPassword: string;
}
export interface CreateToken {
name: string;
integrationId?: string;
userId: string;
token: string;
}
@ -48,6 +44,11 @@ export interface GroupInDB {
users?: UserOut[];
preferences?: ReadGroupPreferences;
}
export interface CategoryBase {
name: string;
id: string;
slug: string;
}
export interface UserOut {
username?: string;
fullName?: string;
@ -83,9 +84,11 @@ export interface ReadGroupPreferences {
}
export interface LongLiveTokenIn {
name: string;
integrationId?: string;
}
export interface LongLiveTokenInDB {
name: string;
integrationId?: string;
userId: string;
token: string;
id: number;
@ -115,6 +118,57 @@ export interface PrivatePasswordResetToken {
token: string;
user: PrivateUser;
}
export interface ResetPassword {
token: string;
email: string;
password: string;
passwordConfirm: string;
}
export interface SavePasswordResetToken {
userId: string;
token: string;
}
export interface Token {
access_token: string;
token_type: string;
}
export interface TokenData {
user_id?: string;
username?: string;
}
export interface UnlockResults {
unlocked?: number;
}
export interface UpdateGroup {
name: string;
id: string;
categories?: CategoryBase[];
webhooks?: unknown[];
}
export interface UserBase {
username?: string;
fullName?: string;
email: string;
admin?: boolean;
group?: string;
advanced?: boolean;
favoriteRecipes?: string[];
canInvite?: boolean;
canManage?: boolean;
canOrganize?: boolean;
}
export interface UserFavorites {
username?: string;
fullName?: string;
email: string;
admin?: boolean;
group?: string;
advanced?: boolean;
favoriteRecipes?: RecipeSummary[];
canInvite?: boolean;
canManage?: boolean;
canOrganize?: boolean;
}
export interface RecipeSummary {
id?: string;
userId?: string;
@ -168,6 +222,9 @@ export interface RecipeIngredient {
export interface IngredientUnit {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
fraction?: boolean;
abbreviation?: string;
useAbbreviation?: boolean;
@ -178,6 +235,9 @@ export interface IngredientUnit {
export interface CreateIngredientUnit {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
fraction?: boolean;
abbreviation?: string;
useAbbreviation?: boolean;
@ -185,6 +245,9 @@ export interface CreateIngredientUnit {
export interface IngredientFood {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
labelId?: string;
id: string;
label?: MultiPurposeLabelSummary;
@ -200,59 +263,11 @@ export interface MultiPurposeLabelSummary {
export interface CreateIngredientFood {
name: string;
description?: string;
extras?: {
[k: string]: unknown;
};
labelId?: string;
}
export interface ResetPassword {
token: string;
email: string;
password: string;
passwordConfirm: string;
}
export interface SavePasswordResetToken {
userId: string;
token: string;
}
export interface Token {
access_token: string;
token_type: string;
}
export interface TokenData {
user_id?: string;
username?: string;
}
export interface UnlockResults {
unlocked?: number;
}
export interface UpdateGroup {
name: string;
id: string;
categories?: CategoryBase[];
webhooks?: unknown[];
}
export interface UserBase {
username?: string;
fullName?: string;
email: string;
admin?: boolean;
group?: string;
advanced?: boolean;
favoriteRecipes?: string[];
canInvite?: boolean;
canManage?: boolean;
canOrganize?: boolean;
}
export interface UserFavorites {
username?: string;
fullName?: string;
email: string;
admin?: boolean;
group?: string;
advanced?: boolean;
favoriteRecipes?: RecipeSummary[];
canInvite?: boolean;
canManage?: boolean;
canOrganize?: boolean;
}
export interface UserIn {
username?: string;
fullName?: string;

View file

@ -1,74 +1,77 @@
// This Code is auto generated by gen_global_components.py
import BaseCardSectionTitle from "@/components/global/BaseCardSectionTitle.vue";
import MarkdownEditor from "@/components/global/MarkdownEditor.vue";
import AppLoader from "@/components/global/AppLoader.vue";
import BaseOverflowButton from "@/components/global/BaseOverflowButton.vue";
import ReportTable from "@/components/global/ReportTable.vue";
import AppToolbar from "@/components/global/AppToolbar.vue";
import BaseButtonGroup from "@/components/global/BaseButtonGroup.vue";
import BaseButton from "@/components/global/BaseButton.vue";
import BannerExperimental from "@/components/global/BannerExperimental.vue";
import BaseDialog from "@/components/global/BaseDialog.vue";
import RecipeJsonEditor from "@/components/global/RecipeJsonEditor.vue";
import StatsCards from "@/components/global/StatsCards.vue";
import HelpIcon from "@/components/global/HelpIcon.vue";
import InputLabelType from "@/components/global/InputLabelType.vue";
import BaseStatCard from "@/components/global/BaseStatCard.vue";
import DevDumpJson from "@/components/global/DevDumpJson.vue";
import LanguageDialog from "@/components/global/LanguageDialog.vue";
import InputQuantity from "@/components/global/InputQuantity.vue";
import ToggleState from "@/components/global/ToggleState.vue";
import ContextMenu from "@/components/global/ContextMenu.vue";
import AppButtonCopy from "@/components/global/AppButtonCopy.vue";
import CrudTable from "@/components/global/CrudTable.vue";
import SafeMarkdown from "@/components/global/SafeMarkdown.vue";
import InputColor from "@/components/global/InputColor.vue";
import BaseDivider from "@/components/global/BaseDivider.vue";
import AutoForm from "@/components/global/AutoForm.vue";
import AppButtonUpload from "@/components/global/AppButtonUpload.vue";
import AdvancedOnly from "@/components/global/AdvancedOnly.vue";
import AppButtonCopy from "@/components/global/AppButtonCopy.vue";
import AppButtonUpload from "@/components/global/AppButtonUpload.vue";
import AppLoader from "@/components/global/AppLoader.vue";
import AppToolbar from "@/components/global/AppToolbar.vue";
import AutoForm from "@/components/global/AutoForm.vue";
import BannerExperimental from "@/components/global/BannerExperimental.vue";
import BaseButton from "@/components/global/BaseButton.vue";
import BaseButtonGroup from "@/components/global/BaseButtonGroup.vue";
import BaseCardSectionTitle from "@/components/global/BaseCardSectionTitle.vue";
import BaseDialog from "@/components/global/BaseDialog.vue";
import BaseDivider from "@/components/global/BaseDivider.vue";
import BaseOverflowButton from "@/components/global/BaseOverflowButton.vue";
import BasePageTitle from "@/components/global/BasePageTitle.vue";
import BaseStatCard from "@/components/global/BaseStatCard.vue";
import ButtonLink from "@/components/global/ButtonLink.vue";
import ContextMenu from "@/components/global/ContextMenu.vue";
import CrudTable from "@/components/global/CrudTable.vue";
import DevDumpJson from "@/components/global/DevDumpJson.vue";
import HelpIcon from "@/components/global/HelpIcon.vue";
import InputColor from "@/components/global/InputColor.vue";
import InputLabelType from "@/components/global/InputLabelType.vue";
import InputQuantity from "@/components/global/InputQuantity.vue";
import LanguageDialog from "@/components/global/LanguageDialog.vue";
import MarkdownEditor from "@/components/global/MarkdownEditor.vue";
import RecipeJsonEditor from "@/components/global/RecipeJsonEditor.vue";
import ReportTable from "@/components/global/ReportTable.vue";
import SafeMarkdown from "@/components/global/SafeMarkdown.vue";
import StatsCards from "@/components/global/StatsCards.vue";
import ToggleState from "@/components/global/ToggleState.vue";
import AppFooter from "@/components/layout/AppFooter.vue";
import AppHeader from "@/components/layout/AppHeader.vue";
import AppSidebar from "@/components/layout/AppSidebar.vue";
import TheSnackbar from "@/components/layout/TheSnackbar.vue";
declare module "vue" {
export interface GlobalComponents {
// Global Components
BaseCardSectionTitle: typeof BaseCardSectionTitle;
MarkdownEditor: typeof MarkdownEditor;
AppLoader: typeof AppLoader;
BaseOverflowButton: typeof BaseOverflowButton;
ReportTable: typeof ReportTable;
AppToolbar: typeof AppToolbar;
BaseButtonGroup: typeof BaseButtonGroup;
BaseButton: typeof BaseButton;
BannerExperimental: typeof BannerExperimental;
BaseDialog: typeof BaseDialog;
RecipeJsonEditor: typeof RecipeJsonEditor;
StatsCards: typeof StatsCards;
HelpIcon: typeof HelpIcon;
InputLabelType: typeof InputLabelType;
BaseStatCard: typeof BaseStatCard;
DevDumpJson: typeof DevDumpJson;
LanguageDialog: typeof LanguageDialog;
InputQuantity: typeof InputQuantity;
ToggleState: typeof ToggleState;
ContextMenu: typeof ContextMenu;
AppButtonCopy: typeof AppButtonCopy;
CrudTable: typeof CrudTable;
SafeMarkdown: typeof SafeMarkdown;
InputColor: typeof InputColor;
BaseDivider: typeof BaseDivider;
AutoForm: typeof AutoForm;
AppButtonUpload: typeof AppButtonUpload;
AdvancedOnly: typeof AdvancedOnly;
AppButtonCopy: typeof AppButtonCopy;
AppButtonUpload: typeof AppButtonUpload;
AppLoader: typeof AppLoader;
AppToolbar: typeof AppToolbar;
AutoForm: typeof AutoForm;
BannerExperimental: typeof BannerExperimental;
BaseButton: typeof BaseButton;
BaseButtonGroup: typeof BaseButtonGroup;
BaseCardSectionTitle: typeof BaseCardSectionTitle;
BaseDialog: typeof BaseDialog;
BaseDivider: typeof BaseDivider;
BaseOverflowButton: typeof BaseOverflowButton;
BasePageTitle: typeof BasePageTitle;
BaseStatCard: typeof BaseStatCard;
ButtonLink: typeof ButtonLink;
ContextMenu: typeof ContextMenu;
CrudTable: typeof CrudTable;
DevDumpJson: typeof DevDumpJson;
HelpIcon: typeof HelpIcon;
InputColor: typeof InputColor;
InputLabelType: typeof InputLabelType;
InputQuantity: typeof InputQuantity;
LanguageDialog: typeof LanguageDialog;
MarkdownEditor: typeof MarkdownEditor;
RecipeJsonEditor: typeof RecipeJsonEditor;
ReportTable: typeof ReportTable;
SafeMarkdown: typeof SafeMarkdown;
StatsCards: typeof StatsCards;
ToggleState: typeof ToggleState;
// Layout Components
TheSnackbar: typeof TheSnackbar;
AppFooter: typeof AppFooter;
AppHeader: typeof AppHeader;
AppSidebar: typeof AppSidebar;
AppFooter: typeof AppFooter;
TheSnackbar: typeof TheSnackbar;
}
}

View file

@ -25,7 +25,7 @@ help:
.PHONY: docs
docs: ## 📄 Start Mkdocs Development Server
poetry run python dev/scripts/api_docs_gen.py && \
poetry run python dev/code-generation/gen_docs_api.py && \
cd docs && poetry run python -m mkdocs serve
code-gen: ## 🤖 Run Code-Gen Scripts
@ -129,3 +129,6 @@ docker-dev: ## 🐳 Build and Start Docker Development Stack
docker-prod: ## 🐳 Build and Start Docker Production Stack
docker-compose -f docker-compose.yml -p mealie up --build
generate:
poetry run python dev/code-generation/main.py

View file

@ -45,7 +45,7 @@ from mealie.schema.group.webhook import ReadWebhook
from mealie.schema.labels import MultiPurposeLabelOut
from mealie.schema.meal_plan.new_meal import ReadPlanEntry
from mealie.schema.meal_plan.plan_rules import PlanRulesOut
from mealie.schema.recipe import Recipe, RecipeCommentOut, RecipeTool
from mealie.schema.recipe import Recipe, RecipeCommentOut, RecipeToolOut
from mealie.schema.recipe.recipe_category import CategoryOut, TagOut
from mealie.schema.recipe.recipe_ingredient import IngredientFood, IngredientUnit
from mealie.schema.recipe.recipe_share_token import RecipeShareToken
@ -104,8 +104,8 @@ class AllRepositories:
return RepositoryUnit(self.session, PK_ID, IngredientUnitModel, IngredientUnit)
@cached_property
def tools(self) -> RepositoryGeneric[RecipeTool, Tool]:
return RepositoryGeneric(self.session, PK_ID, Tool, RecipeTool)
def tools(self) -> RepositoryGeneric[RecipeToolOut, Tool]:
return RepositoryGeneric(self.session, PK_ID, Tool, RecipeToolOut)
@cached_property
def comments(self) -> RepositoryGeneric[RecipeCommentOut, RecipeComment]:

View file

@ -3,10 +3,10 @@ from shutil import copyfileobj
from typing import Optional
from zipfile import ZipFile
import orjson
import sqlalchemy
from fastapi import BackgroundTasks, Depends, File, Form, HTTPException, Query, Request, status
from fastapi.datastructures import UploadFile
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from pydantic import UUID4, BaseModel, Field
from slugify import slugify
@ -25,13 +25,7 @@ from mealie.routes._base.mixins import HttpRepo
from mealie.routes._base.routers import MealieCrudRoute, UserAPIRouter
from mealie.schema.cookbook.cookbook import ReadCookBook
from mealie.schema.recipe import Recipe, RecipeImageTypes, ScrapeRecipe
from mealie.schema.recipe.recipe import (
CreateRecipe,
CreateRecipeByUrlBulk,
RecipePagination,
RecipePaginationQuery,
RecipeSummary,
)
from mealie.schema.recipe.recipe import CreateRecipe, CreateRecipeByUrlBulk, RecipePagination, RecipePaginationQuery
from mealie.schema.recipe.recipe_asset import RecipeAsset
from mealie.schema.recipe.recipe_ingredient import RecipeIngredient
from mealie.schema.recipe.recipe_scraper import ScrapeRecipeTest
@ -55,6 +49,18 @@ from mealie.services.scraper.scraper import create_from_url
from mealie.services.scraper.scraper_strategies import ForceTimeoutException, RecipeScraperPackage
class JSONBytes(JSONResponse):
"""
JSONBytes overrides the render method to return the bytes instead of a string.
You can use this when you want to use orjson and bypass the jsonable_encoder
"""
media_type = "application/json"
def render(self, content: bytes) -> bytes:
return content
class BaseRecipeController(BaseCrudController):
@cached_property
def repo(self) -> RepositoryRecipes:
@ -260,21 +266,10 @@ class RecipeController(BaseRecipeController):
{k: v for k, v in query_params.items() if v is not None},
)
new_items = []
for item in pagination_response.items:
# Pydantic/FastAPI can't seem to serialize the ingredient field on their own.
new_item = item.__dict__
if q.load_food:
new_item["recipe_ingredient"] = [x.__dict__ for x in item.recipe_ingredient]
new_items.append(new_item)
pagination_response.items = [RecipeSummary.construct(**x) for x in new_items]
json_compatible_response = jsonable_encoder(pagination_response)
json_compatible_response = orjson.dumps(pagination_response.dict(by_alias=True))
# Response is returned directly, to avoid validation and improve performance
return JSONResponse(content=json_compatible_response)
return JSONBytes(content=json_compatible_response)
@router.get("/{slug}", response_model=Recipe)
def get_one(self, slug: str):

View file

@ -1,3 +1,6 @@
# GENERATED CODE - DO NOT MODIFY BY HAND
from .mealie_model import *
from .types import *
# This file is auto-generated by gen_schema_exports.py
from .mealie_model import MealieModel
__all__ = [
"MealieModel",
]

View file

@ -1,8 +1,50 @@
# GENERATED CODE - DO NOT MODIFY BY HAND
from .about import *
from .backup import *
from .email import *
from .maintenance import *
from .migration import *
from .restore import *
from .settings import *
# This file is auto-generated by gen_schema_exports.py
from .about import AdminAboutInfo, AppInfo, AppStatistics, CheckAppConfig, DockerVolumeText
from .backup import AllBackups, BackupFile, BackupOptions, CreateBackup, ImportJob
from .email import EmailReady, EmailSuccess, EmailTest
from .maintenance import MaintenanceLogs, MaintenanceStorageDetails, MaintenanceSummary
from .migration import ChowdownURL, MigrationFile, MigrationImport, Migrations
from .restore import (
CommentImport,
CustomPageImport,
GroupImport,
ImportBase,
NotificationImport,
RecipeImport,
SettingsImport,
UserImport,
)
from .settings import CustomPageBase, CustomPageOut
__all__ = [
"AllBackups",
"BackupFile",
"BackupOptions",
"CreateBackup",
"ImportJob",
"MaintenanceLogs",
"MaintenanceStorageDetails",
"MaintenanceSummary",
"AdminAboutInfo",
"AppInfo",
"AppStatistics",
"CheckAppConfig",
"DockerVolumeText",
"EmailReady",
"EmailSuccess",
"EmailTest",
"CustomPageBase",
"CustomPageOut",
"ChowdownURL",
"MigrationFile",
"MigrationImport",
"Migrations",
"CommentImport",
"CustomPageImport",
"GroupImport",
"ImportBase",
"NotificationImport",
"RecipeImport",
"SettingsImport",
"UserImport",
]

View file

@ -1,2 +1,6 @@
# GENERATED CODE - DO NOT MODIFY BY HAND
from .analytics import *
# This file is auto-generated by gen_schema_exports.py
from .analytics import MealieAnalytics
__all__ = [
"MealieAnalytics",
]

View file

@ -1,2 +1,11 @@
# GENERATED CODE - DO NOT MODIFY BY HAND
from .cookbook import *
# This file is auto-generated by gen_schema_exports.py
from .cookbook import CookBookPagination, CreateCookBook, ReadCookBook, RecipeCookBook, SaveCookBook, UpdateCookBook
__all__ = [
"CookBookPagination",
"CreateCookBook",
"ReadCookBook",
"RecipeCookBook",
"SaveCookBook",
"UpdateCookBook",
]

View file

@ -1,12 +1,80 @@
# GENERATED CODE - DO NOT MODIFY BY HAND
from .group import *
from .group_events import *
from .group_exports import *
from .group_migration import *
from .group_permissions import *
from .group_preferences import *
from .group_seeder import *
from .group_shopping_list import *
from .group_statistics import *
from .invite_token import *
from .webhook import * # type: ignore
# This file is auto-generated by gen_schema_exports.py
from .group import GroupAdminUpdate
from .group_events import (
GroupEventNotifierCreate,
GroupEventNotifierOptions,
GroupEventNotifierOptionsOut,
GroupEventNotifierOptionsSave,
GroupEventNotifierOut,
GroupEventNotifierPrivate,
GroupEventNotifierSave,
GroupEventNotifierUpdate,
GroupEventPagination,
)
from .group_exports import GroupDataExport
from .group_migration import DataMigrationCreate, SupportedMigrations
from .group_permissions import SetPermissions
from .group_preferences import CreateGroupPreferences, ReadGroupPreferences, UpdateGroupPreferences
from .group_seeder import SeederConfig
from .group_shopping_list import (
ShoppingListCreate,
ShoppingListItemCreate,
ShoppingListItemOut,
ShoppingListItemRecipeRef,
ShoppingListItemRecipeRefOut,
ShoppingListItemUpdate,
ShoppingListOut,
ShoppingListPagination,
ShoppingListRecipeRefOut,
ShoppingListSave,
ShoppingListSummary,
ShoppingListUpdate,
)
from .group_statistics import GroupStatistics, GroupStorage
from .invite_token import CreateInviteToken, EmailInitationResponse, EmailInvitation, ReadInviteToken, SaveInviteToken
from .webhook import CreateWebhook, ReadWebhook, SaveWebhook, WebhookPagination, WebhookType
__all__ = [
"CreateGroupPreferences",
"ReadGroupPreferences",
"UpdateGroupPreferences",
"GroupDataExport",
"CreateWebhook",
"ReadWebhook",
"SaveWebhook",
"WebhookPagination",
"WebhookType",
"GroupEventNotifierCreate",
"GroupEventNotifierOptions",
"GroupEventNotifierOptionsOut",
"GroupEventNotifierOptionsSave",
"GroupEventNotifierOut",
"GroupEventNotifierPrivate",
"GroupEventNotifierSave",
"GroupEventNotifierUpdate",
"GroupEventPagination",
"DataMigrationCreate",
"SupportedMigrations",
"SeederConfig",
"ShoppingListCreate",
"ShoppingListItemCreate",
"ShoppingListItemOut",
"ShoppingListItemRecipeRef",
"ShoppingListItemRecipeRefOut",
"ShoppingListItemUpdate",
"ShoppingListOut",
"ShoppingListPagination",
"ShoppingListRecipeRefOut",
"ShoppingListSave",
"ShoppingListSummary",
"ShoppingListUpdate",
"GroupAdminUpdate",
"SetPermissions",
"GroupStatistics",
"GroupStorage",
"CreateInviteToken",
"EmailInitationResponse",
"EmailInvitation",
"ReadInviteToken",
"SaveInviteToken",
]

View file

@ -1,2 +1,18 @@
# GENERATED CODE - DO NOT MODIFY BY HAND
from .multi_purpose_label import *
# This file is auto-generated by gen_schema_exports.py
from .multi_purpose_label import (
MultiPurposeLabelCreate,
MultiPurposeLabelOut,
MultiPurposeLabelPagination,
MultiPurposeLabelSave,
MultiPurposeLabelSummary,
MultiPurposeLabelUpdate,
)
__all__ = [
"MultiPurposeLabelCreate",
"MultiPurposeLabelOut",
"MultiPurposeLabelPagination",
"MultiPurposeLabelSave",
"MultiPurposeLabelSummary",
"MultiPurposeLabelUpdate",
]

View file

@ -1,5 +1,48 @@
# GENERATED CODE - DO NOT MODIFY BY HAND
from .meal import *
from .new_meal import *
from .plan_rules import *
from .shopping_list import *
# This file is auto-generated by gen_schema_exports.py
from .meal import MealDayIn, MealDayOut, MealIn, MealPlanIn, MealPlanOut
from .new_meal import (
CreatePlanEntry,
CreateRandomEntry,
PlanEntryPagination,
PlanEntryType,
ReadPlanEntry,
SavePlanEntry,
UpdatePlanEntry,
)
from .plan_rules import (
Category,
PlanRulesCreate,
PlanRulesDay,
PlanRulesOut,
PlanRulesPagination,
PlanRulesSave,
PlanRulesType,
Tag,
)
from .shopping_list import ListItem, ShoppingListIn, ShoppingListOut
__all__ = [
"CreatePlanEntry",
"CreateRandomEntry",
"PlanEntryPagination",
"PlanEntryType",
"ReadPlanEntry",
"SavePlanEntry",
"UpdatePlanEntry",
"MealDayIn",
"MealDayOut",
"MealIn",
"MealPlanIn",
"MealPlanOut",
"Category",
"PlanRulesCreate",
"PlanRulesDay",
"PlanRulesOut",
"PlanRulesPagination",
"PlanRulesSave",
"PlanRulesType",
"Tag",
"ListItem",
"ShoppingListIn",
"ShoppingListOut",
]

View file

@ -0,0 +1,7 @@
# This file is auto-generated by gen_schema_exports.py
from .ocr import OcrAssetReq, OcrTsvResponse
__all__ = [
"OcrAssetReq",
"OcrTsvResponse",
]

View file

@ -1,16 +1,151 @@
# GENERATED CODE - DO NOT MODIFY BY HAND
from .recipe import *
from .recipe_asset import *
from .recipe_bulk_actions import *
from .recipe_category import *
from .recipe_comments import * # type: ignore
from .recipe_image_types import *
from .recipe_ingredient import *
from .recipe_notes import *
from .recipe_nutrition import *
from .recipe_scraper import *
from .recipe_settings import *
from .recipe_share_token import * # type: ignore
from .recipe_step import *
from .recipe_tool import * # type: ignore
from .request_helpers import *
# This file is auto-generated by gen_schema_exports.py
from .recipe import (
CreateRecipe,
CreateRecipeBulk,
CreateRecipeByUrlBulk,
Recipe,
RecipeCategory,
RecipeCategoryPagination,
RecipePagination,
RecipePaginationQuery,
RecipeSummary,
RecipeTag,
RecipeTagPagination,
RecipeTool,
RecipeToolPagination,
)
from .recipe_asset import RecipeAsset
from .recipe_bulk_actions import (
AssignCategories,
AssignSettings,
AssignTags,
DeleteRecipes,
ExportBase,
ExportRecipes,
ExportTypes,
)
from .recipe_category import (
CategoryBase,
CategoryIn,
CategoryOut,
CategorySave,
RecipeCategoryResponse,
RecipeTagResponse,
TagBase,
TagIn,
TagOut,
TagSave,
)
from .recipe_comments import (
RecipeCommentCreate,
RecipeCommentOut,
RecipeCommentPagination,
RecipeCommentSave,
RecipeCommentUpdate,
UserBase,
)
from .recipe_image_types import RecipeImageTypes
from .recipe_ingredient import (
CreateIngredientFood,
CreateIngredientUnit,
IngredientConfidence,
IngredientFood,
IngredientFoodPagination,
IngredientRequest,
IngredientsRequest,
IngredientUnit,
IngredientUnitPagination,
MergeFood,
MergeUnit,
ParsedIngredient,
RecipeIngredient,
RegisteredParser,
SaveIngredientFood,
SaveIngredientUnit,
UnitFoodBase,
)
from .recipe_notes import RecipeNote
from .recipe_nutrition import Nutrition
from .recipe_scraper import ScrapeRecipe, ScrapeRecipeTest
from .recipe_settings import RecipeSettings
from .recipe_share_token import RecipeShareToken, RecipeShareTokenCreate, RecipeShareTokenSave, RecipeShareTokenSummary
from .recipe_step import IngredientReferences, RecipeStep
from .recipe_tool import RecipeToolCreate, RecipeToolOut, RecipeToolResponse, RecipeToolSave
from .request_helpers import RecipeSlug, RecipeZipTokenResponse, SlugResponse, UpdateImageResponse
__all__ = [
"RecipeToolCreate",
"RecipeToolOut",
"RecipeToolResponse",
"RecipeToolSave",
"RecipeAsset",
"RecipeSettings",
"RecipeShareToken",
"RecipeShareTokenCreate",
"RecipeShareTokenSave",
"RecipeShareTokenSummary",
"RecipeSlug",
"RecipeZipTokenResponse",
"SlugResponse",
"UpdateImageResponse",
"RecipeNote",
"CategoryBase",
"CategoryIn",
"CategoryOut",
"CategorySave",
"RecipeCategoryResponse",
"RecipeTagResponse",
"TagBase",
"TagIn",
"TagOut",
"TagSave",
"RecipeCommentCreate",
"RecipeCommentOut",
"RecipeCommentPagination",
"RecipeCommentSave",
"RecipeCommentUpdate",
"UserBase",
"AssignCategories",
"AssignSettings",
"AssignTags",
"DeleteRecipes",
"ExportBase",
"ExportRecipes",
"ExportTypes",
"IngredientReferences",
"RecipeStep",
"RecipeImageTypes",
"Nutrition",
"CreateIngredientFood",
"CreateIngredientUnit",
"IngredientConfidence",
"IngredientFood",
"IngredientFoodPagination",
"IngredientRequest",
"IngredientUnit",
"IngredientUnitPagination",
"IngredientsRequest",
"MergeFood",
"MergeUnit",
"ParsedIngredient",
"RecipeIngredient",
"RegisteredParser",
"SaveIngredientFood",
"SaveIngredientUnit",
"UnitFoodBase",
"CreateRecipe",
"CreateRecipeBulk",
"CreateRecipeByUrlBulk",
"Recipe",
"RecipeCategory",
"RecipeCategoryPagination",
"RecipePagination",
"RecipePaginationQuery",
"RecipeSummary",
"RecipeTag",
"RecipeTagPagination",
"RecipeTool",
"RecipeToolPagination",
"ScrapeRecipe",
"ScrapeRecipeTest",
]

View file

@ -14,7 +14,7 @@ class RecipeToolSave(RecipeToolCreate):
group_id: UUID4
class RecipeTool(RecipeToolCreate):
class RecipeToolOut(RecipeToolCreate):
id: UUID4
slug: str
@ -22,13 +22,13 @@ class RecipeTool(RecipeToolCreate):
orm_mode = True
class RecipeToolResponse(RecipeTool):
class RecipeToolResponse(RecipeToolOut):
recipes: typing.List["Recipe"] = []
class Config:
orm_mode = True
from .recipe import Recipe
from .recipe import Recipe # noqa: E402
RecipeToolResponse.update_forward_refs()

View file

@ -1,2 +1,20 @@
# GENERATED CODE - DO NOT MODIFY BY HAND
from .reports import *
# This file is auto-generated by gen_schema_exports.py
from .reports import (
ReportCategory,
ReportCreate,
ReportEntryCreate,
ReportEntryOut,
ReportOut,
ReportSummary,
ReportSummaryStatus,
)
__all__ = [
"ReportCategory",
"ReportCreate",
"ReportEntryCreate",
"ReportEntryOut",
"ReportOut",
"ReportSummary",
"ReportSummaryStatus",
]

View file

@ -1,3 +1,19 @@
# GENERATED CODE - DO NOT MODIFY BY HAND
from .responses import *
from .validation import *
# This file is auto-generated by gen_schema_exports.py
from .pagination import OrderDirection, PaginationBase, PaginationQuery
from .query_filter import LogicalOperator, QueryFilter, QueryFilterComponent, RelationalOperator
from .responses import ErrorResponse, FileTokenResponse, SuccessResponse
from .validation import ValidationResponse
__all__ = [
"ErrorResponse",
"FileTokenResponse",
"SuccessResponse",
"LogicalOperator",
"QueryFilter",
"QueryFilterComponent",
"RelationalOperator",
"OrderDirection",
"PaginationBase",
"PaginationQuery",
"ValidationResponse",
]

View file

@ -1,2 +1,10 @@
# GENERATED CODE - DO NOT MODIFY BY HAND
from .tasks import *
# This file is auto-generated by gen_schema_exports.py
from .tasks import ServerTask, ServerTaskCreate, ServerTaskNames, ServerTaskPagination, ServerTaskStatus
__all__ = [
"ServerTask",
"ServerTaskCreate",
"ServerTaskNames",
"ServerTaskPagination",
"ServerTaskStatus",
]

View file

@ -1,5 +1,56 @@
# GENERATED CODE - DO NOT MODIFY BY HAND
from .auth import *
from .registration import *
from .user import *
from .user_passwords import *
# This file is auto-generated by gen_schema_exports.py
from .auth import Token, TokenData, UnlockResults
from .registration import CreateUserRegistration
from .user import (
ChangePassword,
CreateToken,
DeleteTokenResponse,
GroupBase,
GroupInDB,
GroupPagination,
LongLiveTokenIn,
LongLiveTokenInDB,
LongLiveTokenOut,
PrivateUser,
UpdateGroup,
UserBase,
UserFavorites,
UserIn,
UserOut,
UserPagination,
)
from .user_passwords import (
ForgotPassword,
PrivatePasswordResetToken,
ResetPassword,
SavePasswordResetToken,
ValidateResetToken,
)
__all__ = [
"CreateUserRegistration",
"Token",
"TokenData",
"UnlockResults",
"ChangePassword",
"CreateToken",
"DeleteTokenResponse",
"GroupBase",
"GroupInDB",
"GroupPagination",
"LongLiveTokenIn",
"LongLiveTokenInDB",
"LongLiveTokenOut",
"PrivateUser",
"UpdateGroup",
"UserBase",
"UserFavorites",
"UserIn",
"UserOut",
"UserPagination",
"ForgotPassword",
"PrivatePasswordResetToken",
"ResetPassword",
"SavePasswordResetToken",
"ValidateResetToken",
]

82
poetry.lock generated
View file

@ -103,7 +103,7 @@ python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*"
dev = ["cloudpickle", "coverage[toml] (>=5.0.2)", "furo", "hypothesis", "mypy", "pre-commit", "pympler", "pytest (>=4.3.0)", "pytest-mypy-plugins", "six", "sphinx", "sphinx-notfound-page", "zope.interface"]
docs = ["furo", "sphinx", "sphinx-notfound-page", "zope.interface"]
tests = ["cloudpickle", "coverage[toml] (>=5.0.2)", "hypothesis", "mypy", "pympler", "pytest (>=4.3.0)", "pytest-mypy-plugins", "six", "zope.interface"]
tests_no_zope = ["cloudpickle", "coverage[toml] (>=5.0.2)", "hypothesis", "mypy", "pympler", "pytest (>=4.3.0)", "pytest-mypy-plugins", "six"]
tests-no-zope = ["cloudpickle", "coverage[toml] (>=5.0.2)", "hypothesis", "mypy", "pympler", "pytest (>=4.3.0)", "pytest-mypy-plugins", "six"]
[[package]]
name = "bcrypt"
@ -213,7 +213,7 @@ optional = false
python-versions = ">=3.6.0"
[package.extras]
unicode_backport = ["unicodedata2"]
unicode-backport = ["unicodedata2"]
[[package]]
name = "click"
@ -567,9 +567,9 @@ python-versions = ">=3.6.1,<4.0"
[package.extras]
colors = ["colorama (>=0.4.3,<0.5.0)"]
pipfile_deprecated_finder = ["pipreqs", "requirementslib"]
pipfile-deprecated-finder = ["pipreqs", "requirementslib"]
plugins = ["setuptools"]
requirements_deprecated_finder = ["pip-api", "pipreqs"]
requirements-deprecated-finder = ["pip-api", "pipreqs"]
[[package]]
name = "jinja2"
@ -825,6 +825,14 @@ setuptools = "*"
[package.extras]
requests = ["requests"]
[[package]]
name = "orjson"
version = "3.8.0"
description = "Fast, correct Python JSON library supporting dataclasses, datetimes, and numpy"
category = "main"
optional = false
python-versions = ">=3.7"
[[package]]
name = "packaging"
version = "21.3"
@ -847,7 +855,7 @@ python-versions = "*"
[package.extras]
argon2 = ["argon2-cffi (>=18.2.0)"]
bcrypt = ["bcrypt (>=3.1.0)"]
build_docs = ["cloud-sptheme (>=1.10.1)", "sphinx (>=1.6)", "sphinxcontrib-fulltoc (>=1.2.0)"]
build-docs = ["cloud-sptheme (>=1.10.1)", "sphinx (>=1.6)", "sphinxcontrib-fulltoc (>=1.2.0)"]
totp = ["cryptography"]
[[package]]
@ -1300,7 +1308,7 @@ urllib3 = ">=1.21.1,<1.27"
[package.extras]
socks = ["PySocks (>=1.5.6,!=1.5.7)"]
use_chardet_on_py3 = ["chardet (>=3.0.2,<6)"]
use-chardet-on-py3 = ["chardet (>=3.0.2,<6)"]
[[package]]
name = "requests-oauthlib"
@ -1397,19 +1405,19 @@ aiomysql = ["aiomysql", "greenlet (!=0.4.17)"]
aiosqlite = ["aiosqlite", "greenlet (!=0.4.17)", "typing_extensions (!=3.10.0.1)"]
asyncio = ["greenlet (!=0.4.17)"]
asyncmy = ["asyncmy (>=0.2.3,!=0.2.4)", "greenlet (!=0.4.17)"]
mariadb_connector = ["mariadb (>=1.0.1)"]
mariadb-connector = ["mariadb (>=1.0.1)"]
mssql = ["pyodbc"]
mssql_pymssql = ["pymssql"]
mssql_pyodbc = ["pyodbc"]
mssql-pymssql = ["pymssql"]
mssql-pyodbc = ["pyodbc"]
mypy = ["mypy (>=0.910)", "sqlalchemy2-stubs"]
mysql = ["mysqlclient (>=1.4.0)", "mysqlclient (>=1.4.0,<2)"]
mysql_connector = ["mysql-connector-python"]
mysql-connector = ["mysql-connector-python"]
oracle = ["cx_oracle (>=7)", "cx_oracle (>=7,<8)"]
postgresql = ["psycopg2 (>=2.7)"]
postgresql_asyncpg = ["asyncpg", "greenlet (!=0.4.17)"]
postgresql_pg8000 = ["pg8000 (>=1.16.6,!=1.29.0)"]
postgresql_psycopg2binary = ["psycopg2-binary"]
postgresql_psycopg2cffi = ["psycopg2cffi"]
postgresql-asyncpg = ["asyncpg", "greenlet (!=0.4.17)"]
postgresql-pg8000 = ["pg8000 (>=1.16.6,!=1.29.0)"]
postgresql-psycopg2binary = ["psycopg2-binary"]
postgresql-psycopg2cffi = ["psycopg2cffi"]
pymysql = ["pymysql", "pymysql (<1)"]
sqlcipher = ["sqlcipher3_binary"]
@ -1667,7 +1675,7 @@ pgsql = ["psycopg2-binary"]
[metadata]
lock-version = "1.1"
python-versions = "^3.10"
content-hash = "cdb8c0e668b4ccc85b017a43f705432d989323a1558274e126e96d6434f2fe71"
content-hash = "8801c9070dbffedd12ab0edbc5459668115763d545b661414bd984b568c01175"
[metadata.files]
aiofiles = [
@ -2284,6 +2292,50 @@ openapi-spec-validator = [
{file = "openapi-spec-validator-0.4.0.tar.gz", hash = "sha256:97f258850afc97b048f7c2653855e0f88fa66ac103c2be5077c7960aca2ad49a"},
{file = "openapi_spec_validator-0.4.0-py3-none-any.whl", hash = "sha256:06900ac4d546a1df3642a779da0055be58869c598e3042a2fef067cfd99d04d0"},
]
orjson = [
{file = "orjson-3.8.0-cp310-cp310-macosx_10_7_x86_64.whl", hash = "sha256:9a93850a1bdc300177b111b4b35b35299f046148ba23020f91d6efd7bf6b9d20"},
{file = "orjson-3.8.0-cp310-cp310-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl", hash = "sha256:7536a2a0b41672f824912aeab545c2467a9ff5ca73a066ff04fb81043a0a177a"},
{file = "orjson-3.8.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:66c19399bb3b058e3236af7910b57b19a4fc221459d722ed72a7dc90370ca090"},
{file = "orjson-3.8.0-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8b391d5c2ddc2f302d22909676b306cb6521022c3ee306c861a6935670291b2c"},
{file = "orjson-3.8.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2bdb1042970ca5f544a047d6c235a7eb4acdb69df75441dd1dfcbc406377ab37"},
{file = "orjson-3.8.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:d189e2acb510e374700cb98cf11b54f0179916ee40f8453b836157ae293efa79"},
{file = "orjson-3.8.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:6a23b40c98889e9abac084ce5a1fb251664b41da9f6bdb40a4729e2288ed2ed4"},
{file = "orjson-3.8.0-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:b68a42a31f8429728183c21fb440c21de1b62e5378d0d73f280e2d894ef8942e"},
{file = "orjson-3.8.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:ff13410ddbdda5d4197a4a4c09969cb78c722a67550f0a63c02c07aadc624833"},
{file = "orjson-3.8.0-cp310-none-win_amd64.whl", hash = "sha256:2d81e6e56bbea44be0222fb53f7b255b4e7426290516771592738ca01dbd053b"},
{file = "orjson-3.8.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:e2defd9527651ad39ec20ae03c812adf47ef7662bdd6bc07dabb10888d70dc62"},
{file = "orjson-3.8.0-cp37-cp37m-macosx_10_7_x86_64.whl", hash = "sha256:9e6ac22cec72d5b39035b566e4b86c74b84866f12b5b0b6541506a080fb67d6d"},
{file = "orjson-3.8.0-cp37-cp37m-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl", hash = "sha256:e2f4a5542f50e3d336a18cb224fc757245ca66b1fd0b70b5dd4471b8ff5f2b0e"},
{file = "orjson-3.8.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e1418feeb8b698b9224b1f024555895169d481604d5d884498c1838d7412794c"},
{file = "orjson-3.8.0-cp37-cp37m-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:6e3da2e4bd27c3b796519ca74132c7b9e5348fb6746315e0f6c1592bc5cf1caf"},
{file = "orjson-3.8.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:896a21a07f1998648d9998e881ab2b6b80d5daac4c31188535e9d50460edfcf7"},
{file = "orjson-3.8.0-cp37-cp37m-manylinux_2_28_aarch64.whl", hash = "sha256:4065906ce3ad6195ac4d1bddde862fe811a42d7be237a1ff762666c3a4bb2151"},
{file = "orjson-3.8.0-cp37-cp37m-manylinux_2_28_x86_64.whl", hash = "sha256:5f856279872a4449fc629924e6a083b9821e366cf98b14c63c308269336f7c14"},
{file = "orjson-3.8.0-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:1b1cd25acfa77935bb2e791b75211cec0cfc21227fe29387e553c545c3ff87e1"},
{file = "orjson-3.8.0-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:3e2459d441ab8fd8b161aa305a73d5269b3cda13b5a2a39eba58b4dd3e394f49"},
{file = "orjson-3.8.0-cp37-none-win_amd64.whl", hash = "sha256:d2b5dafbe68237a792143137cba413447f60dd5df428e05d73dcba10c1ea6fcf"},
{file = "orjson-3.8.0-cp38-cp38-macosx_10_7_x86_64.whl", hash = "sha256:5b072ef8520cfe7bd4db4e3c9972d94336763c2253f7c4718a49e8733bada7b8"},
{file = "orjson-3.8.0-cp38-cp38-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl", hash = "sha256:e68c699471ea3e2dd1b35bfd71c6a0a0e4885b64abbe2d98fce1ef11e0afaff3"},
{file = "orjson-3.8.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3c7225e8b08996d1a0c804d3a641a53e796685e8c9a9fd52bd428980032cad9a"},
{file = "orjson-3.8.0-cp38-cp38-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8f687776a03c19f40b982fb5c414221b7f3d19097841571be2223d1569a59877"},
{file = "orjson-3.8.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7990a9caf3b34016ac30be5e6cfc4e7efd76aa85614a1215b0eae4f0c7e3db59"},
{file = "orjson-3.8.0-cp38-cp38-manylinux_2_28_aarch64.whl", hash = "sha256:02d638d43951ba346a80f0abd5942a872cc87db443e073f6f6fc530fee81e19b"},
{file = "orjson-3.8.0-cp38-cp38-manylinux_2_28_x86_64.whl", hash = "sha256:f4b46dbdda2f0bd6480c39db90b21340a19c3b0fcf34bc4c6e465332930ca539"},
{file = "orjson-3.8.0-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:655d7387a1634a9a477c545eea92a1ee902ab28626d701c6de4914e2ed0fecd2"},
{file = "orjson-3.8.0-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:5edb93cdd3eb32977633fa7aaa6a34b8ab54d9c49cdcc6b0d42c247a29091b22"},
{file = "orjson-3.8.0-cp38-none-win_amd64.whl", hash = "sha256:03ed95814140ff09f550b3a42e6821f855d981c94d25b9cc83e8cca431525d70"},
{file = "orjson-3.8.0-cp39-cp39-macosx_10_7_x86_64.whl", hash = "sha256:7b0e72974a5d3b101226899f111368ec2c9824d3e9804af0e5b31567f53ad98a"},
{file = "orjson-3.8.0-cp39-cp39-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl", hash = "sha256:6ea5fe20ef97545e14dd4d0263e4c5c3bc3d2248d39b4b0aed4b84d528dfc0af"},
{file = "orjson-3.8.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6433c956f4a18112342a18281e0bec67fcd8b90be3a5271556c09226e045d805"},
{file = "orjson-3.8.0-cp39-cp39-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:87462791dd57de2e3e53068bf4b7169c125c50960f1bdda08ed30c797cb42a56"},
{file = "orjson-3.8.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:be02f6acee33bb63862eeff80548cd6b8a62e2d60ad2d8dfd5a8824cc43d8887"},
{file = "orjson-3.8.0-cp39-cp39-manylinux_2_28_aarch64.whl", hash = "sha256:a709c2249c1f2955dbf879506fd43fa08c31fdb79add9aeb891e3338b648bf60"},
{file = "orjson-3.8.0-cp39-cp39-manylinux_2_28_x86_64.whl", hash = "sha256:2065b6d280dc58f131ffd93393737961ff68ae7eb6884b68879394074cc03c13"},
{file = "orjson-3.8.0-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:5fd6cac83136e06e538a4d17117eaeabec848c1e86f5742d4811656ad7ee475f"},
{file = "orjson-3.8.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:25b5e48fbb9f0b428a5e44cf740675c9281dd67816149fc33659803399adbbe8"},
{file = "orjson-3.8.0-cp39-none-win_amd64.whl", hash = "sha256:2058653cc12b90e482beacb5c2d52dc3d7606f9e9f5a52c1c10ef49371e76f52"},
{file = "orjson-3.8.0.tar.gz", hash = "sha256:fb42f7cf57d5804a9daa6b624e3490ec9e2631e042415f3aebe9f35a8492ba6c"},
]
packaging = [
{file = "packaging-21.3-py3-none-any.whl", hash = "sha256:ef103e05f519cdc783ae24ea4e2e0f508a9c99b2d4969652eed6a2e1ea5bd522"},
{file = "packaging-21.3.tar.gz", hash = "sha256:dd47c42927d89ab911e606518907cc2d3a1f38bbd026385970643f9c5b8ecfeb"},

View file

@ -39,6 +39,7 @@ pydantic = "^1.9.1"
tzdata = "^2021.5"
pyhumps = "^3.5.3"
pytesseract = "^0.3.9"
orjson = "^3.8.0"
[tool.poetry.dev-dependencies]
pylint = "^2.6.0"
@ -105,3 +106,4 @@ python_version = "3.10"
ignore_missing_imports = true
follow_imports = "skip"
strict_optional = false # TODO: Fix none type checks - temporary stop-gap to implement mypy
plugins = "pydantic.mypy"

View file

@ -2,6 +2,5 @@ from .fixture_admin import *
from .fixture_database import *
from .fixture_multitenant import *
from .fixture_recipe import *
from .fixture_routes import *
from .fixture_shopping_lists import *
from .fixture_users import *

View file

@ -3,23 +3,24 @@ from starlette.testclient import TestClient
from mealie.core.config import get_app_settings
from tests import utils
from tests.utils import api_routes
@fixture(scope="session")
def admin_token(api_client: TestClient, api_routes: utils.AppRoutes):
def admin_token(api_client: TestClient):
settings = get_app_settings()
form_data = {"username": settings.DEFAULT_EMAIL, "password": settings.DEFAULT_PASSWORD}
return utils.login(form_data, api_client, api_routes)
return utils.login(form_data, api_client)
@fixture(scope="session")
def admin_user(api_client: TestClient, api_routes: utils.AppRoutes):
def admin_user(api_client: TestClient):
settings = get_app_settings()
form_data = {"username": settings.DEFAULT_EMAIL, "password": settings.DEFAULT_PASSWORD}
token = utils.login(form_data, api_client, api_routes)
token = utils.login(form_data, api_client)
user_data = api_client.get(api_routes.users_self, headers=token).json()
assert token is not None

View file

@ -1,8 +0,0 @@
from pytest import fixture
from tests import utils
@fixture(scope="session")
def api_routes():
return utils.AppRoutes()

View file

@ -1,14 +1,15 @@
import json
from typing import Generator
from pytest import fixture
from starlette.testclient import TestClient
from tests import utils
from tests.utils import api_routes
from tests.utils.factories import random_string
def build_unique_user(group: str, api_client: TestClient) -> utils.TestUser:
api_routes = utils.AppRoutes()
group = group or random_string(12)
registration = utils.user_registration_factory()
@ -17,7 +18,7 @@ def build_unique_user(group: str, api_client: TestClient) -> utils.TestUser:
form_data = {"username": registration.username, "password": registration.password}
token = utils.login(form_data, api_client, api_routes)
token = utils.login(form_data, api_client)
user_data = api_client.get(api_routes.users_self, headers=token).json()
assert token is not None
@ -26,14 +27,14 @@ def build_unique_user(group: str, api_client: TestClient) -> utils.TestUser:
_group_id=user_data.get("groupId"),
user_id=user_data.get("id"),
email=user_data.get("email"),
password=registration.password,
username=user_data.get("username"),
password=registration.password,
token=token,
)
@fixture(scope="module")
def g2_user(admin_token, api_client: TestClient, api_routes: utils.AppRoutes):
def g2_user(admin_token, api_client: TestClient):
group = random_string(12)
# Create the user
create_data = {
@ -46,7 +47,7 @@ def g2_user(admin_token, api_client: TestClient, api_routes: utils.AppRoutes):
"tokens": [],
}
response = api_client.post(api_routes.groups, json={"name": group}, headers=admin_token)
response = api_client.post(api_routes.admin_groups, json={"name": group}, headers=admin_token)
response = api_client.post(api_routes.users, json=create_data, headers=admin_token)
assert response.status_code == 201
@ -54,7 +55,7 @@ def g2_user(admin_token, api_client: TestClient, api_routes: utils.AppRoutes):
# Log in as this user
form_data = {"username": create_data["email"], "password": "useruser"}
token = utils.login(form_data, api_client, api_routes)
token = utils.login(form_data, api_client)
self_response = api_client.get(api_routes.users_self, headers=token)
@ -68,9 +69,9 @@ def g2_user(admin_token, api_client: TestClient, api_routes: utils.AppRoutes):
user_id=user_id,
_group_id=group_id,
token=token,
password="useruser",
email=create_data["email"],
username=create_data.get("username"),
email=create_data["email"], # type: ignore
username=create_data.get("username"), # type: ignore
password=create_data.get("password"), # type: ignore
)
finally:
# TODO: Delete User after test
@ -78,14 +79,14 @@ def g2_user(admin_token, api_client: TestClient, api_routes: utils.AppRoutes):
@fixture(scope="module")
def unique_user(api_client: TestClient, api_routes: utils.AppRoutes):
def unique_user(api_client: TestClient):
registration = utils.user_registration_factory()
response = api_client.post("/api/users/register", json=registration.dict(by_alias=True))
assert response.status_code == 201
form_data = {"username": registration.username, "password": registration.password}
token = utils.login(form_data, api_client, api_routes)
token = utils.login(form_data, api_client)
user_data = api_client.get(api_routes.users_self, headers=token).json()
assert token is not None
@ -94,9 +95,9 @@ def unique_user(api_client: TestClient, api_routes: utils.AppRoutes):
yield utils.TestUser(
_group_id=user_data.get("groupId"),
user_id=user_data.get("id"),
password=registration.password,
email=user_data.get("email"),
username=user_data.get("username"),
password=registration.password,
token=token,
)
finally:
@ -105,7 +106,7 @@ def unique_user(api_client: TestClient, api_routes: utils.AppRoutes):
@fixture(scope="module")
def user_tuple(admin_token, api_client: TestClient, api_routes: utils.AppRoutes) -> tuple[utils.TestUser]:
def user_tuple(admin_token, api_client: TestClient) -> Generator[list[utils.TestUser], None, None]:
group_name = utils.random_string()
# Create the user
create_data_1 = {
@ -128,16 +129,17 @@ def user_tuple(admin_token, api_client: TestClient, api_routes: utils.AppRoutes)
"tokens": [],
}
api_client.post(api_routes.admin_groups, json={"name": group_name}, headers=admin_token)
users_out = []
for usr in [create_data_1, create_data_2]:
response = api_client.post(api_routes.groups, json={"name": "New Group"}, headers=admin_token)
response = api_client.post(api_routes.users, json=usr, headers=admin_token)
assert response.status_code == 201
# Log in as this user
form_data = {"username": usr["email"], "password": "useruser"}
token = utils.login(form_data, api_client, api_routes)
token = utils.login(form_data, api_client)
response = api_client.get(api_routes.users_self, headers=token)
assert response.status_code == 200
user_data = json.loads(response.text)
@ -147,8 +149,8 @@ def user_tuple(admin_token, api_client: TestClient, api_routes: utils.AppRoutes)
_group_id=user_data.get("groupId"),
user_id=user_data.get("id"),
username=user_data.get("username"),
password="useruser",
email=user_data.get("email"),
password="useruser",
token=token,
)
)
@ -160,7 +162,7 @@ def user_tuple(admin_token, api_client: TestClient, api_routes: utils.AppRoutes)
@fixture(scope="session")
def user_token(admin_token, api_client: TestClient, api_routes: utils.AppRoutes):
def user_token(admin_token, api_client: TestClient):
# Create the user
create_data = {
"fullName": utils.random_string(),
@ -178,4 +180,4 @@ def user_token(admin_token, api_client: TestClient, api_routes: utils.AppRoutes)
# Log in as this user
form_data = {"username": create_data["email"], "password": "useruser"}
return utils.login(form_data, api_client, api_routes)
return utils.login(form_data, api_client)

View file

@ -2,17 +2,12 @@ from fastapi.testclient import TestClient
from mealie.core.config import get_app_settings
from mealie.core.settings.static import APP_VERSION
from tests.utils import api_routes
from tests.utils.fixture_schemas import TestUser
class Routes:
base = "/api/admin/about"
statistics = f"{base}/statistics"
check = f"{base}/check"
def test_admin_about_get_app_info(api_client: TestClient, admin_user: TestUser):
response = api_client.get(Routes.base, headers=admin_user.token)
response = api_client.get(api_routes.admin_about, headers=admin_user.token)
as_dict = response.json()
@ -28,7 +23,7 @@ def test_admin_about_get_app_info(api_client: TestClient, admin_user: TestUser):
def test_admin_about_get_app_statistics(api_client: TestClient, admin_user: TestUser):
response = api_client.get(Routes.statistics, headers=admin_user.token)
response = api_client.get(api_routes.admin_about_statistics, headers=admin_user.token)
as_dict = response.json()
@ -41,7 +36,7 @@ def test_admin_about_get_app_statistics(api_client: TestClient, admin_user: Test
def test_admin_about_check_app_config(api_client: TestClient, admin_user: TestUser):
response = api_client.get(Routes.check, headers=admin_user.token)
response = api_client.get(api_routes.admin_about_check, headers=admin_user.token)
as_dict = response.json()

View file

@ -1,21 +1,18 @@
from fastapi.testclient import TestClient
from mealie.services.server_tasks.background_executory import BackgroundExecutor
from tests.utils import api_routes
from tests.utils.fixture_schemas import TestUser
class Routes:
base = "/api/admin/server-tasks"
def test_admin_server_tasks_test_and_get(api_client: TestClient, admin_user: TestUser):
# Bootstrap Timer
BackgroundExecutor.sleep_time = 1
response = api_client.post(Routes.base, headers=admin_user.token)
response = api_client.post(api_routes.admin_server_tasks, headers=admin_user.token)
assert response.status_code == 201
response = api_client.get(Routes.base, headers=admin_user.token)
response = api_client.get(api_routes.admin_server_tasks, headers=admin_user.token)
as_dict = response.json()["items"]
assert len(as_dict) == 1

View file

@ -1,41 +1,32 @@
from fastapi.testclient import TestClient
from tests.utils import api_routes
from tests.utils.assertion_helpers import assert_ignore_keys
from tests.utils.factories import random_bool, random_string
from tests.utils.fixture_schemas import TestUser
class Routes:
base = "/api/admin/groups"
def item(id: str) -> str:
return f"{Routes.base}/{id}"
def user(id: str) -> str:
return f"api/admin/users/{id}"
def test_home_group_not_deletable(api_client: TestClient, admin_user: TestUser):
response = api_client.delete(Routes.item(admin_user.group_id), headers=admin_user.token)
response = api_client.delete(api_routes.admin_groups_item_id(admin_user.group_id), headers=admin_user.token)
assert response.status_code == 400
def test_admin_group_routes_are_restricted(api_client: TestClient, unique_user: TestUser, admin_user: TestUser):
response = api_client.get(Routes.base, headers=unique_user.token)
response = api_client.get(api_routes.admin_groups, headers=unique_user.token)
assert response.status_code == 403
response = api_client.post(Routes.base, json={}, headers=unique_user.token)
response = api_client.post(api_routes.admin_groups, json={}, headers=unique_user.token)
assert response.status_code == 403
response = api_client.get(Routes.item(admin_user.group_id), headers=unique_user.token)
response = api_client.get(api_routes.admin_groups_item_id(admin_user.group_id), headers=unique_user.token)
assert response.status_code == 403
response = api_client.get(Routes.user(admin_user.group_id), headers=unique_user.token)
response = api_client.get(api_routes.admin_users_item_id(admin_user.group_id), headers=unique_user.token)
assert response.status_code == 403
def test_admin_create_group(api_client: TestClient, admin_user: TestUser):
response = api_client.post(Routes.base, json={"name": random_string()}, headers=admin_user.token)
response = api_client.post(api_routes.admin_groups, json={"name": random_string()}, headers=admin_user.token)
assert response.status_code == 201
@ -55,7 +46,11 @@ def test_admin_update_group(api_client: TestClient, admin_user: TestUser, unique
},
}
response = api_client.put(Routes.item(unique_user.group_id), json=update_payload, headers=admin_user.token)
response = api_client.put(
api_routes.admin_groups_item_id(unique_user.group_id),
json=update_payload,
headers=admin_user.token,
)
assert response.status_code == 200
@ -67,13 +62,13 @@ def test_admin_update_group(api_client: TestClient, admin_user: TestUser, unique
def test_admin_delete_group(api_client: TestClient, admin_user: TestUser, unique_user: TestUser):
# Delete User
response = api_client.delete(Routes.user(unique_user.user_id), headers=admin_user.token)
response = api_client.delete(api_routes.admin_users_item_id(unique_user.user_id), headers=admin_user.token)
assert response.status_code == 200
# Delete Group
response = api_client.delete(Routes.item(unique_user.group_id), headers=admin_user.token)
response = api_client.delete(api_routes.admin_groups_item_id(unique_user.group_id), headers=admin_user.token)
assert response.status_code == 200
# Ensure Group is Deleted
response = api_client.get(Routes.item(unique_user.group_id), headers=admin_user.token)
response = api_client.get(api_routes.admin_groups_item_id(unique_user.group_id), headers=admin_user.token)
assert response.status_code == 404

View file

@ -2,8 +2,7 @@ from fastapi.testclient import TestClient
from mealie.core.config import get_app_settings
from tests import utils
from tests.utils import routes
from tests.utils.app_routes import AppRoutes
from tests.utils import api_routes
from tests.utils.factories import random_email, random_string
from tests.utils.fixture_schemas import TestUser
@ -27,7 +26,7 @@ def generate_create_data() -> dict:
def test_init_superuser(api_client: TestClient, admin_user: TestUser):
settings = get_app_settings()
response = api_client.get(routes.admin.AdminUsers.item(admin_user.user_id), headers=admin_user.token)
response = api_client.get(api_routes.admin_users_item_id(admin_user.user_id), headers=admin_user.token)
assert response.status_code == 200
admin_data = response.json()
@ -39,15 +38,15 @@ def test_init_superuser(api_client: TestClient, admin_user: TestUser):
assert admin_data["email"] == settings.DEFAULT_EMAIL
def test_create_user(api_client: TestClient, api_routes: AppRoutes, admin_token):
def test_create_user(api_client: TestClient, admin_token):
create_data = generate_create_data()
response = api_client.post(routes.admin.AdminUsers.base, json=create_data, headers=admin_token)
response = api_client.post(api_routes.admin_users, json=create_data, headers=admin_token)
assert response.status_code == 201
form_data = {"username": create_data["email"], "password": create_data["password"]}
header = utils.login(form_data=form_data, api_client=api_client, api_routes=api_routes)
header = utils.login(form_data, api_client)
response = api_client.get(routes.user.Users.self, headers=header)
response = api_client.get(api_routes.users_self, headers=header)
assert response.status_code == 200
user_data = response.json()
@ -60,14 +59,14 @@ def test_create_user(api_client: TestClient, api_routes: AppRoutes, admin_token)
def test_create_user_as_non_admin(api_client: TestClient, user_token):
create_data = generate_create_data()
response = api_client.post(routes.admin.AdminUsers.base, json=create_data, headers=user_token)
response = api_client.post(api_routes.admin_users, json=create_data, headers=user_token)
assert response.status_code == 403
def test_update_user(api_client: TestClient, admin_user: TestUser):
# Create a new user
create_data = generate_create_data()
response = api_client.post(routes.admin.AdminUsers.base, json=create_data, headers=admin_user.token)
response = api_client.post(api_routes.admin_users, json=create_data, headers=admin_user.token)
assert response.status_code == 201
update_data = response.json()
@ -76,7 +75,7 @@ def test_update_user(api_client: TestClient, admin_user: TestUser):
update_data["email"] = random_email()
response = api_client.put(
routes.admin.AdminUsers.item(update_data["id"]), headers=admin_user.token, json=update_data
api_routes.admin_users_item_id(update_data["id"]), headers=admin_user.token, json=update_data
)
assert response.status_code == 200
@ -93,21 +92,21 @@ def test_update_other_user_as_not_admin(api_client: TestClient, unique_user: Tes
"admin": True,
}
response = api_client.put(
routes.admin.AdminUsers.item(g2_user.user_id), headers=unique_user.token, json=update_data
api_routes.admin_users_item_id(g2_user.user_id), headers=unique_user.token, json=update_data
)
assert response.status_code == 403
def test_self_demote_admin(api_client: TestClient, admin_user: TestUser):
response = api_client.get(routes.user.Users.self, headers=admin_user.token)
response = api_client.get(api_routes.users_self, headers=admin_user.token)
assert response.status_code == 200
user_data = response.json()
user_data["admin"] = False
response = api_client.put(
routes.admin.AdminUsers.item(admin_user.user_id), headers=admin_user.token, json=user_data
api_routes.admin_users_item_id(admin_user.user_id), headers=admin_user.token, json=user_data
)
assert response.status_code == 403
@ -122,12 +121,12 @@ def test_self_promote_admin(api_client: TestClient, unique_user: TestUser):
"admin": True,
}
response = api_client.put(
routes.admin.AdminUsers.item(unique_user.user_id), headers=unique_user.token, json=update_data
api_routes.admin_users_item_id(unique_user.user_id), headers=unique_user.token, json=update_data
)
assert response.status_code == 403
def test_delete_user(api_client: TestClient, admin_token, unique_user: TestUser):
response = api_client.delete(routes.admin.AdminUsers.item(unique_user.user_id), headers=admin_token)
response = api_client.delete(api_routes.admin_users_item_id(unique_user.user_id), headers=admin_token)
assert response.status_code == 200

View file

@ -1,11 +1,51 @@
import pytest
from fastapi.testclient import TestClient
from pydantic import UUID4
from mealie.schema.static import recipe_keys
from tests.utils import routes
from tests.utils import api_routes
from tests.utils.factories import random_bool, random_string
from tests.utils.fixture_schemas import TestUser
# ==============================================================================
# Custom Route Classes
# We use these to help with parameterization of tests
def v1(route: str) -> str:
return f"/api{route}"
class RoutesBase:
prefix = "/api"
base = f"{prefix}/"
def __init__(self) -> None:
raise NotImplementedError("This class is not meant to be instantiated.")
@classmethod
def item(cls, item_id: int | str | UUID4) -> str:
return f"{cls.base}/{item_id}"
class RoutesOrganizerBase(RoutesBase):
@classmethod
def slug(cls, slug: str) -> str:
return f"{cls.base}/slug/{slug}"
class Tools(RoutesOrganizerBase):
base = v1("/organizers/tools")
class Tags(RoutesOrganizerBase):
base = v1("/organizers/tags")
class Categories(RoutesOrganizerBase):
base = v1("/organizers/categories")
# Test IDs to be used to identify the test cases - order matters!
test_ids = [
"category",
@ -14,14 +54,14 @@ test_ids = [
]
organizer_routes = [
(routes.organizers.Categories),
(routes.organizers.Tags),
(routes.organizers.Tools),
(Categories),
(Tags),
(Tools),
]
@pytest.mark.parametrize("route", organizer_routes, ids=test_ids)
def test_organizers_create_read(api_client: TestClient, unique_user: TestUser, route: routes.RoutesBase):
def test_organizers_create_read(api_client: TestClient, unique_user: TestUser, route: RoutesBase):
data = {"name": random_string(10)}
response = api_client.post(route.base, json=data, headers=unique_user.token)
@ -43,9 +83,9 @@ def test_organizers_create_read(api_client: TestClient, unique_user: TestUser, r
update_data = [
(routes.organizers.Categories, {"name": random_string(10)}),
(routes.organizers.Tags, {"name": random_string(10)}),
(routes.organizers.Tools, {"name": random_string(10), "onHand": random_bool()}),
(Categories, {"name": random_string(10)}),
(Tags, {"name": random_string(10)}),
(Tools, {"name": random_string(10), "onHand": random_bool()}),
]
@ -53,7 +93,7 @@ update_data = [
def test_organizer_update(
api_client: TestClient,
unique_user: TestUser,
route: routes.RoutesBase,
route: RoutesBase,
update_data: dict,
):
data = {"name": random_string(10)}
@ -84,7 +124,7 @@ def test_organizer_update(
def test_organizer_delete(
api_client: TestClient,
unique_user: TestUser,
route: routes.RoutesBase,
route: RoutesBase,
):
data = {"name": random_string(10)}
@ -101,9 +141,9 @@ def test_organizer_delete(
association_data = [
(routes.organizers.Categories, recipe_keys.recipe_category),
(routes.organizers.Tags, "tags"),
(routes.organizers.Tools, "tools"),
(Categories, recipe_keys.recipe_category),
(Tags, "tags"),
(Tools, "tools"),
]
@ -111,7 +151,7 @@ association_data = [
def test_organizer_association(
api_client: TestClient,
unique_user: TestUser,
route: routes.RoutesBase,
route: RoutesBase,
recipe_key: str,
):
data = {"name": random_string(10)}
@ -123,28 +163,28 @@ def test_organizer_association(
# Setup Recipe
recipe_data = {"name": random_string(10)}
response = api_client.post(routes.recipes.Recipe.base, json=recipe_data, headers=unique_user.token)
response = api_client.post(api_routes.recipes, json=recipe_data, headers=unique_user.token)
slug = response.json()
assert response.status_code == 201
# Get Recipe Data
response = api_client.get(routes.recipes.Recipe.item(slug), headers=unique_user.token)
response = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token)
as_json = response.json()
as_json[recipe_key] = [
{"id": item["id"], "group_id": unique_user.group_id, "name": item["name"], "slug": item["slug"]}
]
# Update Recipe
response = api_client.put(routes.recipes.Recipe.item(slug), json=as_json, headers=unique_user.token)
response = api_client.put(api_routes.recipes_slug(slug), json=as_json, headers=unique_user.token)
assert response.status_code == 200
# Get Recipe Data
response = api_client.get(routes.recipes.Recipe.item(slug), headers=unique_user.token)
response = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token)
as_json = response.json()
assert as_json[recipe_key][0]["slug"] == item["slug"]
# Cleanup
response = api_client.delete(routes.recipes.Recipe.item(slug), headers=unique_user.token)
response = api_client.delete(api_routes.recipes_slug(slug), headers=unique_user.token)
assert response.status_code == 200
response = api_client.delete(route.item(item["id"]), headers=unique_user.token)
@ -155,7 +195,7 @@ def test_organizer_association(
def test_organizer_get_by_slug(
api_client: TestClient,
unique_user: TestUser,
route: routes.organizers.RoutesOrganizerBase,
route: RoutesOrganizerBase,
recipe_key: str,
):
# Create Organizer
@ -170,20 +210,20 @@ def test_organizer_get_by_slug(
for _ in range(10):
# Setup Recipe
recipe_data = {"name": random_string(10)}
response = api_client.post(routes.recipes.Recipe.base, json=recipe_data, headers=unique_user.token)
response = api_client.post(api_routes.recipes, json=recipe_data, headers=unique_user.token)
assert response.status_code == 201
slug = response.json()
recipe_slugs.append(slug)
# Associate 10 Recipes to Organizer
for slug in recipe_slugs:
response = api_client.get(routes.recipes.Recipe.item(slug), headers=unique_user.token)
response = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token)
as_json = response.json()
as_json[recipe_key] = [
{"id": item["id"], "group_id": unique_user.group_id, "name": item["name"], "slug": item["slug"]}
]
response = api_client.put(routes.recipes.Recipe.item(slug), json=as_json, headers=unique_user.token)
response = api_client.put(api_routes.recipes_slug(slug), json=as_json, headers=unique_user.token)
assert response.status_code == 200
# Get Organizer by Slug

View file

@ -2,21 +2,13 @@ from dataclasses import dataclass
import pytest
from fastapi.testclient import TestClient
from pydantic import UUID4
from mealie.repos.repository_factory import AllRepositories
from mealie.schema.recipe.recipe import Recipe
from tests.utils import api_routes
from tests.utils.fixture_schemas import TestUser
class Routes:
base = "/api/explore/recipes"
@staticmethod
def recipe(groud_id: str | UUID4, recipe_slug: str | UUID4) -> str:
return f"{Routes.base}/{groud_id}/{recipe_slug}"
@dataclass(slots=True)
class PublicRecipeTestCase:
private_group: bool
@ -50,7 +42,12 @@ def test_public_recipe_success(
database.recipes.update(random_recipe.slug, random_recipe)
# Try to access recipe
response = api_client.get(Routes.recipe(random_recipe.group_id, random_recipe.slug))
response = api_client.get(
api_routes.explore_recipes_group_id_recipe_slug(
random_recipe.group_id,
random_recipe.slug,
)
)
assert response.status_code == test_case.status_code
if test_case.error:

View file

@ -6,16 +6,10 @@ from fastapi.testclient import TestClient
from mealie.schema.group.group_migration import SupportedMigrations
from tests import data as test_data
from tests.utils import api_routes
from tests.utils.fixture_schemas import TestUser
class Routes:
base = "/api/groups/migrations"
def report(item_id: str) -> str:
return f"/api/groups/reports/{item_id}"
@dataclass
class MigrationTestData:
typ: SupportedMigrations
@ -47,14 +41,16 @@ def test_recipe_migration(api_client: TestClient, unique_user: TestUser, mig: Mi
"archive": mig.archive.read_bytes(),
}
response = api_client.post(Routes.base, data=payload, files=file_payload, headers=unique_user.token)
response = api_client.post(
api_routes.groups_migrations, data=payload, files=file_payload, headers=unique_user.token
)
assert response.status_code == 200
report_id = response.json()["id"]
# Validate Results
response = api_client.get(Routes.report(report_id), headers=unique_user.token)
response = api_client.get(api_routes.groups_reports_item_id(report_id), headers=unique_user.token)
assert response.status_code == 200

View file

@ -5,30 +5,10 @@ from fastapi.testclient import TestClient
from mealie.repos.repository_factory import AllRepositories
from mealie.schema.recipe.recipe import Recipe
from tests.utils import random_string
from tests.utils import api_routes, random_string
from tests.utils.fixture_schemas import TestUser
class Routes:
base = "/api/validators"
@staticmethod
def username(username: str):
return f"{Routes.base}/user/name?name={username}"
@staticmethod
def email(email: str):
return f"{Routes.base}/user/email?email={email}"
@staticmethod
def group(group_name: str):
return f"{Routes.base}/group?name={group_name}"
@staticmethod
def recipe(group_id, name) -> str:
return f"{Routes.base}/recipe?group_id={group_id}&name={name}"
@dataclass(slots=True)
class SimpleCase:
value: str
@ -42,7 +22,7 @@ def test_validators_username(api_client: TestClient, unique_user: TestUser):
]
for user in users:
response = api_client.get(Routes.username(user.value))
response = api_client.get(api_routes.validators_user_name + "?name=" + user.value)
assert response.status_code == 200
response_data = response.json()
assert response_data["valid"] == user.is_valid
@ -55,7 +35,7 @@ def test_validators_email(api_client: TestClient, unique_user: TestUser):
]
for user in emails:
response = api_client.get(Routes.email(user.value))
response = api_client.get(api_routes.validators_user_email + "?email=" + user.value)
assert response.status_code == 200
response_data = response.json()
assert response_data["valid"] == user.is_valid
@ -70,7 +50,7 @@ def test_validators_group_name(api_client: TestClient, unique_user: TestUser, da
]
for user in groups:
response = api_client.get(Routes.group(user.value))
response = api_client.get(api_routes.validators_group + "?name=" + user.value)
assert response.status_code == 200
response_data = response.json()
assert response_data["valid"] == user.is_valid
@ -91,7 +71,7 @@ def test_validators_recipe(api_client: TestClient, random_recipe: Recipe):
]
for recipe in recipes:
response = api_client.get(Routes.recipe(recipe.group, recipe.name))
response = api_client.get(api_routes.validators_recipe + f"?group_id={recipe.group}&name={recipe.name}")
assert response.status_code == 200
response_data = response.json()
assert response_data["valid"] == recipe.is_valid

View file

@ -9,18 +9,12 @@ from pydantic import UUID4
from mealie.repos.repository_factory import AllRepositories
from mealie.schema.cookbook.cookbook import ReadCookBook, SaveCookBook
from tests import utils
from tests.utils import api_routes
from tests.utils.factories import random_string
from tests.utils.fixture_schemas import TestUser
class Routes:
base = "/api/groups/cookbooks"
def item(item_id: int) -> str:
return f"{Routes.base}/{item_id}"
def get_page_data(group_id: UUID):
def get_page_data(group_id: UUID | str):
name_and_slug = random_string(10)
return {
"name": name_and_slug,
@ -60,13 +54,13 @@ def cookbooks(database: AllRepositories, unique_user: TestUser) -> list[TestCook
def test_create_cookbook(api_client: TestClient, unique_user: TestUser):
page_data = get_page_data(unique_user.group_id)
response = api_client.post(Routes.base, json=page_data, headers=unique_user.token)
response = api_client.post(api_routes.groups_cookbooks, json=page_data, headers=unique_user.token)
assert response.status_code == 201
def test_read_cookbook(api_client: TestClient, unique_user: TestUser, cookbooks: list[TestCookbook]):
sample = random.choice(cookbooks)
response = api_client.get(Routes.item(sample.id), headers=unique_user.token)
response = api_client.get(api_routes.groups_cookbooks_item_id(sample.id), headers=unique_user.token)
assert response.status_code == 200
page_data = response.json()
@ -84,10 +78,12 @@ def test_update_cookbook(api_client: TestClient, unique_user: TestUser, cookbook
update_data["name"] = random_string(10)
response = api_client.put(Routes.item(cookbook.id), json=update_data, headers=unique_user.token)
response = api_client.put(
api_routes.groups_cookbooks_item_id(cookbook.id), json=update_data, headers=unique_user.token
)
assert response.status_code == 200
response = api_client.get(Routes.item(cookbook.id), headers=unique_user.token)
response = api_client.get(api_routes.groups_cookbooks_item_id(cookbook.id), headers=unique_user.token)
assert response.status_code == 200
page_data = response.json()
@ -103,10 +99,10 @@ def test_update_cookbooks_many(api_client: TestClient, unique_user: TestUser, co
page["position"] = x
page["group_id"] = str(unique_user.group_id)
response = api_client.put(Routes.base, json=utils.jsonify(reverse_order), headers=unique_user.token)
response = api_client.put(api_routes.groups_cookbooks, json=utils.jsonify(reverse_order), headers=unique_user.token)
assert response.status_code == 200
response = api_client.get(Routes.base, headers=unique_user.token)
response = api_client.get(api_routes.groups_cookbooks, headers=unique_user.token)
assert response.status_code == 200
known_ids = [x.id for x in cookbooks]
@ -119,9 +115,9 @@ def test_update_cookbooks_many(api_client: TestClient, unique_user: TestUser, co
def test_delete_cookbook(api_client: TestClient, unique_user: TestUser, cookbooks: list[TestCookbook]):
sample = random.choice(cookbooks)
response = api_client.delete(Routes.item(sample.id), headers=unique_user.token)
response = api_client.delete(api_routes.groups_cookbooks_item_id(sample.id), headers=unique_user.token)
assert response.status_code == 200
response = api_client.get(Routes.item(sample.slug), headers=unique_user.token)
response = api_client.get(api_routes.groups_cookbooks_item_id(sample.slug), headers=unique_user.token)
assert response.status_code == 404

View file

@ -1,25 +1,15 @@
import pytest
from fastapi.testclient import TestClient
from tests.utils import api_routes
from tests.utils.factories import user_registration_factory
from tests.utils.fixture_schemas import TestUser
class Routes:
base = "/api/groups/invitations"
auth_token = "/api/auth/token"
self = "/api/users/self"
register = "/api/users/register"
def item(item_id: int) -> str:
return f"{Routes.base}/{item_id}"
@pytest.fixture(scope="function")
def invite(api_client: TestClient, unique_user: TestUser) -> None:
# Test Creation
r = api_client.post(Routes.base, json={"uses": 2}, headers=unique_user.token)
r = api_client.post(api_routes.groups_invitations, json={"uses": 2}, headers=unique_user.token)
assert r.status_code == 201
invitation = r.json()
return invitation["token"]
@ -27,7 +17,7 @@ def invite(api_client: TestClient, unique_user: TestUser) -> None:
def test_get_all_invitation(api_client: TestClient, unique_user: TestUser, invite: str) -> None:
# Get All Invites
r = api_client.get(Routes.base, headers=unique_user.token)
r = api_client.get(api_routes.groups_invitations, headers=unique_user.token)
assert r.status_code == 200
@ -46,7 +36,7 @@ def register_user(api_client, invite):
registration.group = ""
registration.group_token = invite
response = api_client.post(Routes.register, json=registration.dict(by_alias=True))
response = api_client.post(api_routes.users_register, json=registration.dict(by_alias=True))
return registration, response
@ -57,13 +47,13 @@ def test_group_invitation_link(api_client: TestClient, unique_user: TestUser, in
# Login as new User
form_data = {"username": registration.email, "password": registration.password}
r = api_client.post(Routes.auth_token, form_data)
r = api_client.post(api_routes.auth_token, form_data)
assert r.status_code == 200
token = r.json().get("access_token")
assert token is not None
# Check user Group is Same
r = api_client.get(Routes.self, headers={"Authorization": f"Bearer {token}"})
r = api_client.get(api_routes.users_self, headers={"Authorization": f"Bearer {token}"})
assert r.status_code == 200
assert r.json()["groupId"] == unique_user.group_id

View file

@ -3,26 +3,13 @@ from datetime import date, timedelta
from fastapi.testclient import TestClient
from mealie.schema.meal_plan.new_meal import CreatePlanEntry
from tests.utils import api_routes
from tests.utils.factories import random_string
from tests.utils.fixture_schemas import TestUser
class Routes:
base = "/api/groups/mealplans"
recipe = "/api/recipes"
today = "/api/groups/mealplans/today"
@staticmethod
def all_slice(page: int, perPage: int, start_date: str, end_date: str):
return f"{Routes.base}?page={page}&perPage={perPage}&start_date={start_date}&end_date={end_date}"
@staticmethod
def item(item_id: int) -> str:
return f"{Routes.base}/{item_id}"
@staticmethod
def recipe_slug(recipe_name: str) -> str:
return f"{Routes.recipe}/{recipe_name}"
def route_all_slice(page: int, perPage: int, start_date: str, end_date: str):
return f"{api_routes.groups_mealplans}?page={page}&perPage={perPage}&start_date={start_date}&end_date={end_date}"
def test_create_mealplan_no_recipe(api_client: TestClient, unique_user: TestUser):
@ -31,7 +18,7 @@ def test_create_mealplan_no_recipe(api_client: TestClient, unique_user: TestUser
new_plan = CreatePlanEntry(date=date.today(), entry_type="breakfast", title=title, text=text).dict()
new_plan["date"] = date.today().strftime("%Y-%m-%d")
response = api_client.post(Routes.base, json=new_plan, headers=unique_user.token)
response = api_client.post(api_routes.groups_mealplans, json=new_plan, headers=unique_user.token)
assert response.status_code == 201
@ -42,10 +29,10 @@ def test_create_mealplan_no_recipe(api_client: TestClient, unique_user: TestUser
def test_create_mealplan_with_recipe(api_client: TestClient, unique_user: TestUser):
recipe_name = random_string(length=25)
response = api_client.post(Routes.recipe, json={"name": recipe_name}, headers=unique_user.token)
response = api_client.post(api_routes.recipes, json={"name": recipe_name}, headers=unique_user.token)
assert response.status_code == 201
response = api_client.get(Routes.recipe_slug(recipe_name), headers=unique_user.token)
response = api_client.get(api_routes.recipes_slug(recipe_name), headers=unique_user.token)
recipe = response.json()
recipe_id = recipe["id"]
@ -53,7 +40,7 @@ def test_create_mealplan_with_recipe(api_client: TestClient, unique_user: TestUs
new_plan["date"] = date.today().strftime("%Y-%m-%d")
new_plan["recipeId"] = str(recipe_id)
response = api_client.post(Routes.base, json=new_plan, headers=unique_user.token)
response = api_client.post(api_routes.groups_mealplans, json=new_plan, headers=unique_user.token)
response_json = response.json()
assert response.status_code == 201
@ -70,7 +57,7 @@ def test_crud_mealplan(api_client: TestClient, unique_user: TestUser):
# Create
new_plan["date"] = date.today().strftime("%Y-%m-%d")
response = api_client.post(Routes.base, json=new_plan, headers=unique_user.token)
response = api_client.post(api_routes.groups_mealplans, json=new_plan, headers=unique_user.token)
response_json = response.json()
assert response.status_code == 201
plan_id = response_json["id"]
@ -79,7 +66,9 @@ def test_crud_mealplan(api_client: TestClient, unique_user: TestUser):
response_json["title"] = random_string()
response_json["text"] = random_string()
response = api_client.put(Routes.item(plan_id), headers=unique_user.token, json=response_json)
response = api_client.put(
api_routes.groups_mealplans_item_id(plan_id), headers=unique_user.token, json=response_json
)
assert response.status_code == 200
@ -87,11 +76,11 @@ def test_crud_mealplan(api_client: TestClient, unique_user: TestUser):
assert response.json()["text"] == response_json["text"]
# Delete
response = api_client.delete(Routes.item(plan_id), headers=unique_user.token)
response = api_client.delete(api_routes.groups_mealplans_item_id(plan_id), headers=unique_user.token)
assert response.status_code == 200
response = api_client.get(Routes.item(plan_id), headers=unique_user.token)
response = api_client.get(api_routes.groups_mealplans_item_id(plan_id), headers=unique_user.token)
assert response.status_code == 404
@ -106,10 +95,10 @@ def test_get_all_mealplans(api_client: TestClient, unique_user: TestUser):
).dict()
new_plan["date"] = date.today().strftime("%Y-%m-%d")
response = api_client.post(Routes.base, json=new_plan, headers=unique_user.token)
response = api_client.post(api_routes.groups_mealplans, json=new_plan, headers=unique_user.token)
assert response.status_code == 201
response = api_client.get(Routes.base, headers=unique_user.token, params={"page": 1, "perPage": -1})
response = api_client.get(api_routes.groups_mealplans, headers=unique_user.token, params={"page": 1, "perPage": -1})
assert response.status_code == 200
assert len(response.json()["items"]) >= 3
@ -128,7 +117,7 @@ def test_get_slice_mealplans(api_client: TestClient, unique_user: TestUser):
# Add the meal plans to the database
for meal_plan in meal_plans:
meal_plan["date"] = meal_plan["date"].strftime("%Y-%m-%d")
response = api_client.post(Routes.base, json=meal_plan, headers=unique_user.token)
response = api_client.post(api_routes.groups_mealplans, json=meal_plan, headers=unique_user.token)
assert response.status_code == 201
# Get meal slice of meal plans from database
@ -138,7 +127,7 @@ def test_get_slice_mealplans(api_client: TestClient, unique_user: TestUser):
start_date = date_range[0].strftime("%Y-%m-%d")
end_date = date_range[-1].strftime("%Y-%m-%d")
response = api_client.get(Routes.all_slice(1, -1, start_date, end_date), headers=unique_user.token)
response = api_client.get(route_all_slice(1, -1, start_date, end_date), headers=unique_user.token)
assert response.status_code == 200
response_json = response.json()
@ -157,11 +146,11 @@ def test_get_mealplan_today(api_client: TestClient, unique_user: TestUser):
# Add the meal plans to the database
for meal_plan in test_meal_plans:
meal_plan["date"] = meal_plan["date"].strftime("%Y-%m-%d")
response = api_client.post(Routes.base, json=meal_plan, headers=unique_user.token)
response = api_client.post(api_routes.groups_mealplans, json=meal_plan, headers=unique_user.token)
assert response.status_code == 201
# Get meal plan for today
response = api_client.get(Routes.today, headers=unique_user.token)
response = api_client.get(api_routes.groups_mealplans_today, headers=unique_user.token)
assert response.status_code == 200

View file

@ -2,24 +2,16 @@ from uuid import UUID
import pytest
from fastapi.testclient import TestClient
from pydantic import UUID4
from mealie.repos.all_repositories import AllRepositories
from mealie.schema.meal_plan.plan_rules import PlanRulesOut, PlanRulesSave
from mealie.schema.recipe.recipe import RecipeCategory
from mealie.schema.recipe.recipe_category import CategorySave
from tests import utils
from tests.utils import api_routes
from tests.utils.fixture_schemas import TestUser
class Routes:
base = "/api/groups/mealplans/rules"
@staticmethod
def item(item_id: UUID4) -> str:
return f"{Routes.base}/{item_id}"
@pytest.fixture(scope="function")
def category(
database: AllRepositories,
@ -65,7 +57,9 @@ def test_group_mealplan_rules_create(
"categories": [category.dict()],
}
response = api_client.post(Routes.base, json=utils.jsonify(payload), headers=unique_user.token)
response = api_client.post(
api_routes.groups_mealplans_rules, json=utils.jsonify(payload), headers=unique_user.token
)
assert response.status_code == 201
# Validate the response data
@ -90,7 +84,7 @@ def test_group_mealplan_rules_create(
def test_group_mealplan_rules_read(api_client: TestClient, unique_user: TestUser, plan_rule: PlanRulesOut):
response = api_client.get(Routes.item(plan_rule.id), headers=unique_user.token)
response = api_client.get(api_routes.groups_mealplans_rules_item_id(plan_rule.id), headers=unique_user.token)
assert response.status_code == 200
# Validate the response data
@ -109,7 +103,9 @@ def test_group_mealplan_rules_update(api_client: TestClient, unique_user: TestUs
"entryType": "lunch",
}
response = api_client.put(Routes.item(plan_rule.id), json=payload, headers=unique_user.token)
response = api_client.put(
api_routes.groups_mealplans_rules_item_id(plan_rule.id), json=payload, headers=unique_user.token
)
assert response.status_code == 200
# Validate the response data
@ -124,7 +120,7 @@ def test_group_mealplan_rules_update(api_client: TestClient, unique_user: TestUs
def test_group_mealplan_rules_delete(
api_client: TestClient, unique_user: TestUser, plan_rule: PlanRulesOut, database: AllRepositories
):
response = api_client.delete(Routes.item(plan_rule.id), headers=unique_user.token)
response = api_client.delete(api_routes.groups_mealplans_rules_item_id(plan_rule.id), headers=unique_user.token)
assert response.status_code == 200
# Validate no entry in database

View file

@ -10,19 +10,12 @@ from mealie.services.event_bus_service.event_types import (
EventOperation,
EventTypes,
)
from tests.utils import api_routes
from tests.utils.assertion_helpers import assert_ignore_keys
from tests.utils.factories import random_bool, random_email, random_int, random_string
from tests.utils.fixture_schemas import TestUser
class Routes:
base = "/api/groups/events/notifications"
@staticmethod
def item(item_id: int) -> str:
return f"{Routes.base}/{item_id}"
def preferences_generator():
return GroupEventNotifierOptions(
recipe_created=random_bool(),
@ -66,7 +59,7 @@ def event_generator():
def test_create_notification(api_client: TestClient, unique_user: TestUser):
payload = notifier_generator()
response = api_client.post(Routes.base, json=payload, headers=unique_user.token)
response = api_client.post(api_routes.groups_events_notifications, json=payload, headers=unique_user.token)
assert response.status_code == 201
payload_as_dict = response.json()
@ -78,12 +71,14 @@ def test_create_notification(api_client: TestClient, unique_user: TestUser):
assert "apprise_url" not in payload_as_dict
# Cleanup
response = api_client.delete(Routes.item(payload_as_dict["id"]), headers=unique_user.token)
response = api_client.delete(
api_routes.groups_events_notifications_item_id(payload_as_dict["id"]), headers=unique_user.token
)
def test_ensure_apprise_url_is_secret(api_client: TestClient, unique_user: TestUser):
payload = notifier_generator()
response = api_client.post(Routes.base, json=payload, headers=unique_user.token)
response = api_client.post(api_routes.groups_events_notifications, json=payload, headers=unique_user.token)
assert response.status_code == 201
payload_as_dict = response.json()
@ -94,7 +89,7 @@ def test_ensure_apprise_url_is_secret(api_client: TestClient, unique_user: TestU
def test_update_apprise_notification(api_client: TestClient, unique_user: TestUser):
payload = notifier_generator()
response = api_client.post(Routes.base, json=payload, headers=unique_user.token)
response = api_client.post(api_routes.groups_events_notifications, json=payload, headers=unique_user.token)
assert response.status_code == 201
update_payload = response.json()
@ -104,12 +99,18 @@ def test_update_apprise_notification(api_client: TestClient, unique_user: TestUs
update_payload["enabled"] = random_bool()
update_payload["options"] = preferences_generator()
response = api_client.put(Routes.item(update_payload["id"]), json=update_payload, headers=unique_user.token)
response = api_client.put(
api_routes.groups_events_notifications_item_id(update_payload["id"]),
json=update_payload,
headers=unique_user.token,
)
assert response.status_code == 200
# Re-Get The Item
response = api_client.get(Routes.item(update_payload["id"]), headers=unique_user.token)
response = api_client.get(
api_routes.groups_events_notifications_item_id(update_payload["id"]), headers=unique_user.token
)
assert response.status_code == 200
# Validate Updated Values
@ -120,20 +121,26 @@ def test_update_apprise_notification(api_client: TestClient, unique_user: TestUs
assert_ignore_keys(updated_payload["options"], update_payload["options"])
# Cleanup
response = api_client.delete(Routes.item(update_payload["id"]), headers=unique_user.token)
response = api_client.delete(
api_routes.groups_events_notifications_item_id(update_payload["id"]), headers=unique_user.token
)
def test_delete_apprise_notification(api_client: TestClient, unique_user: TestUser):
payload = notifier_generator()
response = api_client.post(Routes.base, json=payload, headers=unique_user.token)
response = api_client.post(api_routes.groups_events_notifications, json=payload, headers=unique_user.token)
assert response.status_code == 201
payload_as_dict = response.json()
response = api_client.delete(Routes.item(payload_as_dict["id"]), headers=unique_user.token)
response = api_client.delete(
api_routes.groups_events_notifications_item_id(payload_as_dict["id"]), headers=unique_user.token
)
assert response.status_code == 204
response = api_client.get(Routes.item(payload_as_dict["id"]), headers=unique_user.token)
response = api_client.get(
api_routes.groups_events_notifications_item_id(payload_as_dict["id"]), headers=unique_user.token
)
assert response.status_code == 404

View file

@ -3,16 +3,11 @@ from uuid import uuid4
from fastapi.testclient import TestClient
from mealie.repos.repository_factory import AllRepositories
from tests.utils import api_routes
from tests.utils.factories import random_bool
from tests.utils.fixture_schemas import TestUser
class Routes:
self = "/api/groups/self"
members = "/api/groups/members"
permissions = "/api/groups/permissions"
def get_permissions_payload(user_id: str, can_manage=None) -> dict:
return {
"user_id": user_id,
@ -25,7 +20,7 @@ def get_permissions_payload(user_id: str, can_manage=None) -> dict:
def test_get_group_members(api_client: TestClient, user_tuple: list[TestUser]):
usr_1, usr_2 = user_tuple
response = api_client.get(Routes.members, headers=usr_1.token)
response = api_client.get(api_routes.groups_members, headers=usr_1.token)
assert response.status_code == 200
members = response.json()
@ -48,7 +43,7 @@ def test_set_memeber_permissions(api_client: TestClient, user_tuple: list[TestUs
payload = get_permissions_payload(str(usr_2.user_id))
# Test
response = api_client.put(Routes.permissions, json=payload, headers=usr_1.token)
response = api_client.put(api_routes.groups_permissions, json=payload, headers=usr_1.token)
assert response.status_code == 200
@ -67,7 +62,7 @@ def test_set_memeber_permissions_unauthorized(api_client: TestClient, unique_use
}
# Test
response = api_client.put(Routes.permissions, json=payload, headers=unique_user.token)
response = api_client.put(api_routes.groups_permissions, json=payload, headers=unique_user.token)
assert response.status_code == 403
@ -82,7 +77,7 @@ def test_set_memeber_permissions_other_group(
database.users.update(user.id, user)
payload = get_permissions_payload(str(g2_user.user_id))
response = api_client.put(Routes.permissions, json=payload, headers=unique_user.token)
response = api_client.put(api_routes.groups_permissions, json=payload, headers=unique_user.token)
assert response.status_code == 403
@ -96,5 +91,5 @@ def test_set_memeber_permissions_no_user(
database.users.update(user.id, user)
payload = get_permissions_payload(str(uuid4()))
response = api_client.put(Routes.permissions, json=payload, headers=unique_user.token)
response = api_client.put(api_routes.groups_permissions, json=payload, headers=unique_user.token)
assert response.status_code == 404

View file

@ -1,17 +1,13 @@
from fastapi.testclient import TestClient
from mealie.schema.group.group_preferences import UpdateGroupPreferences
from tests.utils import api_routes
from tests.utils.assertion_helpers import assert_ignore_keys
from tests.utils.fixture_schemas import TestUser
class Routes:
base = "/api/groups/self"
preferences = "/api/groups/preferences"
def test_get_preferences(api_client: TestClient, unique_user: TestUser) -> None:
response = api_client.get(Routes.preferences, headers=unique_user.token)
response = api_client.get(api_routes.groups_preferences, headers=unique_user.token)
assert response.status_code == 200
preferences = response.json()
@ -21,7 +17,7 @@ def test_get_preferences(api_client: TestClient, unique_user: TestUser) -> None:
def test_preferences_in_group(api_client: TestClient, unique_user: TestUser) -> None:
response = api_client.get(Routes.base, headers=unique_user.token)
response = api_client.get(api_routes.groups_self, headers=unique_user.token)
assert response.status_code == 200
@ -37,7 +33,7 @@ def test_preferences_in_group(api_client: TestClient, unique_user: TestUser) ->
def test_update_preferences(api_client: TestClient, unique_user: TestUser) -> None:
new_data = UpdateGroupPreferences(recipe_public=False, recipe_show_nutrition=True)
response = api_client.put(Routes.preferences, json=new_data.dict(), headers=unique_user.token)
response = api_client.put(api_routes.groups_preferences, json=new_data.dict(), headers=unique_user.token)
assert response.status_code == 200

View file

@ -1,24 +1,19 @@
from fastapi.testclient import TestClient
from tests.utils import api_routes
from tests.utils.factories import user_registration_factory
class Routes:
self = "/api/users/self"
base = "/api/users/register"
auth_token = "/api/auth/token"
def test_user_registration_new_group(api_client: TestClient):
registration = user_registration_factory()
response = api_client.post(Routes.base, json=registration.dict(by_alias=True))
response = api_client.post(api_routes.users_register, json=registration.dict(by_alias=True))
assert response.status_code == 201
# Login
form_data = {"username": registration.email, "password": registration.password}
response = api_client.post(Routes.auth_token, form_data)
response = api_client.post(api_routes.auth_token, form_data)
assert response.status_code == 200
token = response.json().get("access_token")
@ -28,13 +23,13 @@ def test_user_registration_new_group(api_client: TestClient):
def test_new_user_group_permissions(api_client: TestClient):
registration = user_registration_factory()
response = api_client.post(Routes.base, json=registration.dict(by_alias=True))
response = api_client.post(api_routes.users_register, json=registration.dict(by_alias=True))
assert response.status_code == 201
# Login
form_data = {"username": registration.email, "password": registration.password}
response = api_client.post(Routes.auth_token, form_data)
response = api_client.post(api_routes.auth_token, form_data)
assert response.status_code == 200
token = response.json().get("access_token")
@ -43,7 +38,7 @@ def test_new_user_group_permissions(api_client: TestClient):
# Get User
headers = {"Authorization": f"Bearer {token}"}
response = api_client.get(Routes.self, headers=headers)
response = api_client.get(api_routes.users_self, headers=headers)
assert response.status_code == 200
user = response.json()

View file

@ -1,12 +1,12 @@
from fastapi.testclient import TestClient
from mealie.repos.repository_factory import AllRepositories
from tests.utils import routes
from tests.utils import api_routes
from tests.utils.fixture_schemas import TestUser
def test_seed_invalid_locale(api_client: TestClient, unique_user: TestUser):
for route in [routes.seeders.Seeders.foods, routes.seeders.Seeders.labels, routes.seeders.Seeders.units]:
for route in (api_routes.groups_seeders_foods, api_routes.groups_seeders_labels, api_routes.groups_seeders_units):
resp = api_client.post(route, json={"locale": "invalid"}, headers=unique_user.token)
assert resp.status_code == 422
@ -18,7 +18,7 @@ def test_seed_foods(api_client: TestClient, unique_user: TestUser, database: All
foods = database.ingredient_foods.by_group(unique_user.group_id).get_all()
assert len(foods) == 0
resp = api_client.post(routes.seeders.Seeders.foods, json={"locale": "en-US"}, headers=unique_user.token)
resp = api_client.post(api_routes.groups_seeders_foods, json={"locale": "en-US"}, headers=unique_user.token)
assert resp.status_code == 200
# Check that the foods was created
@ -33,7 +33,7 @@ def test_seed_units(api_client: TestClient, unique_user: TestUser, database: All
units = database.ingredient_units.by_group(unique_user.group_id).get_all()
assert len(units) == 0
resp = api_client.post(routes.seeders.Seeders.units, json={"locale": "en-US"}, headers=unique_user.token)
resp = api_client.post(api_routes.groups_seeders_units, json={"locale": "en-US"}, headers=unique_user.token)
assert resp.status_code == 200
# Check that the foods was created
@ -48,7 +48,7 @@ def test_seed_labels(api_client: TestClient, unique_user: TestUser, database: Al
labels = database.group_multi_purpose_labels.by_group(unique_user.group_id).get_all()
assert len(labels) == 0
resp = api_client.post(routes.seeders.Seeders.labels, json={"locale": "en-US"}, headers=unique_user.token)
resp = api_client.post(api_routes.groups_seeders_labels, json={"locale": "en-US"}, headers=unique_user.token)
assert resp.status_code == 200
# Check that the foods was created

View file

@ -7,23 +7,11 @@ from pydantic import UUID4
from mealie.schema.group.group_shopping_list import ShoppingListItemOut, ShoppingListOut
from tests import utils
from tests.utils import api_routes
from tests.utils.factories import random_string
from tests.utils.fixture_schemas import TestUser
class Routes:
shopping = "/api/groups/shopping"
items = shopping + "/items"
@staticmethod
def item(item_id: str | UUID4) -> str:
return f"{Routes.items}/{item_id}"
@staticmethod
def shopping_list(list_id: str | UUID4) -> str:
return f"{Routes.shopping}/lists/{list_id}"
def create_item(list_id: UUID4) -> dict:
return {
"shopping_list_id": str(list_id),
@ -59,19 +47,19 @@ def test_shopping_list_items_create_one(
) -> None:
item = create_item(shopping_list.id)
response = api_client.post(Routes.items, json=item, headers=unique_user.token)
response = api_client.post(api_routes.groups_shopping_items, json=item, headers=unique_user.token)
as_json = utils.assert_derserialize(response, 201)
# Test Item is Getable
created_item_id = as_json["id"]
response = api_client.get(Routes.item(created_item_id), headers=unique_user.token)
response = api_client.get(api_routes.groups_shopping_items_item_id(created_item_id), headers=unique_user.token)
as_json = utils.assert_derserialize(response, 200)
# Ensure List Id is Set
assert as_json["shoppingListId"] == str(shopping_list.id)
# Test Item In List
response = api_client.get(Routes.shopping_list(shopping_list.id), headers=unique_user.token)
response = api_client.get(api_routes.groups_shopping_lists_item_id(shopping_list.id), headers=unique_user.token)
response_list = utils.assert_derserialize(response, 200)
assert len(response_list["listItems"]) == 1
@ -89,12 +77,12 @@ def test_shopping_list_items_get_one(
for _ in range(3):
item = random.choice(list_with_items.list_items)
response = api_client.get(Routes.item(item.id), headers=unique_user.token)
response = api_client.get(api_routes.groups_shopping_items_item_id(item.id), headers=unique_user.token)
assert response.status_code == 200
def test_shopping_list_items_get_one_404(api_client: TestClient, unique_user: TestUser) -> None:
response = api_client.get(Routes.item(uuid4()), headers=unique_user.token)
response = api_client.get(api_routes.groups_shopping_items_item_id(uuid4()), headers=unique_user.token)
assert response.status_code == 404
@ -111,7 +99,9 @@ def test_shopping_list_items_update_one(
update_data = create_item(list_with_items.id)
update_data["id"] = str(item.id)
response = api_client.put(Routes.item(item.id), json=update_data, headers=unique_user.token)
response = api_client.put(
api_routes.groups_shopping_items_item_id(item.id), json=update_data, headers=unique_user.token
)
item_json = utils.assert_derserialize(response, 200)
assert item_json["note"] == update_data["note"]
@ -124,11 +114,11 @@ def test_shopping_list_items_delete_one(
item = random.choice(list_with_items.list_items)
# Delete Item
response = api_client.delete(Routes.item(item.id), headers=unique_user.token)
response = api_client.delete(api_routes.groups_shopping_items_item_id(item.id), headers=unique_user.token)
assert response.status_code == 200
# Validate Get Item Returns 404
response = api_client.get(Routes.item(item.id), headers=unique_user.token)
response = api_client.get(api_routes.groups_shopping_items_item_id(item.id), headers=unique_user.token)
assert response.status_code == 404
@ -158,11 +148,11 @@ def test_shopping_list_items_update_many_reorder(
# update list
# the default serializer fails on certain complex objects, so we use FastAPI's serliazer first
as_dict = utils.jsonify(as_dict)
response = api_client.put(Routes.items, json=as_dict, headers=unique_user.token)
response = api_client.put(api_routes.groups_shopping_items, json=as_dict, headers=unique_user.token)
assert response.status_code == 200
# retrieve list and check positions against list
response = api_client.get(Routes.shopping_list(list_with_items.id), headers=unique_user.token)
response = api_client.get(api_routes.groups_shopping_lists_item_id(list_with_items.id), headers=unique_user.token)
response_list = utils.assert_derserialize(response, 200)
for i, item_data in enumerate(response_list["listItems"]):
@ -185,11 +175,13 @@ def test_shopping_list_items_update_many_consolidates_common_items(
li.note = master_note
# update list
response = api_client.put(Routes.items, json=serialize_list_items(list_items), headers=unique_user.token)
response = api_client.put(
api_routes.groups_shopping_items, json=serialize_list_items(list_items), headers=unique_user.token
)
assert response.status_code == 200
# retrieve list and check positions against list
response = api_client.get(Routes.shopping_list(list_with_items.id), headers=unique_user.token)
response = api_client.get(api_routes.groups_shopping_lists_item_id(list_with_items.id), headers=unique_user.token)
response_list = utils.assert_derserialize(response, 200)
assert len(response_list["listItems"]) == 1
@ -220,7 +212,7 @@ def test_shopping_list_item_extras(
new_item_data = create_item(shopping_list.id)
new_item_data["extras"] = {key_str_1: val_str_1}
response = api_client.post(Routes.items, json=new_item_data, headers=unique_user.token)
response = api_client.post(api_routes.groups_shopping_items, json=new_item_data, headers=unique_user.token)
item_as_json = utils.assert_derserialize(response, 201)
# make sure the extra persists
@ -231,7 +223,9 @@ def test_shopping_list_item_extras(
# add more extras to the item
item_as_json["extras"][key_str_2] = val_str_2
response = api_client.put(Routes.item(item_as_json["id"]), json=item_as_json, headers=unique_user.token)
response = api_client.put(
api_routes.groups_shopping_items_item_id(item_as_json["id"]), json=item_as_json, headers=unique_user.token
)
item_as_json = utils.assert_derserialize(response, 200)
# make sure both the new extra and original extra persist

View file

@ -1,29 +1,17 @@
import random
from fastapi.testclient import TestClient
from pydantic import UUID4
from mealie.schema.group.group_shopping_list import ShoppingListOut
from mealie.schema.recipe.recipe import Recipe
from tests import utils
from tests.utils import api_routes
from tests.utils.factories import random_string
from tests.utils.fixture_schemas import TestUser
class Routes:
base = "/api/groups/shopping/lists"
@staticmethod
def item(item_id: str | UUID4) -> str:
return f"{Routes.base}/{item_id}"
@staticmethod
def add_recipe(item_id: str | UUID4, recipe_id: str | UUID4) -> str:
return f"{Routes.item(item_id)}/recipe/{recipe_id}"
def test_shopping_lists_get_all(api_client: TestClient, unique_user: TestUser, shopping_lists: list[ShoppingListOut]):
response = api_client.get(Routes.base, headers=unique_user.token)
response = api_client.get(api_routes.groups_shopping_lists, headers=unique_user.token)
assert response.status_code == 200
all_lists = response.json()["items"]
@ -40,7 +28,7 @@ def test_shopping_lists_create_one(api_client: TestClient, unique_user: TestUser
"name": random_string(10),
}
response = api_client.post(Routes.base, json=payload, headers=unique_user.token)
response = api_client.post(api_routes.groups_shopping_lists, json=payload, headers=unique_user.token)
response_list = utils.assert_derserialize(response, 201)
assert response_list["name"] == payload["name"]
@ -50,7 +38,7 @@ def test_shopping_lists_create_one(api_client: TestClient, unique_user: TestUser
def test_shopping_lists_get_one(api_client: TestClient, unique_user: TestUser, shopping_lists: list[ShoppingListOut]):
shopping_list = shopping_lists[0]
response = api_client.get(Routes.item(shopping_list.id), headers=unique_user.token)
response = api_client.get(api_routes.groups_shopping_lists_item_id(shopping_list.id), headers=unique_user.token)
assert response.status_code == 200
response_list = response.json()
@ -72,7 +60,9 @@ def test_shopping_lists_update_one(
"listItems": [],
}
response = api_client.put(Routes.item(sample_list.id), json=payload, headers=unique_user.token)
response = api_client.put(
api_routes.groups_shopping_lists_item_id(sample_list.id), json=payload, headers=unique_user.token
)
assert response.status_code == 200
response_list = response.json()
@ -87,10 +77,10 @@ def test_shopping_lists_delete_one(
):
sample_list = random.choice(shopping_lists)
response = api_client.delete(Routes.item(sample_list.id), headers=unique_user.token)
response = api_client.delete(api_routes.groups_shopping_lists_item_id(sample_list.id), headers=unique_user.token)
assert response.status_code == 200
response = api_client.get(Routes.item(sample_list.id), headers=unique_user.token)
response = api_client.get(api_routes.groups_shopping_lists_item_id(sample_list.id), headers=unique_user.token)
assert response.status_code == 404
@ -104,12 +94,14 @@ def test_shopping_lists_add_recipe(
recipe = recipe_ingredient_only
response = api_client.post(Routes.add_recipe(sample_list.id, recipe.id), headers=unique_user.token)
response = api_client.post(
api_routes.groups_shopping_lists_item_id_recipe_recipe_id(sample_list.id, recipe.id), headers=unique_user.token
)
assert response.status_code == 200
# Get List and Check for Ingredients
response = api_client.get(Routes.item(sample_list.id), headers=unique_user.token)
response = api_client.get(api_routes.groups_shopping_lists_item_id(sample_list.id), headers=unique_user.token)
as_json = utils.assert_derserialize(response, 200)
assert len(as_json["listItems"]) == len(recipe.recipe_ingredient)
@ -137,11 +129,13 @@ def test_shopping_lists_remove_recipe(
recipe = recipe_ingredient_only
response = api_client.post(Routes.add_recipe(sample_list.id, recipe.id), headers=unique_user.token)
response = api_client.post(
api_routes.groups_shopping_lists_item_id_recipe_recipe_id(sample_list.id, recipe.id), headers=unique_user.token
)
assert response.status_code == 200
# Get List and Check for Ingredients
response = api_client.get(Routes.item(sample_list.id), headers=unique_user.token)
response = api_client.get(api_routes.groups_shopping_lists_item_id(sample_list.id), headers=unique_user.token)
as_json = utils.assert_derserialize(response, 200)
assert len(as_json["listItems"]) == len(recipe.recipe_ingredient)
@ -152,10 +146,12 @@ def test_shopping_lists_remove_recipe(
assert item["note"] in known_ingredients
# Remove Recipe
response = api_client.delete(Routes.add_recipe(sample_list.id, recipe.id), headers=unique_user.token)
response = api_client.delete(
api_routes.groups_shopping_lists_item_id_recipe_recipe_id(sample_list.id, recipe.id), headers=unique_user.token
)
# Get List and Check for Ingredients
response = api_client.get(Routes.item(sample_list.id), headers=unique_user.token)
response = api_client.get(api_routes.groups_shopping_lists_item_id(sample_list.id), headers=unique_user.token)
as_json = utils.assert_derserialize(response, 200)
assert len(as_json["listItems"]) == 0
assert len(as_json["recipeReferences"]) == 0
@ -172,10 +168,13 @@ def test_shopping_lists_remove_recipe_multiple_quantity(
recipe = recipe_ingredient_only
for _ in range(3):
response = api_client.post(Routes.add_recipe(sample_list.id, recipe.id), headers=unique_user.token)
response = api_client.post(
api_routes.groups_shopping_lists_item_id_recipe_recipe_id(sample_list.id, recipe.id),
headers=unique_user.token,
)
assert response.status_code == 200
response = api_client.get(Routes.item(sample_list.id), headers=unique_user.token)
response = api_client.get(api_routes.groups_shopping_lists_item_id(sample_list.id), headers=unique_user.token)
as_json = utils.assert_derserialize(response, 200)
assert len(as_json["listItems"]) == len(recipe.recipe_ingredient)
@ -186,10 +185,12 @@ def test_shopping_lists_remove_recipe_multiple_quantity(
assert item["note"] in known_ingredients
# Remove Recipe
response = api_client.delete(Routes.add_recipe(sample_list.id, recipe.id), headers=unique_user.token)
response = api_client.delete(
api_routes.groups_shopping_lists_item_id_recipe_recipe_id(sample_list.id, recipe.id), headers=unique_user.token
)
# Get List and Check for Ingredients
response = api_client.get(Routes.item(sample_list.id), headers=unique_user.token)
response = api_client.get(api_routes.groups_shopping_lists_item_id(sample_list.id), headers=unique_user.token)
as_json = utils.assert_derserialize(response, 200)
# All Items Should Still Exists
@ -218,7 +219,7 @@ def test_shopping_list_extras(
new_list_data: dict = {"name": random_string()}
new_list_data["extras"] = {key_str_1: val_str_1}
response = api_client.post(Routes.base, json=new_list_data, headers=unique_user.token)
response = api_client.post(api_routes.groups_shopping_lists, json=new_list_data, headers=unique_user.token)
list_as_json = utils.assert_derserialize(response, 201)
# make sure the extra persists
@ -229,7 +230,9 @@ def test_shopping_list_extras(
# add more extras to the list
list_as_json["extras"][key_str_2] = val_str_2
response = api_client.put(Routes.item(list_as_json["id"]), json=list_as_json, headers=unique_user.token)
response = api_client.put(
api_routes.groups_shopping_lists_item_id(list_as_json["id"]), json=list_as_json, headers=unique_user.token
)
list_as_json = utils.assert_derserialize(response, 200)
# make sure both the new extra and original extra persist

View file

@ -3,18 +3,10 @@ from datetime import datetime, timezone
import pytest
from fastapi.testclient import TestClient
from tests.utils import assert_derserialize, jsonify
from tests.utils import api_routes, assert_derserialize, jsonify
from tests.utils.fixture_schemas import TestUser
class Routes:
base = "/api/groups/webhooks"
@staticmethod
def item(item_id: int) -> str:
return f"{Routes.base}/{item_id}"
@pytest.fixture()
def webhook_data():
return {
@ -27,15 +19,15 @@ def webhook_data():
def test_create_webhook(api_client: TestClient, unique_user: TestUser, webhook_data):
response = api_client.post(Routes.base, json=jsonify(webhook_data), headers=unique_user.token)
response = api_client.post(api_routes.groups_webhooks, json=jsonify(webhook_data), headers=unique_user.token)
assert response.status_code == 201
def test_read_webhook(api_client: TestClient, unique_user: TestUser, webhook_data):
response = api_client.post(Routes.base, json=jsonify(webhook_data), headers=unique_user.token)
response = api_client.post(api_routes.groups_webhooks, json=jsonify(webhook_data), headers=unique_user.token)
item_id = response.json()["id"]
response = api_client.get(Routes.item(item_id), headers=unique_user.token)
response = api_client.get(api_routes.groups_webhooks_item_id(item_id), headers=unique_user.token)
webhook = assert_derserialize(response, 200)
assert webhook["id"] == item_id
@ -46,7 +38,7 @@ def test_read_webhook(api_client: TestClient, unique_user: TestUser, webhook_dat
def test_update_webhook(api_client: TestClient, webhook_data, unique_user: TestUser):
response = api_client.post(Routes.base, json=jsonify(webhook_data), headers=unique_user.token)
response = api_client.post(api_routes.groups_webhooks, json=jsonify(webhook_data), headers=unique_user.token)
item_dict = assert_derserialize(response, 201)
item_id = item_dict["id"]
@ -54,7 +46,9 @@ def test_update_webhook(api_client: TestClient, webhook_data, unique_user: TestU
webhook_data["url"] = "https://my-new-fake-url.com"
webhook_data["enabled"] = False
response = api_client.put(Routes.item(item_id), json=jsonify(webhook_data), headers=unique_user.token)
response = api_client.put(
api_routes.groups_webhooks_item_id(item_id), json=jsonify(webhook_data), headers=unique_user.token
)
updated_webhook = assert_derserialize(response, 200)
assert updated_webhook["name"] == webhook_data["name"]
@ -63,12 +57,12 @@ def test_update_webhook(api_client: TestClient, webhook_data, unique_user: TestU
def test_delete_webhook(api_client: TestClient, webhook_data, unique_user: TestUser):
response = api_client.post(Routes.base, json=jsonify(webhook_data), headers=unique_user.token)
response = api_client.post(api_routes.groups_webhooks, json=jsonify(webhook_data), headers=unique_user.token)
item_dict = assert_derserialize(response, 201)
item_id = item_dict["id"]
response = api_client.delete(Routes.item(item_id), headers=unique_user.token)
response = api_client.delete(api_routes.groups_webhooks_item_id(item_id), headers=unique_user.token)
assert response.status_code == 200
response = api_client.get(Routes.item(item_id), headers=unique_user.token)
response = api_client.get(api_routes.groups_webhooks_item_id(item_id), headers=unique_user.token)
assert response.status_code == 404

View file

@ -1,4 +1,5 @@
from pathlib import Path
from typing import Generator
import pytest
import sqlalchemy
@ -9,30 +10,21 @@ from mealie.repos.repository_factory import AllRepositories
from mealie.schema.recipe.recipe_bulk_actions import ExportTypes
from mealie.schema.recipe.recipe_category import CategorySave, TagSave
from tests import utils
from tests.utils import api_routes
from tests.utils.factories import random_string
from tests.utils.fixture_schemas import TestUser
class Routes:
create_recipes = "/api/recipes"
bulk_tag = "api/recipes/bulk-actions/tag"
bulk_categorize = "api/recipes/bulk-actions/categorize"
bulk_delete = "api/recipes/bulk-actions/delete"
bulk_export = "api/recipes/bulk-actions/export"
bulk_export_download = f"{bulk_export}/download"
bulk_export_purge = f"{bulk_export}/purge"
@pytest.fixture(scope="function")
def ten_slugs(api_client: TestClient, unique_user: TestUser, database: AllRepositories) -> list[str]:
def ten_slugs(
api_client: TestClient, unique_user: TestUser, database: AllRepositories
) -> Generator[list[str], None, None]:
slugs = []
slugs: list[str] = []
for _ in range(10):
payload = {"name": random_string(length=20)}
response = api_client.post(Routes.create_recipes, json=payload, headers=unique_user.token)
response = api_client.post(api_routes.recipes, json=payload, headers=unique_user.token)
assert response.status_code == 201
response_data = response.json()
@ -59,14 +51,16 @@ def test_bulk_tag_recipes(
payload = {"recipes": ten_slugs, "tags": tags}
response = api_client.post(Routes.bulk_tag, json=utils.jsonify(payload), headers=unique_user.token)
response = api_client.post(
api_routes.recipes_bulk_actions_tag, json=utils.jsonify(payload), headers=unique_user.token
)
assert response.status_code == 200
# Validate Recipes are Tagged
for slug in ten_slugs:
recipe = database.recipes.get_one(slug)
for tag in recipe.tags:
for tag in recipe.tags: # type: ignore
assert tag.slug in [x["slug"] for x in tags]
@ -85,14 +79,16 @@ def test_bulk_categorize_recipes(
payload = {"recipes": ten_slugs, "categories": categories}
response = api_client.post(Routes.bulk_categorize, json=utils.jsonify(payload), headers=unique_user.token)
response = api_client.post(
api_routes.recipes_bulk_actions_categorize, json=utils.jsonify(payload), headers=unique_user.token
)
assert response.status_code == 200
# Validate Recipes are Categorized
for slug in ten_slugs:
recipe = database.recipes.get_one(slug)
for cat in recipe.recipe_category:
for cat in recipe.recipe_category: # type: ignore
assert cat.slug in [x["slug"] for x in categories]
@ -105,7 +101,7 @@ def test_bulk_delete_recipes(
payload = {"recipes": ten_slugs}
response = api_client.post(Routes.bulk_delete, json=payload, headers=unique_user.token)
response = api_client.post(api_routes.recipes_bulk_actions_delete, json=payload, headers=unique_user.token)
assert response.status_code == 200
# Validate Recipes are Tagged
@ -120,11 +116,11 @@ def test_bulk_export_recipes(api_client: TestClient, unique_user: TestUser, ten_
"export_type": ExportTypes.JSON.value,
}
response = api_client.post(Routes.bulk_export, json=payload, headers=unique_user.token)
response = api_client.post(api_routes.recipes_bulk_actions_export, json=payload, headers=unique_user.token)
assert response.status_code == 202
# Get All Exports Available
response = api_client.get(Routes.bulk_export, headers=unique_user.token)
response = api_client.get(api_routes.recipes_bulk_actions_export, headers=unique_user.token)
assert response.status_code == 200
response_data = response.json()
@ -133,7 +129,9 @@ def test_bulk_export_recipes(api_client: TestClient, unique_user: TestUser, ten_
export_path = response_data[0]["path"]
# Get Export Token
response = api_client.get(f"{Routes.bulk_export_download}?path={export_path}", headers=unique_user.token)
response = api_client.get(
f"{api_routes.recipes_bulk_actions_export_download}?path={export_path}", headers=unique_user.token
)
assert response.status_code == 200
response_data = response.json()
@ -150,11 +148,11 @@ def test_bulk_export_recipes(api_client: TestClient, unique_user: TestUser, ten_
assert len(response.content) > 0
# Purge Export
response = api_client.delete(Routes.bulk_export_purge, headers=unique_user.token)
response = api_client.delete(api_routes.recipes_bulk_actions_export_purge, headers=unique_user.token)
assert response.status_code == 200
# Validate Export was purged
response = api_client.get(Routes.bulk_export, headers=unique_user.token)
response = api_client.get(api_routes.recipes_bulk_actions_export, headers=unique_user.token)
assert response.status_code == 200
response_data = response.json()

View file

@ -1,17 +1,10 @@
import pytest
from fastapi.testclient import TestClient
from tests.utils import api_routes
from tests.utils.fixture_schemas import TestUser
class Routes:
base = "/api/recipes"
bulk = "/api/recipes/create-url/bulk"
def item(item_id: str) -> str:
return f"{Routes.base}/{item_id}"
@pytest.mark.skip("Long Running Scraper")
def test_bulk_import(api_client: TestClient, unique_user: TestUser):
recipes = {
@ -26,10 +19,10 @@ def test_bulk_import(api_client: TestClient, unique_user: TestUser):
"best-chocolate-chip-cookies",
]
response = api_client.post(Routes.bulk, json=recipes, headers=unique_user.token)
response = api_client.post(api_routes.recipes_create_url_bulk, json=recipes, headers=unique_user.token)
assert response.status_code == 201
for slug in slugs:
response = api_client.get(Routes.item(slug), headers=unique_user.token)
response = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token)
assert response.status_code == 200

View file

@ -3,32 +3,19 @@ from fastapi.testclient import TestClient
from pydantic import UUID4
from mealie.schema.recipe.recipe import Recipe
from tests.utils import api_routes
from tests.utils.factories import random_string
from tests.utils.fixture_schemas import TestUser
class Routes:
base = "/api/comments"
recipes = "/api/recipes"
def item(item_id: int) -> str:
return f"{Routes.base}/{item_id}"
def recipe(recipe_id: int) -> str:
return f"{Routes.recipes}/{recipe_id}"
def recipe_comments(recipe_slug: str) -> str:
return f"{Routes.recipe(recipe_slug)}/comments"
@pytest.fixture(scope="function")
def unique_recipe(api_client: TestClient, unique_user: TestUser):
payload = {"name": random_string(length=20)}
response = api_client.post(Routes.recipes, json=payload, headers=unique_user.token)
response = api_client.post(api_routes.recipes, json=payload, headers=unique_user.token)
assert response.status_code == 201
response_data = response.json()
recipe_response = api_client.get(Routes.recipe(response_data), headers=unique_user.token)
recipe_response = api_client.get(api_routes.recipes_slug(response_data), headers=unique_user.token)
return Recipe(**recipe_response.json())
@ -45,7 +32,7 @@ def random_comment(recipe_id: UUID4) -> dict:
def test_create_comment(api_client: TestClient, unique_recipe: Recipe, unique_user: TestUser):
# Create Comment
create_data = random_comment(unique_recipe.id)
response = api_client.post(Routes.base, json=create_data, headers=unique_user.token)
response = api_client.post(api_routes.comments, json=create_data, headers=unique_user.token)
assert response.status_code == 201
response_data = response.json()
@ -55,7 +42,7 @@ def test_create_comment(api_client: TestClient, unique_recipe: Recipe, unique_us
assert response_data["userId"] == unique_user.user_id
# Check for Proper Association
response = api_client.get(Routes.recipe_comments(unique_recipe.slug), headers=unique_user.token)
response = api_client.get(api_routes.recipes_slug_comments(unique_recipe.slug), headers=unique_user.token)
assert response.status_code == 200
response_data = response.json()
@ -69,7 +56,7 @@ def test_create_comment(api_client: TestClient, unique_recipe: Recipe, unique_us
def test_update_comment(api_client: TestClient, unique_recipe: Recipe, unique_user: TestUser):
# Create Comment
create_data = random_comment(unique_recipe.id)
response = api_client.post(Routes.base, json=create_data, headers=unique_user.token)
response = api_client.post(api_routes.comments, json=create_data, headers=unique_user.token)
assert response.status_code == 201
comment_id = response.json()["id"]
@ -78,7 +65,7 @@ def test_update_comment(api_client: TestClient, unique_recipe: Recipe, unique_us
update_data = random_comment(unique_recipe.id)
update_data["id"] = comment_id
response = api_client.put(Routes.item(comment_id), json=update_data, headers=unique_user.token)
response = api_client.put(api_routes.comments_item_id(comment_id), json=update_data, headers=unique_user.token)
assert response.status_code == 200
@ -92,16 +79,16 @@ def test_update_comment(api_client: TestClient, unique_recipe: Recipe, unique_us
def test_delete_comment(api_client: TestClient, unique_recipe: Recipe, unique_user: TestUser):
# Create Comment
create_data = random_comment(unique_recipe.id)
response = api_client.post(Routes.base, json=create_data, headers=unique_user.token)
response = api_client.post(api_routes.comments, json=create_data, headers=unique_user.token)
assert response.status_code == 201
# Delete Comment
comment_id = response.json()["id"]
response = api_client.delete(Routes.item(comment_id), headers=unique_user.token)
response = api_client.delete(api_routes.comments_item_id(comment_id), headers=unique_user.token)
assert response.status_code == 200
# Validate Deletion
response = api_client.get(Routes.item(comment_id), headers=unique_user.token)
response = api_client.get(api_routes.comments_item_id(comment_id), headers=unique_user.token)
assert response.status_code == 404
@ -109,15 +96,15 @@ def test_delete_comment(api_client: TestClient, unique_recipe: Recipe, unique_us
def test_admin_can_delete(api_client: TestClient, unique_recipe: Recipe, unique_user: TestUser, admin_user: TestUser):
# Create Comment
create_data = random_comment(unique_recipe.id)
response = api_client.post(Routes.base, json=create_data, headers=unique_user.token)
response = api_client.post(api_routes.comments, json=create_data, headers=unique_user.token)
assert response.status_code == 201
# Delete Comment
comment_id = response.json()["id"]
response = api_client.delete(Routes.item(comment_id), headers=admin_user.token)
response = api_client.delete(api_routes.comments_item_id(comment_id), headers=admin_user.token)
assert response.status_code == 200
# Validate Deletion
response = api_client.get(Routes.item(comment_id), headers=admin_user.token)
response = api_client.get(api_routes.comments_item_id(comment_id), headers=admin_user.token)
assert response.status_code == 404

View file

@ -14,8 +14,7 @@ from mealie.schema.recipe.recipe import RecipeCategory
from mealie.services.recipe.recipe_data_service import RecipeDataService
from mealie.services.scraper.scraper_strategies import RecipeScraperOpenGraph
from tests import data, utils
from tests.utils import routes
from tests.utils.app_routes import AppRoutes
from tests.utils import api_routes
from tests.utils.factories import random_string
from tests.utils.fixture_schemas import TestUser
from tests.utils.recipe_data import RecipeSiteTestCase, get_recipe_test_cases
@ -58,7 +57,6 @@ def open_graph_override(html: str):
@pytest.mark.parametrize("recipe_data", recipe_test_data)
def test_create_by_url(
api_client: TestClient,
api_routes: AppRoutes,
recipe_data: RecipeSiteTestCase,
unique_user: TestUser,
monkeypatch: MonkeyPatch,
@ -82,7 +80,7 @@ def test_create_by_url(
lambda *_: "TEST_IMAGE",
)
api_client.delete(api_routes.recipes_recipe_slug(recipe_data.expected_slug), headers=unique_user.token)
api_client.delete(api_routes.recipes_slug(recipe_data.expected_slug), headers=unique_user.token)
response = api_client.post(
api_routes.recipes_create_url, json={"url": recipe_data.url, "include_tags": False}, headers=unique_user.token
@ -94,7 +92,6 @@ def test_create_by_url(
def test_create_by_url_with_tags(
api_client: TestClient,
api_routes: AppRoutes,
unique_user: TestUser,
monkeypatch: MonkeyPatch,
):
@ -128,7 +125,7 @@ def test_create_by_url_with_tags(
slug = "nutty-umami-noodles-with-scallion-brown-butter-and-snow-peas"
# Get the recipe
response = api_client.get(api_routes.recipes_recipe_slug(slug), headers=unique_user.token)
response = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token)
assert response.status_code == 200
# Verifiy the tags are present
@ -162,7 +159,7 @@ def test_read_update(
unique_user: TestUser,
recipe_categories: list[RecipeCategory],
):
recipe_url = routes.recipes.Recipe.item(recipe_data.expected_slug)
recipe_url = api_routes.recipes_slug(recipe_data.expected_slug)
response = api_client.get(recipe_url, headers=unique_user.token)
assert response.status_code == 200
@ -197,7 +194,7 @@ def test_read_update(
@pytest.mark.parametrize("recipe_data", recipe_test_data)
def test_rename(api_client: TestClient, recipe_data: RecipeSiteTestCase, unique_user: TestUser):
recipe_url = routes.recipes.Recipe.item(recipe_data.expected_slug)
recipe_url = api_routes.recipes_slug(recipe_data.expected_slug)
response = api_client.get(recipe_url, headers=unique_user.token)
assert response.status_code == 200
@ -216,18 +213,18 @@ def test_rename(api_client: TestClient, recipe_data: RecipeSiteTestCase, unique_
@pytest.mark.parametrize("recipe_data", recipe_test_data)
def test_delete(api_client: TestClient, recipe_data: RecipeSiteTestCase, unique_user: TestUser):
response = api_client.delete(routes.recipes.Recipe.item(recipe_data.expected_slug), headers=unique_user.token)
response = api_client.delete(api_routes.recipes_slug(recipe_data.expected_slug), headers=unique_user.token)
assert response.status_code == 200
def test_recipe_crud_404(api_client: TestClient, api_routes: AppRoutes, unique_user: TestUser):
response = api_client.put(routes.recipes.Recipe.item("test"), json={"test": "stest"}, headers=unique_user.token)
def test_recipe_crud_404(api_client: TestClient, unique_user: TestUser):
response = api_client.put(api_routes.recipes_slug("test"), json={"test": "stest"}, headers=unique_user.token)
assert response.status_code == 404
response = api_client.get(routes.recipes.Recipe.item("test"), headers=unique_user.token)
response = api_client.get(api_routes.recipes_slug("test"), headers=unique_user.token)
assert response.status_code == 404
response = api_client.delete(routes.recipes.Recipe.item("test"), headers=unique_user.token)
response = api_client.delete(api_routes.recipes_slug("test"), headers=unique_user.token)
assert response.status_code == 404
response = api_client.patch(api_routes.recipes_create_url, json={"test": "stest"}, headers=unique_user.token)
@ -237,11 +234,11 @@ def test_recipe_crud_404(api_client: TestClient, api_routes: AppRoutes, unique_u
def test_create_recipe_same_name(api_client: TestClient, unique_user: TestUser):
slug = random_string(10)
response = api_client.post(routes.recipes.Recipe.base, json={"name": slug}, headers=unique_user.token)
response = api_client.post(api_routes.recipes, json={"name": slug}, headers=unique_user.token)
assert response.status_code == 201
assert json.loads(response.text) == slug
response = api_client.post(routes.recipes.Recipe.base, json={"name": slug}, headers=unique_user.token)
response = api_client.post(api_routes.recipes, json={"name": slug}, headers=unique_user.token)
assert response.status_code == 201
assert json.loads(response.text) == f"{slug}-1"
@ -250,10 +247,10 @@ def test_create_recipe_too_many_time(api_client: TestClient, unique_user: TestUs
slug = random_string(10)
for _ in range(10):
response = api_client.post(routes.recipes.Recipe.base, json={"name": slug}, headers=unique_user.token)
response = api_client.post(api_routes.recipes, json={"name": slug}, headers=unique_user.token)
assert response.status_code == 201
response = api_client.post(routes.recipes.Recipe.base, json={"name": slug}, headers=unique_user.token)
response = api_client.post(api_routes.recipes, json={"name": slug}, headers=unique_user.token)
assert response.status_code == 400
@ -262,19 +259,19 @@ def test_delete_recipe_same_name(api_client: TestClient, unique_user: utils.Test
# Create recipe for both users
for user in (unique_user, g2_user):
response = api_client.post(routes.recipes.Recipe.base, json={"name": slug}, headers=user.token)
response = api_client.post(api_routes.recipes, json={"name": slug}, headers=user.token)
assert response.status_code == 201
assert json.loads(response.text) == slug
# Delete recipe for user 1
response = api_client.delete(routes.recipes.Recipe.item(slug), headers=unique_user.token)
response = api_client.delete(api_routes.recipes_slug(slug), headers=unique_user.token)
assert response.status_code == 200
# Ensure recipe for user 2 still exists
response = api_client.get(routes.recipes.Recipe.item(slug), headers=g2_user.token)
response = api_client.get(api_routes.recipes_slug(slug), headers=g2_user.token)
assert response.status_code == 200
# Make sure recipe for user 1 doesn't exist
response = api_client.get(routes.recipes.Recipe.item(slug), headers=unique_user.token)
response = api_client.get(routes.recipes.Recipe.item(slug), headers=unique_user.token)
response = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token)
response = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token)
assert response.status_code == 404

View file

@ -1,21 +1,13 @@
from fastapi.testclient import TestClient
from tests.utils import api_routes
from tests.utils.factories import random_string
from tests.utils.fixture_schemas import TestUser
class Routes:
base = "/api/recipes"
exports = base + "/exports"
@staticmethod
def item(slug: str, file_name: str) -> str:
return f"/api/recipes/{slug}/exports?template_name={file_name}"
def test_get_available_exports(api_client: TestClient, unique_user: TestUser) -> None:
# Get Templates
response = api_client.get(Routes.exports, headers=unique_user.token)
response = api_client.get(api_routes.recipes_exports, headers=unique_user.token)
# Assert Templates are Available
assert response.status_code == 200
@ -29,12 +21,14 @@ def test_get_available_exports(api_client: TestClient, unique_user: TestUser) ->
def test_render_jinja_template(api_client: TestClient, unique_user: TestUser) -> None:
# Create Recipe
recipe_name = random_string()
response = api_client.post(Routes.base, json={"name": recipe_name}, headers=unique_user.token)
response = api_client.post(api_routes.recipes, json={"name": recipe_name}, headers=unique_user.token)
assert response.status_code == 201
slug = response.json()
# Render Template
response = api_client.get(Routes.item(slug, "recipes.md"), headers=unique_user.token)
response = api_client.get(
api_routes.recipes_slug_exports(slug) + "?template_name=recipes.md", headers=unique_user.token
)
assert response.status_code == 200
# Assert Template is Rendered Correctly

View file

@ -1,30 +1,24 @@
from typing import Generator
import pytest
import sqlalchemy
from fastapi.testclient import TestClient
from mealie.repos.repository_factory import AllRepositories
from tests.utils import api_routes
from tests.utils.factories import random_string
from tests.utils.fixture_schemas import TestUser
class Routes:
create_recipes = "/api/recipes"
def base(item_id: int) -> str:
return f"api/users/{item_id}/favorites"
def toggle(item_id: int, slug: str) -> str:
return f"{Routes.base(item_id)}/{slug}"
@pytest.fixture(scope="function")
def ten_slugs(api_client: TestClient, unique_user: TestUser, database: AllRepositories) -> list[str]:
def ten_slugs(
api_client: TestClient, unique_user: TestUser, database: AllRepositories
) -> Generator[list[str], None, None]:
slugs = []
for _ in range(10):
payload = {"name": random_string(length=20)}
response = api_client.post(Routes.create_recipes, json=payload, headers=unique_user.token)
response = api_client.post(api_routes.recipes, json=payload, headers=unique_user.token)
assert response.status_code == 201
response_data = response.json()
@ -41,26 +35,30 @@ def ten_slugs(api_client: TestClient, unique_user: TestUser, database: AllReposi
def test_recipe_favorites(api_client: TestClient, unique_user: TestUser, ten_slugs: list[str]):
# Check that the user has no favorites
response = api_client.get(Routes.base(unique_user.user_id), headers=unique_user.token)
response = api_client.get(api_routes.users_id_favorites(unique_user.user_id), headers=unique_user.token)
assert response.status_code == 200
assert response.json()["favoriteRecipes"] == []
# Add a few recipes to the user's favorites
for slug in ten_slugs:
response = api_client.post(Routes.toggle(unique_user.user_id, slug), headers=unique_user.token)
response = api_client.post(
api_routes.users_id_favorites_slug(unique_user.user_id, slug), headers=unique_user.token
)
assert response.status_code == 200
# Check that the user has the recipes in their favorites
response = api_client.get(Routes.base(unique_user.user_id), headers=unique_user.token)
response = api_client.get(api_routes.users_id_favorites(unique_user.user_id), headers=unique_user.token)
assert response.status_code == 200
assert len(response.json()["favoriteRecipes"]) == 10
# Remove a few recipes from the user's favorites
for slug in ten_slugs[:5]:
response = api_client.delete(Routes.toggle(unique_user.user_id, slug), headers=unique_user.token)
response = api_client.delete(
api_routes.users_id_favorites_slug(unique_user.user_id, slug), headers=unique_user.token
)
assert response.status_code == 200
# Check that the user has the recipes in their favorites
response = api_client.get(Routes.base(unique_user.user_id), headers=unique_user.token)
response = api_client.get(api_routes.users_id_favorites(unique_user.user_id), headers=unique_user.token)
assert response.status_code == 200
assert len(response.json()["favoriteRecipes"]) == 5

View file

@ -5,18 +5,11 @@ from fastapi.testclient import TestClient
from mealie.schema.recipe.recipe_ingredient import CreateIngredientFood
from tests import utils
from tests.utils import api_routes
from tests.utils.factories import random_string
from tests.utils.fixture_schemas import TestUser
class Routes:
base = "/api/foods"
@staticmethod
def item(item_id: int) -> str:
return f"{Routes.base}/{item_id}"
@pytest.fixture(scope="function")
def food(api_client: TestClient, unique_user: TestUser) -> Generator[dict, None, None]:
data = CreateIngredientFood(
@ -24,13 +17,13 @@ def food(api_client: TestClient, unique_user: TestUser) -> Generator[dict, None,
description=random_string(10),
).dict(by_alias=True)
response = api_client.post(Routes.base, json=data, headers=unique_user.token)
response = api_client.post(api_routes.foods, json=data, headers=unique_user.token)
assert response.status_code == 201
yield response.json()
response = api_client.delete(Routes.item(response.json()["id"]), headers=unique_user.token)
response = api_client.delete(api_routes.foods_item_id(response.json()["id"]), headers=unique_user.token)
def test_create_food(api_client: TestClient, unique_user: TestUser):
@ -39,12 +32,12 @@ def test_create_food(api_client: TestClient, unique_user: TestUser):
description=random_string(10),
).dict(by_alias=True)
response = api_client.post(Routes.base, json=data, headers=unique_user.token)
response = api_client.post(api_routes.foods, json=data, headers=unique_user.token)
assert response.status_code == 201
def test_read_food(api_client: TestClient, food: dict, unique_user: TestUser):
response = api_client.get(Routes.item(food["id"]), headers=unique_user.token)
response = api_client.get(api_routes.foods_item_id(food["id"]), headers=unique_user.token)
assert response.status_code == 200
as_json = response.json()
@ -60,7 +53,7 @@ def test_update_food(api_client: TestClient, food: dict, unique_user: TestUser):
"name": random_string(10),
"description": random_string(10),
}
response = api_client.put(Routes.item(food["id"]), json=update_data, headers=unique_user.token)
response = api_client.put(api_routes.foods_item_id(food["id"]), json=update_data, headers=unique_user.token)
assert response.status_code == 200
as_json = response.json()
@ -72,11 +65,11 @@ def test_update_food(api_client: TestClient, food: dict, unique_user: TestUser):
def test_delete_food(api_client: TestClient, food: dict, unique_user: TestUser):
id = food["id"]
response = api_client.delete(Routes.item(id), headers=unique_user.token)
response = api_client.delete(api_routes.foods_item_id(id), headers=unique_user.token)
assert response.status_code == 200
response = api_client.get(Routes.item(id), headers=unique_user.token)
response = api_client.get(api_routes.foods_item_id(id), headers=unique_user.token)
assert response.status_code == 404
@ -94,7 +87,7 @@ def test_food_extras(
new_food_data: dict = {"name": random_string()}
new_food_data["extras"] = {key_str_1: val_str_1}
response = api_client.post(Routes.base, json=new_food_data, headers=unique_user.token)
response = api_client.post(api_routes.foods, json=new_food_data, headers=unique_user.token)
food_as_json = utils.assert_derserialize(response, 201)
# make sure the extra persists
@ -105,7 +98,9 @@ def test_food_extras(
# add more extras to the food
food_as_json["extras"][key_str_2] = val_str_2
response = api_client.put(Routes.item(food_as_json["id"]), json=food_as_json, headers=unique_user.token)
response = api_client.put(
api_routes.foods_item_id(food_as_json["id"]), json=food_as_json, headers=unique_user.token
)
food_as_json = utils.assert_derserialize(response, 200)
# make sure both the new extra and original extra persist

View file

@ -3,14 +3,10 @@ from fastapi.testclient import TestClient
from mealie.schema.recipe.recipe_ingredient import RegisteredParser
from tests.unit_tests.test_ingredient_parser import TestIngredient, crf_exists, test_ingredients
from tests.utils import api_routes
from tests.utils.fixture_schemas import TestUser
class Routes:
ingredient = "/api/parser/ingredient"
ingredients = "/api/parser/ingredients"
def assert_ingredient(api_response: dict, test_ingredient: TestIngredient):
assert api_response["ingredient"]["quantity"] == pytest.approx(test_ingredient.quantity)
assert api_response["ingredient"]["unit"]["name"] == test_ingredient.unit
@ -22,7 +18,7 @@ def assert_ingredient(api_response: dict, test_ingredient: TestIngredient):
@pytest.mark.parametrize("test_ingredient", test_ingredients)
def test_recipe_ingredient_parser_nlp(api_client: TestClient, test_ingredient: TestIngredient, unique_user: TestUser):
payload = {"parser": RegisteredParser.nlp, "ingredient": test_ingredient.input}
response = api_client.post(Routes.ingredient, json=payload, headers=unique_user.token)
response = api_client.post(api_routes.parser_ingredient, json=payload, headers=unique_user.token)
assert response.status_code == 200
assert_ingredient(response.json(), test_ingredient)
@ -30,7 +26,7 @@ def test_recipe_ingredient_parser_nlp(api_client: TestClient, test_ingredient: T
@pytest.mark.skipif(not crf_exists(), reason="CRF++ not installed")
def test_recipe_ingredients_parser_nlp(api_client: TestClient, unique_user: TestUser):
payload = {"parser": RegisteredParser.nlp, "ingredients": [x.input for x in test_ingredients]}
response = api_client.post(Routes.ingredients, json=payload, headers=unique_user.token)
response = api_client.post(api_routes.parser_ingredients, json=payload, headers=unique_user.token)
assert response.status_code == 200
for api_ingredient, test_ingredient in zip(response.json(), test_ingredients):

View file

@ -1,20 +1,16 @@
from fastapi.testclient import TestClient
from tests.utils import api_routes
from tests.utils.factories import random_string
from tests.utils.fixture_schemas import TestUser
class Routes:
base = "/api/recipes"
user = "/api/users/self"
def test_ownership_on_new_with_admin(api_client: TestClient, admin_user: TestUser):
recipe_name = random_string()
response = api_client.post(Routes.base, json={"name": recipe_name}, headers=admin_user.token)
response = api_client.post(api_routes.recipes, json={"name": recipe_name}, headers=admin_user.token)
assert response.status_code == 201
recipe = api_client.get(Routes.base + f"/{recipe_name}", headers=admin_user.token).json()
recipe = api_client.get(api_routes.recipes + f"/{recipe_name}", headers=admin_user.token).json()
assert recipe["userId"] == admin_user.user_id
assert recipe["groupId"] == admin_user.group_id
@ -22,10 +18,10 @@ def test_ownership_on_new_with_admin(api_client: TestClient, admin_user: TestUse
def test_ownership_on_new_with_user(api_client: TestClient, g2_user: TestUser):
recipe_name = random_string()
response = api_client.post(Routes.base, json={"name": recipe_name}, headers=g2_user.token)
response = api_client.post(api_routes.recipes, json={"name": recipe_name}, headers=g2_user.token)
assert response.status_code == 201
response = api_client.get(Routes.base + f"/{recipe_name}", headers=g2_user.token)
response = api_client.get(api_routes.recipes + f"/{recipe_name}", headers=g2_user.token)
assert response.status_code == 200
@ -38,9 +34,9 @@ def test_ownership_on_new_with_user(api_client: TestClient, g2_user: TestUser):
def test_get_all_only_includes_group_recipes(api_client: TestClient, unique_user: TestUser):
for _ in range(5):
recipe_name = random_string()
response = api_client.post(Routes.base, json={"name": recipe_name}, headers=unique_user.token)
response = api_client.post(api_routes.recipes, json={"name": recipe_name}, headers=unique_user.token)
response = api_client.get(Routes.base, headers=unique_user.token)
response = api_client.get(api_routes.recipes, headers=unique_user.token)
assert response.status_code == 200
@ -56,14 +52,14 @@ def test_get_all_only_includes_group_recipes(api_client: TestClient, unique_user
def test_unique_slug_by_group(api_client: TestClient, unique_user: TestUser, g2_user: TestUser) -> None:
create_data = {"name": random_string()}
response = api_client.post(Routes.base, json=create_data, headers=unique_user.token)
response = api_client.post(api_routes.recipes, json=create_data, headers=unique_user.token)
assert response.status_code == 201
response = api_client.post(Routes.base, json=create_data, headers=g2_user.token)
response = api_client.post(api_routes.recipes, json=create_data, headers=g2_user.token)
assert response.status_code == 201
# Try to create a recipe again with the same name and check that the name was incremented
response = api_client.post(Routes.base, json=create_data, headers=g2_user.token)
response = api_client.post(api_routes.recipes, json=create_data, headers=g2_user.token)
assert response.status_code == 201
assert response.json() == create_data["name"] + "-1"
@ -73,20 +69,20 @@ def test_user_locked_recipe(api_client: TestClient, user_tuple: list[TestUser])
# Setup Recipe
recipe_name = random_string()
response = api_client.post(Routes.base, json={"name": recipe_name}, headers=usr_1.token)
response = api_client.post(api_routes.recipes, json={"name": recipe_name}, headers=usr_1.token)
assert response.status_code == 201
# Get Recipe
response = api_client.get(Routes.base + f"/{recipe_name}", headers=usr_1.token)
response = api_client.get(api_routes.recipes + f"/{recipe_name}", headers=usr_1.token)
assert response.status_code == 200
recipe = response.json()
# Lock Recipe
recipe["settings"]["locked"] = True
response = api_client.put(Routes.base + f"/{recipe_name}", json=recipe, headers=usr_1.token)
response = api_client.put(api_routes.recipes + f"/{recipe_name}", json=recipe, headers=usr_1.token)
# Try To Update Recipe with User 2
response = api_client.put(Routes.base + f"/{recipe_name}", json=recipe, headers=usr_2.token)
response = api_client.put(api_routes.recipes + f"/{recipe_name}", json=recipe, headers=usr_2.token)
assert response.status_code == 403
@ -95,15 +91,15 @@ def test_other_user_cant_lock_recipe(api_client: TestClient, user_tuple: list[Te
# Setup Recipe
recipe_name = random_string()
response = api_client.post(Routes.base, json={"name": recipe_name}, headers=usr_1.token)
response = api_client.post(api_routes.recipes, json={"name": recipe_name}, headers=usr_1.token)
assert response.status_code == 201
# Get Recipe
response = api_client.get(Routes.base + f"/{recipe_name}", headers=usr_2.token)
response = api_client.get(api_routes.recipes + f"/{recipe_name}", headers=usr_2.token)
assert response.status_code == 200
recipe = response.json()
# Lock Recipe
recipe["settings"]["locked"] = True
response = api_client.put(Routes.base + f"/{recipe_name}", json=recipe, headers=usr_2.token)
response = api_client.put(api_routes.recipes + f"/{recipe_name}", json=recipe, headers=usr_2.token)
assert response.status_code == 403

View file

@ -1,27 +1,21 @@
from typing import Generator
import pytest
import sqlalchemy
from fastapi.testclient import TestClient
from mealie.repos.repository_factory import AllRepositories
from mealie.schema.recipe.recipe_share_token import RecipeShareTokenSave
from tests.utils import api_routes
from tests.utils.factories import random_string
from tests.utils.fixture_schemas import TestUser
class Routes:
base = "/api/shared/recipes"
create_recipes = "/api/recipes"
@staticmethod
def item(item_id: str):
return f"{Routes.base}/{item_id}"
@pytest.fixture(scope="function")
def slug(api_client: TestClient, unique_user: TestUser, database: AllRepositories) -> str:
def slug(api_client: TestClient, unique_user: TestUser, database: AllRepositories) -> Generator[str, None, None]:
payload = {"name": random_string(length=20)}
response = api_client.post(Routes.create_recipes, json=payload, headers=unique_user.token)
response = api_client.post(api_routes.recipes, json=payload, headers=unique_user.token)
assert response.status_code == 201
response_data = response.json()
@ -50,7 +44,7 @@ def test_recipe_share_tokens_get_all(
tokens.append(token)
# Get All Tokens
response = api_client.get(Routes.base, headers=unique_user.token)
response = api_client.get(api_routes.shared_recipes, headers=unique_user.token)
assert response.status_code == 200
response_data = response.json()
@ -72,7 +66,7 @@ def test_recipe_share_tokens_get_all_with_id(
)
tokens.append(token)
response = api_client.get(Routes.base + "?recipe_id=" + str(recipe.id), headers=unique_user.token)
response = api_client.get(api_routes.shared_recipes + "?recipe_id=" + str(recipe.id), headers=unique_user.token)
assert response.status_code == 200
response_data = response.json()
@ -92,10 +86,12 @@ def test_recipe_share_tokens_create_and_get_one(
"recipeId": str(recipe.id),
}
response = api_client.post(Routes.base, json=payload, headers=unique_user.token)
response = api_client.post(api_routes.shared_recipes, json=payload, headers=unique_user.token)
assert response.status_code == 201
response = api_client.get(Routes.item(response.json()["id"]), json=payload, headers=unique_user.token)
response = api_client.get(
api_routes.shared_recipes_item_id(response.json()["id"]), json=payload, headers=unique_user.token
)
assert response.status_code == 200
response_data = response.json()
@ -116,7 +112,7 @@ def test_recipe_share_tokens_delete_one(
)
# Delete Token
response = api_client.delete(Routes.item(token.id), headers=unique_user.token)
response = api_client.delete(api_routes.shared_recipes_item_id(token.id), headers=unique_user.token)
assert response.status_code == 200
# Get Token

View file

@ -5,7 +5,7 @@ from fastapi.testclient import TestClient
from mealie.schema.recipe.recipe import Recipe
from mealie.schema.recipe.recipe_step import IngredientReferences
from tests.utils import jsonify, routes
from tests.utils import api_routes, jsonify
from tests.utils.fixture_schemas import TestUser
@ -13,7 +13,6 @@ def test_associate_ingredient_with_step(api_client: TestClient, unique_user: Tes
recipe: Recipe = random_recipe
# Associate an ingredient with a step
steps = {} # key=step_id, value=ingredient_id
for idx, step in enumerate(recipe.recipe_instructions):
@ -26,7 +25,7 @@ def test_associate_ingredient_with_step(api_client: TestClient, unique_user: Tes
steps[idx] = [str(ingredient.reference_id) for ingredient in ingredients]
response = api_client.put(
routes.recipes.Recipe.item(recipe.slug),
api_routes.recipes_slug(recipe.slug),
json=jsonify(recipe.dict()),
headers=unique_user.token,
)
@ -35,8 +34,7 @@ def test_associate_ingredient_with_step(api_client: TestClient, unique_user: Tes
# Get Recipe and check that the ingredient is associated with the step
response = api_client.get(routes.recipes.Recipe.item(recipe.slug), headers=unique_user.token)
response = api_client.get(api_routes.recipes_slug(recipe.slug), headers=unique_user.token)
assert response.status_code == 200
data: dict = json.loads(response.text)

View file

@ -2,18 +2,11 @@ import pytest
from fastapi.testclient import TestClient
from mealie.schema.recipe.recipe_ingredient import CreateIngredientUnit
from tests.utils import api_routes
from tests.utils.factories import random_bool, random_string
from tests.utils.fixture_schemas import TestUser
class Routes:
base = "/api/units"
@staticmethod
def item(item_id: int) -> str:
return f"{Routes.base}/{item_id}"
@pytest.fixture(scope="function")
def unit(api_client: TestClient, unique_user: TestUser):
data = CreateIngredientUnit(
@ -24,13 +17,13 @@ def unit(api_client: TestClient, unique_user: TestUser):
use_abbreviation=random_bool(),
).dict(by_alias=True)
response = api_client.post(Routes.base, json=data, headers=unique_user.token)
response = api_client.post(api_routes.units, json=data, headers=unique_user.token)
assert response.status_code == 201
yield response.json()
response = api_client.delete(Routes.item(response.json()["id"]), headers=unique_user.token)
response = api_client.delete(api_routes.units_item_id(response.json()["id"]), headers=unique_user.token)
def test_create_unit(api_client: TestClient, unique_user: TestUser):
@ -39,12 +32,12 @@ def test_create_unit(api_client: TestClient, unique_user: TestUser):
description=random_string(10),
).dict(by_alias=True)
response = api_client.post(Routes.base, json=data, headers=unique_user.token)
response = api_client.post(api_routes.units, json=data, headers=unique_user.token)
assert response.status_code == 201
def test_read_unit(api_client: TestClient, unit: dict, unique_user: TestUser):
response = api_client.get(Routes.item(unit["id"]), headers=unique_user.token)
response = api_client.get(api_routes.units_item_id(unit["id"]), headers=unique_user.token)
assert response.status_code == 200
as_json = response.json()
@ -67,7 +60,7 @@ def test_update_unit(api_client: TestClient, unit: dict, unique_user: TestUser):
"useAbbreviation": not unit["useAbbreviation"],
}
response = api_client.put(Routes.item(unit["id"]), json=update_data, headers=unique_user.token)
response = api_client.put(api_routes.units_item_id(unit["id"]), json=update_data, headers=unique_user.token)
assert response.status_code == 200
as_json = response.json()
@ -82,9 +75,9 @@ def test_update_unit(api_client: TestClient, unit: dict, unique_user: TestUser):
def test_delete_unit(api_client: TestClient, unit: dict, unique_user: TestUser):
item_id = unit["id"]
response = api_client.delete(Routes.item(item_id), headers=unique_user.token)
response = api_client.delete(api_routes.units_item_id(item_id), headers=unique_user.token)
assert response.status_code == 200
response = api_client.get(Routes.item(item_id), headers=unique_user.token)
response = api_client.get(api_routes.units_item_id(item_id), headers=unique_user.token)
assert response.status_code == 404

View file

@ -3,29 +3,29 @@ import json
from fastapi.testclient import TestClient
from pytest import fixture
from tests.utils.app_routes import AppRoutes
from tests.utils import api_routes
@fixture
def long_live_token(api_client: TestClient, api_routes: AppRoutes, admin_token):
def long_live_token(api_client: TestClient, admin_token):
response = api_client.post(api_routes.users_api_tokens, json={"name": "Test Fixture Token"}, headers=admin_token)
assert response.status_code == 201
return {"Authorization": f"Bearer {json.loads(response.text).get('token')}"}
def test_api_token_creation(api_client: TestClient, api_routes: AppRoutes, admin_token):
def test_api_token_creation(api_client: TestClient, admin_token):
response = api_client.post(api_routes.users_api_tokens, json={"name": "Test API Token"}, headers=admin_token)
assert response.status_code == 201
def test_use_token(api_client: TestClient, api_routes: AppRoutes, long_live_token):
def test_use_token(api_client: TestClient, long_live_token):
response = api_client.get(api_routes.users, headers=long_live_token)
assert response.status_code == 200
def test_delete_token(api_client: TestClient, api_routes: AppRoutes, admin_token):
def test_delete_token(api_client: TestClient, admin_token):
response = api_client.delete(api_routes.users_api_tokens_token_id(1), headers=admin_token)
assert response.status_code == 200

View file

@ -1,20 +1,13 @@
from fastapi.testclient import TestClient
from tests import data as test_data
from tests.utils import api_routes
from tests.utils.fixture_schemas import TestUser
class Routes:
def get_user_image(user_id: str, file_name: str = "profile.webp") -> str:
return f"/api/media/users/{user_id}/{file_name}"
def user_image(user_id: str) -> str:
return f"/api/users/{user_id}/image"
def test_user_get_image(api_client: TestClient, unique_user: TestUser):
# Get the user's image
response = api_client.get(Routes.get_user_image(str(unique_user.user_id)))
response = api_client.get(api_routes.media_users_user_id_file_name(str(unique_user.user_id), "profile.webp"))
assert response.status_code == 200
# Ensure that the returned value is a valid image
@ -25,9 +18,11 @@ def test_user_update_image(api_client: TestClient, unique_user: TestUser):
image = {"profile": test_data.images_test_image_1.read_bytes()}
# Update the user's image
response = api_client.post(Routes.user_image(str(unique_user.user_id)), files=image, headers=unique_user.token)
response = api_client.post(
api_routes.users_id_image(str(unique_user.user_id)), files=image, headers=unique_user.token
)
assert response.status_code == 200
# Request the image again
response = api_client.get(Routes.get_user_image(str(unique_user.user_id)))
response = api_client.get(api_routes.media_users_user_id_file_name(str(unique_user.user_id), "profile.webp"))
assert response.status_code == 200

View file

@ -5,11 +5,11 @@ from fastapi.testclient import TestClient
from mealie.core.config import get_app_settings
from mealie.repos.repository_factory import AllRepositories
from mealie.services.user_services.user_service import UserService
from tests.utils.app_routes import AppRoutes
from tests.utils import api_routes
from tests.utils.fixture_schemas import TestUser
def test_failed_login(api_client: TestClient, api_routes: AppRoutes):
def test_failed_login(api_client: TestClient):
settings = get_app_settings()
form_data = {"username": settings.DEFAULT_EMAIL, "password": "WRONG_PASSWORD"}
@ -18,7 +18,7 @@ def test_failed_login(api_client: TestClient, api_routes: AppRoutes):
assert response.status_code == 401
def test_superuser_login(api_client: TestClient, api_routes: AppRoutes, admin_token):
def test_superuser_login(api_client: TestClient, admin_token):
settings = get_app_settings()
form_data = {"username": settings.DEFAULT_EMAIL, "password": settings.DEFAULT_PASSWORD}
@ -33,7 +33,7 @@ def test_superuser_login(api_client: TestClient, api_routes: AppRoutes, admin_to
return {"Authorization": f"Bearer {new_token}"}
def test_user_token_refresh(api_client: TestClient, api_routes: AppRoutes, admin_user: TestUser):
def test_user_token_refresh(api_client: TestClient, admin_user: TestUser):
response = api_client.post(api_routes.auth_refresh, headers=admin_user.token)
response = api_client.get(api_routes.users_self, headers=admin_user.token)
assert response.status_code == 200
@ -44,17 +44,16 @@ def test_user_lockout_after_bad_attemps(api_client: TestClient, unique_user: Tes
if the user has more than 5 bad login attempts the user will be locked out for 4 hours
This only applies if there is a user in the database with the same username
"""
routes = AppRoutes()
settings = get_app_settings()
for _ in range(settings.SECURITY_MAX_LOGIN_ATTEMPTS):
form_data = {"username": unique_user.email, "password": "bad_password"}
response = api_client.post(routes.auth_token, form_data)
response = api_client.post(api_routes.auth_token, form_data)
assert response.status_code == 401
valid_data = {"username": unique_user.email, "password": unique_user.password}
response = api_client.post(routes.auth_token, valid_data)
response = api_client.post(api_routes.auth_token, valid_data)
assert response.status_code == 423
# Cleanup

View file

@ -5,17 +5,11 @@ from fastapi.testclient import TestClient
from mealie.db.db_setup import session_context
from mealie.services.user_services.password_reset_service import PasswordResetService
from tests.utils import api_routes
from tests.utils.factories import random_string
from tests.utils.fixture_schemas import TestUser
class Routes:
base = "/api/users/reset-password"
login = "/api/auth/token"
self = "/api/users/self"
@pytest.mark.parametrize("casing", ["lower", "upper", "mixed"])
def test_password_reset(api_client: TestClient, unique_user: TestUser, casing: str):
cased_email = ""
@ -46,19 +40,19 @@ def test_password_reset(api_client: TestClient, unique_user: TestUser, casing: s
}
# Test successful password reset
response = api_client.post(Routes.base, json=payload)
response = api_client.post(api_routes.users_reset_password, json=payload)
assert response.status_code == 200
# Test Login
form_data = {"username": unique_user.email, "password": new_password}
response = api_client.post(Routes.login, form_data)
response = api_client.post(api_routes.auth_token, form_data)
assert response.status_code == 200
# Test Token
new_token = json.loads(response.text).get("access_token")
response = api_client.get(Routes.self, headers={"Authorization": f"Bearer {new_token}"})
response = api_client.get(api_routes.users_self, headers={"Authorization": f"Bearer {new_token}"})
assert response.status_code == 200
# Test successful password reset
response = api_client.post(Routes.base, json=payload)
response = api_client.post(api_routes.users_reset_password, json=payload)
assert response.status_code == 400

View file

@ -4,7 +4,7 @@ from mealie.schema.recipe.recipe import RecipeCategory
from mealie.schema.recipe.recipe_category import CategorySave
from tests import utils
from tests.multitenant_tests.case_abc import ABCMultiTenantTestCase
from tests.utils import routes
from tests.utils import api_routes
class CategoryTestCase(ABCMultiTenantTestCase):
@ -44,7 +44,7 @@ class CategoryTestCase(ABCMultiTenantTestCase):
return g1_item_ids, g2_item_ids
def get_all(self, token: str) -> Response:
return self.client.get(routes.organizers.Categories.base, headers=token)
return self.client.get(api_routes.organizers_categories, headers=token)
def cleanup(self) -> None:
for item in self.items:

View file

@ -3,14 +3,14 @@ from requests import Response
from mealie.schema.recipe.recipe_ingredient import IngredientFood, SaveIngredientFood
from tests import utils
from tests.multitenant_tests.case_abc import ABCMultiTenantTestCase
from tests.utils import routes
from tests.utils import api_routes
class FoodsTestCase(ABCMultiTenantTestCase):
items: list[IngredientFood]
def seed_action(self, group_id: str) -> set[int]:
food_ids: set[int] = set()
def seed_action(self, group_id: str) -> set[str]:
food_ids: set[str] = set()
for _ in range(10):
food = self.database.ingredient_foods.create(
SaveIngredientFood(
@ -25,8 +25,8 @@ class FoodsTestCase(ABCMultiTenantTestCase):
return food_ids
def seed_multi(self, group1_id: str, group2_id: str) -> tuple[set[str], set[str]]:
g1_item_ids = set()
g2_item_ids = set()
g1_item_ids: set[str] = set()
g2_item_ids: set[str] = set()
for group_id, item_ids in [(group1_id, g1_item_ids), (group2_id, g2_item_ids)]:
for _ in range(10):
@ -43,7 +43,7 @@ class FoodsTestCase(ABCMultiTenantTestCase):
return g1_item_ids, g2_item_ids
def get_all(self, token: str) -> Response:
return self.client.get(routes.recipes.Foods.base, headers=token)
return self.client.get(api_routes.foods, headers=token)
def cleanup(self) -> None:
for item in self.items:

Some files were not shown because too many files have changed in this diff Show more