python - Pytest 在使用预定义参数 vai argparse 运行测试时抛出参数错误

抱歉,这太长了。在运行 pytest 之前,我们已经创建了许多 Selenium 测试脚本。每个测试都导入一个我们创建的框架;该框架具有类似于以下设置的参数解析器:

# Methods class

from ConfigParser import SafeConfigParser
import argparse

config = SafeConfigParser()
parser = argparse.ArgumentParser()

parser.add_argument("-d", "--logdirectory", help="help for directory")
parser.add_argument("-b", "--browser", help="help for browser")
parser.add_argument("--debug", help="help for debug")

args = parser.parse_args()

每个测试都导入该类:

from TestMethods import Methods

app = "specific tool to test"
test = Methods(app)
print "just doing something"

让我们假设这就是正在发生的一切。据我了解,为了让 pytest 工作,您需要在方法中进行测试,因此:

from TestMethods import Methods

@pytest.mark.run
def test_test1():
    app = "specific tool to test"
    test = Methods(app)
    print "just doing something"

现在要运行这个,我可以调用:

py.test

这在技术上是可行的。但是,如果我想指定测试:

py.test test_script_name.py

或者只查找标记为运行的方法:

py.test test_script_name.py -m run

或做任何涉及添加参数的事情:

py.test test_script_name.py -d logname

它会抛出一个参数错误,例如:

---------------------------- Captured stderr call ----------------------
usage: py.test [-h] [-d LOGDIRECTORY] [-b {firefox,chrome,ie}] [--debug]
py.test: error: unrecognized arguments: test_script_name.py

我假设这是因为 argparse 不允许除我在框架中指定的参数之外的参数。我如何做到这一点,以便在我发送参数时测试不会中断?我更愿意继续使用 argparse,但如果不可能,那么我可能会接受其他想法。

编辑:

我很确定我基本上只是希望 py.test 在从命令行调用测试时允许附加参数。在这种情况下,我希望能够发送 -d 和 -b;测试将能够很好地读取那些,我只需要 py.test 允许它。另外需要注意的是 argparse 允许这个命令:

parser.parse_known_args()

这使得它忽略任何未使用 add_argument 指定的参数。

最佳答案

我有一个类似的问题,我可以提供一个不使用 argparse 的答案,但是 pytest_addoption Hook - 另见 http://pytest.readthedocs.org/en/2.0.3/example/simple.html .有了这个,您可以将选项(例如 cmdopt)传递给 py.test,然后运行 ​​

py.test --debug=<whatever> test_script_name.py

引用链接示例,您的 conftest.py应包含:

# content of conftest.py
import pytest

def pytest_addoption(parser):
parser.addoption("--debug", help="help for debug")

然后您可以将选项(或所有选项)的值传递给测试函数,如本例所示:

# content of test_test1.py
def test_test1(pytestconfig):
    debug = pytestconfig.option.debug # pass a single option
    all_options = pytestconfig.option # pass all options
    assert(False)

或者您可以在 fixture 中使用该选项(这是我的问题)。在这种情况下,您可以从请求对象中获取值。我认为您也可以将您的方法作为固定装置调用。

@pytest.fixture(scope='class')
def method_instance(request):
    custom_options = request.config.option
    app = "specific tool to test"
    this_instance = Method(app, custom_options)
    return this_instance

https://stackoverflow.com/questions/33311530/

相关文章:

python - AssertListEqual 不改变类 __eq__ 方法

python - 标准Django/python单位转换包

python - 无法使用 OS X El Capitan pip 安装任何东西

git - 我们可以将 git-annex 添加到 GitLab CE 吗?

linux-kernel - Linux 内核模块在卸载期间挂起

java - Android,如何在运行时设置导航 View 组可见性?

java - Kafka集群zookeeper故障处理

python - 使用 pyresample 绘制卫星 strip 数据

google-chrome - 如何禁用谷歌浏览器 url 转义?

javascript - 当鼠标进入非事件浏览器窗口时触发一次 mousemove (Chrome)