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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17536916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:27:55  来源:igfitidea点击:

Python/Django: how to assert that unit test result contains a certain string?

pythonjsondjangounit-testingassert

提问by user798719

In a python unit test (actually Django), what is the correct assertstatement that will tell me if my test result contains a string of my choosing?

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

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

I want to make sure that my resultcontains at least the json object (or string) that I specified as the second argument above

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

{"car" : ["toyota","honda"]}

采纳答案by Akshar Raaj

self.assertContains(result, "abcd")

You can modify it to work with json.

您可以修改它以使用 json。

Use self.assertContainsonly for HttpResponseobjects. For other objects, use self.assertIn.

使用self.assertContains只为HttpResponse对象。对于其他对象,请使用self.assertIn.

回答by Vincent Audebert

Build a JSON object using json.dumps().

使用 构建一个 JSON 对象json.dumps()

Then compare them using assertEqual(result, your_json_dict)

然后使用它们进行比较 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)

回答by Pierre Criulanscy

You can write assertion about expected part of string in another string with a simple assertTrue + in python keyword :

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

self.assertTrue("expected_part_of_string" in my_longer_string)

回答by tombishop83

I found myself in a similar problem and I used the attribute rendered_content, so I wrote

我发现自己在一个类似的问题,我使用的属性rendered_content,所以我写了

assertTrue('string' in response.rendered_content)and similarly

assertTrue('string' in response.rendered_content)同样

assertFalse('string' in response.rendered_content)if I want to test that a string is not rendered

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

But it also worked the early suggested method,

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

AssertContains(response, 'html string as rendered')

AssertContains(response, 'html string as rendered')

So I'd say that the first one is more straightforward. I hope it will help.

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

回答by Ed I

To assert if a string is or is not a substring of another, you should use assertInand assertNotIn:

要断言一个字符串是否是另一个字符串的子字符串,您应该使用assertInand assertNotIn

# Passes
self.assertIn('bcd', 'abcde')

# AssertionError: 'bcd' unexpectedly found in 'abcde'
self.assertNotIn('bcd', 'abcde')

These are new since Python 2.7and Python 3.1

这些是自Python 2.7Python 3.1以来的新功能

回答by jamesc

As mentioned by Ed I, assertInis probably the simplest answer to finding one string in another. However, the question states:

正如 Ed I 所提到的assertIn可能是在另一个字符串中查找一个字符串的最简单的答案。但是,问题指出:

I want to make sure that my resultcontains at least the json object (or string) that I specified as the second argument above,i.e., {"car" : ["toyota","honda"]}

我想确保我result的至少包含我指定为上面第二个参数的 json 对象(或字符串),即,{"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:

因此,我会使用多个断言,以便在失败时收到有用的消息 - 将来必须理解和维护测试,可能是由最初没有编写它们的人来理解和维护的。因此假设我们在 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']