Django REST Framework Tutorial : Testing

Welcome back to the 4th series of my Django Rest framework tutorial. This post would be a continuation of my previous post, please click on any link below to view any post you missed

OUTLINE OF DJANGO REST FRAMEWORK SERIES

 

The code to this tutorial is hosted on Github

At the end of this post, you will learn the following

  • You learn how to add tests to our API.

Importance of writing tests

  • When you’re writing new code or shipping new features, you can use tests to validate your code works as expected.
  • When you’re refactoring or modifying old code, you can use tests to ensure your changes haven’t affected your application’s behavior unexpectedly.

REST framework includes a few helper classes that extend Django’s existing test framework and improve support for making API requests.

DRF provides a few important classes which make testing APIs simpler.

  • APIRequestFactory: Extends Django’s RequestFactory    class
  • APIClient: Extends Django’s   Client    class
  • APITestCase:  similar to Django’s TestCase.

We will use the APITestCasefor our tests.

Now lets us write simple test cases to our Blog API application.

Create a new folder test, add the following files

tests
| - __init__.py
| - test_model.py
| - test_authentication.py
#tests/test_authentication.py


from datetime import date, datetime
import json

from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
from rest_framework.test import APIRequestFactory, APITestCase,APIClient

from blog_api.models import Category, Post


class TestCategoryEndPoint(APITestCase):

    def setUp(self):

        self.user = get_user_model()
        self.user.objects.create_user(
            'oluchi_testing',
            email='oluchiuser@test.com',
            password='oluchipassword'
        )

        self.token = Token.objects.create(user=User.objects.get(id=1))
        self.uri = '/api/v1/category/'
        self.client = APIClient( HTTP_AUTHORIZATION='Token {}'.format(self.token.key))
        self.params ={'title':"Data analyis"}

        self.category = Category.objects.create(title='Data Science')



    def test_create_category(self):
        response = self.client.post(self.uri,data=json.dumps(self.params),content_type='application/json')
        self.assertEqual(response.status_code, 201)
        self.assertEqual(json.loads(response.content), {"id":2,"title":"Data analyis"})

    def test_get_category(self):
        response = self.client.get(self.uri,content_type='application/json')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(json.loads(response.content),  [{"id":1,"title":"Data Science"}])

    def test_update_category(self):

        response = self.client.put('/api/v1/category/1', data=json.dumps(self.params),content_type='application/json')
        self.assertEqual(response.status_code, 301)
        self.assertNotEqual(response.content,[])


#tests/test_model.py


from datetime import date, datetime

from django.contrib.auth import get_user_model
from rest_framework.test import APITestCase
from django.contrib.auth.models import User
from blog_api.models import Category, Post


class TestModel(APITestCase):


    @classmethod 
    def setUpTestData(cls):
        User = get_user_model()
        User.objects.create_user(
                'oluchi_testing',
                email='oluchiuser@test.com',
                password='oluchipassword'
            )
        category = Category.objects.create(title='Data Science')
        post = Post.objects.create(title = "Introduction to Machine Learning",
                                slug = "introduction-to-Machine-Learning",
                                author = User.objects.get(id=1),
                                body =  "Machine learning is a method of data analysis that automates analytical model building" +
                                        "It is a branch of artificial intelligence based on the idea that systems can"  +
                                        "learn from data, identify patterns and make decisions with minimal human intervention.",
                                status =  "draft",
                                created =  date.today(), 
                                category= Category.objects.get(id=1))


    def test_post_model(self):
        post=Post.objects.get(id=1)
        expected_object_name=f'{post.title}'
        self.assertNotEquals(expected_object_name,'Data Analysis')
        self.assertEquals(post.category.title,'Data Science')
        
    def test_user_model(self):
        user=User.objects.get(id=1)
        username=f'{user.username}'
        email=f'{user.email}'
        self.assertNotEquals(email,'example@org.com')
        self.assertEquals(username,'oluchi_testing')
        
    def test_category_model(self):
        category=Category.objects.get(id=1)
        expected_object_name=f'{category.title}'
        self.assertNotEquals(expected_object_name,'Data Analysis')
        
        
        
        

On your terminal

python3 manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
......
----------------------------------------------------------------------
Ran 6 tests in 0.796s

OK
Destroying test database for alias 'default'...

 

There is so much more we can test for, but this tutorial is kept as simple as possible.

Happy coding

Leave a Reply

Your email address will not be published. Required fields are marked *