1) debug 熟悉使用debug的图标以及调试代码
2)用例
## 1)用例执行
1.右击 unittest 运行
2. python 运行 unittest.main()
3. 运行所有的测试用例
## 2)用例的组织
会把测试用例的代码放到一个统一的文件夹当中,目录当中。
tests/ testcases
## 3)收集用例
需要把每个测试用例模块当中的测试用例收集到一起,一起执行。
## 4)运行用例的流程
1.写用例方法。用例方法放到一个目录当中。
2.写脚本 run.py ,(收集用例,运行用例)
3.loader 收集用例, suite = discover()
4.得到测试集 suite
5.运行。 test_runner = HTMLTestRunner()
附带代码:
"""运行程序
收集所有的测试用例,
执行。
生成测试报告。
"""
import os
import unittest
from HTMLTestRunnerNew import HTMLTestRunner
# 初始化一个加载器 test_loader
loader = unittest.TestLoader()
# 获取测试用例目录的路径
dir_path = os.path.dirname(os.path.abspath(__file__))
case_path = os.path.join(dir_path, "tests")
# 1)使用 loader 收集所有的测试用例
test_suit = loader.discover(case_path)
print(test_suit)
# # 2)只加载注册和登录的用例
# suite_login = loader.loadTestsFromModule(test_login)
# suite_register = loader.loadTestsFromModule(test_register)
#
# # 初始化一个suite
# suite_total = unittest.TestSuite()
# suite_total.addTests([suite_login, suite_register])
# # 1)执行测试用例
# runner = unittest.TextTestRunner()
# runner.run(test_suit)
# # 2)生成测试报告
# with open("test_reports.txt", "w", encoding="utf-8") as f:
# runner = unittest.TextTestRunner(f)
# runner.run(test_suit)
# 3)HTML测试报告 第三方
with open("test_reports.html", "wb", ) as f:
runner = HTMLTestRunner(
f,
title="python29期第一次测试报告",
description="测试报告描述",
tester="wu"
)
runner.run(test_suit)
作业:
1, 编写上课的 login 函数的测试用例方法; 2, 通过 run.py 收集和运行所有的测试; 3, 使用 htmltestrunner 生成测试报告。
上期答案:
import unittest def login(username=None, password=None): """登录""" if username != None and password != None: if username == "xinhua" and password == "123456": return {"mgs": "登录成功"} else: return {"mgs": "用户名或密码错误"} else: return {"mgs": "用户名或密码为空"} """ 1、用户名密码正确,登录成功 2、用户名或密码错误,登录失败 3、用户名或密码为None,登录失败 """ class TestLogin(unittest.TestCase): @classmethod def setUpClass(cls): print("一个测试类只执行一次的前置") @classmethod def tearDownClass(cls): print("一个测试类只执行一次的后置") def setUp(self): """前置 一个测试方法执行一次""" print("连接数据库") def tearDown(self): """后置""" print("断开数据库") def test_login_success(self): """登录成功测试用例""" username = "xinhua" password = "123456" expected = {"mgs": "登录成功"} # 调用被测单元 actual = login(username, password) # 判断预期结果和实际结果是否存在某种关系 断言 assert self.assertTrue(expected == actual) def test_login_error(self): username = "xinhua" password = "1456" expected = {"mgs": "用户名或密码错误"} actual = login(username, password) self.assertTrue(expected == actual) def test_login_error_username(self): username = "xinha" password = "123456" expected = {"mgs": "用户名或密码错误"} actual = login(username, password) self.assertTrue(expected == actual) def test_login_empty(self): username = "xinhua" password = None expected = {"mgs": "用户名或密码为空"} actual = login(username, password) self.assertTrue(expected == actual) def test_login_empty_username(self): username = None password = "123456" expected = {"mgs": "用户名或密码为空"} actual = login(username, password) self.assertTrue(expected == actual)