我正在使用pytest模块进行测试
问题:运行pytest时,它工作正常,但是如何阻止它在我正在测试的函数中调用函数
例如
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
答案 0 :(得分:0)
您将“模拟”该函数以返回一个值,该值允许测试被测系统中的其余逻辑(在本例中为HomePageModule
方法)。
假设我们有一个requirements.txt,
download_csv
使用这样的文件pytest
mock
,我们可以模拟test.py
函数。
decompress_csv
请注意,在正常情况下,您的测试代码可能位于与所测试代码不同的文件中;这就是为什么我指出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"
至关重要。