自定义错误单元测试编写咨询及lang.py类代码相关技术问题
自定义错误的单元测试编写指南(针对LangModel类)
没问题,我来一步步拆解怎么给这个LangModel类编写针对自定义错误的单元测试。咱们从基础准备到分场景覆盖,把所有错误分支都测到:
1. 准备工作:测试框架与依赖模拟
- 优先选择Python标准库的
unittest(无需额外安装)或者更简洁的pytest,这里以unittest为例。 - 必须用
unittest.mock来模拟requests库的行为——绝对不要让单元测试发起真实的HTTP请求,不然测试会依赖外部服务,稳定性极差。 - 确保测试文件(比如命名为
test_lang.py)能正确导入目标类和错误:from unittest import TestCase, mock from lang import LangModel from errors import ConnectionErr, StatusCodeError import requests
2. 测试场景1:模拟连接失败,验证ConnectionErr抛出
这个场景要覆盖requests.ConnectionError被捕获后,抛出自定义ConnectionErr的逻辑:
class TestLangModel(TestCase): def test_state_update_connection_error(self): # 初始化LangModel实例 lang_model = LangModel("dummy_path", host="192.168.1.1", port="8080") # 模拟requests.post抛出ConnectionError with mock.patch('lang.requests.post') as mock_post: mock_post.side_effect = requests.ConnectionError # 断言调用state_update时会抛出预期的自定义错误 with self.assertRaises(ConnectionErr) as ctx: lang_model.state_update() # 可选:验证错误信息包含正确的host和port self.assertIn("192.168.1.1:8080", str(ctx.exception))
- 重点:mock的路径是
lang.requests.post,因为LangModel里是直接导入requests并调用,必须mock它在lang模块中的引用,否则mock会失效。
3. 测试场景2:模拟非200状态码,验证StatusCodeError抛出
这个场景要覆盖响应状态码非OK时抛出StatusCodeError的逻辑:
def test_state_update_non_ok_status_code(self): lang_model = LangModel("dummy_path") # 构造一个模拟的响应对象,状态码设为400(Bad Request) mock_response = mock.Mock() mock_response.status_code = 400 mock_response.ok = False with mock.patch('lang.requests.post', return_value=mock_response): # 断言抛出StatusCodeError with self.assertRaises(StatusCodeError) as ctx: lang_model.state_update() # 可选:验证错误包含对应的状态码 self.assertEqual(ctx.exception.status_code, 400)
- 提示:如果你的
StatusCodeError类还没实现接收状态码的属性,建议给它加个status_code参数,这样测试能更精准地验证错误细节。
4. 测试场景3:验证正常请求不抛出错误
不要忘了覆盖正常路径,确保没有误抛出错误:
def test_state_update_success(self): lang_model = LangModel("dummy_path") # 模拟响应状态码为200(OK) mock_response = mock.Mock() mock_response.status_code = requests.codes.ok mock_response.ok = True with mock.patch('lang.requests.post', return_value=mock_response): # 调用方法,断言没有异常抛出 try: lang_model.state_update() except Exception as e: self.fail(f"state_update()抛出了意外的异常: {e}")
额外注意事项
- 如果用
pytest,可以用pytest.raises上下文管理器,写法会更简洁,比如:def test_state_update_connection_error_pytest(): lang_model = LangModel("dummy_path", host="192.168.1.1", port="8080") with mock.patch('lang.requests.post') as mock_post: mock_post.side_effect = requests.ConnectionError with pytest.raises(ConnectionErr) as ctx: lang_model.state_update() assert "192.168.1.1:8080" in str(ctx.value) - 测试时尽量覆盖不同的非OK状态码(比如401、500),确保
StatusCodeError在所有非200场景下都能正确抛出。
内容的提问来源于stack exchange,提问作者Shiran Dudy
相关产品推荐
相关产品推荐

