How to pass in command line arguments when scripting selenium tests using python unittest

I have been using a python unittest framework to write my selenium scripts in for about 6 months now and i must say i am really enjoying it.

Not having been a developer learning how to write scripts in python has really opened my eyes to the more powerful features of selenium.

One of the things that i need to cover in my role is testing on a number of different ecommerce web sites. Our main brand site has 6 different variations for different countries. These are:

  • UK
  • USA
  • Australia
  • EU (Site is in English but uses Euros as the currency)
  • France
  • Germany

Many of the elements of these sites are shared such as the buttons and forms so I didn’t really want to create a script to test each, this would mean more maintenance if things change and more work to create.

I wanted to create a script that i could tell to run on any of these sites. After a bit of head scratching and googling i decided that the best way to do this would be to pass in command line arguments to tell the script to run for a particular site. The problem with this is that when you run a python unittest script it has its own set of command line arguments you can pass in so on the face of it creating and using my own seemed to be a non starter.

However i then found a way around this problem, what i needed to do was to extract my command line arguments into separate variables and remove them from the sys.arg before calling unittest.main()

Example of this at the end of a script.

Screen Shot 2015-09-17 at 23.23.55


And this is the line that uses that arg to get the passed in website url:

Screen Shot 2015-09-17 at 23.34.55

Now I can pass in the website i want the test to run on as the first sys.argv and then use this with the webdriver.get command to start my script on the right site.

Hope this helps if you’re looking for a similar solution for your python unitest selenium script. I will be posting more on how i have expanded my scripts in other ways by using command line arguments soon.

Thanks for reading!