Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"]} 
like image 747
user798719 Avatar asked Jul 08 '13 22:07

user798719


People also ask

How do you assert in unit testing?

Assert the exact desired behavior; avoid overly precise or overly loose conditions. One assertion, one condition. Don't aggregate multiple checks in one assertion. Write assertions that check requirements, not implementation details of the unit under test.

How do I run a specific test case in Django?

You need to open you init.py and import your tests. Show activity on this post. If you want to run a test case class which has the path <module_name>/tests/test_views.py , you can run the command python manage.py test <module_name>. tests.

How do you assert a Boolean value in Python?

assertTrue() in Python is a unittest library function that is used in unit testing to compare test value with true. This function will take two parameters as input and return a boolean value depending upon the assert condition. If test value is true then assertTrue() will return true else return false.


1 Answers

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

like image 115
Ed I Avatar answered Sep 27 '22 17:09

Ed I