Python快照测试实践 Python 快照测试实践完整指南本文介绍 pytest-snapshot 插件包括 JSON 快照生成与验证、快照更新流程、代码审查中的快照管理等。import pytestimport jsonclass UserSerializer:用户数据序列化器def serialize(self, user_data):将用户数据序列化为结构化输出return {id: user_data.get(id),username: user_data.get(username),email: user_data.get(email),is_active: user_data.get(is_active, True),roles: sorted(user_data.get(roles, [])),created_at: str(user_data.get(created_at)),}class TestSnapshotBasics:快照测试基础def test_用户数据快照(self, snapshot):首次运行生成快照后续运行进行比较serializer UserSerializer()user {id: 1,username: alice,email: aliceexample.com,is_active: True,roles: [user, admin],created_at: 2024-01-15T10:30:00,}result serializer.serialize(user)# snapshot.assert_match 自动保存并比较快照snapshot.assert_match(json.dumps(result, indent2),user_serialized.json)def test_新用户快照(self, snapshot):测试新注册用户的序列化结果serializer UserSerializer()new_user {id: 2,username: bob_new,email: bobexample.com,created_at: 2024-06-01T08:00:00,}result serializer.serialize(new_user)snapshot.assert_match(json.dumps(result, indent2),new_user.json)def test_非活跃用户快照(self, snapshot):测试非活跃用户的序列化结果serializer UserSerializer()inactive_user {id: 3,username: charlie,email: charlieexample.com,is_active: False,roles: [viewer],created_at: 2024-03-20T15:45:00,}result serializer.serialize(inactive_user)snapshot.assert_match(json.dumps(result, indent2),inactive_user.json)