|
| 1 | +""" |
| 2 | +Tests for the CreateAPIView class. |
| 3 | +""" |
| 4 | + |
| 5 | +import pytest |
| 6 | +from fastapi.testclient import TestClient |
| 7 | +from fireframe.core.api import FireFrameAPI |
| 8 | +from fireframe.core.models import Model |
| 9 | +from fireframe.core.serializers import ModelSerializer |
| 10 | +from fireframe.core.views import BaseCreateAPIView |
| 11 | +from ._fixtures import test_thread |
| 12 | + |
| 13 | + |
| 14 | +class TestCreateAPIView: |
| 15 | + def test_view_no_serializer(self): |
| 16 | + """ |
| 17 | + Test the BaseCreateAPIView raises TypeError when |
| 18 | + serializer_class is not a subclass of ModelSerializer. |
| 19 | + """ |
| 20 | + |
| 21 | + class TestBadView(BaseCreateAPIView): |
| 22 | + pass |
| 23 | + |
| 24 | + with pytest.raises(TypeError): |
| 25 | + TestBadView() |
| 26 | + |
| 27 | + @pytest.fixture(scope="function") |
| 28 | + def _TestModel(self, test_thread) -> Model: |
| 29 | + """ |
| 30 | + Cleanup the test collection after the test is done. |
| 31 | + """ |
| 32 | + |
| 33 | + class TestModel(Model): |
| 34 | + example: str |
| 35 | + flag: bool |
| 36 | + price: float |
| 37 | + |
| 38 | + class Meta: |
| 39 | + collection_name = f"test_collection_example_{test_thread}" |
| 40 | + |
| 41 | + yield TestModel |
| 42 | + |
| 43 | + # cleanup test collection |
| 44 | + TestModel.collection.delete_every(child=True) |
| 45 | + |
| 46 | + def test_create_view_ok(self, test_thread, _TestModel): |
| 47 | + """ |
| 48 | + Test the BaseCreateAPIView works as expected. |
| 49 | + """ |
| 50 | + |
| 51 | + class TestSerializer(ModelSerializer): |
| 52 | + class Meta: |
| 53 | + model = _TestModel |
| 54 | + fields = ["example", "flag", "price"] |
| 55 | + |
| 56 | + class TestCreateView(BaseCreateAPIView): |
| 57 | + serializer_class = TestSerializer |
| 58 | + |
| 59 | + app = FireFrameAPI() |
| 60 | + app.include_router(TestCreateView.as_router()) |
| 61 | + client = TestClient(app) |
| 62 | + response = client.post( |
| 63 | + "/", json={"example": "This is a test from test_create_view_ok method", "flag": True, "price": 10.0} |
| 64 | + ) |
| 65 | + assert response.status_code == 201 |
| 66 | + assert response.json() == { |
| 67 | + "example": "This is a test from test_create_view_ok method", |
| 68 | + "flag": True, |
| 69 | + "price": 10.0, |
| 70 | + } |
0 commit comments