Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用exec()自动测试函数_Python_Testing_Exec_Eval - Fatal编程技术网

Python 使用exec()自动测试函数

Python 使用exec()自动测试函数,python,testing,exec,eval,Python,Testing,Exec,Eval,我想为我的一些python函数创建一个测试框架(尽管这种方法可能适用于任何其他语言) 我的想法是创建一个文件,其中包含: 要测试的函数的名称 此函数的输入参数 预期产出 我的文件将如下所示: # Test 1: Description of the test # foo test1 Function: foo Input: param1, param2, param3 Output: out1, out2 # Test 2: Description of the test #

我想为我的一些python函数创建一个测试框架(尽管这种方法可能适用于任何其他语言)

我的想法是创建一个文件,其中包含:

  • 要测试的函数的名称
  • 此函数的输入参数
  • 预期产出
我的文件将如下所示:

# Test 1: Description of the test    # foo test1
Function: foo
Input: param1, param2, param3
Output: out1, out2

# Test 2: Description of the test    # foo test2
Function: foo
Input: param1, param2, param3
Output: out1, out2

# Test 3: Description of the test    # bar test1
Function: bar
Input: param1, param2, param3, param4
Output: out1, out2, out3
def test(func_name, args, out):
    func = getattr(functions, func_name)
    # `args` is a tuple for example.
    assert func(*args) == out, "Test routine failed"
然后我可以读取这个文件并开始执行测试

我最初的想法是首先在字符串中构建命令:

command = function + '(' + ''.join(inputs) + ')'
然后使用
exec()
执行每个命令

exec(command)
不过我猜这是个好主意还是有更好的办法

我这么说是因为exec和eval被认为是在可能的情况下应该避免的坏做法


所以我的问题是:我的方法行吗,或者有一种简单的方法我没有找到?

对于您描述的特定情况,我建议使用
getattr
。假设要测试的函数位于名为
functions
的模块中。您的测试功能如下所示:

# Test 1: Description of the test    # foo test1
Function: foo
Input: param1, param2, param3
Output: out1, out2

# Test 2: Description of the test    # foo test2
Function: foo
Input: param1, param2, param3
Output: out1, out2

# Test 3: Description of the test    # bar test1
Function: bar
Input: param1, param2, param3, param4
Output: out1, out2, out3
def test(func_name, args, out):
    func = getattr(functions, func_name)
    # `args` is a tuple for example.
    assert func(*args) == out, "Test routine failed"
您可以从配置文件中提取函数名、参数和输出

当涉及到一般的测试时,我建议使用。乍一看,它可能看起来很复杂,但它有一个非常好的文档,对于更大的项目来说,它绝对值得付出努力。您可以将测试过程包装在
unittest.TestCase
中,如下所示:

FunctionTestCase(unittest.TestCase):
    def __init__(self, func_name, args, out):
        self.func = getattr(functions, func_name)
        self.args = args
        self.out = out
    def test_func(self):
        self.assertEqual(self.func(*self.args), self.out)

您是否考虑过使用自己的测试框架而不是编写自己的测试框架?