【重点】【装饰器看这篇二】装饰器和ddt装饰器在ui自动化中的应用【杭州多测师】【多测师_王sir】
#定义一个装饰器 #只要你被装饰、那么就相当于这个被装饰的函数的函数名=装饰器(被装饰的函数名) #装饰器的作用: #在不改变原有函数功能的基础之上、给函数增加新的功能 import time def runtime(func): def warper(): before = time.time() func() #调用传进来的参数 after = time.time() result = after - before print('所花费的时间为:{}秒'.format(result)) return warper @runtime #foo = runtime(foo) def foo(): '''我是一个打印的函数''' print('测试一下') time.sleep(2) if __name__ == '__main__': foo()
#第一种方法: from time import time from time import sleep def run_time(func): def wrapper(): start = time() func() # 函数在这里运行 end = time() cost_time = end - start print("func three run time {}".format(cost_time)) return wrapper @run_time def fun_one(): sleep(1) @run_time def fun_two(): sleep(1) @run_time def fun_three(): sleep(1) fun_one() fun_two() fun_three() 运行结果: func three run time 1.000584602355957 func three run time 1.0003924369812012 func three run time 1.0006859302520752
#第二种方法: from time import time from time import sleep def logger(msg=None): def run_time(func): def wrapper(*args, **kwargs): start = time() func() # 函数在这里运行 end = time() cost_time = end - start print("[{}] func three run time {}".format(msg, cost_time)) return wrapper return run_time @logger(msg="One") def fun_one(): sleep(1) @logger(msg="Two") def fun_two(): sleep(1) @logger(msg="Three") def fun_three(): sleep(1) fun_one() fun_two() fun_three() 运行结果: [One] func three run time 1.0002033710479736 [Two] func three run time 1.0000429153442383 [Three] func three run time 1.0008385181427002
装饰器运用在ui自动化里面的场景 ==》可以变为数据提供者 ==》进行数据驱动 import unittest from ddt import ddt,data,unpack from selenium import webdriver def testdata(): '''测试数据''' return [('admin', '123456'), ('duoceshi', '123456'), ('duoceshi1', '123456')] @ddt class Cms_Login(unittest.TestCase): def setUp(self): self.url = 'http://cms.duoceshi.cn/cms/manage/login.do' self.driver = webdriver.Chrome() self.driver.maximize_window() self.driver.get(self.url) self.driver.implicitly_wait(30) @data(*testdata()) #这里加*后会将返回数据分为一个个的元组 @unpack def test_login(self,username,password): '''测试登录多测师cms后台管理系统''' self.driver.find_element_by_id('userAccount').send_keys(username) self.driver.find_element_by_id('loginPwd').send_keys(password) self.driver.find_element_by_id('loginBtn').click() def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main(verbosity=2)