当我断言一个方法被调用时,如何通配一个字符串?Python3 模拟

Cia*_*ans 1 unit-testing assert wildcard mocking python-3.x

mockcall()对象与 一起使用时assert_has_calls,我很难断言已使用给定字符串并在末尾附加了未知值。

例如:

被测代码:

mystring = 'a known string with an unknown value: {0}'.format(unknown_value)
method_to_call(mystring)
Run Code Online (Sandbox Code Playgroud)

当前测试代码:

with mock.patch('method_to_call') as mocked_method:
  calls = [call('a known string with and unknown value: {0}'.format(mock.ANY)]
  call_method()
  mocked_method.assert_has_calls(calls)
Run Code Online (Sandbox Code Playgroud)

这给了我一些类似的东西:

AssertionError: Calls not found.
Expected: [call('a known string with and unknown value: <ANY>')]
Run Code Online (Sandbox Code Playgroud)

如何断言给定的字符串已传递给方法但允许未知值?

use*_*641 7

您可以使用calleelib 对方法调用中使用的字符串进行部分匹配:

from callee import String, Regex

with mock.patch('method_to_call') as mocked_method:
    call_method()
    mocked_method.assert_called_with(String() & Regex('a known string with an unknown value: .*'))
Run Code Online (Sandbox Code Playgroud)

或者,如果您不想添加另一个库并且您确定您知道调用的顺序,则可以从调用参数中提取字符串,然后使用正则表达式进行匹配

import re

with mock.patch('method_to_call') as mocked_method:
  call_method()
  argument_string = mocked_method.call_args[0][0]

  pattern = re.compile("a known string with an unknown value: .*")
  assert pattern.match(argument_string)

Run Code Online (Sandbox Code Playgroud)