Search code examples
pythondjangounit-testingdjango-viewsdjango-unittest

I can't figure out how to test these views using unittests


I need to test this code using unittest help me figure it out show how they are tested

def post(self, request, pk):
    form = ReviewForm(request.POST)
    movie = Movie.objects.get(id=pk)
    if form.is_valid():
        form = form.save(commit=False)
        if request.POST.get("parent", None):
            form.parent_id = int(request.POST.get("parent"))
        form.movie = movie
        form.save()
    return redirect(movie.get_absolute_url())

Solution

  • Django’s unit tests use the Python standard library module: unittest. This module defines tests using a class-based approach.

    To use it, go to test.py inside your app folder. There, you can start to write your tests:

    1. First thing you'll need to do is import TestCase and the model you want to test, for example:

      from django.test import TestCase from myapp.models import Post

    2. Second you need to write your tests. Think, what do you need to test? If it's a form to create a post for example, you need to test that the post is created and saved in the database.

    For that, you'll need to set up an initial state to run your tests in a safe environment.

    Let's take the post as example:

    from django.test import TestCase
    from myapp.models import Post
    
    class CreateNewPostsTest(TestCase):
        """
        This class contains tests that test if the posts are being correctly created
        """
    
       def setUp(self):
            """Set up initial database to run before each test, it'll create a database, run a test and then delete it"""
    
            # Create a new user to test
            user1 = User.objects.create_user(
                username="test_user_1", email="test1@example.com", password="falcon"
            )
    
            # Create a new post
            post1 = NewPosts.objects.create(
                user_post=user1,
                post_time="2020-09-23T20:16:46.971223Z",
                content='This is a test to check if a post is correctly created',
            )
    
    1. The code above set up a safe state to test our code. Now we need to write a test check, it'll run a test and see if the code we define at setUp did what we expect it should do.

    So, inside of our class CreateNewPostsTest, you'll need to define a new function to run the tests:

    def test_create_post_db(self):
        """Test if the new posts from different users where saved"""
        self.assertEqual(NewPosts.objects.count(), 1)
    

    This code will run an assertEqualand it'll check if the count of objects in the database is equal to 1 (because we just created one post in the setUp).

    1. Now you need to run the tests with:

      python manage.py test

    It'll run the tests and you'll see in your Terminal if the tests failed or not.

    In your case, you can do the same with your Movie model.

    You can find more information about tests in the Django Documentation: https://docs.djangoproject.com/en/3.1/topics/testing/overview/