77π
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
.
161π
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
- [Django]-Django β Static file not found
- [Django]-Paginating the results of a Django forms POST request
- [Django]-Django, creating a custom 500/404 error page
30π
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)
- [Django]-Django Admin Form for Many to many relationship
- [Django]-RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
- [Django]-Laravel's dd() equivalent in django
11π
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)
- [Django]-Best practices for getting the most testing coverage with Django/Python?
- [Django]-Get the latest record with filter in Django
- [Django]-Why is iterating through a large Django QuerySet consuming massive amounts of memory?
10π
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']
- [Django]-How to monkey patch Django?
- [Django]-Django.contrib.gis.db.backends.postgis vs django.db.backends.postgresql_psycopg2
- [Django]-Allowing only super user login