Python/Django: how to assert that unit test result contains a certain string?
PythonJsonDjangoUnit TestingAssertPython Problem Overview
In a python unit test (actually Django), what is the correct assert
statement that will tell me if my test result contains a string of my choosing?
self.assertContainsTheString(result, {"car" : ["toyota","honda"]})
I want to make sure that my result
contains at least the json object (or string) that I specified as the second argument above
{"car" : ["toyota","honda"]}
Python Solutions
Solution 1 - Python
To assert if a string is or is not a substring of another, you should use assertIn
and assertNotIn
:
# Passes
self.assertIn('bcd', 'abcde')
# AssertionError: 'bcd' unexpectedly found in 'abcde'
self.assertNotIn('bcd', 'abcde')
These are new since Python 2.7 and Python 3.1
Solution 2 - Python
self.assertContains(result, "abcd")
You can modify it to work with json.
Use self.assertContains
only for HttpResponse
objects. For other objects, use self.assertIn
.
Solution 3 - Python
You can write assertion about expected part of string in another string with a simple assertTrue + in python keyword :
self.assertTrue("expected_part_of_string" in my_longer_string)
Solution 4 - Python
Build a JSON object using json.dumps()
.
Then compare them using assertEqual(result, your_json_dict)
import json
expected_dict = {"car":["toyota", "honda"]}
expected_dict_json = json.dumps(expected_dict)
self.assertEqual(result, expected_dict_json)
Solution 5 - Python
As mentioned by Ed I, assertIn
is probably the simplest answer to finding one string in another. However, the question states:
> I want to make sure that my result
contains at least the json object (or string) that I specified as the second argument above,i.e., {"car" : ["toyota","honda"]}
Therefore I would use multiple assertions so that helpful messages are received on failure - tests will have to be understood and maintained in the future, potentially by someone that didn't write them originally. Therefore assuming we're inside a django.test.TestCase
:
# Check that `car` is a key in `result`
self.assertIn('car', result)
# Compare the `car` to what's expected (assuming that order matters)
self.assertEqual(result['car'], ['toyota', 'honda'])
Which gives helpful messages as follows:
# If 'car' isn't in the result:
AssertionError: 'car' not found in {'context': ..., 'etc':... }
# If 'car' entry doesn't match:
AssertionError: Lists differ: ['toyota', 'honda'] != ['honda', 'volvo']
First differing element 0:
toyota
honda
- ['toyota', 'honda']
+ ['honda', 'volvo']