Python/Django: 如何断言单元测试结果包含某个字符串?

在 python 单元测试(实际上是 Django)中,正确的 assert语句是什么,它将告诉我测试结果是否包含我选择的字符串?

self.assertContainsTheString(result, {"car" : ["toyota","honda"]})

我希望确保我的 result至少包含我在上面第二个参数中指定的 json 对象(或字符串)

{"car" : ["toyota","honda"]}
108155 次浏览

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)
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.

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)

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

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']