1
0
Fork 0
mirror of https://github.com/mealie-recipes/mealie.git synced 2025-08-05 13:35:23 +02:00

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

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