在python中进行测试时,确保可靠和孤立的测试至关重要。一个普遍的挑战是如何模拟或修改测试过程中对象和功能的行为。这是Pytest monkeypatch灯具发光的地方。它提供了一种灵活的方法,可以在测试过程中动态替换代码的部分。
什么是monkeypatch?
对象的属性
测试边缘案例
想象您正在测试一个取决于环境变量的函数:
# my_app.py def fetch_data(): # Simulate an API call return "Real API Response"#config.py 导入操作系统 def get_database_url(): 返回os.getEnv(“ database_url”,“ default_url”)
您可以使用monkeypatch模拟不同的环境:
# my_app.py def fetch_data(): # Simulate an API call return "Real API Response"#test_config.py 从配置imimt get_database_url def test_get_get_database_url(monkeypatch): monkeypatch.setenv(“ database_url”,“模拟_url”) assert get_database_url()==“ Mocked_url”
如果您需要临时替换课堂中的方法:
# my_app.py def fetch_data(): # Simulate an API call return "Real API Response"#my_class.py 类计算器: def add(self,a,b): 返回b
用模拟方法测试行为:
# my_app.py def fetch_data(): # Simulate an API call return "Real API Response"#test_my_class.py 来自my_class导入计算器 def test_calculator_add(monkeypatch): def mock_add(self,a,b): 返回42 monkeypatch.setAttr(计算器,“ add”,mock_add) calc =计算器() assert calc.add(1,2)== 42
您甚至可以为特定方案模拟内置功能:
# my_app.py def fetch_data(): # Simulate an API call return "Real API Response"#my_module.py def is_file_openable(文件名): 尝试: 带有打开(文件名,“ R”): 返回true 除了ioerror: 返回false
模拟打开以模拟不同的行为:
# my_app.py def fetch_data(): # Simulate an API call return "Real API Response"#test_my_module.py 来自my_module import is_file_openable def test_is_file_openable(monkeypatch): def mock_open(文件名,模式): 提高ioError(“嘲笑IoError”) monkeypatch.setAttr(“ helidins.open”,mock_open) 断言不是is_file_openable(“ test.txt”)
MonkeyPatch的最佳实践
# my_module.py def is_file_openable(filename): try: with open(filename, "r"): return True except IOError: return False范围
:仅在测试范围内使用monkeypatch来避免副作用。
# my_module.py def is_file_openable(filename): try: with open(filename, "r"): return True except IOError: return False使用explicit路径
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3