如何使用Pytest测试相对路径?新手寻求技术指导
用Pytest验证JSON文件读取代码的实操方法
首先得把你给出的代码片段封装成一个可测试的函数,否则没法直接用Pytest测试:
from pathlib import Path import json import logging logger = logging.getLogger(__name__) def load_test_json(): base_path = Path(__file__).parent file_path = (base_path / "test.json").resolve() logger.info(file_path) with open(file_path) as f1: # 改成with语句自动关闭文件,避免句柄泄漏 json_load = json.load(f1) logger.info(json_load) return json_load
核心测试场景与用例
1. 正常读取场景:验证返回内容符合预期
这个场景要确保当test.json存在且格式正确时,函数能返回正确的JSON数据。
import json from pathlib import Path import pytest from your_module import load_test_json # 替换成你实际的模块名 def test_load_valid_json(): # 定义预期的JSON数据 expected = {"name": "test", "version": 1.0} # 先把预期数据写入测试用的test.json test_file = Path(__file__).parent / "test.json" with open(test_file, "w") as f: json.dump(expected, f) # 调用目标函数 result = load_test_json() # 断言返回值和预期一致 assert result == expected
2. 异常场景:覆盖错误情况
测试文件不存在的情况
def test_load_file_not_found(): # 确保测试文件不存在 test_file = Path(__file__).parent / "test.json" if test_file.exists(): test_file.unlink() # 断言函数会抛出FileNotFoundError with pytest.raises(FileNotFoundError): load_test_json()
测试JSON格式错误的情况
def test_load_invalid_json(): # 写入无效的JSON内容 test_file = Path(__file__).parent / "test.json" with open(test_file, "w") as f: f.write("{this is not valid json}") # 断言函数会抛出JSON解码错误 with pytest.raises(json.JSONDecodeError): load_test_json()
进阶测试技巧
使用临时目录避免污染真实文件
Pytest的tmp_path fixture可以创建临时目录,测试完自动销毁,不会影响你的真实文件:
def test_load_with_tmp_path(tmp_path, monkeypatch): expected = {"foo": "bar"} # 在临时目录创建test.json temp_test_file = tmp_path / "test.json" with open(temp_test_file, "w") as f: json.dump(expected, f) # 替换函数里的Path(__file__).parent为临时目录 monkeypatch.setattr("your_module.Path", lambda x: tmp_path if x == __file__ else Path(x)) # 调用函数并断言结果 result = load_test_json() assert result == expected
验证日志输出
如果要确认logger.info的内容是否正确,可以用Pytest的caplog fixture捕获日志:
def test_load_logs(caplog): expected = {"key": "value"} test_file = Path(__file__).parent / "test.json" with open(test_file, "w") as f: json.dump(expected, f) # 设置日志级别为INFO,捕获输出 with caplog.at_level(logging.INFO): load_test_json() # 断言日志里包含文件路径和JSON内容 assert str(test_file.resolve()) in caplog.text assert str(expected) in caplog.text
内容的提问来源于stack exchange,提问作者mac34
相关产品推荐
相关产品推荐

