0

我在目录 A 中有一个文件 conftest.py。我在 A 中的目录 B 中有一些测试文件。我使用 py.test -sv B/ 运行所有这些文件。但是有时我想传递参数 -val="Hello" 并存储在文件中。

我正在尝试按以下方式进行操作:

import argparse
parser=argparse.ArgumentParser()
parser.add_argument("val",help="value")
args=parser.parse_args()
print(args.val)
a_file=open("file_val","w")
a_file.write(args.val)
a.file.close()
def pytest_addoption(parser):
    parser.addoption("--name", action="store", default="default name")

但是它什么也没写并给出错误:无法识别的参数:-sv —val=hello,当我运行 py.test -sv B/ —val=Hello

所以我尝试了以下操作:

import argparse

def pytest_addoption(parser):
    parser.addoption("--name", action="store", default="default name")
    parser.add_argument("val",help="value")
    args=parser.parse_args()
    print(args.val)
    a_file=open("file_val","w")
    a_file.write(args.val)
    a.file.close()

但它给出了错误:当我运行 py.test -sv B/ —val=Hello 时没有方法 add_argument

4

1 回答 1

0

运行 pytest -sv B/ 时读取命令行参数

它应该适合你:

首先,您需要使用addoption将读取选项的夹具传递参数。

为此,您应该创建一个单独的文件并将其命名conftest.py在您的测试文件夹中。

文件内容 conftest.py

import pytest


def pytest_addoption(parser):
    parser.addoption("--name", action="store", default="default name")


@pytest.fixture
def name(request):
    return request.config.getoption("--name")

然后,您需要创建一个带有参数的测试函数,该参数以单独文件中的夹具命名,或者在您的情况下,即使在单独的文件夹中也是如此。

内容B/test_write_file.py

def test_write_file(name):
    print(name)
    a_file = open("file_val.txt", "w")
    a_file.write(name)
    a_file.close()
    assert 0 # or whatever you want

之后,您可以从测试根文件夹自由地运行您的测试: pytest -sv B/ --name=Hello

输出:

________________ test_write_file _________________
name = 'Hello'

    def test_write_file(name):
        print(name)
        a_file = open("file_val.txt", "w")
        a_file.write(name)
        a_file.close()
>       assert 0
E       assert 0

B\test_write_file.py:8: AssertionError

你不需要使用argparsepytest为你做一切。

测试文件夹的结构:

在此处输入图像描述

就像在这个例子中一样:

https://docs.pytest.org/en/6.2.x/example/simple.html

干杯!

于 2021-06-15T15:30:01.303 回答