Skip to content

Instantly share code, notes, and snippets.

@rhenter
Created February 2, 2017 12:06
Show Gist options
  • Save rhenter/060a5af0a1299fc3baa5ed08147ed926 to your computer and use it in GitHub Desktop.
Save rhenter/060a5af0a1299fc3baa5ed08147ed926 to your computer and use it in GitHub Desktop.
from .models import YourModel
from .serializers import YourModelSerialize
from .viewsets import CRUDViewSet
# As good practice, create your viewset using the Resource as Prefix: YourModel
class YourModelViewSet(CRUDViewSet):
queryset = Invoice.objects.all()
serializer_class = InvoiceSerializer
lookup_field = 'id'
# This file should be on the project root
import pytest
@pytest.fixture()
def client_api():
"""A Django API client """
from django.test.client import Client
return Client()
from rest_framework import routers
from .api import YourModelViewSet
app_name = 'your-app'
router = routers.SimpleRouter()
router.register(r'your-url/', YourModelViewSet, , base_name='your-app-route')
urlpatterns = router.urls
'''
This file should be on test folder from app or project
Options:
1 - projetct/test
2 - project/your-app/test
'''
import json
import pytest
from rest_framework.status import is_success
from rest_framework.reverse import reverse
from your-app.models import YourModel
def test_get_list(client_api):
# the list is automatic
url = reverse('your-app:your-app-route-list')
response = client_api.get(url)
assert is_success(response.status_code)
def test_put(client_api):
# Create a object on your Model
obj = YourModel.objects.create(some_attr=1)
# The detail is automatic
url = reverse('your-app:your-app-route-detail', [obj.id])
data = {'some_attr': 2}
response = client_api.put(url, data=json.dumps(data), content_type='application/json')
assert is_success(response.status_code)
assert response.data['some_attr'] == 2
stored_data = YourModel.objects.get(id=obj.id)
assert stored_data.some_attr == 2
from rest_framework import mixins, viewsets
logger = logging.getLogger(__name__)
class CRUDViewSet(mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DeleteModelMixin,
mixins.ListModelMixin,
viewsets.GenericViewSet):
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment