测试代码
Web 自动化测试用例¶
测试用例编写¶
使用 pytest 测试类组织测试用例。在测试类中编写具体的测试方法,每一个测试方法是一个测试用例。
Web 自动化测试需要在用例执行之前打开浏览器进入对应页面,在用例执行结束后关闭浏览器。所以需要用到 pytest 提供的测试装置 setup 和 teardown 来实现。
class TestOwnerSearch:
OWNER_URL = "https://spring-petclinic-angular.poc.ceshiren.com/#/owners"
def setup(self):
"""
准备测试环境,打开宠物主人信息页面:
https://spring-petclinic-angular.poc.ceshiren.com/#/owners
:return:
"""
self.driver = webdriver.Chrome()
self.driver.get(self.OWNER_URL)
self.driver.maximize_window()
self.driver.implicitly_wait(15)
def teardown(self):
self.driver.quit()
def test_search_more_exists(self):
"""
测试步骤:
1. 进入宠物主人信息页面
2. Last name输入框输入【searchkey】
3. 点击 Find Owner 按钮"
预期结果:结果数量大于=2 不止一个
:return:
"""
searchkey = "Davis"
self.driver.find_element(By.ID, "lastName").send_keys(searchkey)
logger.info("点击 Find Owner 按钮")
self.driver.find_element(By.CSS_SELECTOR, ".form-group .btn-default").click()
ownerlist = self.driver.find_elements(By.CSS_SELECTOR, ".table .ownerFullName")
assert len(ownerlist) >= 2
添加日志¶
在测试用例中添加日志
logger.info(f"打开地址:{self.OWNER_URL}")
参数化¶
如果多个测试用例,测试步骤完全相同,只有测试数据不同,可以使用参数化的方式,在一个测试方法中完成多个测试用例的执行。
@pytest.mark.parametrize("searchkey", [
"1","霍格沃兹","#@"
])
def test_search_failure_P2(self,searchkey):
...
设置测试用例优先级¶
使用 pytest 添加标签的特性,为测试用例设置优先级。这样可以方便单独执行其中一种优先级的测试用例。
在 pytest.ini 文件中声明用例优先级
[pytest]
markers = P0
P1
P2
在测试用例中添加优先级
@pytest.mark.P0
def test_search_more_exists(self):
...
添加测试报告¶
使用 allure,在测试用例的不同位置添加测试报告信息。
@allure.epic("宠物商店")
@allure.feature("搜索功能")
class TestOwnerSearch:
...
代码¶
部分用例代码如下:
@allure.epic("宠物商店")
@allure.feature("搜索功能")
class TestOwnerSearch:
OWNER_URL = "https://spring-petclinic-angular.poc.ceshiren.com/#/owners"
def setup(self):
"""
准备测试环境,打开宠物主人信息页面:
https://spring-petclinic-angular.poc.ceshiren.com/#/owners
:return:
"""
self.driver = webdriver.Chrome()
logger.info(f"打开地址:{self.OWNER_URL}")
self.driver.get(self.OWNER_URL)
self.driver.maximize_window()
logger.info(f"设置隐式等待15秒")
self.driver.implicitly_wait(15)
def teardown(self):
logger.info("保存当面页面截图tmp.png")
self.driver.save_screenshot("tmp.png")
logger.info("将截图添加到报告中")
allure.attach.file("tmp.png", name="页面截图",
attachment_type=allure.attachment_type.PNG)
self.driver.quit()
@pytest.mark.P0
@allure.story("Owners搜索")
@allure.title("搜索-结果不止一个")
def test_search_more_exists(self):
"""
测试步骤:
1. 进入宠物主人信息页面
2. Last name输入框输入【searchkey】
3. 点击 Find Owner 按钮"
预期结果:结果数量大于=2 不止一个
:return:
"""
searchkey = "Davis"
logger.info(f"向搜索框中输入内容:{searchkey}")
self.driver.find_element(By.ID, "lastName").send_keys(searchkey)
logger.info("点击 Find Owner 按钮")
self.driver.find_element(By.CSS_SELECTOR, ".form-group .btn-default").click()
logger.info("查看结果列表")
ownerlist = self.driver.find_elements(By.CSS_SELECTOR, ".table .ownerFullName")
logger.info("断言比较结果列表的长度大于2 len(ownerlist) >= 2")
assert len(ownerlist) >= 2
完整的自动化测试用例代码请查看源码:web自动化测试代码