测试函数的行为是否与已知函数相同

时间:2017-03-07 18:58:48

标签: python python-3.x

我有一个文件correct.py,我可以假设其中定义的所有方法都是正确的,我想测试student.py中的方法。假设这包含与correct.py相同的方法。

我正在尝试使用unittest模块,到目前为止,我的测试看起来很像:

import correct
import student

def test_func(self):
    self.assertEquals(correct.func(<input>),student.func(<input>))

这将在各种输入上完成。有没有什么方法可以定义一个函数,我只需要运行f(<input>)f(<input>,func)来获得同样的行为?

1 个答案:

答案 0 :(得分:2)

您可以创建如下函数:

def test(self, argument, func): 
    Fcorrect = getattr(correct, func)
    Fstudent = getattr(student, func)
    self.assertEquals(Fcorrect(argument), Fstudent(argument))

只需将您想要的任何类型的<input>传递给argument参数,并将函数名称作为字符串传递给func参数。

例如,要以"foo"为参数测试函数3,您可以执行以下操作:

self.test("foo", 3)