问题
I have some unit tests, but I'm looking for a way to tag some specific unit tests to have them skipped unless you declare an option when you call the tests.
Example:
If I call pytest test_reports.py
, I'd want a couple specific unit tests to not be run.
But if I call pytest -<something> test_reports
, then I want all my tests to be run.
I looked into the @pytest.mark.skipif(condition)
tag but couldn't quite figure it out, so not sure if I'm on the right track or not. Any guidance here would be great!
回答1:
We are using markers with addoption in conftest.py
testcase:
@pytest.mark.no_cmd
def test_skip_if_no_command_line():
assert True
conftest.py: in function
def pytest_addoption(parser):
parser.addoption("--no_cmd", action="store_true",
help="run the tests only in case of that command line (marked with marker @no_cmd)")
in function
def pytest_runtest_setup(item):
if 'no_cmd' in item.keywords and not item.config.getoption("--no_cmd"):
pytest.skip("need --no_cmd option to run this test")
pytest call:
py.test test_the_marker
-> test will be skipped
py.test test_the_marker --no_cmd
-> test will run
回答2:
There are two ways to do that:
First method is to tag the functions with @pytest.mark
decorator and run / skip the tagged functions alone using -m
option.
@pytest.mark.anytag
def test_calc_add():
assert True
@pytest.mark.anytag
def test_calc_multiply():
assert True
def test_calc_divide():
assert True
Running the script as py.test -m anytag test_script.py
will run only the first two functions.
Alternatively run as py.test -m "not anytag" test_script.py
will run only the third function and skip the first two functions.
Here 'anytag' is the name of the tag. It can be anything.!
Second way is to run the functions with a common substring in their name using -k
option.
def test_calc_add():
assert True
def test_calc_multiply():
assert True
def test_divide():
assert True
Running the script as py.test -k calc test_script.py
will run the functions and skip the last one.
Note that 'calc' is the common substring present in both the function name and any other function having 'calc' in its name like 'calculate' will also be run.
回答3:
I think what you are looking for is sys.argv
. Details on that can be found here: http://www.pythonforbeginners.com/system/python-sys-argv
There's another easier(but arguably boring) way to do it How do I run Python script using arguments in windows command line
来源:https://stackoverflow.com/questions/47559524/pytest-how-to-skip-tests-unless-you-declare-an-option-flag