Reputation: 189
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*
Upvotes: 1
Views: 930
Reputation: 104
Another way to achive this is by using 'request' in pytest.
def pytest_addoption(parser):
parser.addoption("--email", action="store", default="[email protected]", help="Your email here")
parser.addoption("--password", action="store", default="strongpassword", help="your password")
from selenium import webdriver
import pytest
def test_login(request):
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(request.config.getoption("--email"))
pwBox.send_keys(request.config.getoption("--password"))
In the command prompt you can use -
pytest --email="[email protected]" --password="myPassword"
pytest --password="mysecondPassword" --email="[email protected]"
pytest --email="[email protected]"
You get two advantages by this approch.
Upvotes: 0
Reputation: 14145
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])
Upvotes: 2