Skip to content

Commit

Permalink
Merge pull request #67 from Ori-Roza/general_fixes
Browse files Browse the repository at this point in the history
checkpoint
  • Loading branch information
Ori-Roza authored Apr 27, 2024
2 parents d54cdaa + 91a7453 commit c5c0ef2
Show file tree
Hide file tree
Showing 25 changed files with 177 additions and 394 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,6 @@ coverage.xml
/coverage.xml
.pytest_cache/
.DS_Store
*.sqlite3
/tests/test_server/test_app/migrations/
notes
20 changes: 0 additions & 20 deletions LICENSE.txt

This file was deleted.

133 changes: 28 additions & 105 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@


The drf-api-action Python package is designed to elevate your testing experience for Django Rest Framework (DRF) REST endpoints.
With the api-action fixture/custom decorator api-action, this package empowers you to effortlessly test your REST endpoints as if they were conventional functions.
With the api-action fixture, this package empowers you to effortlessly test your REST endpoints as if they were conventional functions.

Features:

Expand All @@ -18,11 +18,6 @@ Features:

* **Pagination Support**: Paginating easily through pages by a single kwarg.

This package was designed in a way that you can use it in the following ways:

* As a pytest fixture

* As part of your ViewSet implementation

## Demo

Expand All @@ -44,9 +39,8 @@ pip install drf-api-action

```python
import pytest
from tests.test_app.models import DummyModel
from tests.test_app.views import DummyViewSetFixture
from drf_api_action.fixtures import action_api
from tests.test_server.test_app.models import DummyModel
from tests.test_server.test_app.views import DummyViewSetFixture
```

#### Step 2: use the following action_api mark decorator:
Expand All @@ -55,104 +49,48 @@ from drf_api_action.fixtures import action_api

e.g:
our ViewSet is called `DummyViewSetFixture`

```python
import pytest
from tests.test_server.test_app.views import DummyViewSetFixture


@pytest.mark.action_api(view_set_class=DummyViewSetFixture)
def test_call_as_api_fixture(db, action_api):
pass
pass
```
Now you can use all `DummyViewSetFixture` functionality!

#### Step 3: write your test
#### Step 3: write your tests

e.g:
our ViewSet is called `DummyViewSetFixture`
```python
@pytest.mark.action_api(view_set_class=DummyViewSetFixture)
def test_call_as_api_fixture(db, action_api):
dummy_model = DummyModel()
dummy_model.dummy_int = 1
dummy_model.save()
res = action_api.api_dummy(pk=1)
assert res["dummy_int"] == 1

```

### To use `drf-api-action` in your ViewSet, you need to follow these steps:

#### Step 1: Import the Required Classes and Decorators

Import the necessary classes and decorators from `drf-api-action` and `rest_framework`:

```python
from drf_api_action.decorators import action_api
from drf_api_action.mixins import APIRestMixin
from rest_framework.viewsets import ModelViewSet
```

#### Step 2: Inherit `APIRestMixin` in your View

Create your view class by inheriting the `APIRestMixin` class.

For example, we want to inherit `ModelViewSet` (Could be any ViewSet) in our View:

```python
class DummyView(APIRestMixin, ModelViewSet):
queryset = DummyModel.objects.all()
serializer_class = DummySerializer
```

Another example:

```python
class UsersViewSet(APIRestMixin, mixins.RetrieveModelMixin,
mixins.ListModelMixin, viewsets.GenericViewSet):
serializer_class = UsersSerializer
```

#### Step 3: Define Your API Actions

Use the `action_api` decorator instead of `action` decorator to define your API actions as functions inside your view class:
import pytest
from tests.test_server.test_app.models import DummyModel
from tests.test_server.test_app.views import DummyViewSetFixture

From:
```python
@action(detail=True, methods=["get"], serializer_class=DummySerializer)
def dummy(self, request, **kwargs):
serializer = self.get_serializer(instance=self.get_object())
return Response(data=serializer.data, status=status.HTTP_200_OK)
```

To:
@pytest.mark.action_api(view_set_class=DummyViewSetFixture)
def test_call_as_api_fixture(db, action_api):
dummy_model = DummyModel()
dummy_model.dummy_int = 1
dummy_model.save()
res = action_api.api_dummy(pk=1)
assert res["dummy_int"] == 1

```python
@action_api(detail=True, methods=["get"], serializer_class=DummySerializer)
def dummy(self, request, **kwargs):
serializer = self.get_serializer(instance=self.get_object())
return Response(data=serializer.data, status=status.HTTP_200_OK)
```

In the example above, the `dummy` function is decorated with `action_api`.
It specifies that the action requires a detail argument, supports the `GET` method, and uses the `DummySerializer` for serialization.

#### Step 4: test REST methods

* Create an instance of your view class and call the API actions as regular functions:

```python
def test_dummy():
api = DummyView()
result = api.dummy(pk=1)
assert result['dummy_int'] == 1
```

*query parameters/post payload are treated as function arguments as kwargs*
import pytest
from tests.test_server.test_app.views import DummyViewSetFixture


* Exceptions are raised explicitly:
```python
def test_dummy():
api = DummyView()
result = api.dummy(pk='bbb')
assert result['dummy_int'] == 1
@pytest.mark.action_api(view_set_class=DummyViewSetFixture)
def test_dummy(db, action_api):
result = action_api.dummy(pk='bbb')
assert result['dummy_int'] == 1
```

```shell
Expand Down Expand Up @@ -187,28 +125,13 @@ filter_kwargs = {'pk': 'bb'}
and so on....
```
* Pagination support with `page`/`offset` kwarg (depends on `DEFAULT_PAGINATION_CLASS`):
```python
>>> api = DummyAPIViewSet()
>>> response = api.by_dummy_int(request=None, dummy_int=1, page=2)

>>> {'count': 2, 'next': None, 'previous': '', 'results': [OrderedDict([('id', 2), ('dummy_int', 1)])]}

```
## Package Testing
The `drf-api-action` library includes tests to ensure the functionality works as expected. To run the tests, follow these steps:
1. Navigate to the root directory of the `drf-api-action/` project.
```shell
cd tests/
```
2. Run the tests using `pytest`
The `drf-api-action` library includes tests to ensure the functionality works as expected. To run the tests run `pytest`:
```shell
python -m pytest -vv
PYTHONPATH=`pwd` pytest
```
The tests will be executed, and the results will be displayed in the console.
Expand Down
6 changes: 0 additions & 6 deletions conftest.py

This file was deleted.

27 changes: 0 additions & 27 deletions drf_api_action/api_utils.py

This file was deleted.

76 changes: 0 additions & 76 deletions drf_api_action/decorators.py

This file was deleted.

13 changes: 11 additions & 2 deletions drf_api_action/fixtures.py → drf_api_action/plugin.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,27 @@
import pytest

from drf_api_action.api_utils import run_as_api
from drf_api_action.mixins import APIRestMixin
from drf_api_action.utils import run_as_api
from drf_api_action.exceptions import ActionsAPIException


def run_function(self, func):
def api_item(*args, **kwargs):
serializer_class = func.kwargs['serializer_class']
return run_as_api(self, func, serializer_class, *args, **kwargs)

return api_item


@pytest.fixture
def action_api(request):
"""
Make Dango WebView endpoints accessible
"""
from drf_api_action.mixins import APIRestMixin # pylint: disable=import-outside-toplevel

if request.keywords['action_api'].kwargs.get("view_set_class") is None:
raise ActionsAPIException('using action_api fixture must require a view_set_class kwarg')

view_set_class = request.keywords['action_api'].kwargs["view_set_class"]

class WrapperApiClass(APIRestMixin, view_set_class):
Expand Down
Loading

0 comments on commit c5c0ef2

Please sign in to comment.