Spaces:
Sleeping
Sleeping
Praneeth Yerrapragada commited on
Commit ·
b6fbea9
1
Parent(s): 9c3303f
test: setup pytest | pytest for users apis
Browse filesFiles changed (11)
- app/engine/postgresdb.py+14-2
- app/model/user.py+60-11
- config/index.py-2
- main.py+15-25
- poetry.lock+167-1
- pyproject.toml+7-1
- tests/conftest.py+32-43
- tests/pytest.ini+3-1
- tests/test_main.pyDeleted-9
- tests/test_users.pyAdded+40
- tests/test_users_crud.pyDeleted-49
4 unmodified lines56789108 unmodified lines1920212223242534 unmodified lines60616263646566674 unmodified linesfrom sqlalchemy.ext.asyncio import (AsyncConnection,AsyncSession,async_sessionmaker,create_async_engine,)8 unmodified linesclass PostgresDatabase:def __init__(self, host: str, engine_kwargs: dict[str, Any] = {}):self._engine = create_async_engine(host, **engine_kwargs)self._sessionmaker = async_sessionmaker(autocommit=False, bind=self._engine)34 unmodified linesdef get_engine(self):return self._enginepostgresdb = PostgresDatabase(env.SQLALCHEMY_DATABASE_URL, {"echo": True, "future": True})async def get_db_session():4 unmodified lines5678910118 unmodified lines202122232425262728293034 unmodified lines6566676869707172737475767778794 unmodified linesfrom sqlalchemy.ext.asyncio import (AsyncConnection,AsyncSession,AsyncEngine,async_sessionmaker,create_async_engine,)8 unmodified linesclass PostgresDatabase:def __init__(self):self._engine: AsyncEngine | None = Noneself._sessionmaker: async_sessionmaker | None = Nonedef init(self, host: str, engine_kwargs: dict[str, Any] = {}):self._engine = create_async_engine(host, **engine_kwargs)self._sessionmaker = async_sessionmaker(autocommit=False, bind=self._engine)34 unmodified linesdef get_engine(self):return self._engine# Used for testingasync def create_all(self, connection: AsyncConnection):await connection.run_sync(Base.metadata.create_all)async def drop_all(self, connection: AsyncConnection):await connection.run_sync(Base.metadata.drop_all)postgresdb = PostgresDatabase()async def get_db_session():
4 unmodified lines56789109 unmodified lines202122232425262728293031323334353637383940414243443 unmodified lines484950515253545556575859604 unmodified linesfrom app.model.base import BaseModelfrom app.engine.postgresdb import Baselogger = logging.getLogger(__name__)9 unmodified linestransactions = relationship("Transaction", back_populates="user")@classmethodasync def create(cls: "type[User]", db: AsyncSession, **kwargs) -> "User":logging.info(f"Creating user: {kwargs}")query = sql.insert(cls).values(**kwargs)users = await db.scalars(query)user = users.first()logging.info(f"User created: {users.first()}")await db.commit()return user@classmethodasync def update(cls: "type[User]", db: AsyncSession, id: int, **kwargs) -> "User":query = sql.update(cls).where(cls.id == id).values(**kwargs).execution_options(synchronize_session="fetch")users = await db.scalars(query)user = users.first()await db.commit()return user@classmethodasync def get(cls: "type[User]", db: AsyncSession, email: str) -> "User":logging.info(f"Getting user: {email}")query = sql.select(cls).where(cls.email == email)logging.info(f"Query: {query}")3 unmodified lines@classmethodasync def delete(cls: "type[User]", db: AsyncSession, email: str) -> "User":query = (sql.update(cls).where(cls.email == email).values(is_deleted=True).execution_options(synchronize_session="fetch"))users = await db.scalars(query)user = users.first()await db.commit()return user4 unmodified lines5678910119 unmodified lines21222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081823 unmodified lines86878889909192939495969798991001011021031041051061071081094 unmodified linesfrom app.model.base import BaseModelfrom app.engine.postgresdb import Basefrom app.schema.index import UserCreate, UserUpdatelogger = logging.getLogger(__name__)9 unmodified linestransactions = relationship("Transaction", back_populates="user")@classmethodasync def create(cls: "type[User]", db: AsyncSession, **kwargs: UserCreate) -> "User":"""Creates a new user in the database.Args:cls (type[User]): The class object representing the User model.db (AsyncSession): The asynchronous session object for interacting with the database.**kwargs (UserCreate): The keyword arguments representing the user's attributes.Returns:User"""print(f"Creating user: {kwargs}")# query = sql.insert(cls).values(**kwargs)user = cls(name=kwargs["name"], email=kwargs["email"], hashed_password=kwargs["hashed_password"])db.add(user)await db.commit()await db.refresh(user)return user@classmethodasync def update(cls: "type[User]", db: AsyncSession, id: int, **kwargs: UserUpdate) -> "User":"""Updates a user in the database with the given ID and keyword arguments.Args:cls (type[User]): The class object representing the User model.db (AsyncSession): The asynchronous session object for interacting with the database.id (int): The ID of the user to update.**kwargs (UserUpdate): The keyword arguments representing the user's attributes to update.Returns:User"""query = sql.update(cls).where(cls.id == id).values(**kwargs).execution_options(synchronize_session="fetch")results = await db.execute(query)user = results.fetchone()await db.commit()return user@classmethodasync def get(cls: "type[User]", db: AsyncSession, email: str) -> "User":"""Retrieves a user from the database based on their email.Args:cls (type[User]): The class object representing the User model.db (AsyncSession): The asynchronous session object for interacting with the database.email (str): The email of the user to retrieve.Returns:User"""logging.info(f"Getting user: {email}")query = sql.select(cls).where(cls.email == email)logging.info(f"Query: {query}")3 unmodified lines@classmethodasync def delete(cls: "type[User]", db: AsyncSession, email: str) -> "User":"""Deletes a user from the database based on their email.Args:cls (type[User]): The class object representing the User model.db (AsyncSession): The asynchronous session object for interacting with the database.email (str): The email of the user to delete.Returns:User"""query = (sql.update(cls).where(cls.email == email).values(is_deleted=True).execution_options(synchronize_session="fetch"))result = await db.execute(query)user = result.fetchone()await db.commit()return user
25 unmodified lines262728293031323334353625 unmodified linesPOSTGRES_USER = os.getenv("POSTGRES_USER")POSTGRES_PASSWORD = os.getenv("POSTGRES_PASSWORD")POSTGRES_DB_NAME = os.getenv("POSTGRES_DB_NAME")POSTGRES_TEST_DB_NAME = os.getenv("POSTGRES_TEST_DB_NAME")POSTGRES_DB_HOST = os.getenv("POSTGRES_DB_HOST")POSTGRES_DB_PORT = os.getenv("POSTGRES_DB_PORT")SQLALCHEMY_DATABASE_URL = f"postgresql+asyncpg://{POSTGRES_USER}:{POSTGRES_PASSWORD}@{POSTGRES_DB_HOST}:{POSTGRES_DB_PORT}/{POSTGRES_DB_NAME}"SQLALCHEMY_TEST_DATABASE_URL = f"postgresql+asyncpg://{POSTGRES_USER}:{POSTGRES_PASSWORD}@{POSTGRES_DB_HOST}:{POSTGRES_DB_PORT}/{POSTGRES_TEST_DB_NAME}"config = Config25 unmodified lines26272829303132333425 unmodified linesPOSTGRES_USER = os.getenv("POSTGRES_USER")POSTGRES_PASSWORD = os.getenv("POSTGRES_PASSWORD")POSTGRES_DB_NAME = os.getenv("POSTGRES_DB_NAME")POSTGRES_DB_HOST = os.getenv("POSTGRES_DB_HOST")POSTGRES_DB_PORT = os.getenv("POSTGRES_DB_PORT")SQLALCHEMY_DATABASE_URL = f"postgresql+asyncpg://{POSTGRES_USER}:{POSTGRES_PASSWORD}@{POSTGRES_DB_HOST}:{POSTGRES_DB_PORT}/{POSTGRES_DB_NAME}"config = Config
14 unmodified lines1516171819202122232425262728293031323334353637383940414243444546474849505152535420 unmodified lines7576777814 unmodified linesfrom app.engine.postgresdb import postgresdbfrom config.index import configlogger = logging.getLogger("uvicorn")def run_migrations(connection, cfg):cfg.attributes["connection"] = connectioncommand.upgrade(cfg, "head")async def run_async_migrations():logger.info("Running migrations...")async_engine = postgresdb.get_engine()async with async_engine.begin() as conn:await conn.run_sync(run_migrations, Config("alembic.ini"))logger.info("Finished running migrations")@asynccontextmanagerasync def lifespan(app_: FastAPI):yieldif postgresdb.get_engine() is not None:await postgresdb.close()init_settings()# init_observability()def init_app():app = FastAPI(lifespan=lifespan)if config.ENVIRONMENT == "dev":logger.warning("Running in development mode - allowing CORS for all origins")app.add_middleware(CORSMiddleware,20 unmodified linesasync def redirect_to_docs():return RedirectResponse(url="/docs")uvicorn.run(app="main:app", host=config.APP_HOST, port=config.APP_PORT, reload=(config.ENVIRONMENT == "dev"))14 unmodified lines15161718192021222324252627282930313233343536373839404142434420 unmodified lines6566676814 unmodified linesfrom app.engine.postgresdb import postgresdbfrom config.index import config as envlogger = logging.getLogger("uvicorn")init_settings()# init_observability()def init_app(init_db: bool = True) -> FastAPI:lifespan = Noneif init_db:postgresdb.init(env.SQLALCHEMY_DATABASE_URL, {"echo": True, "future": True})@asynccontextmanagerasync def lifespan(app: FastAPI):yieldif postgresdb.get_engine() is not None:await postgresdb.close()app = FastAPI(lifespan=lifespan)if env.ENVIRONMENT == "dev":logger.warning("Running in development mode - allowing CORS for all origins")app.add_middleware(CORSMiddleware,20 unmodified linesasync def redirect_to_docs():return RedirectResponse(url="/docs")uvicorn.run(app="main:app", host=env.APP_HOST, port=env.APP_PORT, reload=(env.ENVIRONMENT == "dev"))
1696 unmodified lines169716981699170017011702996 unmodified lines26992700270127022703270437 unmodified lines274227432744274527462747160 unmodified lines2908290929102911291229131296 unmodified lines42104211421242131696 unmodified linesdocs = ["alabaster (==0.7.16)", "autodocsumm (==0.2.12)", "sphinx (==7.3.7)", "sphinx-issues (==4.1.0)", "sphinx-version-warning (==1.1.2)"]tests = ["pytest", "pytz", "simplejson"][[package]]name = "monotonic"version = "1.6"996 unmodified linesdev = ["pre-commit", "tox"]testing = ["pytest", "pytest-benchmark"][[package]]name = "posthog"version = "3.5.0"37 unmodified lines{file = "protobuf-4.25.3.tar.gz", hash = "sha256:25b5d0b42fd000320bd7830b349e3b696435f3b329810427a6bcce6a5492cc5c"},][[package]]name = "pydantic"version = "2.7.2"160 unmodified linesdocs = ["sphinx (>=5.3)", "sphinx-rtd-theme (>=1.0)"]testing = ["coverage (>=6.2)", "hypothesis (>=5.7.1)"][[package]]name = "pytest-xdist"version = "3.6.1"1296 unmodified lines[metadata]lock-version = "2.0"python-versions = "^3.11,<3.12"content-hash = "ea7579f435b0c476a57fe23453277a8e90d2815e0a86efc7ff300a5ddbd434bb"1696 unmodified lines16971698169917001701170217031704170517061707170817091710171117121713171417151716996 unmodified lines2713271427152716271727182719272027212722272327242725272627272728272937 unmodified lines276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895160 unmodified lines3056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830791296 unmodified lines43764377437843791696 unmodified linesdocs = ["alabaster (==0.7.16)", "autodocsumm (==0.2.12)", "sphinx (==7.3.7)", "sphinx-issues (==4.1.0)", "sphinx-version-warning (==1.1.2)"]tests = ["pytest", "pytz", "simplejson"][[package]]name = "mirakuru"version = "2.5.2"description = "Process executor (not only) for tests."optional = falsepython-versions = ">=3.8"files = [{file = "mirakuru-2.5.2-py3-none-any.whl", hash = "sha256:90c2d90a8cf14349b2f33e6db30a16acd855499811e0312e56cf80ceacf2d3e5"},{file = "mirakuru-2.5.2.tar.gz", hash = "sha256:41ca583d355eb7a6cfdc21c1aea549979d685c27b57239b88725434f115a7132"},][package.dependencies]psutil = {version = ">=4.0.0", markers = "sys_platform != \"cygwin\""}[[package]]name = "monotonic"version = "1.6"996 unmodified linesdev = ["pre-commit", "tox"]testing = ["pytest", "pytest-benchmark"][[package]]name = "port-for"version = "0.7.2"description = "Utility that helps with local TCP ports management. It can find an unused TCP localhost port and remember the association."optional = falsepython-versions = ">=3.8"files = [{file = "port-for-0.7.2.tar.gz", hash = "sha256:074f29335130578aa42fef3726985e57d01c15189e509633a8a1b0b7f9226349"},{file = "port_for-0.7.2-py3-none-any.whl", hash = "sha256:16b279ab4f210bad33515c45bd9af0c6e048ab24c3b6bbd9cfc7e451782617df"},][[package]]name = "posthog"version = "3.5.0"37 unmodified lines{file = "protobuf-4.25.3.tar.gz", hash = "sha256:25b5d0b42fd000320bd7830b349e3b696435f3b329810427a6bcce6a5492cc5c"},][[package]]name = "psutil"version = "5.9.8"description = "Cross-platform lib for process and system monitoring in Python."optional = falsepython-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*"files = [{file = "psutil-5.9.8-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:26bd09967ae00920df88e0352a91cff1a78f8d69b3ecabbfe733610c0af486c8"},{file = "psutil-5.9.8-cp27-cp27m-manylinux2010_i686.whl", hash = "sha256:05806de88103b25903dff19bb6692bd2e714ccf9e668d050d144012055cbca73"},{file = "psutil-5.9.8-cp27-cp27m-manylinux2010_x86_64.whl", hash = "sha256:611052c4bc70432ec770d5d54f64206aa7203a101ec273a0cd82418c86503bb7"},{file = "psutil-5.9.8-cp27-cp27mu-manylinux2010_i686.whl", hash = "sha256:50187900d73c1381ba1454cf40308c2bf6f34268518b3f36a9b663ca87e65e36"},{file = "psutil-5.9.8-cp27-cp27mu-manylinux2010_x86_64.whl", hash = "sha256:02615ed8c5ea222323408ceba16c60e99c3f91639b07da6373fb7e6539abc56d"},{file = "psutil-5.9.8-cp27-none-win32.whl", hash = "sha256:36f435891adb138ed3c9e58c6af3e2e6ca9ac2f365efe1f9cfef2794e6c93b4e"},{file = "psutil-5.9.8-cp27-none-win_amd64.whl", hash = "sha256:bd1184ceb3f87651a67b2708d4c3338e9b10c5df903f2e3776b62303b26cb631"},{file = "psutil-5.9.8-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:aee678c8720623dc456fa20659af736241f575d79429a0e5e9cf88ae0605cc81"},{file = "psutil-5.9.8-cp36-abi3-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:8cb6403ce6d8e047495a701dc7c5bd788add903f8986d523e3e20b98b733e421"},{file = "psutil-5.9.8-cp36-abi3-manylinux_2_12_x86_64.manylinux2010_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d06016f7f8625a1825ba3732081d77c94589dca78b7a3fc072194851e88461a4"},{file = "psutil-5.9.8-cp36-cp36m-win32.whl", hash = "sha256:7d79560ad97af658a0f6adfef8b834b53f64746d45b403f225b85c5c2c140eee"},{file = "psutil-5.9.8-cp36-cp36m-win_amd64.whl", hash = "sha256:27cc40c3493bb10de1be4b3f07cae4c010ce715290a5be22b98493509c6299e2"},{file = "psutil-5.9.8-cp37-abi3-win32.whl", hash = "sha256:bc56c2a1b0d15aa3eaa5a60c9f3f8e3e565303b465dbf57a1b730e7a2b9844e0"},{file = "psutil-5.9.8-cp37-abi3-win_amd64.whl", hash = "sha256:8db4c1b57507eef143a15a6884ca10f7c73876cdf5d51e713151c1236a0e68cf"},{file = "psutil-5.9.8-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:d16bbddf0693323b8c6123dd804100241da461e41d6e332fb0ba6058f630f8c8"},{file = "psutil-5.9.8.tar.gz", hash = "sha256:6be126e3225486dff286a8fb9a06246a5253f4c7c53b475ea5f5ac934e64194c"},][package.extras]test = ["enum34", "ipaddress", "mock", "pywin32", "wmi"][[package]]name = "psycopg"version = "3.1.19"description = "PostgreSQL database adapter for Python"optional = falsepython-versions = ">=3.7"files = [{file = "psycopg-3.1.19-py3-none-any.whl", hash = "sha256:dca5e5521c859f6606686432ae1c94e8766d29cc91f2ee595378c510cc5b0731"},{file = "psycopg-3.1.19.tar.gz", hash = "sha256:92d7b78ad82426cdcf1a0440678209faa890c6e1721361c2f8901f0dccd62961"},][package.dependencies]typing-extensions = ">=4.1"tzdata = {version = "*", markers = "sys_platform == \"win32\""}[package.extras]binary = ["psycopg-binary (==3.1.19)"]c = ["psycopg-c (==3.1.19)"]dev = ["black (>=24.1.0)", "codespell (>=2.2)", "dnspython (>=2.1)", "flake8 (>=4.0)", "mypy (>=1.4.1)", "types-setuptools (>=57.4)", "wheel (>=0.37)"]docs = ["Sphinx (>=5.0)", "furo (==2022.6.21)", "sphinx-autobuild (>=2021.3.14)", "sphinx-autodoc-typehints (>=1.12)"]pool = ["psycopg-pool"]test = ["anyio (>=3.6.2,<4.0)", "mypy (>=1.4.1)", "pproxy (>=2.7)", "pytest (>=6.2.5)", "pytest-cov (>=3.0)", "pytest-randomly (>=3.5)"][[package]]name = "psycopg-binary"version = "3.1.19"description = "PostgreSQL database adapter for Python -- C optimisation distribution"optional = falsepython-versions = ">=3.7"files = [{file = "psycopg_binary-3.1.19-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:7204818f05151dd08f8f851defb01972ec9d2cc925608eb0de232563f203f354"},{file = "psycopg_binary-3.1.19-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:6d4e67fd86758dbeac85641419a54f84d74495a8683b58ad5dfad08b7fc37a8f"},{file = "psycopg_binary-3.1.19-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e12173e34b176e93ad2da913de30f774d5119c2d4d4640c6858d2d77dfa6c9bf"},{file = "psycopg_binary-3.1.19-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:052f5193304066318853b4b2e248f523c8f52b371fc4e95d4ef63baee3f30955"},{file = "psycopg_binary-3.1.19-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:29008f3f8977f600b8a7fb07c2e041b01645b08121760609cc45e861a0364dc9"},{file = "psycopg_binary-3.1.19-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7c6a9a651a08d876303ed059c9553df18b3c13c3406584a70a8f37f1a1fe2709"},{file = "psycopg_binary-3.1.19-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:91a645e6468c4f064b7f4f3b81074bdd68fe5aa2b8c5107de15dcd85ba6141be"},{file = "psycopg_binary-3.1.19-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:5c6956808fd5cf0576de5a602243af8e04594b25b9a28675feddc71c5526410a"},{file = "psycopg_binary-3.1.19-cp310-cp310-musllinux_1_1_ppc64le.whl", hash = "sha256:1622ca27d5a7a98f7d8f35e8b146dc7efda4a4b6241d2edf7e076bd6bcecbeb4"},{file = "psycopg_binary-3.1.19-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:a100482950a55228f648bd382bb71bfaff520002f29845274fccbbf02e28bd52"},{file = "psycopg_binary-3.1.19-cp310-cp310-win_amd64.whl", hash = "sha256:955ca8905c0251fc4af7ce0a20999e824a25652f53a558ab548b60969f1f368e"},{file = "psycopg_binary-3.1.19-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:1cf49e91dcf699b8a449944ed898ef1466b39b92720613838791a551bc8f587a"},{file = "psycopg_binary-3.1.19-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:964c307e400c5f33fa762ba1e19853e048814fcfbd9679cc923431adb7a2ead2"},{file = "psycopg_binary-3.1.19-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3433924e1b14074798331dc2bfae2af452ed7888067f2fc145835704d8981b15"},{file = "psycopg_binary-3.1.19-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:00879d4c6be4b3afc510073f48a5e960f797200e261ab3d9bd9b7746a08c669d"},{file = "psycopg_binary-3.1.19-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:34a6997c80f86d3dd80a4f078bb3b200079c47eeda4fd409d8899b883c90d2ac"},{file = "psycopg_binary-3.1.19-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0106e42b481677c41caa69474fe530f786dcef88b11b70000f0e45a03534bc8f"},{file = "psycopg_binary-3.1.19-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:81efe09ba27533e35709905c3061db4dc9fb814f637360578d065e2061fbb116"},{file = "psycopg_binary-3.1.19-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:d312d6dddc18d9c164e1893706269c293cba1923118349d375962b1188dafb01"},{file = "psycopg_binary-3.1.19-cp311-cp311-musllinux_1_1_ppc64le.whl", hash = "sha256:bfd2c734da9950f7afaad5f132088e0e1478f32f042881fca6651bb0c8d14206"},{file = "psycopg_binary-3.1.19-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:8a732610a5a6b4f06dadcf9288688a8ff202fd556d971436a123b7adb85596e2"},{file = "psycopg_binary-3.1.19-cp311-cp311-win_amd64.whl", hash = "sha256:321814a9a3ad785855a821b842aba08ca1b7de7dfb2979a2f0492dca9ec4ae70"},{file = "psycopg_binary-3.1.19-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:4aa0ca13bb8a725bb6d12c13999217fd5bc8b86a12589f28a74b93e076fbb959"},{file = "psycopg_binary-3.1.19-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:469424e354ebcec949aa6aa30e5a9edc352a899d9a68ad7a48f97df83cc914cf"},{file = "psycopg_binary-3.1.19-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b04f5349313529ae1f1c42fe1aa0443faaf50fdf12d13866c2cc49683bfa53d0"},{file = "psycopg_binary-3.1.19-cp312-cp312-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:959feabddc7fffac89b054d6f23f3b3c62d7d3c90cd414a02e3747495597f150"},{file = "psycopg_binary-3.1.19-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e9da624a6ca4bc5f7fa1f03f8485446b5b81d5787b6beea2b4f8d9dbef878ad7"},{file = "psycopg_binary-3.1.19-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c1823221a6b96e38b15686170d4fc5b36073efcb87cce7d3da660440b50077f6"},{file = "psycopg_binary-3.1.19-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:866db42f986298f0cf15d805225eb8df2228bf19f7997d7f1cb5f388cbfc6a0f"},{file = "psycopg_binary-3.1.19-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:738c34657305b5973af6dbb6711b07b179dfdd21196d60039ca30a74bafe9648"},{file = "psycopg_binary-3.1.19-cp312-cp312-musllinux_1_1_ppc64le.whl", hash = "sha256:fb9758473200384a04374d0e0cac6f451218ff6945a024f65a1526802c34e56e"},{file = "psycopg_binary-3.1.19-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:0e991632777e217953ac960726158987da684086dd813ac85038c595e7382c91"},{file = "psycopg_binary-3.1.19-cp312-cp312-win_amd64.whl", hash = "sha256:1d87484dd42c8783c44a30400949efb3d81ef2487eaa7d64d1c54df90cf8b97a"},{file = "psycopg_binary-3.1.19-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:d1d1723d7449c12bb61aca7eb6e0c6ab2863cd8dc0019273cc4d4a1982f84bdb"},{file = "psycopg_binary-3.1.19-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e538a8671005641fa195eab962f85cf0504defbd3b548c4c8fc27102a59f687b"},{file = "psycopg_binary-3.1.19-cp37-cp37m-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c50592bc8517092f40979e4a5d934f96a1737a77724bb1d121eb78b614b30fc8"},{file = "psycopg_binary-3.1.19-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:95f16ae82bc242b76cd3c3e5156441e2bd85ff9ec3a9869d750aad443e46073c"},{file = "psycopg_binary-3.1.19-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:aebd1e98e865e9a28ce0cb2c25b7dfd752f0d1f0a423165b55cd32a431dcc0f4"},{file = "psycopg_binary-3.1.19-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:49cd7af7d49e438a39593d1dd8cab106a1912536c2b78a4d814ebdff2786094e"},{file = "psycopg_binary-3.1.19-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:affebd61aa3b7a8880fd4ac3ee94722940125ff83ff485e1a7c76be9adaabb38"},{file = "psycopg_binary-3.1.19-cp37-cp37m-musllinux_1_1_ppc64le.whl", hash = "sha256:d1bac282f140fa092f2bbb6c36ed82270b4a21a6fc55d4b16748ed9f55e50fdb"},{file = "psycopg_binary-3.1.19-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:1285aa54449e362b1d30d92b2dc042ad3ee80f479cc4e323448d0a0a8a1641fa"},{file = "psycopg_binary-3.1.19-cp37-cp37m-win_amd64.whl", hash = "sha256:6cff31af8155dc9ee364098a328bab688c887c732c66b8d027e5b03818ca0287"},{file = "psycopg_binary-3.1.19-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:d9b689c4a17dd3130791dcbb8c30dbf05602f7c2d56c792e193fb49adc7bf5f8"},{file = "psycopg_binary-3.1.19-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:017518bd2de4851adc826a224fb105411e148ad845e11355edd6786ba3dfedf5"},{file = "psycopg_binary-3.1.19-cp38-cp38-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c35fd811f339a3cbe7f9b54b2d9a5e592e57426c6cc1051632a62c59c4810208"},{file = "psycopg_binary-3.1.19-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:38ed45ec9673709bfa5bc17f140e71dd4cca56d4e58ef7fd50d5a5043a4f55c6"},{file = "psycopg_binary-3.1.19-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:433f1c256108f9e26f480a8cd6ddb0fb37dbc87d7f5a97e4540a9da9b881f23f"},{file = "psycopg_binary-3.1.19-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:ed61e43bf5dc8d0936daf03a19fef3168d64191dbe66483f7ad08c4cea0bc36b"},{file = "psycopg_binary-3.1.19-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:4ae8109ff9fdf1fa0cb87ab6645298693fdd2666a7f5f85660df88f6965e0bb7"},{file = "psycopg_binary-3.1.19-cp38-cp38-musllinux_1_1_ppc64le.whl", hash = "sha256:a53809ee02e3952fae7977c19b30fd828bd117b8f5edf17a3a94212feb57faaf"},{file = "psycopg_binary-3.1.19-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:9d39d5ffc151fb33bcd55b99b0e8957299c0b1b3e5a1a5f4399c1287ef0051a9"},{file = "psycopg_binary-3.1.19-cp38-cp38-win_amd64.whl", hash = "sha256:e14bc8250000921fcccd53722f86b3b3d1b57db901e206e49e2ab2afc5919c2d"},{file = "psycopg_binary-3.1.19-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:cd88c5cea4efe614d5004fb5f5dcdea3d7d59422be796689e779e03363102d24"},{file = "psycopg_binary-3.1.19-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:621a814e60825162d38760c66351b4df679fd422c848b7c2f86ad399bff27145"},{file = "psycopg_binary-3.1.19-cp39-cp39-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:46e50c05952b59a214e27d3606f6d510aaa429daed898e16b8a37bfbacc81acc"},{file = "psycopg_binary-3.1.19-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:03354a9db667c27946e70162cb0042c3929154167f3678a30d23cebfe0ad55b5"},{file = "psycopg_binary-3.1.19-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:703c2f3b79037581afec7baa2bdbcb0a1787f1758744a7662099b0eca2d721cb"},{file = "psycopg_binary-3.1.19-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:6469ebd9e93327e9f5f36dcf8692fb1e7aeaf70087c1c15d4f2c020e0be3a891"},{file = "psycopg_binary-3.1.19-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:85bca9765c04b6be90cb46e7566ffe0faa2d7480ff5c8d5e055ac427f039fd24"},{file = "psycopg_binary-3.1.19-cp39-cp39-musllinux_1_1_ppc64le.whl", hash = "sha256:a836610d5c75e9cff98b9fdb3559c007c785c09eaa84a60d5d10ef6f85f671e8"},{file = "psycopg_binary-3.1.19-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:ef8de7a1d9fb3518cc6b58e3c80b75a824209ad52b90c542686c912db8553dad"},{file = "psycopg_binary-3.1.19-cp39-cp39-win_amd64.whl", hash = "sha256:76fcd33342f38e35cd6b5408f1bc117d55ab8b16e5019d99b6d3ce0356c51717"},][[package]]name = "pydantic"version = "2.7.2"160 unmodified linesdocs = ["sphinx (>=5.3)", "sphinx-rtd-theme (>=1.0)"]testing = ["coverage (>=6.2)", "hypothesis (>=5.7.1)"][[package]]name = "pytest-postgresql"version = "6.0.0"description = "Postgresql fixtures and fixture factories for Pytest."optional = falsepython-versions = ">=3.8"files = [{file = "pytest-postgresql-6.0.0.tar.gz", hash = "sha256:6a4d8e600a2eef273f3c0e846cd0b2ea577282e252de29b4ca854bfb929bb682"},{file = "pytest_postgresql-6.0.0-py3-none-any.whl", hash = "sha256:f14272bffad16a74d9a63f4cc828f243a12ae92995e236b68fd53154760e6a5a"},][package.dependencies]mirakuru = "*"port-for = ">=0.6.0"psycopg = ">=3.0.0"pytest = ">=6.2"setuptools = "*"[[package]]name = "pytest-xdist"version = "3.6.1"1296 unmodified lines[metadata]lock-version = "2.0"python-versions = "^3.11,<3.12"content-hash = "83b595a344a5db9263207b122c781f07b9cd8ac777e04fb1b743e3e3ce5016e1"
2 unmodified lines345678924 unmodified lines34353637383940414243442 unmodified linesname = "app"version = "0.1.0"description = ""authors = [ "Marcus Schiesser <mail@marcusschiesser.de>" ]readme = "README.md"package-mode = false24 unmodified linesalembic = "^1.13.1"asyncpg = "^0.29.0"asyncio = "^3.4.3"[tool.poetry.dependencies.uvicorn]extras = [ "standard" ]version = "^0.23.2"[tool.poetry.dependencies.llama-index-agent-openai]version = "0.2.2"2 unmodified lines345678924 unmodified lines34353637383940414243444546474849502 unmodified linesname = "app"version = "0.1.0"description = ""authors = [ "Praneeth Yerrapragada, Patrick Alexis" ]readme = "README.md"package-mode = false24 unmodified linesalembic = "^1.13.1"asyncpg = "^0.29.0"asyncio = "^3.4.3"pytest-postgresql = "^6.0.0"psycopg-binary = "^3.1.19"[tool.poetry.dependencies.uvicorn]extras = [ "standard" ]version = "^0.23.2"[tool.poetry.dependencies.sqlalchemy]extras = [ "asyncio" ]version = "^2.0.30"[tool.poetry.dependencies.llama-index-agent-openai]version = "0.2.2"
9 unmodified lines1011121314151617181920212223242 unmodified lines2728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485869 unmodified linesfrom alembic.script import ScriptDirectoryfrom config.index import config as settingsfrom app.engine.postgresdb import Base, get_db_session, postgresdb as sessionmanagerfrom main import app as actual_appfrom asyncpg import Connectionfrom fastapi.testclient import TestClient@pytest.fixture(autouse=True)def app():with ExitStack():yield actual_app@pytest.fixture2 unmodified linesyield c@pytest.fixture(scope="session")def event_loop(request):loop = asyncio.get_event_loop_policy().new_event_loop()yield looploop.close()def run_migrations(connection: Connection):config = Config("alembic.ini")config.set_main_option("script_location", "app/migration")config.set_main_option("sqlalchemy.url", settings.SQLALCHEMY_TEST_DATABASE_URL)script = ScriptDirectory.from_config(config)def upgrade(rev, context):return script._upgrade_revs("head", rev)context = MigrationContext.configure(connection, opts={"target_metadata": Base.metadata, "fn": upgrade})with context.begin_transaction():with Operations.context(context):context.run_migrations()@pytest.fixture(scope="session", autouse=True)async def setup_database():# Run alembic migrations on test DBasync with sessionmanager.connect() as connection:await connection.run_sync(run_migrations)yield# Teardownawait sessionmanager.close()# Each test function is a clean slate@pytest.fixture(scope="function", autouse=True)async def transactional_session():async with sessionmanager.session() as session:try:await session.begin()yield sessionfinally:await session.rollback() # Rolls back the outer transaction@pytest.fixture(scope="function")async def db_session(transactional_session):yield transactional_session@pytest.fixture(scope="function", autouse=True)async def session_override(app, db_session):async def get_db_session_override():yield db_session[0]app.dependency_overrides[get_db_session] = get_db_session_override9 unmodified lines101112131415161718192021222324252627282930313233342 unmodified lines3738394041424344454647484950515253545556575859606162636465666768697071727374759 unmodified linesfrom alembic.script import ScriptDirectoryfrom config.index import config as settingsfrom app.engine.postgresdb import Base, get_db_session, postgresdb as sessionmanagerfrom main import init_appfrom asyncpg import Connectionfrom fastapi.testclient import TestClientfrom pytest_postgresql import factoriesfrom pytest_postgresql.factories.noprocess import postgresql_noprocfrom pytest_postgresql.janitor import DatabaseJanitorfrom sqlalchemy.testing.entities import ComparableEntityfrom config.index import config as envtest_db = factories.postgresql_proc(dbname="test_db", port=5433)@pytest.fixture(autouse=True)def app():with ExitStack():# Don't initialize database connection.# This is because we want to initialize the database connection manually, so that we can create the test database.yield init_app(init_db=False)@pytest.fixture2 unmodified linesyield c@pytest.mark.asyncio(scope="session")def event_loop(request):loop = asyncio.get_event_loop_policy().new_event_loop()yield looploop.close()@pytest.fixture(scope="function", autouse=True)async def connection_test(test_db, event_loop):pg_host = test_db.hostpg_port = test_db.portpg_user = test_db.userpg_db = test_db.dbnamepg_password = test_db.passwordwith DatabaseJanitor(pg_user, pg_host, pg_port, pg_db, test_db.version, pg_password):connection_str = f"postgresql+asyncpg://{pg_user}:@{pg_host}:{pg_port}/{pg_db}"sessionmanager.init(connection_str)yieldawait sessionmanager.close()@pytest.fixture(scope="function", autouse=True)async def create_tables(connection_test):async with sessionmanager.connect() as connection:await sessionmanager.drop_all(connection)await sessionmanager.create_all(connection)@pytest.fixture(scope="function", autouse=True)async def session_override(app, connection_test):async def get_db_session_override():async with sessionmanager.session() as session:yield sessionapp.dependency_overrides[get_db_session] = get_db_session_override
12[pytest]asyncio_mode = auto1234[pytest]asyncio_mode = autotimeout = 60addopts = -vv --disable-warnings --durations=10 --durations-min=1.0
123456789from main import appfrom fastapi.testclient import TestClient
client = TestClient(app)
def test_read_main(): response = client.get("/") assert response.status_code == 20012345678910111213141516171819202122232425262728293031323334353637383940from random import randint
from fastapi.testclient import TestClient
def test_users(client: TestClient) -> None: rand_int = randint(0, 1000) email = f"test{rand_int}@example.com" response = client.get(f"/api/v1/users/{email}") assert response.status_code == 404
response = client.post( "/api/v1/users", json={"email": email, "name": "Full Name Test", "hashed_password": "test"}, ) assert response.status_code == 200 assert response.json().get("email") == email assert response.json().get("name") == "Full Name Test" assert response.json().get("is_deleted") == False
response = client.get(f"/api/v1/users/{email}") assert response.status_code == 200 assert response.json().get("email") == email assert response.json().get("name") == "Full Name Test" assert response.json().get("is_deleted") == False
response = client.put( f"/api/v1/users/{email}", json={"email": email, "name": "Full Name Test 2", "hashed_password": "test"}, ) assert response.status_code == 200 assert response.json().get("email") == email assert response.json().get("name") == "Full Name Test 2" assert response.json().get("is_deleted") == False
response = client.delete(f"/api/v1/users/{email}") assert response.status_code == 200 assert response.json().get("email") == email assert response.json().get("name") == "Full Name Test 2" assert response.json().get("is_deleted") == True12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import jsonfrom httpx import AsyncClientimport pytest
from app.core.config import settings
@pytest.mark.asyncioasync def test_users_crud(httpx_async_client: AsyncClient): # Test CREATE user_data = { "name": "John Doe", "email": "john.doe@example.com", "password": "password123", } response = await httpx_async_client.post( f"{settings.API_V1_STR}/users/", data=json.dumps(user_data), headers={"Content-Type": "application/json"}, ) assert response.status_code == 200 user_id = response.json()["user_id"]
# Test READ response = await httpx_async_client.get(f"{settings.API_V1_STR}/users/{user_id}") assert response.status_code == 200 user = response.json() assert user["name"] == user_data["name"] assert user["email"] == user_data["email"] assert "password" not in user
# Test UPDATE updated_user_data = { "name": "Jane Doe", } response = await httpx_async_client.put( f"{settings.API_V1_STR}/users/{user_id}", data=json.dumps(updated_user_data), headers={"Content-Type": "application/json"}, ) assert response.status_code == 200 updated_user = response.json() assert updated_user["name"] == updated_user_data["name"] assert updated_user["email"] == user_data["email"] assert "password" not in updated_user
# Test DELETE response = await httpx_async_client.delete(f"{settings.API_V1_STR}/users/{user_id}") assert response.status_code == 200app/engine/postgresdb.py+14-2
app/model/user.py+60-11
config/index.py-2
main.py+15-25
poetry.lock+167-1
pyproject.toml+7-1
tests/conftest.py+32-43
tests/pytest.ini+3-1
tests/test_main.pyDeleted-9
tests/test_users.pyAdded+40
tests/test_users_crud.pyDeleted-49