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')
Related
I am new to python and test complete just trying to automate a sample webpage but stuck with below error.
I have searched and know that I am surely making mistakes in defining the variables.
have recorded the below script and it runs fine if I keep it one function but when I keep it in separate functions(to login into page have kept the code in Login() function and calling it in Test1() ) it fails though it login into the page .
global browser,page
def Login():
Browsers.Item[btChrome].Navigate("http://secure.smartbearsoftware.com/samples/testcomplete11/WebOrders/login.aspx")
browser=Aliases.browser
page = browser.pageWebOrdersLogin
form = page.formAspnetform
form.textboxUsername.Keys("[Enter]")
page.Wait()
textbox = form.textboxUsername2
textbox.SetText("Tester")
textbox.Keys("[Tab]")
passwordBox = form.passwordboxPassword
passwordBox.SetText(Project.Variables.Password1)
passwordBox.Keys("[Enter]")
page = browser.pageDefault
page.Wait()
def Test1():
global page
Login()
page.formAspnetform.link.Click()
page = browser.pageProcess
page.Wait()
form = page.formAspnetform
form.selectProduct.ClickItem("FamilyAlbum")
textbox = form.textboxQuantity
textbox.SetText("40")
form.submitbuttonCalculate.ClickButton()
textbox = form.textboxCustomerName
textbox.SetText("nitin")
textbox.Keys("[Tab]")
textbox = form.textboxStreet
textbox.SetText("marvel")
textbox.Keys("[Tab]")
textbox = form.textboxCity
textbox.SetText("pune")
textbox.Keys("[Tab]")
textbox = form.textboxState
textbox.SetText("maharashta")
textbox.Keys("[Tab]")
form.textboxZip.SetText("411014")
cell = form.cell
cell.radiobuttonVisa.ClickButton()
textbox = form.textboxCardNr
textbox.SetText("411882781991")
textbox = form.textboxExpireDateMmYy
textbox.SetText("01/23")
form.linkInsertbutton.Click()
page.Wait()
textNode = page.textnode
aqObject.CheckProperty(textNode, "contentText", cmpEqual, "New order has been successfully added.")
page.link.Click()
browser.pageDefault2.Wait()
Error:
Python runtime error.
NameError: name 'page' is not defined
Error location:
Unit: "WebTesting\WebTesting\Script\WebTest"
Line: 22 Column: 1.
The global declaration for page needs to be repeated inside the def Login; but a much better design is to pass non-global variables between these functions. Either
def login():
browser = ...
page = ...
...
return browser, page
def test1():
browser, page = login()
...
or perhaps conversely have the caller define and pass these in;
def login(browser, page):
...
def test1()
browser = ...
page = ...
login(browser, page)
...
Your current design calls for the former, but both patterns are common, and the second is perhaps more logical. Generally, try to define variables in the context where they are going to be used, and then pass them down into other functions as necessary. As a rule of thumb, try to make your variables as narrowly scoped and short-lived as possible.
Notice also how we usually do not capitalize function names in Python.
I am attempting to automate a login process.
To do so, I am using send_keys('email') and send_keys('password') in their respective fields like so:
email = driver.find_element_by_xpath('//*[#id="email"]')
email.send_keys('e#mail.com')
pwd = driver.find_element_by_xpath('//*[#id="password"]')
pwd.send_keys('pwd12345')
These two steps are successful. Now, I would like to use the "return" key to submit the login credentials and be logged in. To do so, I have tried:
pwd.send_keys(Keys.RETURN)
The password I am attempting to enter is 8 characters long. After the 8 characters have been entered, pwd.send_keys(Keys.RETURN) enters a 9th character into the password field JUST before the credentials are submitted, resulting in "incorrect email address or password".
I have also tried:
email.send_keys(Keys.RETURN) - which also returns "incorrect email address or password"
pwd.submit() - which clears the email and password fields completely and does not log in (?)
Thoughts?
Can you try code below?
pwd = driver.find_element_by_xpath('//*[#id="password"]')
ActionChains(driver).send_keys_to_element(pwd,'pwd12345').send_keys_to_element(pwd, Keys.RETURN).perform()
Here is the Answer to your Question:
Considering you are trying to login in to your PayPal Account with a valid set of credentials the following code block works through all the 3 options as in:
Using click()
Using Keys.ENTER
Using Keys.RETURN
Having said that I will suggest you to consider using the click() and clear() methods before entering any text into any input tag. Here is the working code block:
driver.get('https://www.paypal.com/in/home');
driver.implicitly_wait(20);
driver.find_element_by_id('ul-btn').click();
email = driver.find_element_by_id('email')
email.click();
email.clear();
email.send_keys('debanjan.selenium#gmail.com');
password = driver.find_element_by_id('password');
password.click();
password.clear();
password.send_keys('dev_anjan');
#Using Keys.ENTER
#password.send_keys(Keys.ENTER);
#Using Keys.RETURN
password.send_keys(Keys.RETURN);
#Using LogIn Button Click
#login_button = driver.find_element_by_id('btnLogin')
#login_button.click();
Let me know if this Answers your Question.
Please try this way, it's working for me:
email = driver.find_element_by_xpath('//*[#id="email"]')
email.send_keys('e#mail.com')
pwd = driver.find_element_by_xpath('//*[#id="password"]')
pwd.send_keys('pwd12345')
login_button = driver.find_element_by_xpath('//*[#id="btnLogin"]')
login_button.click()
Insted of pressing Enter on the password field you should do what a normal guy does and press the Log In button.
I'm trying to use send_keys to fill a field and in the same time, store this value in a variable. When I run this code, the text of the variable is not printed.
locators.py
from selenium.webdriver.common.by import By
class CreateNewContractor(object):
FIRST_NAME = (By.ID, "id_0-first_name")
pages.py
from locators import *
class CreateNewContractor1(Page):
def fill_contractor(self):
email = self.find_element(*CreateNewContractor.FIRST_NAME).send_keys("Hello")
email.text
print email
How can I store and print the text filled in the email variable?
The email variable would get the value None - this is what send_keys() method returns.
Instead, you can simply keep the text in a variable:
text = "hello"
self.find_element(*CreateNewContractor.FIRST_NAME).send_keys(text)
print(text)
Or, if you want to actually get the value of the input, use get_attribute() method:
elm = self.find_element(*CreateNewContractor.FIRST_NAME)
elm.send_keys("hello")
print(elm.get_attribute("value"))
I know I have already asked a question like this before but I have made my code much cleaner and I am still coming up with a problem.
My code goes like this:
class Email_Stuff:
def Get_From_Email():
#code to open up window and get email address
emailaddr = #the input
return emailaddr
def Get_To_Email():
#code to open up window and get to email address
recipaddr = #the input
return recipaddr
def Get_Email_Address():
#code to open up window and get email username
EmailUser = #the input
return EmailUser
def Get_Email_Password():
#code to open up window and get email password
EmailPass = #the input
return EmailPass
def Send_Email():
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.login((EmailUser),(EmailPass))
message = "Python Test Email"
server.sendmail(emailaddr,recipaddr,message)
I need to get the variables: emailaddr, recipaddr, EmailUser, and EmailPass into the function Send_Email. I'm not sure how I could do that though because when I run this code, it tells me that "the global name isn't defined".
Any ideas?
Make emailaddr, recipaddr, EmailUser, and EmailPass become instance variables by adding prefix "self.".
class Email_Stuff():
def Get_From_Email(self):
#code to open up window and get email address
self.emailaddr = #the input
def Get_To_Email(self):
#code to open up window and get to email address
self.recipaddr = #the input
def Get_Email_Address(self):
#code to open up window and get email username
self.EmailUser = #the input
def Get_Email_Password(self):
#code to open up window and get email password
self.EmailPass = #the input
def Send_Email(self):
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.login((self.EmailUser),(self.EmailPass))
message = "Python Test Email"
server.sendmail(self.emailaddr,self.recipaddr,self.message)
instance = Email_Stuff()
instance.Get_From_Email()
instance.Get_To_Email()
instance.Get_Email_Address()
instance.Get_Email_Password()
instance.Send_Email()
BTW, name of methods should be lowercase.
First, if you want these functions to methods associated with an instance of this class, then each method will need a reference to the instance itself as the first argument, usually designated as self, though you can name it anything you like.
For example:
def Get_Email_Password(self):
#code to open up window and get email password
EmailPass = #the input
return EmailPass
Next, you have two options to get the values ready for sendmail. You can either call each method from within the Send_Email method and store the returned values for each one. That would look like this:
def Send_Email(self):
emailaddr = self.Get_For_Email()
recipaddr = self.Get_Email_Address()
...
Or you can store the values, instead of returning them, as instance variables. So, you would have something like this:
def Get_Email_Password(self):
#code to open up window and get email password
EmailPass = #the input
self.emailaddr = EmailPass
And then, in your Send_Email method, you would reference the instance variables you have saved:
def Send_Email(self):
...
server.sendmail(self.emailaddr, self.recipaddr, self.message)
How you choose to do it is up to you, but I prefer the first way. I also suggest you read up on PEP8
I am attempting to create a login script. I have the usernames and passwords in a text file that I want python to read and check through to find usernames and passwords.
The biggest problem I am having is "attaching" the password to a username. I can currently only scan the whole of the document for both but not necessarily attached to each other.
#-------------------------------------------------------------------------------
# Name: LogIn
# Purpose: Logging In
#
# Author: Dark Ariel7
#
# Created: 19/02/2013
# Copyright: (c) Dark Ariel7 2013
# Licence: I take no responsability for anything.
#-------------------------------------------------------------------------------
from getpass import getpass
from time import sleep
Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", encoding='utf-8')
Username = ("")
Password = ()
def LogIn():
Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", encoding='utf-8')
Data = (Database.read())
Username = ("")
Password = ()
Username = input("Username: ")
Password = getpass(str("Password: "))
LogIn= ",".join((Username,Password))
if LogIn in Data:
print("Welcome, " + Username)
sleep(3)
pass
else:
print("Failed, Sucker!")
sleep(5)
exit()
LogIn()
If you guys could help me figure out what exactly .join part is for that would be great. Should i make a dictionary and use the index for a login sheet? I also want some general feedback on how to make the code better.
This is the txt file that it will be reading:
[Dark Ariel7,123456]
[Poop,Anko]
*Edit Sorry guys I forgot to mention that I am using python 3 not 2. Thanks so far. Very quick replies. Also after the last else instead of exit what do I put so that the function loops until I get the right username password combo?
The ".join" part joins the username and password that the user types in with a comma between them (i.e. Poop,Anko) because that's the format in which it's stored in the database, so you can search for it that way.
Here's your code, edited up a bit, with some comments about functionality and style.
from getpass import getpass
from time import sleep
Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", encoding='utf-8')
# These next two lines aren't necessary - these variables are never used; you may want to read up about namespaces: http://bytebaker.com/2008/07/30/python-namespaces/
#Username = ("")
#Password = ()
def LogIn():
Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", encoding='utf-8')
# Removed the parentheses; they have no effect here. Putting parens around lone statements doesn't have any effect in python.
Data = Database.read()
# These next two lines are pointless, because you subsequently overwrite the values you give these variables. It looks like you're trying to "declare" variables, as you would in Java, but this isn't necessary in python.
# Username = ("")
# Password = ()
# Changed this from "input" to "raw_input" because input does something else that you don't want.
Username = raw_input("Username: ")
Password = getpass(str("Password: "))
LogIn= ",".join((Username,Password))
if LogIn in Data:
print("Welcome, " + Username)
# Not sure why you want the script to sleep, but I assume you have your reasons?
sleep(3)
# no need to pass
# pass
else:
print("Failed, Sucker!")
sleep(5)
# exit() isn't necessary - the function will end by itself.
# exit()
LogIn()
The basic problem you have is that your file has [ ] surrounding the username and password combination, but you fail to account for this.
There are some other stylistic issues with your code, here is an edited version:
import getpass
from time import sleep
password_file = r'C:\....\Database.txt'
def login(user,passwd):
''' Checks the credentials of a user '''
with open(password_file) as f:
for line in f:
if line.strip(): # skips blank lines
username,password = line.split(',') # this gets the individual parts
username = username[1:] # gets rid of the [
password = password[:-1] # the same for the password
if user == username and password == passwd:
return True
return False
if __name__ == '__main__':
username = input('Please enter the username: ')
passwd = getpass('Please enter the password: ')
if login(user,passwd):
print('Welcome {1}'.format(user))
sleep(3)
else:
print('Failed! Mwahahaha!!')
sleep(5)
To start off with, you don't need () to "initialize" variables; more to the point in Python you don't need to initialize variables at all. This is because Python doesn't have variables; but rather names that point to things.
Next, the python style guide says that variable names should be lowercase, along with method names.
Now - the main part of the code:
>>> username, password = '[username,sekret]'.split(',')
>>> username
'[username'
>>> password
'sekret]'
I used split() to break up the line into the username and password parts; but as you see there is still the [ messing things up. Next I did this:
>>> username[1:]
'username'
>>> password[:-1]
'sekret'
This uses the slice notation to strip of the leading and ending characters, getting rid of the [ ].
These lines:
with open(password_file) as f: # 1
for line in f: # 2
if line.strip(): # skips blank lines
Do the following:
Opens the file and assigns it to the variable f (see more on the with statement)
This for loop steps through each line in f and assigns the name line to each line from the file.
The third part makes sure we skip blank lines. strip() will remove all non-printable characters; so if there are no characters left, the line is blank and will have a 0 length. Since if loops only work when the condition is true, and 0 is a false value - in effect what happens is we only operate on non-blank lines.
The final part of the code is another if statement. This is a check to make sure that the file will run when you execute it from the command prompt.