测试在pytest中被跳过

test getting skipped in pytest

我正在尝试使用参数化,我想为其提供测试用例,这些测试用例是我使用 pytest 从不同的函数获得的。 我试过这个

test_input = []
rarp_input1 = ""
rarp_output1 = ""
count =1
def test_first_rarp():
    global test_input
    config = ConfigParser.ConfigParser()
    config.read(sys.argv[2])
    global rarp_input1
    global rarp_output1
    rarp_input1 = config.get('rarp', 'rarp_input1')
    rarp_input1 =dpkt.ethernet.Ethernet(rarp_input1)
    rarp_input2 = config.get('rarp','rarp_input2')
    rarp_output1 = config.getint('rarp','rarp_output1')
    rarp_output2 = config.get('rarp','rarp_output2')
    dict_input = []
    dict_input.append(rarp_input1)
    dict_output = []
    dict_output.append(rarp_output1)
    global count
    test_input.append((dict_input[0],count,dict_output[0]))
    #assert test_input == [something something,someInt]

@pytest.mark.parametrize("test_input1,test_input2,expected1",test_input)
def test_mod_rarp(test_input1,test_input2,expected1):
    global test_input
    assert mod_rarp(test_input1,test_input2) == expected1

但是第二个测试用例被跳过了。它说

test_mod_rarp1.py::test_mod_rarp[test_input10-test_input20-expected10]

为什么测试用例会被跳过?我已经检查过函数和输入都没有错。因为下面的代码工作正常

@pytest.mark.parametrize("test_input1,test_input2,expected1,[something something,someInt,someInt])
def test_mod_rarp(test_input1,test_input2,expected1):
    assert mod_rarp(test_input1,test_input2) == expected1

我没有在这里输入实际信息。无论如何它是正确的。我也有配置文件,我正在使用 configParser 从中获取输入。 test_mod_rarp1.py 是我执行此操作的 python 文件名。我基本上想知道我们是否可以从其他函数访问变量(在我的示例中为 test_input)以在参数化中使用,如果这是在这里引起问题的话。如果我们不能,我该如何更改变量的范围?

参数化发生在编译时,所以如果你想对在 运行 时生成的数据进行参数化,它会跳过那个。

实现您想要做的事情的理想方法是使用夹具参数化。

下面的示例应该可以为您解决问题,然后您可以在您的案例中应用相同的逻辑

import pytest
input = []

def generate_input():
    global input
    input = [10,20,30]



@pytest.mark.parametrize("a", input)
def test_1(a):
    assert a < 25

def generate_input2():
    return [10, 20, 30]


@pytest.fixture(params=generate_input2())
def a(request):
    return request.param

def test_2(a):
    assert a < 25

OP

<SKIPPED:>pytest_suites/test_sample.py::test_1[a0]


********** test_2[10] **********
<EXECUTING:>pytest_suites/test_sample.py::test_2[10]
Collected Tests
TEST::pytest_suites/test_sample.py::test_1[a0]
TEST::pytest_suites/test_sample.py::test_2[10]
TEST::pytest_suites/test_sample.py::test_2[20]
TEST::pytest_suites/test_sample.py::test_2[30]

请参阅 test_1 被跳过,因为参数化发生在执行 generate_input() 之前,但 test_2 已根据需要进行参数化