DEV Community

loading...

Using cmd switches with pytest to share data between tests

tswiftma profile image tswiftma ・2 min read

I'm kind of new to using Python Selenium with pytest and I needed to pass in come custom cmd line options when running tests with pytest. Specifically I needed the ability to pass in a custom url, hostheader, email and password value to my tests so they could run in different environments. I would think that everyone needs this for CI/CD tests today!

After lots of Googling for solutions I found that the suggestions on how to use switches were all over the place! I finally figured out to use the conftest.py file with the pytest_addoption method. Now there seems to be a lot of discussion on where to place the conftest.py file. I placed it above my \Tests folder, I haven't figured out the other complexities of it yet. Here's the content of conftest.py:

Alt Text

Note that in the pytest_addoption(parser) function I set default values for the switches that are for my most common test environment. The params(request): function is the key to returning an array of the params to the tests.

So how do you access the data in your tests? Really easy! Just pass params into your test functions and reference the params using params['MyParam']

Alt Text

Running the tests:

I can run my tests using only the pytest command because it has default values for the command line switches or I can substitute values by adding the actual switches themselves. Now you can run the tests anywhere in your CI/CD environment by substituting environment vars for the command line switches :)

Alt Text

Discussion (0)

pic
Editor guide