您的位置:首页 > 编程语言 > Python开发

python3.5+selenium3.4自动化测试2_参数化

2017-05-22 17:16 567 查看

这边继续讲一个简单得登陆窗口,一般登陆窗口保护用户名和密码,那测试登陆的时候必然会用到不同的用户名和密码,这个时候就需要对参数化用户名和密码,先上一下代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchAttributeException
import unittest,time,re
from time import strftime, localtime
from datetime import datetime

import HTMLTestRunner
import mod_usr_pass

class LoginUser(unittest.TestCase):
def setUp(self):
self.driver=webdriver.Chrome()
self.driver.implicitly_wait(30)
self.base_url="http://192.168.1.131"
self.verificationErrors=[]
self.accept_next_alert=True

def test_loginuser(self):
'''
1.3.用户名和密码分别按以下填入:
1.用户名为admin,密码为正确密码
2.用户名为admin前加空格,密码为正确密码
3.用户名为admin后加空格,密码为正确密码
4.用户名为数字,密码为数字
5.用户名为monitor,密码为正确密码
点击“Login”登录
'''
driver=self.driver
driver.get(self.base_url+"/")

try:

driver.implicitly_wait(10) #智能等待30

for u,p in mod_usr_pass.usrpassdict().items():

driver.find_element_by_id("username").send_keys(u)

driver.find_element_by_id("secret").send_keys(p)

driver.find_element_by_id("login_button").click()
time.sleep(3)

if u!="1000":
driver.switch_to_alert().accept()

driver.find_element_by_xpath(".//*[@id='nav']/ul/li[1]/a").click()

driver.switch_to_alert().accept()

time.sleep(3)#等待10
else:
driver.find_element_by_xpath(".//*[@id='nav']/ul/li[1]/a").click()

driver.switch_to_alert().accept()

time.sleep(3)#等待10

except:

driver.get_screenshot_as_file(u"D:/python/selenium/error_png/1.login/1.3/%s.png" % datetime.now().strftime("%Y%m%d.%H%M%S.%f")[:-3])

def tearDown(self):
time.sleep(3)
self.driver.quit()
self.assertEqual([],self.verificationErrors)
if __name__=="__main__":
suite=unittest.TestSuite()
suite.addTest(LoginUser("test_loginuser"))

unittest.TextTestRunner().run(suite)


1. 下面是用户名和密码的函数,新建一个mod_usr_pass.py文件

def usrpassdict():

d={'admin':'password',
' admin':'password',
'admin ':'password',
'monitor':'password',
'1000':'1000',
}

return d


函数中定义了用户名对应密码的字典

2.主函数中,需要import mod_usr_pass ,然后循环调用字典中的用户名和密码

for u,p in mod_usr_pass.usrpassdict().items():

driver.find_element_by_id("username").send_keys(u)

driver.find_element_by_id("secret").send_keys(p)


以后只要在mod_usr_pass.py函数中修改不同的登陆用户名或密码就可以被多个不同的用例函数调用

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息