import time
# 定义装饰器
def performance_test(func):
def wrapper(*args, **kwargs):
start_time = time.time() # 记录函数开始执行的时间
result = func(*args, **kwargs) # 执行函数
end_time = time.time() # 记录函数结束执行的时间
print(f"{func.__name__} 函数执行耗时:{end_time - start_time:.6f} 秒")
return result
return wrapper
# 使用装饰器
@performance_test
def example_function(n):
# 模拟一个耗时操作,例如计算斐波那契数列
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
# 执行被装饰的函数
print(example_function(100000))
代码解释:
装饰器定义:
performance_test
是一个装饰器,它接受一个函数func
作为参数,并返回一个新的函数wrapper
。wrapper
函数会在调用func
之前和之后记录时间,并打印出执行时间。装饰器应用:
@performance_test
语法糖将performance_test
装饰器应用到example_function
函数上。执行函数:调用
example_function(100000)
时,实际上会先执行wrapper
函数,然后wrapper
函数会记录时间并调用原始的example_function
函数。输出结果:装饰器会打印出
example_function
的执行时间,然后函数会返回计算结果
同时,也可以使用装饰器来计算函数调用次数
def count_calls(func):
def wrapper(*args, **kwargs):
wrapper.calls += 1
return func(*args, **kwargs)
wrapper.calls = 0
return wrapper
# 使用装饰器
@count_calls
def greet(name):
print(f"Hello, {name}!")
# 调用被装饰的函数
greet("Alice")
greet("Bob")
greet("Charlie")
# 打印函数调用次数
print(f"greet 函数被调用了 {greet.calls} 次")
装饰器定义:
count_calls
是一个装饰器,它返回一个包装函数wrapper
。wrapper
有一个属性calls
用来记录函数被调用的次数。装饰器应用:
@count_calls
将count_calls
装饰器应用到greet
函数上。执行函数:每次调用
greet
函数时,实际上是调用了wrapper
函数,它在调用原始的greet
函数前后,会增加wrapper.calls
的值。输出结果:最后,我们打印出
greet
函数的调用次数。
结合Appium和Python装饰器来针对相机相册功能完成自动化脚本开发与后续优化
假设我们有一个相机应用,我们想要编写自动化测试脚本来测试以下功能:
- 打开相机应用
- 拍照
- 进入相册查看最后一张照片
编写一个装饰器来测量每个测试步骤的执行时间
import time
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
def time_measuring(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} executed in {end_time - start_time:.2f} seconds")
return result
return wrapper
# 设定Appium所需参数
desired_caps = {
"platformName": "Android",
"deviceName": "emulator-5554",
"appPackage": "com.example.camera",
"appActivity": ".MainActivity",
"noReset": True
}
# 初始化WebDriver
driver = webdriver.Remote('http://localhost:4727/wd/hub', desired_caps)
@time_measuring
def take_photo():
# 模拟点击拍照按钮
photo_button = driver.find_element(AppiumBy.ACCESSIBILITY_ID, "Take Photo")
photo_button.click()
# 等待拍照完成
time.sleep(2)
@time_measuring
def open_album():
# 模拟点击进入相册按钮
album_button = driver.find_element(AppiumBy.ACCESSIBILITY_ID, "Album")
album_button.click()
# 等待相册打开
time.sleep(2)
@time_measuring
def verify_last_photo():
# 假设最后一张照片总是列表中的第一个
last_photo = driver.find_element(AppiumBy.ID, "com.example.camera:id/latest_photo")
assert last_photo.is_displayed(), "Last photo is not displayed"
# 执行测试步骤
take_photo()
open_album()
verify_last_photo()
# 关闭WebDriver
driver.quit()
- 装饰器:
time_measuring
装饰器在调用被装饰的函数前后记录时间,并打印出执行时间。- 测试脚本:我们定义了三个函数
take_photo
、open_album
和verify_last_photo
,每个函数都被time_measuring
装饰器装饰,用于测量执行时间。- 执行测试:脚本按照顺序执行拍照、打开相册和验证最后一张照片的步骤