一个小测试(搜索+新开标签页)
项目地址:https://gitee.com/jtwen/item_test
1 文件结构
-
在 pycharm 中新建一个项目 item_test,结构如下
-
result 为测试结果文件夹(随后需在此文件夹里生成测试报告)
-
testcase 为测试用例文件夹
-
exe.py 此处为执行文件(可执行它来生成测试报告)
2 编写用例
- 在testcase文件夹中新建 testcase_jd.py
# 此处以京东网址为例,为了保证通过率只设置两个简单的用例(实际情况会略有不同)
import time
import unittest
from selenium import webdriver
class testcase_case(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.get("https://www.jd.com")
time.sleep(3) # 显示等待3秒
def test_search(self): # 搜索查找
driver = self.driver
driver.find_element_by_id("key").send_keys("iphone12") # 通过 id 定位
driver.find_element_by_css_selector("div.form>button.button").click() # 通过 css 选择器定位
title = "京东"
self.assertIn(title, driver.title) # 设置断言,判断网页名称是否包含title,包含就算通过
def test_miaosha(self): # 秒杀
driver = self.driver
driver.find_element_by_link_text("秒杀").click() # 通过链接的文字定位
print(driver.title)
title2 = "京东(JD.COM)-正品低价、品质保障、配送及时、轻松购物!"
self.assertEqual(title2, driver.title) # 采用强匹配,只有相等才算通过用例
time.sleep(3)
driver.close() # 2条用例执行完毕
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()
-
HtmlTestRunner安装
a. 打开此网址: http://tungwaiyip.info/software/HTMLTestRunner.html,找到 HTMLTestRunner.py 右键,另存为;
b. 此文件适用 python2,在python3中需手动修改:
94行 import io
539 self.outputBuffer = io.StringO()
642 if not cls in rmap
766 uo = e
772 ue = e
631 print(sys.stderr,'\nTime Elapsed:%s'%(self.stopTime-self.startTime))
修改之后文件如下:
"""
A TestRunner for use with the Python unit testing framework. It
generates a HTML report to show the result at a glance.
The simplest way to use this is to invoke its main method. E.g.
import unittest
import HTMLTestRunner
... define your tests ...
if __name__ == '__main__':
HTMLTestRunner.main()
For more customization options, instantiates a HTMLTestRunner object.
HTMLTestRunner is a counterpart to unittest's TextTestRunner. E.g.
# output to a file
fp = file('my_report.html', 'wb')
runner = HTMLTestRunner.HTMLTestRunner(
stream=fp,
title='My unit test',
description='This demonstrates the report output by HTMLTestRunner.'
)
# Use an external stylesheet.
# See the Template_mixin class for more customizable options
runner.STYLESHEET_TMPL = '<link rel="stylesheet" href="my_stylesheet.css" type="text/css">'
# run the test
runner.run(my_test_suite)
------------------------------------------------------------------------
Copyright (c) 2004-2007, Wai Yip Tung
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the f