抱歉,这很长。我们在运行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
或仅查找标记为run的方法:
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指定的参数。
答案 0 :(得分:0)
我遇到了类似的问题,我可以提供不使用argparse
但pytest_addoption
挂钩 - 的答案 - 另请参阅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)
或者您可以在灯具中使用该选项(这是我的问题)。在这种情况下,您可以从请求对象中获取值。我想你也可以调用你的方法作为固定装置。
@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