是否可以在测试中检查调用参数?
如果我们调用主方法 run 来调用我感兴趣的方法 - self. get_request()。
file.py
class A:
def run():
some logic...
request = self.get_request()
some logic...
return response
test.py
from file.py import A
def test():
"""
Inside this test, I want to check the parameters and the value returned by the
get_request method, but I don't want to check it separately
I want to check it by calling the parent method - run
"""
instance = A()
response = instance.run()
assertions logic for instance.get_request..
我知道可以模拟一个方法,然后我们可以访问调用次数、参数等。如果我所要求的内容可以通过模拟以某种方式实现,我只想添加我的模拟必须与它模拟的方法具有相同的逻辑(相同)。
is it possible to check in the test with what parameters the method is called and what result it returns, if we call the main method run which calls the method I'm interested in - self.get_request().
file.py
class A:
def run():
some logic...
request = self.get_request()
some logic...
return response
test.py
from file.py import A
def test():
"""
Inside this test, I want to check the parameters and the value returned by the
get_request method, but I don't want to check it separately
I want to check it by calling the parent method - run
"""
instance = A()
response = instance.run()
assertions logic for instance.get_request..
I know that it is possible to mock a method and then we have access to the number of calls, parameters, etc. If what I'm asking is possible in some way through mock, I just want to add that my mock would have to have the same logic as the method it mocks (be the same).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您要求的可能是可在 patch - 这允许您模拟函数,同时它仍然保留以前的(或其他一些)功能(请注意,参数本身在 <一个href="https://docs.python.org/3/library/unittest.mock.html?highlight=patch#unittest.mock.Mock" rel="nofollow noreferrer">模拟)。与任何模拟一样,这确实允许您测试调用和调用参数,但不允许您检查函数的返回值。这必须通过其副作用进行测试(在您的情况下,通过返回的响应,该响应应取决于 get_request 的返回值)。
以下是您的情况的说明:
在这种情况下,模拟调用真正的 get_request 方法并返回其结果,同时记录调用和调用参数。
我向
get_request
添加了一些参数进行演示,并直接在run
中返回调用结果 - 在您的情况下,这当然会有所不同,但想法应该是相同的。What you are asking for is probably the
wraps
argument that can be used in patch - this allows you to mock a function, while it still retains the previous (or some other) functionality (note that the argument itself is described under Mock). As with any mock, this does allow you to test the calls and call args, but does not allow you to check the return value of the function. This has to be tested via its side effects (in your case via the returnedresponse
which should depend on the return value ofget_request
).Here is an illustration for your case:
In this case the mock calls the real
get_request
method and returns its result, while recording the call and the call args.I added some argument to
get_request
for demonstration, and returned the result of the call directly inrun
- in your case this will differ of course, but the idea should be the same.