kav*_*veh 13 python string django unit-testing assertions
我使用 Django Rest Framework APIClient 对 Django API 进行了一些单元测试。API 的不同端点返回自定义错误消息,其中一些带有格式化字符串,例如:'Geometry type "{}" is not supported'。
我断言来自客户端响应和错误消息键的状态代码,但在某些情况下,我想弄清楚返回了什么错误消息,以确保没有其他原因导致该错误。
所以我也想根据原始的未格式化字符串验证返回的错误消息。例如,如果我收到类似 的错误消息'Geometry type "Point" is not supported',我想检查它是否与原始未格式化的消息匹配,即'Geometry type "{}" is not supported'。
目前我想到的解决方案:
首先:用正则表达式模式替换原始字符串中的括号,然后查看它是否与响应匹配。
第二:(很酷的想法,但在某些情况下可能会失败)使用difflib.SequenceMatcher并测试相似度是否大于例如 90%。
这是一个例子:
有许多dict错误消息,每个错误都会从中选择相关消息,根据需要添加格式参数,然后引发错误:
ERROR_MESSAGES = {
'ERROR_1': 'Error message 1: {}. Do something about it',
'ERROR_2': 'Something went wrong',
'ERROR_3': 'Check you args: {}. Here is an example: {}'
}
Run Code Online (Sandbox Code Playgroud)
现在,我的 DRF 序列化器在处理请求期间发生错误,并引发错误:
try:
some_validation()
except SomeError as e:
raise serializers.ValidationError({'field1': [ERROR_MESSAGES['ERROR_N1'], ERROR_MESSAGES['ERROR_N2']], 'field2': ['ERROR_N3']})
Run Code Online (Sandbox Code Playgroud)
现在在一个特定的测试中,我想确保存在某个错误消息:
class SomeTestCases(TestCase):
def test_something(self):
response = self.client.post(...)
self.assertThisMessageIsInResponse(response.data, ERROR_MESSAGES['ERROR_K'])
Run Code Online (Sandbox Code Playgroud)
response.data可以只是一个字符串或一个字典或错误列表;即任何可以进去的东西ValidationError。
指向response.data每个测试用例中的错误消息位置没有问题。这个问题关注的是处理格式化和未格式化字符串之间的比较。
到目前为止,最简单的方法是正则表达式。我主要好奇是否有内置断言以及可以使用哪些其他解决方案。
mrt*_*rts 25
您正在寻找assertRegex():
class SomeTestCases(TestCase):
def test_something(self):
response = self.client.post(...)
self.assertRegex(response.data, r'^your regex here$')
Run Code Online (Sandbox Code Playgroud)
也可以看看assertNotRegex。
似乎正则表达式是这里最简单的解决方案
import re
msg = 'Geometry type "point" is not supported'
assert re.match(r'^Geometry type ".+" is not supported$', msg)
Run Code Online (Sandbox Code Playgroud)