From 246eccd60640b4d9422d8eed83673a09f2bd722e Mon Sep 17 00:00:00 2001 From: Conrad Date: Mon, 1 Apr 2024 20:01:15 +0200 Subject: [PATCH] feat: Added testing for CRUD --- .github/workflows/lint.yml | 3 +-- test.py | 53 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 2 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index b027f68..1724078 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -52,5 +52,4 @@ jobs: - uses: stefanzweifel/git-auto-commit-action@v5 with: commit_message: Adjusted files for isort & autopep - commit_options: --tags - + push_options: --tags diff --git a/test.py b/test.py index 0980648..231bc2b 100644 --- a/test.py +++ b/test.py @@ -1,11 +1,41 @@ import unittest +from typing import Type, Union +from uuid import UUID +from fastapi import HTTPException from fastapi.routing import APIRoute +from sqlalchemy import create_engine +from sqlalchemy.orm import Session, sessionmaker from creyPY.fastapi.app import generate_unique_id +from creyPY.fastapi.crud import ( + create_obj_from_data, + delete_object, + get_object_or_404, + update_obj_from_data, +) +from creyPY.fastapi.models.base import Base + + +class MockDBClass(Base): + def __init__(self, id): + self.id = id class TestMyFunction(unittest.TestCase): + def setUp(self): + # Create a SQLite in-memory database for testing + engine = create_engine("sqlite:///:memory:") + + # Create a sessionmaker bound to this engine + Session = sessionmaker(bind=engine) + + # Now you can use Session() to get a session bound to the engine + self.db = Session() + + # create the table + Base.metadata.create_all(engine) + def test_generate_unique_id(self): # Test case 1: Route with no path parameters and GET method route1 = APIRoute(path="/users", methods={"GET"}, endpoint=lambda: None) @@ -36,6 +66,29 @@ class TestMyFunction(unittest.TestCase): route6 = APIRoute(path="/users", methods={"PUT"}, endpoint=lambda: None) assert generate_unique_id(route6) == "users_put" + def test_get_object_or_404_existing_object(self): + # Arrange + obj_id = UUID("123e4567-e89b-12d3-a456-426614174000") + obj = MockDBClass(obj_id) + self.db.add(obj) + self.db.commit() + + # Act + result = get_object_or_404(MockDBClass, obj_id, self.db) + + # Assert + assert result == obj + + def test_get_object_or_404_non_existing_object(self): + # Arrange + obj_id = UUID("123e4567-e89b-12d3-a456-426614174000") + + # Act & Assert + with self.assertRaises(HTTPException) as exc_info: + get_object_or_404(MockDBClass, obj_id, self.db) + assert exc_info.exception.status_code == 404 + assert exc_info.exception.detail == "The object does not exist." + if __name__ == "__main__": unittest.main()