Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using APITestCase with django-rest-framework

I followed this code:

from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase

class AccountTests(APITestCase):
    def test_create_account(self):
        """
        Ensure we can create a new account object.
        """
        url = reverse('account-list')
        data = {'name': 'DabApps'}
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(response.data, data)

Found in the django-rest-framewok docs here:

DRF API-guide: Testing example

I created a single Model with a single field name, and I am still getting a "bad request 400 error". The view and reverse name is also set up correctly, and I have manually tested viewing the URL with success. I don't have Authentication enabled

And can't figure out if I am missing a step?

Does anyone have a working example of a django-rest-framework APITestCase create model object test code snippet?

like image 604
Aaron Lelevier Avatar asked Jan 29 '15 18:01

Aaron Lelevier


People also ask

How do I run test cases in Django REST Framework?

Once you have coded a couple of tests, you can execute them with this command in the main folder of the project (the one that has the manage.py file): python manage.py test This will search for all of your tests files under that folder and then execute them, showing the error or success of each unit test.

Can I use Django and Django REST Framework together?

Django Rest Framework makes it easy to use your Django Server as an REST API. REST stands for "representational state transfer" and API stands for application programming interface.

Can Fastapi work with Django?

Short Answer. Yes it's possible with WSGIMiddleware. For example, you can use all Django features (yes admin too) with mounting, with this example code. Also this one is from WSGIMiddleware documentation, it's a more straight-forward example (This one is for Flask but it demonstrates the same idea.).

Which authentication is best in Django REST Framework?

JSON Web Token Authentication Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. A package for JWT authentication is djangorestframework-simplejwt which provides some features as well as a pluggable token blacklist app.


1 Answers

This GIT repo has several working examples, which I was able to follow and get APITestCase working:

django-rest-framework-oauth2-provider-example/apps/users/tests.py

like image 106
Aaron Lelevier Avatar answered Sep 19 '22 10:09

Aaron Lelevier