Python/Django: how to assert that unit test result contains a certain string?

user798719 picture user798719 · Jul 9, 2013 · Viewed 74.9k times · Source

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"]}

Answer

Ed I picture Ed I · Mar 15, 2016

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