How it works...

Just like in the previous recipe, when you run tests for the likes app, at first, a temporary test database is created. Then, the setUpClass() method is called. Later, the methods whose names start with test are executed, and, finally, the tearDownClass() method is called.

Unit tests inherit from the SimpleTestCase class, but, here, we are using TestCase, which is a specialization that adds safeguards around test isolation when database queries are involved. In setUpClass(), we create a location and a superuser. Also, we find out the ContentType object for the Location model; we will need it for the view that sets or removes likes for different objects. As a reminder, the view looks similar to the following, and returns the JSON string as a result:

def json_set_like(request, content_type_id, object_id):
    # ...all the view logic goes here...
    return JsonResponse(result) 

In the test_authenticated_json_set_like() and test_anonymous_json_set_like() methods, we use the Mock objects. These are objects that can have any attributes or methods. Each undefined attribute or method of a Mock object is another Mock object. Therefore, in the shell, you can try to chain attributes, as follows:

>>> import mock
>>> m = mock.Mock()
>>> m.whatever.anything().whatsoever
<Mock name='mock.whatever.anything().whatsoever' id='4464778896'>

In our tests, we use the Mock objects to simulate the HttpRequest object. For the anonymous user, a MockUser is generated as a patch of the standard Django User object, via the @mock.patch() decorator. For the authenticated user, we still need the real User object, as the view needs the user's ID to save in the database for the Like object.

Therefore, we call the json_set_like() function, and check that the returned JSON response is correct:

  • It returns {"success": false} in the response, if the visitor is unauthenticated.

  • It returns something like {"action": "add", "count": 1, "success": true} for authenticated users.

In the end, the tearDownClass() class method is called, deleting the location and superuser from the test database.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.151.45