Codementor Events

Quick tip: Adding pytest CLI options

Published Mar 06, 2021Last updated Sep 01, 2021

Pytest has the ability to add CLI options during invocation to add more flexibility in your test suite. If you've ever used a pytest extension you've likley seen this in action. In this quick example I'll show you how to add a CLI option to switch a pytest-selenium into headless mode for running in a CI/CD pipeline. While writing tests locally I like to have the tests run the browser so I can catch any potential issues, however in a CI/CD build you'll want to run them headless. For simplicity we will just use the Chrome driver in Selenium in this example.

First we need to setup the CLI option. In conftest.py simply implement the pytest_addopts function that takes the argument parser. The interface for parser.addoption is the same as argparse.ArgumentParser.add_argument (docs).

def pytest_addopts(parser):
    parser.addoption(
    	"--headless",
        action="store_true",
        help="Run driver in headless mode."
  )

Using the action store_true we will set --headless to be True when present and default to False when not provided.

The next part will be to consume the CLI value in the driver options. For Chrome you do this by implementing the fixture chrome_options as follows.

@pytest.fixture()
def chrome_options(request, chrome_options):
  if not request.config.getoption("--headless"):
    	chrome_options.add_argument("--window-size=2560,1440")
        # any other config values to be ran when not headless
    else:
    	chrome_options.add_argument("--headless")
        chrome_options.add_argument("--window-size=2560,1440")
        # any other config values to be ran when headless
    return chrome_options

To run you test headless now just run pytest --driver chrome --headless or with the browser simply omit the --headless and you should be good.

I hope this was helpful in introducing an awesome feature of pytest. Let me know if there are any other quick tidbits that would be helpful or a more in depth example of what pytest has to offer.

Discover and read more posts from Adam Mertz
get started
post commentsBe the first to share your opinion
Show more replies