PyTest:测试在if语句中调用的函数

时间:2016-05-31 13:19:28

标签: python python-2.7 testing pytest

我有一个函数,它考虑三种不同的情况,并且每种情况都调用一个不同的函数,如下例所示

def my_fun(input):
 if input == 1:
    fun1()
 if input == 2:
    fun2()
 if input == 3:
    fun3()

我想使用my_fun编写函数py.test的测试,但我不知道如何测试是否为给定的输入调用了正确的函数?

3 个答案:

答案 0 :(得分:4)

正如@fmarc评论的那样,调用哪个函数比测试my_fun做正确的事情要重要得多。但是,您可以模拟三个函数中的每一个,然后测试是否正确调用了每个函数,而不管每个函数实际执行的操作。 (请注意,mock是Python 2中的第三方模块,您需要安装;它可以在Python 3.3(?)中作为unittest.mock使用标准库。)

一个简单的例子:

import mock

def test_my_fun():
    with mock.patch('fun1', wraps=fun1) as mock_fun1:
        with mock.patch('fun2', wraps=fun2) as mock_fun2:
            with mock.patch('fun3', wraps=fun3) as mock_fun3:
                my_fun(1)
                mock_fun1.assert_called_with()
                mock_fun2.assert_not_called()
                mock_fun3.assert_not_called()

查看mock安装的文档,了解支持哪些方法。

答案 1 :(得分:3)

如果所有fun1(),fun2()和fun3()都返回结果,我会选择参数化。

# Here an example of functions to be tested

def fun1():
    return 1
def fun2():
    return 2
def fun3():
    return 3

def my_fun(input):
    if input == 1:
        return fun1()
    if input == 2:
        return fun2()
    if input == 3:
        return fun3()

这里是测试矩阵。预期的结果也是对被测函数的调用,因此您可以匹配测试中的函数调用(如您在问题中所述):

# Parametrized test
import pytest

@pytest.mark.parametrize("test_input, expected", [(1, fun1()), (2, fun2()), (3, fun3())])
# ---------------------------------------
# test_input |   1    |   2    |   3    |
# ---------------------------------------
#   expected | fun1() | fun2() | fun3() |
# ---------------------------------------
def test_my_fun(test_input, expected):
    assert my_fun(test_input) == expected

试运行:

mac: py.test -v test_parametrization.py
=================================================================================== test session starts ====================================================================================
platform darwin -- Python 2.7.11, pytest-2.9.1, py-1.4.31, pluggy-0.3.1 -- /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
cachedir: .cache
rootdir: /Users/user/Repos/playground, inifile:
plugins: hidecaptured-0.1.2, instafail-0.3.0
collected 3 items

test_parametrization.py::test_my_fun[1-1] PASSED
test_parametrization.py::test_my_fun[2-2] PASSED
test_parametrization.py::test_my_fun[3-3] PASSED

================================================================================= 3 passed in 0.01 seconds =================================================================================

答案 2 :(得分:-3)

为什么多个if语句而不是elif?他们的条件是互相排斥的,那么为什但无论如何,虚拟打印怎么样,如:

InventMov_Sales

如果我有足够的声誉,我会评论btw。 #JustWannaGetTo50

相关问题