简体   繁体   中英

Passing variables to functions in Python

Im writing test scripts in Python for Selenium web testing.

How do I pass parameters through a Python function to call in a later function? I first have a login test function. Then I have a new user registration function. Im trying to pass the Username and Password I use in the registration function to the testLogin() function that I call inside the testRegister() function.

This is my python code:

userName = "admin"
password = "admin"

#pass username and password variables to this function
def testLogin(userName,password):
  browser = webdriver.Firefox()
  browser.get("http://url/login")

  element = browser.find_element_by_name("userName")
  element.send_keys(userName)

  element = browser.find_element_by_name("userPassword")
  element.send_keys(password)

  element.send_keys(Keys.RETURN)

  browser.close()

# test registration
def testRegister():
  browser = webdriver.Firefox()
  browser.get("http://url/register")

  #new username variable
  newUserName = "test"
  element = browser.find_element_by_name("regUser")
  element.send_keys(newUserName)

  #new password variable
  newUserPassword = "test"
  element = browser.find_element_by_name("regPassword")
  element.send_keys(newUserPassword)

  #
  #now test if user is registered, I want to call testLogin with the test user name and pw.
  testLogin(newUserName,newUserPassword)

  browser.close()

Any values you have around—whether you got them as function arguments, or received them by calling functions, or just defined them on the fly—you can pass as arguments to any other function.

So, if you want to pass some values through testRegister for it to use with testLogin , just do this:

# test registration
def testRegister(userName, password):
  browser = webdriver.Firefox()
  browser.get("http://url/register")

  element = browser.find_element_by_name("regUser")
  element.send_keys(userName)

  element = browser.find_element_by_name("regPassword")
  element.send_keys(password)

Is there something more you wanted?

You can create a new function to run all of your tests.

def run_tests(username, password):
    testLogin(username,password)
    testRegister(username, password)

You will need to modify testRegister so it accepts username and password parameters.

Then you can start your script with run_tests('admin', 'letmein')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM