首页 > 其他分享 >14.1 unittest初识 14.2 unittestdiscovery 14。3testsuite 14.4textloader 14.5discover方法14.6setupclass和tea

14.1 unittest初识 14.2 unittestdiscovery 14。3testsuite 14.4textloader 14.5discover方法14.6setupclass和tea

时间:2022-09-07 19:44:54浏览次数:87  
标签:__ skip unittest driver test 方法 self def

14.1 unittest初识

import time
import random
from selenium import webdriver
from selenium.webdriver.common.by import By

class WX:
def __init__(self):
self.user_argument1 = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
self.user_argument2 = 'MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22;CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'
self.options = webdriver.ChromeOptions()
self.options.add_argument('user-agent=%s' % self.user_argument1)
self.driver = webdriver.Chrome(chrome_options=self.options)
self.driver.get('https://work.weixin.qq.com/wework_admin/frame')
cookie_dict = {
"RK": "/Phs2XUDPQ",
"ptcz": "bbc0c092e7450a1449e6e7719599f27d71a994fbd61fd7a1e75d9c0f70f44a29",
"pgv_pvid": "6127127366",
"tvfe_boss_uuid": "a845f7b21688a6e9",
"pgv_pvi": "1084163072",
"iip": "0",
"pac_uid": '1_154439155',
"wwrtx.i18n_lan": 'zh',
"wwrtx.c_gdpr": '0',
"wwrtx.ref": "direct",
"wwrtx.refid": "01794903",
"wwrtx.d2st": "a3118983",
"wwrtx.sid": "AtBSMo3TBCnpmym5yvwy5vPyy9p28vgEkZsadZXgnUkjfT_KlhK-PvJKHmZtnfDT",
"wwrtx.ltype": '1',
"wwrtx.vst": "wyIoLFbxbqip4EKcbLqph547_s4bpj7uwLFLFmrsEGG7PHLkrVNkNdUsL4EoNulnLr5bTCZXYG_N1ngxtd4oBRk4LerkawOyt7rffLOWKXTGTUj6i0MhYJjxdeQy1yAtyYkGWVuYUTSQfKezbuvYXuUYRnNgXSVeX4zhnpqRtg2SYpounHOs5iCrx74yKpP1kQXnEG_D-9r0Cf7BA3pttZINpA-VrIl0Jy9oAG40kqtiNlf0kb8aqoIyG7Xq2YNEQKb3cWxOv9yoKPcyA1tUZQ",
"wwrtx.vid": "1688855804348075",
"wxpay.corpid": "1970326358988015",
"wxpay.vid": "1688855804348075",
"wwrtx.cs_ind": "",
"wwrtx.logined": "true"

}
[self.driver.add_cookie({'name': k, 'value': v}) for k, v in cookie_dict.items()]
self.driver.get('https://work.weixin.qq.com/wework_admin/frame')
self.driver.maximize_window()
self.driver.implicitly_wait(30)
time.sleep(10)


WX()





"""

RK=/Phs2XUDPQ;
ptcz=bbc0c092e7450a1449e6e7719599f27d71a994fbd61fd7a1e75d9c0f70f44a29;
pgv_pvid=6127127366;
tvfe_boss_uuid=a845f7b21688a6e9;
pgv_pvi=1084163072;
iip=0;
pac_uid=1_154439155;
wwrtx.i18n_lan=zh;
wwrtx.c_gdpr=0;
wwrtx.ref=direct;
wwrtx.refid=01794903;
wwrtx.ltype=1;
wwrtx.vid=1688855804348075;
wxpay.corpid=1970326358988015;
wxpay.vid=1688855804348075;
wwrtx.d2st=a3118983;
wwrtx.sid=AtBSMo3TBCnpmym5yvwy5vPyy9p28vgEkZsadZXgnUkjfT_KlhK-PvJKHmZtnfDT;
wwrtx.vst=wyIoLFbxbqip4EKcbLqph547_s4bpj7uwLFLFmrsEGG7PHLkrVNkNdUsL4EoNulnLr5bTCZXYG_N1ngxtd4oBRk4LerkawOyt7rffLOWKXTGTUj6i0MhYJjxdeQy1yAtyYkGWVuYUTSQfKezbuvYXuUYRnNgXSVeX4zhnpqRtg2SYpounHOs5iCrx74yKpP1kQXnEG_D-9r0Cf7BA3pttZINpA-VrIl0Jy9oAG40kqtiNlf0kb8aqoIyG7Xq2YNEQKb3cWxOv9yoKPcyA1tUZQ;
wwrtx.cs_ind=;
wwrtx.logined=true

"""
14。2 unittestdiscovery。py
import unittest
import os
from HTMLTestRunner import HTMLTestRunner

class TestSet:

def __init__(self):
self.SCRTPTS_DIR=os.path.dirname(os.path.abspath(__file__))
print(self.SCRTPTS_DIR)
self.START_DIR=os.path.join(self.SCRTPTS_DIR,'TestCases')
print(self.START_DIR)
self.f=open('./report/report.html','wb')

def run_case_html_report(self):
suite=unittest.TestLoader().discover(
start_dir=self.START_DIR,
pattern='test*.py',
)
HTMLTestRunner(
stream=self.f,
verbosity=2,
title='cms系统',
description='so easy'

).run(suite)

if __name__=='__main__':
t=TestSet()
t.run_case_html_report()
14.3 testsuite
import unittest
# TestSuite 是测试套件,是一个承载多个用例的集合,或者想象成一个盒子
# 需要:
# 1.实例化所有的用例
# 2.创建一个盒子(容器)
# 3.将用例添加到盒子中
# 4.收集用例完毕后,使用执行器执行盒子中的用例

class MyCase(unittest.TestCase):

def test_is_upper(self):
self.assertTrue('Foo'.isupper())

def test_is_lower(self):
self.assertTrue('wind'.islower())

if __name__=='__main__':


# 实例化所有的用例
case_1=MyCase(methodName='test_is_upper')#实例化用例
case_2 = MyCase(methodName='test_is_lower')

#创建一个盒子(容器)
suite=unittest.TestSuite()

#将用例添加到盒子中
suite.addTest(case_1)#单个添加
suite.addTest(case_2)
suite.addTests([case_1,case_2])#多个添加

#收集用例完毕后,使用执行器执行盒子中的用例,实例化执行器
runner=unittest.TestTestRunner()
runner.run(suite)
14.4 textloader
import unittest
unittest.TestLoader().loadTestsFromModule()#发现其他目录中的脚本用例
# 1.目录必须是一个包
# 2.找到指定模块下面unittest.TestCase子类,获取其中以test开头的用例

from ok import test1

if __name__=='__main__':

suit=unittest.TestLoader().loadTestsFromModule(test1)
unittest.TextTestRunner(verbosity=2).run(suite)

14.5discovery
# 最重要
# 用discover跑所有的用例
import unittest
import os
import unittest
import os

if __name__=='__main__':
ret=os.path.dirname(os.path.abspath(__file__))
test_path=os.path.join(ret,'testCase')
print(test_path)
suite=unittest.TestLoader().discover(start_dir=test_path,pattern='wind*.py')
unittest.TextTestRunner(verbosity=0).run(suite)




# discover 要求必须是包才能执行
# verbosity三种模式:
# 0 精简模式,通过之后没有提示
# 1 默认模式,通过.,失败F
# 2详细模式,可以看到来自哪个用例,成功或失败

14.6 setupclass和teardownclass
import unittest

class myUnitTest(unittest.TestCase):
def test_add(self):
print('test_add')

def test_sub(self):
print('test_sub')

def setUp(self):
'''如果myUnitTest中有我,我将在用例之前执行,无论我在myUnitTest的什么位置'''
print('敌军还有三十秒到场,碾碎他们....')

def tearDown(self):
'''如果myUnitTest中有我,我将在用例之前执行,无论我在myUnitTest的什么位置'''
print('ace.....')

@classmethod
def setUpClass(cls) -> None:
print('所有用例执行之前,先执行我,执行一次')
@classmethod
def tearDownClass(cls):
print('所有用例执行之后,执行我,执行一次')

if __name--=='__main__':
unittest.main()
14.7skip跳过
import unittest


# unittest.skip(reason)#reason 跳过用例的原因描述,无条件跳过
# unittest.skipIf(condition,reason)#有条件跳过

class MyCase(unittest.TestCase):


@unittest.skip('无条件跳过')
def test_01(self):
print(111111)

def test_is_upper(self):
self.assertTrue('Foo'.isupper())

def test_is_lower(self):
self.assertTrue('wind'.islower())

@unittest.skipIf(condition=2>2,reason='有条件跳过')
def test_02(self):
print(222222)


if __name__=='__main__':
unittest.main(verbosity=2)

14.8生成测试报告
from HTMLTestRunner import HTMLTestRunner

import unittest


class MyCase(unittest.TestCase):

def test_is_upper(self):
self.assertTrue('Foo'.isupper())

def test_is_lower(self):
self.assertTrue('wind'.islower())

@unittest.skipIf(condition=2>2,reason='有条件跳过')
def test_02(self):
print(222222)

if __name__=='__main__':
case_1=MyCase(methodName='test_is_upper')
case_2=MyCase(methodName='test_is_lower')
case_3=MyCase(methodName='test_02')
suite=unittest.TestSuite()
suite.addTests([case_1,case_2,case_3])
f=open('../report/report_html.html','wb')
HTMLTestRunner(
stream=f,
verbosity=2
).run(suite)
14.9 discovery方法
import unittest
import os
from HTMLTestRunner import HTMLTestRunner

if __name__=='__main__':
ret=os.path.dirname(os.path.abspath(__file__))
test_path=os.path.join(ret,'testcase')
print(test_path)
suite=unittest.TestLoader().discover(start_dir=test_path,pattern='test*.py')
f=open('../report/report_html.html','wb')
HTMLTestRunner(
stream=f,
title='南京三班测试报告',
description='今天天气不错!',
verbosity=2
).run(suite)

14.10 发送邮件
import unittest
from HTMLTestRunner import HTMLTestRunner
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart


def send_mail():
# 第三方 SMTP 服务
mail_host = "smtp.qq.com" # 设置服务器
mail_user = "[email protected]" # 用户名
mail_pass = "ygpwcnkcbzlwgdfc" # 获取授权码
sender = '[email protected]' # 发件人账号
receivers = ['[email protected]'] # 接收邮件(可以多个),可设置为你的QQ邮箱或者其他邮箱

send_content = 'Python 邮件发送测试...'
message = MIMEText(send_content, 'plain', 'utf-8') # 第一个参数为邮件内容,第二个设置文本格式,第三个设置编码
message['From'] = Header("我是发件人", 'utf-8') # 发件人
message['To'] = Header("我是收件人", 'utf-8') # 收件人

subject = '邮件大标题'
message['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
print("邮件发送成功")
except smtplib.SMTPException:
print("Error: 无法发送邮件")


send_mail()

14.11自动化结合unittest--main方法
import unittest
from selenium import webdriver
from selenium.webdriver.commom.by import By
import time

'''使用main方法实现'''

class MyTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.driver=webdriver.Chrome()
cls.driver.get('http://124.220.179.221:8081/cms')
cls.driver.maximize_window()
cls.driver.implicitly_wait(30)

def test_01_login(self):
#登录
self.driver.find_element(By.CSS_SELECTOR,'input[id=userAccout]').send_keys('admin')
self.driver.find_element(By.CSS_SELECTOR,'input[id=loginPwd]').send.keys('123456')
self.driver.find_element(By.CSS_SELECTOR,'input[id=loginBtn]').click()

def test_02_add_user(self):
#添加用户
self.driver.find_element(By.CSS_SELECTOR,'dl[id=menu-user]').click()
time.sleep(0.1)
self.driver.find_element(By.LINK_TEXT,'用户管理').click()
time.sleep(0.1)
time.sleep(1)
#进入iframe框
self.driver.switch_to.frame(1)#根据iframe框的索引值
time.sleep(0.1)
#点击添加用户
self.driver.find_element(By.CLASS_NAME,'icon-plus').click()
self.driver.find_element(By.LINK_TEXT,'添加用户').click()
time.sleep(0.1)

#进入第二层iframe
self.driver.switch_to.frame('xubox_iframe1')#根据iframe框的id值
time.sleep(1)

self.driver.find_element(By.ID,'userName').send_keys('老王'+time.strftime('%H:%M:%S'))
self.driver.find_element(By.CSS_SELECTOR,'input[name=userSex]').click()
time.sleep(0.1)
self.driver.find_element(By.ID,'user-tel').send_keys('13512341234')
self.driver.find_element(By.XPATH,'//*[@id="user-email"]')send_keys('[email protected]')
self.driver.find_element(By.CSS_SELECTOR,'input[name=userAccount]').send_key('12'+time.strftime('%H:%M:%S'))
time.sleep(0.1)
self.driver.find_element(By.CSS_SELECTOR,'input[type=password]').send_keys('123456')
self.driver.find_element(By.ID,'confirmpwd').send_keys('123456')
time.sleep(0.1)

self.driver.find_element(By.CSS_SELECTOR,'button[type=submit]').click()
time.sleep()

self.driver.switch_to.parent_frame()#切回上一层的iframe中
time.sleep(1)

@classmethod
def tearDownClass(cls)->None:
cls.driver.quit()

if __name__=='__main__':
unittest.main()






























































标签:__,skip,unittest,driver,test,方法,self,def
From: https://www.cnblogs.com/zhh0125/p/16667043.html

相关文章