如何在Pytest中将参数传递给Selenium测试函数?

时间:2019-03-14 14:14:35

标签: python selenium pytest pytest-selenium

我努力让测试更加灵活。例如,我有一个_test_login_,可以与多个不同的登录凭据重用。如何将它们作为参数传递,而不是对其进行硬编码?

我现在所拥有的:

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")

如何用更灵活的方式替换最后两行中的字符串文字?

我想要这样的东西:

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)

您能否通过调用脚本来解释如何做到这一点:

pytest main.py *specifiedEmail* *specifiedPW*

2 个答案:

答案 0 :(得分:1)

尝试使用sys.arg

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

这是您的代码的外观:

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])

答案 1 :(得分:0)

实现此目标的另一种方法是在pytest中使用“请求”。

sudo ufw disable

在命令提示符下,您可以使用-

def pytest_addoption(parser):
    parser.addoption("--email", action="store", default="myemail@email.com", 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"))

此方法有两个优点。

  1. 该命令更加用户友好。
  2. 您可以更方便地设置默认值。