diff --git a/main.py b/main.py index de56560..af25e4e 100644 --- a/main.py +++ b/main.py @@ -30,9 +30,9 @@ async def root()->dict: def create_dirs(): dirs_to_create=("./DB", - "./upload", - "./upload_bad", - "./upload_finished") + "./uploads/upload", + "./uploads/upload_bad", + "./uploads/upload_finished") for x in dirs_to_create: Path(x).mkdir(parents=True, exist_ok=True) \ No newline at end of file diff --git a/makefile b/makefile index 4c82c3d..ec68e8c 100644 --- a/makefile +++ b/makefile @@ -75,7 +75,7 @@ allure: ## Generate allure report .PHONY: coverage coverage: ## Run pytest coverage - ${VENV} pytest --cov=src tests/ + ${VENV} pytest --cov=src tests/ --cov-report=term-missing .PHONY: clear clear: ## Delete old test results diff --git a/poetry.lock b/poetry.lock index 5484c4f..3ad2723 100644 --- a/poetry.lock +++ b/poetry.lock @@ -98,7 +98,7 @@ version = "4.14.2" description = "High-level concurrency and networking framework on top of asyncio or Trio" optional = false python-versions = ">=3.10" -groups = ["main"] +groups = ["main", "dev"] files = [ {file = "anyio-4.14.2-py3-none-any.whl", hash = "sha256:9f505dda5ac9f0c8309b5e8bd445a8c2bf7246f3ce950121e45ea15bc41d1494"}, {file = "anyio-4.14.2.tar.gz", hash = "sha256:cfa139f3ed1a23ee8f88a145ddb5ac7605b8bbfd8592baacd7ce3d8bb4313c7f"}, @@ -703,12 +703,34 @@ version = "0.16.0" description = "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1" optional = false python-versions = ">=3.8" -groups = ["main"] +groups = ["main", "dev"] files = [ {file = "h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86"}, {file = "h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1"}, ] +[[package]] +name = "httpcore" +version = "1.0.9" +description = "A minimal low-level HTTP client." +optional = false +python-versions = ">=3.8" +groups = ["dev"] +files = [ + {file = "httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55"}, + {file = "httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8"}, +] + +[package.dependencies] +certifi = "*" +h11 = ">=0.16" + +[package.extras] +asyncio = ["anyio (>=4.0,<5.0)"] +http2 = ["h2 (>=3,<5)"] +socks = ["socksio (==1.*)"] +trio = ["trio (>=0.22.0,<1.0)"] + [[package]] name = "httpie" version = "3.2.4" @@ -737,6 +759,32 @@ setuptools = "*" dev = ["Jinja2", "flake8", "flake8-comprehensions", "flake8-deprecated", "flake8-mutable", "flake8-tuple", "pyopenssl", "pytest", "pytest-cov", "pytest-httpbin (>=0.0.6)", "pytest-mock", "pyyaml", "responses", "twine", "werkzeug (<2.1.0)", "wheel"] test = ["pytest", "pytest-httpbin (>=0.0.6)", "pytest-mock", "responses", "werkzeug (<2.1.0)"] +[[package]] +name = "httpx" +version = "0.28.1" +description = "The next generation HTTP client." +optional = false +python-versions = ">=3.8" +groups = ["dev"] +files = [ + {file = "httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad"}, + {file = "httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc"}, +] + +[package.dependencies] +anyio = "*" +certifi = "*" +httpcore = "==1.*" +idna = "*" +socksio = {version = "==1.*", optional = true, markers = "extra == \"socks\""} + +[package.extras] +brotli = ["brotli ; platform_python_implementation == \"CPython\"", "brotlicffi ; platform_python_implementation != \"CPython\""] +cli = ["click (==8.*)", "pygments (==2.*)", "rich (>=10,<14)"] +http2 = ["h2 (>=3,<5)"] +socks = ["socksio (==1.*)"] +zstd = ["zstandard (>=0.18.0)"] + [[package]] name = "idna" version = "3.18" @@ -1844,6 +1892,24 @@ urllib3 = ">=1.26,<3" socks = ["PySocks (>=1.5.6,!=1.5.7)"] use-chardet-on-py3 = ["chardet (>=3.0.2,<8)"] +[[package]] +name = "requests-async" +version = "0.2.4" +description = "Simple async HTTP client with requests-like interface, powered by httpx" +optional = false +python-versions = ">=3.7" +groups = ["dev"] +files = [ + {file = "requests_async-0.2.4-py3-none-any.whl", hash = "sha256:a967efb84eb03a2053a847b1bfbac5917df8100d101368d883e20ae9ab15f7a2"}, + {file = "requests_async-0.2.4.tar.gz", hash = "sha256:7eaa42cbfe4d0f1a5f1ef78625c625248cac5c5323afcbd76e7a2a26b85b56b9"}, +] + +[package.dependencies] +httpx = {version = ">=0.23.0", extras = ["socks"]} + +[package.extras] +dev = ["pytest (>=7.0.0)", "pytest-asyncio (>=0.21.0)", "pytest-cov (>=4.0.0)"] + [[package]] name = "requests-toolbelt" version = "1.0.0" @@ -1942,6 +2008,18 @@ files = [ {file = "six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81"}, ] +[[package]] +name = "socksio" +version = "1.0.0" +description = "Sans-I/O implementation of SOCKS4, SOCKS4A, and SOCKS5." +optional = false +python-versions = ">=3.6" +groups = ["dev"] +files = [ + {file = "socksio-1.0.0-py3-none-any.whl", hash = "sha256:95dc1f15f9b34e8d7b16f06d74b8ccf48f609af32ab33c608d08761c5dcbb1f3"}, + {file = "socksio-1.0.0.tar.gz", hash = "sha256:f88beb3da5b5c38b9890469de67d0cb0f9d494b78b106ca1845f96c10b91c4ac"}, +] + [[package]] name = "sqlalchemy" version = "2.0.51" @@ -2185,4 +2263,4 @@ files = [ [metadata] lock-version = "2.1" python-versions = ">=3.13" -content-hash = "6881b7672e5e0ed6a48d6416f117209ba1d0aefaf3b14db1ccec48360ebc22cb" +content-hash = "e1edf156eafb0e85fb3c090f3f17595ef56216f6bb9a2881f553619a19d83f3f" diff --git a/pyproject.toml b/pyproject.toml index 0ae8685..b404a05 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -22,7 +22,7 @@ dependencies = [ "python-jose (>=3.5.0,<4.0.0)", "python-multipart (>=0.0.32,<0.0.33)", "aiosqlite (>=0.22.1,<0.23.0)", - "greenlet (>=3.5.4,<4.0.0)" + "greenlet (>=3.5.4,<4.0.0)", ] [tool.poetry.group.dev.dependencies] @@ -33,6 +33,7 @@ allure-pytest = ">=2.16.0,<3.0.0" ipython = ">=9.15.0,<10.0.0" httpie = ">=3.2.4,<4.0.0" pytest-asyncio = ">=1.4.0,<2.0.0" +requests-async = ">=0.2.4,<0.3.0" [build-system] requires = ["poetry-core>=2.0.0,<3.0.0"] @@ -40,7 +41,7 @@ build-backend = "poetry.core.masonry.api" [tool.coverage.run] omit = [ - "*/models/*", + # "*/models/*", "*/migrations/*", "*/database/*", "*/errors/*", diff --git a/pytest.ini b/pytest.ini index d943f13..3916c68 100644 --- a/pytest.ini +++ b/pytest.ini @@ -2,6 +2,7 @@ addopts = -l -v + -s --alluredir=tests/allure-results/reports/ testpaths = tests @@ -12,3 +13,4 @@ markers= smoke: smoke tests asyncio_mode = auto +asyncio_default_fixture_loop_scope = function \ No newline at end of file diff --git a/src/database/users/crud.py b/src/database/users/crud.py index 6dd4ec2..de6b43a 100644 --- a/src/database/users/crud.py +++ b/src/database/users/crud.py @@ -1,6 +1,6 @@ from uuid import UUID -from sqlalchemy import select, update +from sqlalchemy import delete, select, update from sqlalchemy.ext.asyncio import async_sessionmaker from src.models.database_models.model import ( @@ -71,7 +71,7 @@ class UsersCrudActions: await session.flush() return UserOutDB.model_validate(new_user) - async def delete_user(self, user_email:str)->bool|None: + async def delete_user_soft(self, user_email:str)->bool|None: async with self.Session() as session, session.begin(): @@ -84,7 +84,20 @@ class UsersCrudActions: response.status=False return True - async def update_user(self, user_email:str, data:dict)->UserOutDB|None: + + async def delete_user_hard(self, user_email:str)->bool|None: + + async with self.Session() as session, session.begin(): + + query=delete(User).where(User.email == user_email).returning(User) + response=(await session.scalars(query)).one_or_none() + + if response is None: + return None + + return True + + async def update_user_partially(self, user_email:str, data:dict)->UserOutDB|None: async with self.Session() as session, session.begin(): diff --git a/src/models/configs_read/env.py b/src/models/configs_read/env.py index 2667b4c..3c9eea1 100644 --- a/src/models/configs_read/env.py +++ b/src/models/configs_read/env.py @@ -12,4 +12,4 @@ class Env(Base): model_config=SettingsConfigDict(env_file="configs/.env", extra=None) -env_settings=Env() \ No newline at end of file +env_settings=Env() # type: ignore[call-arg] \ No newline at end of file diff --git a/src/service/users_crud/users_crud.py b/src/service/users_crud/users_crud.py index 16e4ac7..2889337 100644 --- a/src/service/users_crud/users_crud.py +++ b/src/service/users_crud/users_crud.py @@ -1,3 +1,5 @@ +import asyncio + from src.database.users.crud import UsersCrudActions from src.errors.http_errors.errors import Errors from src.models.pydantic_models.model import UserCreate, UserOut, UserUpdate @@ -12,6 +14,14 @@ class CrudService: self.hash_service=HashService() + async def _plain_to_hash(self, user_data:dict)->dict: + + user_data["hashed_password"]=user_data.pop("plain_password") + user_data["hashed_password"]= await asyncio.to_thread(self.hash_service.plain_to_hash, user_data["hashed_password"]) + + return user_data + + async def get_user_by_email(self, email:str)->UserOut: user_entity=await self.crud_db_actions.get_user_by_email(email) @@ -25,8 +35,7 @@ class CrudService: user_data=UserCreate.model_dump(data) - user_data["hashed_password"]=user_data.pop("plain_password") - user_data["hashed_password"]=self.hash_service.plain_to_hash(user_data["hashed_password"]) + user_data=await self._plain_to_hash(user_data) user_entity=await self.crud_db_actions.create_user(user_data) @@ -35,14 +44,21 @@ class CrudService: return UserOut.model_validate(user_entity) - async def delete_user(self, email:str)->bool: + async def delete_user_soft(self, email:str)->bool: - user_entity=await self.crud_db_actions.delete_user(email) + user_entity=await self.crud_db_actions.delete_user_soft(email) if not user_entity: raise self.errors.not_found_error(detail="User not found") return user_entity + async def delete_user_hard(self, email:str, current_user:UserOut)->bool: + + user_entity=await self.crud_db_actions.delete_user_hard(email) + + if not user_entity: + raise self.errors.not_found_error(detail="User not found") + return user_entity async def update_user(self, email:str, data:UserUpdate)->UserOut: @@ -52,10 +68,9 @@ class CrudService: raise self.errors.bad_request_error(detail="User info to update can not be empty") if user_data.get("plain_password"): - user_data["hashed_password"]=user_data.pop("plain_password") - user_data["hashed_password"]=self.hash_service.plain_to_hash(user_data["hashed_password"]) + user_data=await self._plain_to_hash(user_data) - user_entity=await self.crud_db_actions.update_user(email, user_data) + user_entity=await self.crud_db_actions.update_user_partially(email, user_data) if not user_entity: raise self.errors.not_found_error(detail="User not found") diff --git a/src/web/protected_routes/protected_user_action_routes.py b/src/web/protected_routes/protected_user_action_routes.py index 0fd2087..440852f 100644 --- a/src/web/protected_routes/protected_user_action_routes.py +++ b/src/web/protected_routes/protected_user_action_routes.py @@ -14,11 +14,15 @@ async def get_current_user_by_email(email:str, crud:CrudService=Depends(crud_ser async def create_user(data:UserCreate, crud:CrudService=Depends(crud_service), current_user=Depends(get_current_user))->UserOut: #noqa: B008 return await crud.create_user(data) -@router.post("/delete_user") -async def delete_user(email:str, crud:CrudService=Depends(crud_service), current_user=Depends(get_current_user))->bool: #noqa: B008 - return await crud.delete_user(email) +@router.post("/delete_user_soft") +async def delete_user_soft(email:str, crud:CrudService=Depends(crud_service), current_user=Depends(get_current_user))->bool: #noqa: B008 + return await crud.delete_user_soft(email) -@router.post("/patch_user") +@router.post("/delete_user_hard") +async def delete_user_hard(email:str, crud:CrudService=Depends(crud_service), current_user=Depends(get_current_user))->bool: #noqa: B008 + return await crud.delete_user_hard(email, current_user) + +@router.patch("/patch_user") async def patch_user(email:str, data:UserUpdate, crud:CrudService=Depends(crud_service), current_user=Depends(get_current_user))->UserOut: #noqa: B008 return await crud.update_user(email, data) \ No newline at end of file diff --git a/tests/e2e/conftest.py b/tests/e2e/conftest.py index e69de29..917ae2a 100644 --- a/tests/e2e/conftest.py +++ b/tests/e2e/conftest.py @@ -0,0 +1,75 @@ +from uuid import uuid4 + +import pytest_asyncio +import requests_async +from pydantic_settings import BaseSettings, SettingsConfigDict + + +class Env(BaseSettings): + HOST:str + PORT:str + TEST_USERNAME:str + TEST_PASSWORD:str + + model_config=SettingsConfigDict(env_file="configs/.e2e.env", extra=None) + +e2e_settings=Env() # type: ignore[call-arg] + +class MySession(requests_async.AsyncSession): + def __init__(self): + super().__init__() + self.headers = {} + self.token = None + + async def request(self, method:str, url:str, **kwargs): + if self.token: + self.headers['Authorization'] = f"Bearer {self.token}" + kwargs.setdefault('headers', self.headers) + return await super().request(method, url, **kwargs) + +@pytest_asyncio.fixture(scope="function", autouse=True) +async def auth_fixture(): + + payload = {"username": e2e_settings.TEST_USERNAME, "password": e2e_settings.TEST_PASSWORD} + url = f'http://{e2e_settings.HOST}:{e2e_settings.PORT}' + + async with MySession() as session: + response = await session.post(url + "/protected/token", data=payload) + response.raise_for_status() + session.token = response.json()["access_token"] + yield session + + +@pytest_asyncio.fixture(scope="function") +async def test_user_fixture(request, auth_fixture: MySession): + + url=f"http://{e2e_settings.HOST}:{e2e_settings.PORT}" + test_id=uuid4() + + direct_permission_param, group_param = request.param + + new_user_record={ + "first_name":f"TEST_{test_id}", + "last_name":f"TEST_{test_id}", + "middle_name":f"TEST_{test_id}", + "email":f"TEST_{test_id}@d.d", + "plain_password":"Test1234!", + "direct_permissions":direct_permission_param, + "group":group_param + } + response=await auth_fixture.post(f"{url}/user/create_user", json=new_user_record) + response.raise_for_status() + + + async with MySession() as session: + + payload={"username": new_user_record.get("email"), "password": new_user_record.get("plain_password")} + + response = await session.post(url + "/protected/token", data=payload) + response.raise_for_status() + session.token = response.json()["access_token"] + + yield (session, new_user_record) + + response=await auth_fixture.post(f"{url}/user/delete_user_hard", params={"email":new_user_record.get("email")}) + response.raise_for_status() \ No newline at end of file diff --git a/tests/e2e/test_users_crud.py b/tests/e2e/test_users_crud.py new file mode 100644 index 0000000..d30ca64 --- /dev/null +++ b/tests/e2e/test_users_crud.py @@ -0,0 +1,284 @@ + +from uuid import uuid4 + +import allure +import pytest +from httpx import HTTPStatusError + +from tests.e2e.conftest import MySession, e2e_settings + + +@pytest.mark.integra +class TestCrud: + + @pytest.mark.parametrize("test_user_fixture", [(["admin"], ["admin_group"])], indirect=True) + async def test_get_user_by_email_positive(self,test_user_fixture)->None: + + session, new_user_record=test_user_fixture + + with allure.step("Get user by email"): + + email = new_user_record.get("email") #get email from the fixture in yield sector + + target_url=f"http://{e2e_settings.HOST}:{e2e_settings.PORT}" + response = await session.get(f"{target_url}/user/get_by_email",params={"email":email}) + response.raise_for_status() + response=response.json() + + with allure.step("Validate response"): + + assert response.get("email")==email + assert "TEST_" in response.get("first_name") + assert "TEST_" in response.get("last_name") + assert "TEST_" in response.get("middle_name") + assert response.get("direct_permissions") != [] + assert response.get("group") != [] + assert not response.get("hashed_password") or not response.get("plain_password") or not response.get("password") + + + @pytest.mark.parametrize("email, expected_status", [ + pytest.param("test@test.test", 404, id="non_existed_email"), + pytest.param("test",404, id="wrong_email"), + pytest.param("@d", 404, id="wrong_email") + ]) + async def test_get_user_by_email_negative(self, email:str, expected_status:int, auth_fixture:MySession)->None: + + with allure.step("Get user by email"): + target_url = f"http://{e2e_settings.HOST}:{e2e_settings.PORT}" + + with pytest.raises(HTTPStatusError) as exc_info: + response = await auth_fixture.get(f"{target_url}/user/get_by_email", params={"email": email}) + response.raise_for_status() + + assert exc_info.value.response.status_code == expected_status + + + @pytest.mark.parametrize("new_user_record",[ + pytest.param({ "first_name":"TEST", + "last_name":"TEST", + "middle_name":"TEST", + "email":f"TEST_{uuid4()}@d.d", + "plain_password":"Test1234!", + "direct_permissions":[], + "group":[]}, id="Positive_user_creation_with_all_the_fields"), + + pytest.param({ "first_name":"TEST", + "last_name":"TEST", + "middle_name":"TEST", + "email":f"TEST_{uuid4()}@d.d", + "plain_password":"Test1234!", + "direct_permissions":["WRONG_PERMISSIONS"], + "group":["WRONG_GROUP"]},id="Positive_wrong_permissions"), + ]) + async def test_create_delete_user_hard_positive(self, new_user_record:dict,auth_fixture:MySession)->None: + + with allure.step("Setting target_url"): + + target_url=f"http://{e2e_settings.HOST}:{e2e_settings.PORT}" + + with allure.step("Create new test user and check for the new user"): + + response=await auth_fixture.post(f"{target_url}/user/create_user", json=new_user_record) + response.raise_for_status() + + try: + with allure.step("Check for the new user"): + + response = await auth_fixture.get(f"{target_url}/user/get_by_email",params={"email":new_user_record.get("email")}) + response.raise_for_status() + response=response.json() + + assert response.get("email")==new_user_record["email"] + assert response.get("first_name")==new_user_record["first_name"] + assert response.get("last_name")==new_user_record["last_name"] + assert response.get("middle_name")==new_user_record["middle_name"] + assert response.get("direct_permissions") == new_user_record["direct_permissions"] or response.get("direct_permissions") == [] + assert response.get("group") == new_user_record["group"] or response.get("group") == [] + assert not response.get("hashed_password") or not response.get("plain_password") or not response.get("password") + + finally: + with allure.step("delete new user"): + response=await auth_fixture.post(f"{target_url}/user/delete_user_hard", params={"email":new_user_record["email"]}) + response.raise_for_status() + + + @pytest.mark.parametrize("new_user_record, expected_status", [ + pytest.param({ "first_name":"TEST", + "last_name":"TEST", + "middle_name":"TEST", + "email":"WRONGEMAIL", + "plain_password":"Test1234!", + "direct_permissions":[], + "group":[]},422,id="Non_existed_email"), + + pytest.param({ "first_name":"TEST", + "last_name":"TEST", + "middle_name":"TEST", + "email":"TEST1@d.d", + "plain_password":"1234", + "direct_permissions":[], + "group":[]},422,id="Wrong_password"), + + pytest.param({ "first_name":"TEST", + "email":"TEST1@d.d", + "plain_password":"Test1234!", + },422,id="Not_all_the_fields"), + ]) + async def test_create_user_negative(self, new_user_record:dict, auth_fixture:MySession, expected_status:int): + + with allure.step("Preparing data to create new user negative"): + + user_created=False + target_url=f"http://{e2e_settings.HOST}:{e2e_settings.PORT}" + + try: + with allure.step("Create new test user and check for the new user"): + + response=await auth_fixture.post(f"{target_url}/user/create_user", json=new_user_record) + if response.status_code < 400: + user_created = True + + with pytest.raises(HTTPStatusError) as exc_info: + response.raise_for_status() + + assert exc_info.value.response.status_code == expected_status + + finally: + if user_created: + with allure.step("delete new user"): + + response = await auth_fixture.post( + f"{target_url}/user/delete_user_hard", + params={"email": new_user_record["email"]} + ) + response.raise_for_status() + + + @pytest.mark.parametrize("new_user_record",[ + pytest.param({ "first_name":"TEST", + "last_name":"TEST", + "middle_name":"TEST", + "email":f"TEST_{uuid4()}@d.d", + "plain_password":"Test1234!", + "direct_permissions":[], + "group":[]}, id="Positive_user_delete_soft"), + ]) + async def test_user_create_delete_soft_positive(self, new_user_record:dict, auth_fixture:MySession)->None: + with allure.step("Setting target_url"): + + target_url=f"http://{e2e_settings.HOST}:{e2e_settings.PORT}" + + with allure.step("Create new test user and check for the new user"): + + response=await auth_fixture.post(f"{target_url}/user/create_user", json=new_user_record) + response.raise_for_status() + + try: + with allure.step("Check for the new user"): + + response = await auth_fixture.get(f"{target_url}/user/get_by_email",params={"email":new_user_record.get("email")}) + response.raise_for_status() + + with allure.step("Delete user soft"): + response=await auth_fixture.post(f"{target_url}/user/delete_user_soft", params={"email":new_user_record["email"]}) + response.raise_for_status() + + finally: + with allure.step("delete new user"): + response=await auth_fixture.post(f"{target_url}/user/delete_user_hard", params={"email":new_user_record["email"]}) + response.raise_for_status() + + @pytest.mark.parametrize("email, expected_status, ",[ + pytest.param("Test", 404,id="Wrong_email") + ]) + async def test_user_delete_soft_negative(self, email:str,expected_status:int, auth_fixture:MySession)->None: + + with allure.step("Delete user soft"): + + target_url=f"http://{e2e_settings.HOST}:{e2e_settings.PORT}" + + with pytest.raises(HTTPStatusError) as exc_info: + + response=await auth_fixture.post(f"{target_url}/user/delete_user_soft", params={"email":email}) + response.raise_for_status() + + assert exc_info.value.response.status_code == expected_status + + + @pytest.mark.parametrize("email, expected_status, ",[ + pytest.param("Test", 404,id="Wrong_email") + ]) + async def test_user_delete_hard_negative(self, email:str,expected_status:int, auth_fixture:MySession)->None: + + with allure.step("Delete user hard"): + + target_url=f"http://{e2e_settings.HOST}:{e2e_settings.PORT}" + + with pytest.raises(HTTPStatusError) as exc_info: + + response=await auth_fixture.post(f"{target_url}/user/delete_user_soft", params={"email":email}) + response.raise_for_status() + + assert exc_info.value.response.status_code == expected_status + + + + @pytest.mark.parametrize("test_user_fixture", [ + ([], []) + ], indirect=True) + @pytest.mark.parametrize("user_record_to_update",[ + pytest.param({"first_name": "Test_New"},id="Positive_user_update_partially") + ]) + async def test_user_update_partially_positive(self, test_user_fixture, user_record_to_update:dict)->None: + + session, new_user_record=test_user_fixture + + with allure.step("Setting target_url"): + + target_url=f"http://{e2e_settings.HOST}:{e2e_settings.PORT}" + + with allure.step("Update user"): + response= await session.patch(f"{target_url}/user/patch_user", json=user_record_to_update, params={"email":new_user_record["email"]}) + response.raise_for_status() + + with allure.step("Check for the updated user"): + response=await session.get(f"{target_url}/user/get_by_email", params={"email":new_user_record["email"]}) + response.raise_for_status() + response=response.json() + + actual_permissions = [item.get("direct_permissions") for item in response.get("direct_permissions")] #unpacking json like {group:[{},{}]} + actual_groups =[item.get("group") for item in response.get("group")] + + + assert response.get("email")==new_user_record["email"] + assert response.get("first_name")==user_record_to_update["first_name"] + assert response.get("last_name")==new_user_record["last_name"] + assert response.get("middle_name")==new_user_record["middle_name"] + assert actual_permissions == new_user_record["direct_permissions"] or actual_permissions == [None] + assert actual_groups == new_user_record["group"] or actual_groups == [None] + assert not response.get("hashed_password") or not response.get("plain_password") or not response.get("password") + + + + @pytest.mark.parametrize("test_user_fixture", [ + ([], []) + ], indirect=True) + @pytest.mark.parametrize("user_record_to_update, expected_exception, expected_status",[ + pytest.param({"plain_password": "Wrong_pass"},HTTPStatusError,422,id="Wrong_password"), + pytest.param({"email": "Wrong_email"},HTTPStatusError,422,id="Wrong_email"), + pytest.param({},HTTPStatusError, 400,id="Positive_user_update_nothing") + ]) + async def test_user_update_partially_negative(self, test_user_fixture, user_record_to_update:dict, expected_exception, expected_status:int)->None: + + session, new_user_record=test_user_fixture + + with allure.step("Setting target_url"): + + target_url=f"http://{e2e_settings.HOST}:{e2e_settings.PORT}" + + with allure.step("Update user"), pytest.raises(expected_exception) as exc_info: + + response= await session.patch(f"{target_url}/user/patch_user", json=user_record_to_update, params={"email":new_user_record["email"]}) + response.raise_for_status() + + assert exc_info.value.response.status_code == expected_status diff --git a/tests/integrated/test_auth.py b/tests/integrated/test_auth.py index ac27a59..d8efa94 100644 --- a/tests/integrated/test_auth.py +++ b/tests/integrated/test_auth.py @@ -43,12 +43,12 @@ class TestAuth: assert test_result.group==user_data.group - @pytest.mark.parametrize("user_data, uuid, expected_exception",[ - pytest.param(SimpleNamespace(first_name="test",last_name="test",middle_name="test",email="d@d.d",direct_permissions=[],group=[],status=False), uuid4(), HTTPException, id="false_status"), - pytest.param(SimpleNamespace(first_name="test",last_name="test",middle_name="test",email="d@d.d",direct_permissions=[],group=[],status=True),1234, HTTPException, id="wrong_id"), - pytest.param(SimpleNamespace(status=True),uuid4(), ValidationError,id="empty_model_data") + @pytest.mark.parametrize("user_data, uuid, expected_exception,expected_status",[ + pytest.param(SimpleNamespace(first_name="test",last_name="test",middle_name="test",email="d@d.d",direct_permissions=[],group=[],status=False), uuid4(), HTTPException,401, id="false_status"), + pytest.param(SimpleNamespace(first_name="test",last_name="test",middle_name="test",email="d@d.d",direct_permissions=[],group=[],status=True),1234, HTTPException,401, id="wrong_id"), + pytest.param(SimpleNamespace(status=True),uuid4(), ValidationError,None,id="empty_model_data") ]) - async def test_get_current_user_negative(self,current_user_service:CurrentUserService, jwt_service:JwtService, monkeypatch, user_data:SimpleNamespace, expected_exception, uuid)->None: + async def test_get_current_user_negative(self,current_user_service:CurrentUserService, jwt_service:JwtService, monkeypatch, user_data:SimpleNamespace,expected_exception, expected_status:int, uuid)->None: with allure.step("create token"): @@ -58,10 +58,11 @@ class TestAuth: monkeypatch.setattr(current_user_service.crud_db_actions, "get_user_by_id", AsyncMock(return_value=user_data)) - with allure.step("test get_current_user_with_fake_token"), pytest.raises(expected_exception): - + with allure.step("test get_current_user_with_fake_token"), pytest.raises(expected_exception) as exc_info: await current_user_service.get_current_user(token) - + + if expected_exception is HTTPException: + assert exc_info.value.status_code == expected_status @pytest.mark.parametrize("user_data, form_data_email,form_data_password",[ pytest.param(SimpleNamespace(id=uuid4(),hashed_password="1234", first_name="test",last_name="test",middle_name="test",email="d@d.d",direct_permissions=[],group=[],status=True), "d@d.d", "1234", id="correct_data"), @@ -87,12 +88,12 @@ class TestAuth: assert len(parts_b)==3 - @pytest.mark.parametrize("user_data, form_data_email,form_data_password, expected_exception",[ - pytest.param(SimpleNamespace(id=uuid4(),hashed_password="1234", first_name="test",last_name="test",middle_name="test",email="d@d.d",direct_permissions=[],group=[],status=True), "d@d.d", "wrong_password", HTTPException, id="wrong_password"), - pytest.param(SimpleNamespace(id=uuid4(),hashed_password="1234", first_name="test",last_name="test",middle_name="test",email="d@d.d",direct_permissions=[],group=[],status=False), "d@d.d", "1234",HTTPException, id="false_status"), - pytest.param(SimpleNamespace(id=1234,hashed_password="1234", first_name="test",last_name="test",middle_name="test",email="d@d.d",direct_permissions=[],group=[],status=True), "d@d.d", "1234",ValidationError, id="wrong_id"), + @pytest.mark.parametrize("user_data, form_data_email,form_data_password, expected_exception, expected_status",[ + pytest.param(SimpleNamespace(id=uuid4(),hashed_password="1234", first_name="test",last_name="test",middle_name="test",email="d@d.d",direct_permissions=[],group=[],status=True), "d@d.d", "wrong_password", HTTPException,401, id="wrong_password"), + pytest.param(SimpleNamespace(id=uuid4(),hashed_password="1234", first_name="test",last_name="test",middle_name="test",email="d@d.d",direct_permissions=[],group=[],status=False), "d@d.d", "1234",HTTPException,401, id="false_status"), + pytest.param(SimpleNamespace(id=1234,hashed_password="1234", first_name="test",last_name="test",middle_name="test",email="d@d.d",direct_permissions=[],group=[],status=True), "d@d.d", "1234",ValidationError,None, id="wrong_id"), ]) - async def test_login_negative(self, current_user_service:CurrentUserService, user_data:SimpleNamespace, jwt_service:JwtService, monkeypatch, requests, hash_service:HashService, form_data_email:str, form_data_password:str, expected_exception): + async def test_login_negative(self, current_user_service:CurrentUserService, user_data:SimpleNamespace, jwt_service:JwtService, monkeypatch, requests, hash_service:HashService, form_data_email:str, form_data_password:str, expected_exception, expected_status:int): with allure.step("patching db call functions"): @@ -103,10 +104,12 @@ class TestAuth: fake_request = requests - with allure.step("test login_with_fake_data"), pytest.raises(expected_exception): + with allure.step("test login_with_fake_data"), pytest.raises(expected_exception) as exc_info: await current_user_service.login(form_data_email, form_data_password,fake_request) - + + if expected_exception is HTTPException: + assert exc_info.value.status_code == expected_status async def test_logout_positive(self, jwt_service:JwtService, monkeypatch, current_user_service:CurrentUserService)->None: @@ -124,12 +127,12 @@ class TestAuth: status=await current_user_service.logout(token[0]) assert status is True - @pytest.mark.parametrize("jti,db_result, expected_exception",[ - pytest.param(None, True, HTTPException, id="jti_none"), - pytest.param(1234, True, HTTPException, id="jti_int"), - pytest.param(str(uuid4()), False, HTTPException, id="db_result_none"), + @pytest.mark.parametrize("jti,db_result, expected_exception, expected_status",[ + pytest.param(None, True, HTTPException,401, id="jti_none"), + pytest.param(1234, True, HTTPException,401, id="jti_int"), + pytest.param(str(uuid4()), False, HTTPException,404,id="db_result_none"), ]) - async def test_logout_negative(self, jwt_service:JwtService, monkeypatch, current_user_service:CurrentUserService, expected_exception, jti, db_result)->None: + async def test_logout_negative(self, jwt_service:JwtService, monkeypatch, current_user_service:CurrentUserService, expected_exception, jti, db_result, expected_status:int)->None: with allure.step("patching db call functions"): @@ -145,9 +148,12 @@ class TestAuth: token=await fake_create_refresh_token({"sub":str(uuid4()), "jti":jti, "token_type":"refresh", "exp":datetime.now(UTC)+timedelta(days=45)}) - with allure.step("test logout with fake data"), pytest.raises(expected_exception): + with allure.step("test logout with fake data"), pytest.raises(expected_exception) as exc_info: await current_user_service.logout(token) + + if expected_exception is HTTPException: + assert exc_info.value.status_code==expected_status @pytest.mark.parametrize("db_result_token, user_data_result_db", [ @@ -186,15 +192,15 @@ class TestAuth: assert new_access_token!=token assert new_refresh_token!=token - @pytest.mark.parametrize("db_result_token, user_data_result_db, update_result, fake_token_data,expected_exception", [ - pytest.param(SimpleNamespace(is_revoked=True,user_id="123", expires_at=datetime.now(UTC)+timedelta(days=15)),SimpleNamespace(status=True),False,{"sub":str(uuid4()), "jti":str(uuid4()), "token_type":"refresh", "exp":datetime.now(UTC)+timedelta(days=45)}, HTTPException,id="false_revoke_status"), - pytest.param(SimpleNamespace(is_revoked=False,user_id="123", expires_at=datetime.now(UTC)+timedelta(days=15)),SimpleNamespace(status=True),True,{"sub":str(uuid4()), "token_type":"refresh", "exp":datetime.now(UTC)+timedelta(days=45)}, HTTPException, id="jti_missing"), - pytest.param(None,SimpleNamespace(status=True),True,{"sub":str(uuid4()), "jti":str(uuid4()),"token_type":"refresh", "exp":datetime.now(UTC)+timedelta(days=45)}, HTTPException, id="token_missing"), - pytest.param(SimpleNamespace(is_revoked=False,user_id="123", expires_at=datetime.now(UTC)+timedelta(days=15)),SimpleNamespace(status=False),True,{"sub":str(uuid4()), "jti":str(uuid4()), "token_type":"refresh", "exp":datetime.now(UTC)+timedelta(days=45)}, HTTPException,id="false_user_status"), - pytest.param(SimpleNamespace(is_revoked=False, user_id="123",expires_at=datetime.now(UTC)+timedelta(days=15)),None,True,{"sub":str(uuid4()), "jti":str(uuid4()), "token_type":"refresh", "exp":datetime.now(UTC)+timedelta(days=45)}, HTTPException,id="user_missing"), - pytest.param(SimpleNamespace(is_revoked=False,user_id="123", expires_at=datetime.now(UTC)-timedelta(days=15)),SimpleNamespace(status=True),True,{"sub":str(uuid4()), "jti":str(uuid4()), "token_type":"refresh", "exp":datetime.now(UTC)+timedelta(days=45)}, HTTPException,id="wrong_exp") + @pytest.mark.parametrize("db_result_token, user_data_result_db, update_result, fake_token_data,expected_exception, expected_status", [ + pytest.param(SimpleNamespace(is_revoked=True,user_id="123", expires_at=datetime.now(UTC)+timedelta(days=15)),SimpleNamespace(status=True),False,{"sub":str(uuid4()), "jti":str(uuid4()), "token_type":"refresh", "exp":datetime.now(UTC)+timedelta(days=45)}, HTTPException,404,id="false_revoke_status"), + pytest.param(SimpleNamespace(is_revoked=False,user_id="123", expires_at=datetime.now(UTC)+timedelta(days=15)),SimpleNamespace(status=True),True,{"sub":str(uuid4()), "token_type":"refresh", "exp":datetime.now(UTC)+timedelta(days=45)}, HTTPException,401, id="jti_missing"), + pytest.param(None,SimpleNamespace(status=True),True,{"sub":str(uuid4()), "jti":str(uuid4()),"token_type":"refresh", "exp":datetime.now(UTC)+timedelta(days=45)}, HTTPException, 404,id="token_missing"), + pytest.param(SimpleNamespace(is_revoked=False,user_id="123", expires_at=datetime.now(UTC)+timedelta(days=15)),SimpleNamespace(status=False),True,{"sub":str(uuid4()), "jti":str(uuid4()), "token_type":"refresh", "exp":datetime.now(UTC)+timedelta(days=45)}, HTTPException,401,id="false_user_status"), + pytest.param(SimpleNamespace(is_revoked=False, user_id="123",expires_at=datetime.now(UTC)+timedelta(days=15)),None,True,{"sub":str(uuid4()), "jti":str(uuid4()), "token_type":"refresh", "exp":datetime.now(UTC)+timedelta(days=45)}, HTTPException,404,id="user_missing"), + pytest.param(SimpleNamespace(is_revoked=False,user_id="123", expires_at=datetime.now(UTC)-timedelta(days=15)),SimpleNamespace(status=True),True,{"sub":str(uuid4()), "jti":str(uuid4()), "token_type":"refresh", "exp":datetime.now(UTC)+timedelta(days=45)}, HTTPException,401,id="wrong_exp") ]) - async def test_refresh_token_negative(self, monkeypatch, current_user_service:CurrentUserService, db_result_token, requests, jwt_service:JwtService,user_data_result_db, expected_exception, fake_token_data, update_result)->None: + async def test_refresh_token_negative(self, monkeypatch, current_user_service:CurrentUserService, db_result_token, requests, jwt_service:JwtService,user_data_result_db, expected_exception, fake_token_data, update_result, expected_status:int)->None: with allure.step("patching db call functions"): monkeypatch.setattr(current_user_service.jwt_db_actions,"get_token_by_id", AsyncMock(return_value=db_result_token)) monkeypatch.setattr(current_user_service.jwt_db_actions, "revoke_all", AsyncMock(return_value=True)) @@ -211,5 +217,8 @@ class TestAuth: with allure.step("create fake refresh token"): token=await fake_create_refresh_token(fake_token_data) - with allure.step("test refresh token with fake data"), pytest.raises(expected_exception): - await current_user_service.refresh_token(token, fake_request) \ No newline at end of file + with allure.step("test refresh token with fake data"), pytest.raises(expected_exception) as exc_info: + await current_user_service.refresh_token(token, fake_request) + + if expected_exception is HTTPException: + assert exc_info.value.status_code==expected_status \ No newline at end of file diff --git a/tests/unit/test_jwt.py b/tests/unit/test_jwt.py index be8e0e5..614d3f0 100644 --- a/tests/unit/test_jwt.py +++ b/tests/unit/test_jwt.py @@ -25,15 +25,16 @@ class TestJwt: - @pytest.mark.parametrize("data, expected_exception",[ - pytest.param("", AttributeError,id="not_dict_value"), - pytest.param({"sub":""},HTTPException, id="empty_value"), - pytest.param({"":""},HTTPException, id="empty_key_value") + @pytest.mark.parametrize("data, expected_exception, expected_status",[ + pytest.param("", AttributeError,None,id="not_dict_value"), + pytest.param({"sub":""},HTTPException,401,id="empty_value"), + pytest.param({"":""},HTTPException,401,id="empty_key_value") ]) - async def test_access_create_negative(self, jwt_service:JwtService, data:dict, expected_exception)->None: - with allure.step("create invalid access token"),pytest.raises(expected_exception): + async def test_access_create_negative(self, jwt_service:JwtService, data:dict, expected_exception, expected_status:int)->None: + with allure.step("create invalid access token"),pytest.raises(expected_exception) as exc_info: await jwt_service.create_access_token(data) - + if expected_exception is HTTPException: + assert expected_status == exc_info.value.status_code @pytest.mark.parametrize("data", [ @@ -76,22 +77,25 @@ class TestJwt: assert payload.get("exp") assert payload.get("token_type") - @pytest.mark.parametrize("data, expected_exception", [ - pytest.param({"sub": "123", "exp":datetime.now(UTC)-timedelta(minutes=15), "token_type":"access"}, HTTPException, id="wrong_exp"), - pytest.param({"sub": "123", "exp":datetime.now(UTC)+timedelta(minutes=15)}, HTTPException, id="no_token_type"), - pytest.param({"sub": "123", "token_type":"access"}, HTTPException,id="no_exp"), - pytest.param({}, HTTPException, id="empty_data"), - pytest.param("", AttributeError, id="not_dict_data") + @pytest.mark.parametrize("data, expected_exception, expected_status", [ + pytest.param({"sub": "123", "exp":datetime.now(UTC)-timedelta(minutes=15), "token_type":"access"}, HTTPException,401, id="wrong_exp"), + pytest.param({"sub": "123", "exp":datetime.now(UTC)+timedelta(minutes=15)}, HTTPException, 401,id="no_token_type"), + pytest.param({"sub": "123", "token_type":"access"}, HTTPException,401,id="no_exp"), + pytest.param({}, HTTPException, 401,id="empty_data"), + pytest.param("", AttributeError, None,id="not_dict_data") ]) - async def test_jwt_decode_invalid(self,jwt_service:JwtService, expected_exception, data, monkeypatch)->None: + async def test_jwt_decode_invalid(self,jwt_service:JwtService, expected_exception, data, monkeypatch, expected_status)->None: with allure.step("patch a create token function"): async def fake_create_access_token(data:dict)->str: return jwt.encode(data, env_settings.SECRET_KEY, env_settings.ALGORITHM) monkeypatch.setattr(jwt_service, "create_access_token", fake_create_access_token) - with allure.step("create and decode invalid token"), pytest.raises(expected_exception): + with allure.step("create and decode invalid token"), pytest.raises(expected_exception) as exc_info: fake_token=await jwt_service.create_access_token(data) await jwt_service.jwt_decode(fake_token) + + if expected_exception is HTTPException: + assert expected_status == exc_info.value.status_code @pytest.mark.parametrize("time, key, algorithm", [