python实现自动化脚本编写

时间:2021-10-19 03:36:19

本文以修改用户名密码单元为案例,编写测试脚本。完成修改用户名密码模块单元测试。

(ps.这个demo中登陆密码为“admin”)

1. 打开浏览器,访问p.to

?
1
2
3
4
5
# 1. 打开浏览器,访问p.to
driver = webdriver.Chrome()
def openDriver():
    driver.get("http://p.to")
    driver.maximize_window()

2. 登陆

登陆这动作传入的参数只有一个“用户密码”

需要执行的操作有两个:1. 向输入框输入密码 2. 点击确定

需要注意的是在登陆的时候可能出现页面还没有加载出来,我们的程序就开始填写表单的情况。

为了防止异常出现,编写了函数waitandSendkeys和waitandClick来处理异常。(后面将会介绍异常处理函数)

?
1
2
3
4
5
6
7
class loginClass(object):
    """docstring for login"""
    def __init__(self, arg):
        self.login_pwd = arg
    def login(self):
        waitandSendkeys('//*[@id="Pwd"]', self.login_pwd)
        waitandClick('//*[@id="Save"]')

3. 修改管理员密码

需要传入的参数有两个:1.旧密码 2. 新密码

要注意的是由于修改管理员密码是一个弹窗,所以要判断等弹窗弹出之后再进行操作

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class changePwdClass(object):
    """docstring for changePwdClass"""
    def __init__(self, pwdNew, pwdOld):
        self.pwdNew = pwdNew       
        self.pwdOld = pwdOld
 
    def changeUserPwd(self):
        waitandClick('//*[@id="Con"]/div[1]/ul[2]/li[1]')
        waitandClick('//*[@id="Con"]/div[1]/ul[2]/li[1]/ul/li[3]')
        waitforDisplay('//*[@id="_Widget"]')
        waitandSendkeys('//*[@id="PwdOld"]', self.pwdOld)
        waitandSendkeys('//*[@id="PwdNew"]', self.pwdNew)
        waitandSendkeys('//*[@id="PwdCfm"]', self.pwdNew)
        waitandClick('//*[@id="SavePwd"]')

到这里,我们可以完成修改用户名密码这一动作。后面将进行单元测试。

4. 单元测试数据

修改用户名密码这个功能的防呆规则如下:

 

输入项 允许输入 可为空 格式规范 合法性 依赖项
原管理员密码 字符串 长度限制:5-63; 字符集:英文字符集; 需要与管理员密码相同
新管理员密码 字符串 长度限制:5-63; 字符集:英文字符集;  
确认管理员密码 字符串 需要与新管理员密码相同  

 

根据防呆规则可以列出:1.可能出现的错误 2.出现错误时页面应有的提示语

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#可能出现的错误
errcode = ['oldPwdErr', 'lenErr', 'charErr', 'matchErr', 'pwdSameErr',\
    'oldPwdBlankErr', 'newPwdBlankErr']
 
#出现错误时页面应有的提示语
errTips = {
    'oldPwdErr' :'原密码错误',
    'lenErr' : '新密码长度应为5~63位',
    'charErr' : "新密码包含非法字符",
    'matchErr' : '两次密码输入不一致',
    'pwdSameErr' : '新密码与原密码相同,请重新输入',
    'oldPwdBlankErr' : '请输入原密码',
    'newPwdBlankErr' : '请输入新密码'
}

5. 检查输入的数据合法性

需要输入的数据为要检查的data和登陆密码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def checkData(data, loginPwd):#检查顺序跟页面顺序相同
    pwd = loginPwd
    #'oldPwdBlankErr'
    if data['pwdOld'] == "":
        return errcode[5]
    #newPwdBlankErr
    if data['pwdNew'] == "":
        return errcode[6]
    #charErr
    strTmp = data['pwdNew']
    for x in xrange(0,len(data['pwdNew'])):
        if ord(strTmp[x]) < 33 or ord(strTmp[x]) > 127:#ASCII表示范围:32-127
            return errcode[2]
    #lenErr
    if len(data['pwdNew']) > 63 or len(data['pwdNew']) < 5:
        return errcode[1]
    #oldPwdErr
    if pwd != loginData.login_data['login_pwd']:
        return errcode[0]
    #pwdSameErr
    if data['pwdNew'] == pwd:
        return errcode[4]
    #no error
    return None

6. 获取输入错误数据之后的页面提示语

?
1
2
3
4
5
6
7
8
9
10
11
12
def checkResponse(error):
    if error == None:
        return
 
    webText = getText('//*[@id="PwdTip"]')
    if webText == False:#没有提示
        print('###Error: no tips on web!')
    else:
        webText = webText.decode('UTF-8')
    waitandClick('//*[@id="ModifyPwd"]/i')
    time.sleep(1)
    return webText

7. 编写测试用例

?
1
2
3
4
5
6
7
8
data = [
    {"pwdNew" : "12345678","pwdOld" : '8dadla'},#"oldPwdErr"
    {"pwdNew" : "admi","pwdOld" : 'admin'},#lenErr
    {'pwdNew' : '1  2  3','pwdOld' : 'admin'},#charErr
    {'pwdNew' : 'admin','pwdOld' : 'admin'},#pwdSameErr
    {'pwdNew' : "",'pwdOld' : ""},#oldPwdBlank
    {'pwdNew' : "",'pwdOld' : "admin"}#newPwdBlank
]

8.编写单元测试类

8.1 单元测试中的通用操作

单元测试中,不同的部分应该是数据,所以可以定义一个通用的操作。

其中self.assertEqual(checkResponse(error), errTips[error])是判定测试是否通过的条件:页面提示语是否正确。

?
1
2
3
4
def commonAction(self, arg):
        error = checkData(arg)
        changeUserPwd.main(arg)
        self.assertEqual(checkResponse(error), errTips[error])

8.2 测试类

测试类中主要包括了测试用例6个,和对应的以“test”开头的测试函数。

这里继承了python的unittest。

关于unittest的语法请参考:http://www.zzvips.com/article/79252.html

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class TestCase(unittest.TestCase):
    data = [
        {"pwdNew" : "12345678","pwdOld" : '8dadla'},#"oldPwdErr"
        {"pwdNew" : "admi","pwdOld" : '*'},#lenErr
        {'pwdNew' : '1  2  3','pwdOld' : '*'},#charErr
        {'pwdNew' : 'admin','pwdOld' : '*'},#pwdSameErr
        {'pwdNew' : "",'pwdOld' : ""},#oldPwdBlank
        {'pwdNew' : "",'pwdOld' : "*"}#newPwdBlank
    ]
 
    def commonAction(self, arg):
        error = checkData(arg)
        changeUserPwd.main(arg)
        self.assertEqual(checkResponse(error), errTips[error])
 
    def test_oldPwdErr(self):
        self.commonAction(self.data[0])
    def test_lenErr(self):
        self.commonAction(self.data[1])
    def test_charErr(self):
        self.commonAction(self.data[2])
    def test_pwdSameErr(self):
        self.commonAction(self.data[3])
    def test_oldPwdBlank(self):
        self.commonAction(self.data[4])
    def test_newPwdBlank(self):
        self.commonAction(self.data[5])

9. 进行单元测试并生成测试报告

这里利用了HTMLTestRunner来生成测试报告。

HTMLTestRunner语法请参看:https://testerhome.com/topics/7576

生成的测试报告将会存放在reports/test_report文件夹下,按照时间命名。测试报告的title叫做“修改管理员密码试报告”

?
1
unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='test_report',report_title='修改管理员密码试报告'))

10. 关闭浏览器

?
1
2
3
4
5
def closeDriver():
    time.sleep(3)
    driver.quit()
    os.system('killall chromedriver')
    os.system('killall geckodriver')

到这里,我们可以完成修改用户名密码模块的单元测试了,为了增加代码的健壮性,下面介绍异常处理。

11. 异常处理

11.1 点击函数

点击按钮的时候可能出现的异常情况是:可能页面元素还没有加载出来的时候,点击的动作就发生了。这样就会引发找不到元素异常。

解决的方法是通过显示等待,每10ms检查一次页面元素是否加载完成,完成后就点击,否则就等到超时时间之后结束动作。

?
1
2
3
4
5
6
7
def waitandClick(xpath):
    try:
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, xpath)))
    except TimeoutException as e:
        print('Error:waitandClick, TimeoutException, xpath = %s\n' % xpath)
    else:
        driver.find_element_by_xpath(xpath).click()

11.2 填写表单

在填写表单时,除了页面元素还没有加载完成的异常外,还可能原有表单中有文本,而我们的输入则是以追加模式填写的。这就会导致填写的文本不准确。

?
1
2
3
4
5
6
7
8
def waitandSendkeys(xpath, keys):
    try:
        WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath)))
    except TimeoutException as e:
        print('Error:waitandSendkeys, TimeoutException, xpath = %s\n' % xpath)
    else:
        driver.find_element_by_xpath(xpath).clear()
        driver.find_element_by_xpath(xpath).send_keys(keys)

11.3 元素加载

在元素加载中可能出现: 1. 在超时时间内元素没有加载完成 2. 查询的元素根本不存在

针对这两种情况进行异常处理:

?
1
2
3
4
5
6
7
8
9
10
11
def waitforDisplay(xpath):
    try:
        WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath)))
    except TimeoutException as e:
        print('Error:waitforDisplay, TimeoutException, xpath = %s\n' % xpath)
    else:
        try:
            process = driver.find_element_by_xpath(xpath)
            WebDriverWait(driver, 10).until(lambda driver: process.is_displayed())
        except NoSuchElementException as e:
            print('Error:waitforDisplay, NoSuchElementException, xpath = %s\n' % xpath)

12. 完整的测试代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# -*- coding: UTF-8 -*-
#!/usr/bin/env python
 
from selenium import webdriver
 
import time, os
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import TimeoutException
 
import unittest
import HtmlTestRunner
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
 
 
# 1. 打开浏览器,访问p.to
driver = webdriver.Chrome()
def openDriver():
    driver.get("http://p.to")
    driver.maximize_window()
 
# 2. 登陆
class loginClass(object):
    """docstring for login"""
    def __init__(self, arg):
        self.login_pwd = arg
 
    def login(self):
        waitandSendkeys('//*[@id="Pwd"]', self.login_pwd)
        waitandClick('//*[@id="Save"]')
 
def login(data):
    openDriver()
    test1 = loginClass(data)
    test1.login()
 
# 3.修改管理员密码
class changePwdClass(object):
    """docstring for changePwdClass"""
    def __init__(self, arg):
        self.pwdNew = arg.get('pwdNew', '')
        self.pwdOld = arg.get('pwdOld', '')
 
    def changeUserPwd(self):
        waitandClick('//*[@id="Con"]/div[1]/ul[2]/li[1]')
        waitandClick('//*[@id="Con"]/div[1]/ul[2]/li[1]/ul/li[3]')
        waitforDisplay('//*[@id="_Widget"]')
        waitandSendkeys('//*[@id="PwdOld"]', self.pwdOld)
        waitandSendkeys('//*[@id="PwdNew"]', self.pwdNew)
        waitandSendkeys('//*[@id="PwdCfm"]', self.pwdNew)
        waitandClick('//*[@id="SavePwd"]')
 
def changeUserPwd_main(data):
    changePwdObj = changePwdClass(data)
    changePwdObj.changeUserPwd()
 
# 4. 单元测试数据
errcode = ['oldPwdErr', 'lenErr', 'charErr', 'matchErr', 'pwdSameErr',\
    'oldPwdBlankErr', 'newPwdBlankErr']
errTips = {
    'oldPwdErr' :'原密码错误',
    'lenErr' : '新密码长度应为5~63位',
    'charErr' : "新密码包含非法字符",
    'matchErr' : '两次密码输入不一致',
    'pwdSameErr' : '新密码与原密码相同,请重新输入',
    'oldPwdBlankErr' : '请输入原密码',
    'newPwdBlankErr' : '请输入新密码'
}
 
# 5. 检查输入的数据合法性
def checkData(data):#检查顺序跟页面顺序相同
    #pwd = loginPwd
    pwd='admin'
    #'oldPwdBlankErr'
    if data['pwdOld'] == "":
        return errcode[5]
    #newPwdBlankErr
    if data['pwdNew'] == "":
        return errcode[6]
    #charErr
    strTmp = data['pwdNew']
    for x in xrange(0,len(data['pwdNew'])):
        if ord(strTmp[x]) < 33 or ord(strTmp[x]) > 127:#ASCII表示范围:32-127
            return errcode[2]
    #lenErr
    if len(data['pwdNew']) > 63 or len(data['pwdNew']) < 5:
        return errcode[1]
    #oldPwdErr
    if pwd != data['pwdOld']:
        return errcode[0]
    #pwdSameErr
    if data['pwdNew'] == data['pwdOld']:
        return errcode[4]
    #no error
    return None
 
# 6. 获取输入错误数据之后的页面提示语
def checkResponse(error):
    if error == None:
        return
    # webText = driver.find_element_by_xpath('//*[@id="PwdTip"]').text
    webText = getText('//*[@id="PwdTip"]')
    if webText == False:#没有提示
        print('###Error: no tips on web!')
    else:
        webText = webText.decode('UTF-8')
    waitandClick('//*[@id="ModifyPwd"]/i')
    return webText
 
# 8.单元测试类
class TestCase(unittest.TestCase):
    # 7. 编写测试用例
    data = [
        {"pwdNew" : "12345678","pwdOld" : '8dadla'},#"oldPwdErr"
        {"pwdNew" : "admi","pwdOld" : 'admin'},#lenErr
        {'pwdNew' : '1  2  3','pwdOld' : 'admin'},#charErr
        {'pwdNew' : 'admin','pwdOld' : 'admin'},#pwdSameErr
        {'pwdNew' : "",'pwdOld' : ""},#oldPwdBlank
        {'pwdNew' : "",'pwdOld' : "admin"}#newPwdBlank
    ]
 
    def commonAction(self, arg):
        error = checkData(arg)
        changeUserPwd_main(arg)
        self.assertEqual(checkResponse(error), errTips[error])
        time.sleep(1)
 
    def test_oldPwdErr(self):
        self.commonAction(self.data[0])
    def test_lenErr(self):
        self.commonAction(self.data[1])
    def test_charErr(self):
        self.commonAction(self.data[2])
    def test_pwdSameErr(self):
        self.commonAction(self.data[3])
    def test_oldPwdBlank(self):
        self.commonAction(self.data[4])
    def test_newPwdBlank(self):
        self.commonAction(self.data[5])
 
# 10. 关闭浏览器
def closeDriver():
    time.sleep(3)
    driver.quit()
    os.system('killall chromedriver')
    os.system('killall geckodriver')
 
# 11. 异常处理
## 11.1 点击函数
def waitandClick(xpath):
    try:
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, xpath)))
    except TimeoutException as e:
        print('Error:waitandClick, TimeoutException, xpath = %s\n' % xpath)
    else:
        driver.find_element_by_xpath(xpath).click()
 
## 11.2 填写表单
def waitandSendkeys(xpath, keys):
    try:
        WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath)))
    except TimeoutException as e:
        print('Error:waitandSendkeys, TimeoutException, xpath = %s\n' % xpath)
    else:
        driver.find_element_by_xpath(xpath).clear()
        driver.find_element_by_xpath(xpath).send_keys(keys)
 
## 11.3 元素加载
def waitforDisplay(xpath):
    try:
        WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath)))
    except TimeoutException as e:
        print('Error:waitforDisplay, TimeoutException, xpath = %s\n' % xpath)
    else:
        try:
            process = driver.find_element_by_xpath(xpath)
            WebDriverWait(driver, 10).until(lambda driver: process.is_displayed())
        except NoSuchElementException as e:
            print('Error:waitforDisplay, NoSuchElementException, xpath = %s\n' % xpath)
 
def elementIsDisplayed(xpath):
    try:
        driver.find_element_by_xpath(xpath)
    except NoSuchElementException as e:
        return False
 
def getText(xpath):
    time.sleep(1)
    return driver.find_element_by_xpath(xpath).text
 
if __name__ == '__main__':
    openDriver()
    login('admin')
    #data = {'pwdNew'='admin', 'pwdOld'='12345678'}
    #changeUserPwd_main(data)
    #9. 进行单元测试并生成测试报告
    unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='test_report',report_title='修改管理员密码试报告'))
    closeDriver()

完整demo请参看:https://github.com/niununu/k2p_web_test

到此这篇关于python实现自动化脚本编写的文章就介绍到这了,更多相关python 自动化脚本 内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/vivianliulu/article/details/74188330