什么是使用Python unittest测试回调调用的正确方法? [英] What is the right way to test callback invocation using Python unittest?

查看:1077
本文介绍了什么是使用Python unittest测试回调调用的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的应用程序代码。

I have an application code that looks like the following.

# Filename: app.py
class Foo:
    def __init__(self):
        self.callback = None

    def set_handler(self, callback):
        self.callback = callback

    def run(self, details):
        name, age = details.split('/')
        if age.isdigit():
            age = int(age)
        else:
            age = -1
        return self.callback(name, age)


$ b b

如你所见,它提供了一个 set_handler 方法来设置回调。该回调必须稍后使用两个参数调用:一个字符串和一个整数。我尝试在单元测试中确保这一点。

As you can see, it offers a set_handler method to set a callback. The callback must later be invoked with two arguments: a string and an integer. I am trying to ensure this in a unittest.

# Filename: test_app.py
import unittest
from app import Foo

class AppTest(unittest.TestCase):
    def f(self, a, b):
        # This callback should get called with the first argument as
        # string and the second argument as integer
        return repr(a) + ',' + repr(b)

    def test_callback(self):
        foo = Foo()
        foo.set_handler(self.f)
        self.assertEqual(foo.run('John/20'), "'John',20")
        self.assertEqual(foo.run('John/xyz'), "'John',-1")

if __name__ == '__main__':
    unittest.main()

此单元测试成功。但我不认为我的测试方法是健壮的。这个单元测试基本上是一个黑客,因为我不知道如何正确测试一个回调是否被调用了正确的类型的参数。我觉得奇怪的是,AppTest的 f 方法是共享类型检查的责任,试图返回一个由 repr()

This unit test succeeds. But I don't think my way of testing is robust. This unit test is basically a hack because I don't know how to correctly test if a callback has been invoked with the right type of arguments. What I find weird about it is that AppTest's f method is sharing the responsibility of type checking by attempting to return a value which are composed of repr() of the arguments, and this is not at all robust to say the least.

你能帮我吗?是否可以减轻测试类型的责任的 f 方法?

Could you please help me? Is it possible to relieve the f method of the responsibility of testing the types?

推荐答案

编辑:

尝试使用 unittest.mock (Python 3.3上的标准库)。它允许你断言如何调用方法。例如:

Try using unittest.mock (standard library on Python 3.3). It allows you to assert how methods were called. For example:

import unittest
from unittest.mock import Mock

from app import Foo

class AppTest(unittest.TestCase):

    def test_callback(self):
        foo = Foo()
        f = Mock()
        foo.set_handler(f)

        foo.run('John/20')
        f.assert_called_with('John', 20)

        foo.run('John/xyz')
        f.assert_called_with('John', -1)

if __name__ == '__main__':
    unittest.main()

这篇关于什么是使用Python unittest测试回调调用的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆