Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between `assertIn` and `assertContains` in Django?

I am studying some Django testing codes and I find assertIn and assertContains quite similar, I read the documentation wherein they didn't say anything about assertIn or maybe I couldn't find it.

This example below checks if 'john' appears at the content of self.email.body

self.assertIn('john', self.email.body)

similary this example checks if csrfmiddlewaretoken appears at content of self.response

self.assertContains(self.response, 'csrfmiddlewaretoken')

Looks like there syntax is different, but there functionality is the same. Hence, what is the difference?

If you could kindly help me understand this with some basic examples, I would really appreciate it.

Thank you so much

like image 256
Mir Stephen Avatar asked Apr 28 '19 16:04

Mir Stephen


2 Answers

assertIn is a member of python's built-in test suit. It is a normal test for membership. For example, you can check the membership of an element of an array. A key in a dictionary etc. You can use it for everything the in operator can be used for.

assertContains is added by Django in its test suit. It is used specifically for responses. That means you can pass it response object returned by the view. It will evaluate it and check for membership then.

You can read about assertIn and assertContains in respective documentations.

like image 128
Nafees Anwar Avatar answered Oct 04 '22 04:10

Nafees Anwar


Django testing inherits from unittest in Python.

assertContains is specific to Django and allows you to evaluate additional things beyond a simple assertIn:

SimpleTestCase.assertContains(response, text, count=None, status_code=200, msg_prefix='', html=False)[source]

Asserts that a Response instance produced the given status_code and that text appears in the content of the response. If count is provided, text must occur exactly count times in the response.

While assertIn does simple evaluation:

assertIn(first, second, msg=None)

assertIn(a, b) checks for a in b

like image 29
MyNameIsCaleb Avatar answered Oct 04 '22 05:10

MyNameIsCaleb