在python单元测试(实际上是Django)中,正确的assert
语句是什么,它会告诉我我的测试结果是否包含我选择的字符串?
self.assertContainsTheString(result, {"car" : ["toyota","honda"]})
我想确保我的result
至少包含我指定为上面第二个参数的json对象(或字符串)
{"car" : ["toyota","honda"]}
您可以在python关键字中使用简单的assertTrue +在另一个字符串中编写关于字符串的预期部分的断言:
self.assertTrue("expected_part_of_string" in my_longer_string)
使用json.dumps()
构建JSON对象。
然后使用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)
As mentioned by 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'])
其中提供了有用的消息如下:
# 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']
我发现自己处于类似的问题,我使用了属性rendered_content,所以我写道
assertTrue('string' in response.rendered_content)
和类似的
assertFalse('string' in response.rendered_content)
如果我想测试一个字符串没有呈现
但它也适用于早期建议的方法,
AssertContains(response, 'html string as rendered')
所以我会说第一个更简单。我希望它会有所帮助。