[英]How to run exception Unit test for one function that calls another function inside of it
[英]How to test one function that calls another function inside of it
我正在使用模块 pytest 进行测试
问题:当我运行 pytest 时,它工作正常,但我如何阻止它在我正在测试的 function 中调用 function
例如
def download_csv(self):
# code here will download csv
# I want to test code up until here and dont run the decompress_csv() function
self.decompress_csv()
# assume this function is in a separate test file
def test_download_csv():
assert download_csv() == # i will check if it downloaded
您将“模拟”该 function 以返回一个值,该值允许测试被测系统中逻辑的 rest(在本例中为download_csv
方法)。
假设我们有一个这样的 requirements.txt,
pytest
mock
使用这样的文件test.py
,我们可以模拟decompress_csv
function。
import mock
def decompress_csv():
raise Exception("This will never be called by the test below")
def download_csv():
decompressed = decompress_csv()
return f"{decompressed} downloaded and processed"
def test_download_csv():
# These additional variables are just to underscore what's going on:
module_that_contains_function_to_be_mocked = 'test'
mock_target = f"{module_that_contains_function_to_be_mocked}.decompress_csv"
with mock.patch(mock_target, return_value='fake decompressed output'):
assert download_csv() == "fake decompressed output downloaded and processed"
请注意,在正常情况下,您的测试代码可能位于与其正在测试的代码不同的文件中; 这就是为什么我指出module_that_contains_function_to_be_mocked
很关键。
将self.decompress_csv()
变成 function 如:
def decompress_csv(file):
file.decompress_csv()
当你想测试它时,只需从 download_csv() 调用它,并将 self 作为文件参数:
def download_csv(self):
def decompress_csv(file):
file.decompress_csv()
decompress_csv(self)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.