use*_*719 59 python django json unit-testing assert
在python单元测试中(实际上是Django),assert如果我的测试结果中包含我选择的字符串,那么正确的语句是什么?
即,像 result
我想确保我assert至少包含我指定为上面第二个参数的json对象(或字符串),即result
Ed *_*d I 98
要断言字符串是否是另一个字符串的子字符串,您应该使用assertIn和assertNotIn:
# Passes
self.assertIn('bcd', 'abcde')
# AssertionError: 'bcd' unexpectedly found in 'abcde'
self.assertNotIn('bcd', 'abcde')
Run Code Online (Sandbox Code Playgroud)
这些是自Python 2.7和Python 3.1以来的新功能
Aks*_*aaj 51
self.assertContains(result, "abcd")
Run Code Online (Sandbox Code Playgroud)
您可以修改它以使用json.
使用self.assertContains只为HttpResponse对象.对于其他对象,请使用self.assertIn.
Pie*_*scy 21
您可以在python关键字中使用简单的assertTrue +在另一个字符串中编写关于字符串的预期部分的断言:
self.assertTrue("expected_part_of_string" in my_longer_string)
Run Code Online (Sandbox Code Playgroud)
使用构建JSON对象json.dumps().
然后用它们比较它们 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)
Run Code Online (Sandbox Code Playgroud)
正如Ed I所提到的,assertIn可能是在另一个字符串中找到一个字符串的最简单答案.但问题是:
我想确保我
result至少包含我指定为上面第二个参数的json对象(或字符串),即{"car" : ["toyota","honda"]}
因此,我会使用多个断言,以便在失败时收到有用的消息 - 将来必须理解和维护测试,可能是那些最初没有编写它们的人.因此假设我们在一个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'])
Run Code Online (Sandbox Code Playgroud)
其中提供了有用的消息如下:
# 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']
Run Code Online (Sandbox Code Playgroud)