Search code examples
pythonseleniumpytestpytest-selenium

How to pass arguments to Selenium test functions in Pytest?


I wamt to make my tests more flexible. For example I have a _test_login_ that could be reused with multiple different login credentials. How do I pass them as arguments instead of hard-coding them?

What I have right now:

from selenium import webdriver
import pytest
def test_login():
    driver = webdriver.Chrome()
    driver.get("https://semantic-ui.com/examples/login.html")

    emailBox = driver.find_element_by_name("email")
    pwBox = driver.find_element_by_name("password")

    emailBox.send_keys("someLogin")
    pwBox.send_keys("somePW")

How can I replace the string literals in the last two lines with something more flexible?

I want to have something like this:

from selenium import webdriver
import pytest
def test_login(specifiedEmail, specifiedPW):
    driver = webdriver.Chrome()
    driver.get("https://semantic-ui.com/examples/login.html")

    emailBox = driver.find_element_by_name("email")
    pwBox = driver.find_element_by_name("password")

    emailBox.send_keys(specifiedEmail)
    pwBox.send_keys(specificedPW)

Could you explain how to do this by calling the script as:

pytest main.py *specifiedEmail* *specifiedPW*


Solution

  • Try to use sys.arg.

    import sys
    for arg in sys.argv:
        print(arg)
    print ("email:" + sys.argv[2])
    print ("password:" + sys.argv[3])
    

    Here is how your code will look like:

    from selenium import webdriver
    import pytest
    import sys
    
    def test_login(specifiedEmail, specifiedPW):
        driver = webdriver.Chrome()
        driver.get("https://semantic-ui.com/examples/login.html")
    
        emailBox = driver.find_element_by_name("email")
        pwBox = driver.find_element_by_name("password")
    
        emailBox.send_keys(sys.argv[2])
        pwBox.send_keys(sys.argv[3])