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

问题描述 投票:45回答:6

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

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

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

{"car" : ["toyota","honda"]}
python json django unit-testing assert
6个回答
18
投票

您可以在python关键字中使用简单的assertTrue +在另一个字符串中编写关于字符串的预期部分的断言:

self.assertTrue("expected_part_of_string" in my_longer_string)

8
投票

使用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)

5
投票

As mentioned by Ed IassertIn可能是在另一个中找到一个字符串的最简单答案。但问题是:

我想确保我的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']

-2
投票

我发现自己处于类似的问题,我使用了属性rendered_content,所以我写道

assertTrue('string' in response.rendered_content)和类似的

assertFalse('string' in response.rendered_content)如果我想测试一个字符串没有呈现

但它也适用于早期建议的方法,

AssertContains(response, 'html string as rendered')

所以我会说第一个更简单。我希望它会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.