[英]How to test one function that calls another function inside of it
I'm using module pytest to do testing我正在使用模块 pytest 进行测试
Problem: When i run the pytest, it works fine, but how do i stop it from calling a function within the function i'm testing问题:当我运行 pytest 时,它工作正常,但我如何阻止它在我正在测试的 function 中调用 function
eg例如
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
You would "mock" that function to return a value that allows testing of the rest of the logic in the system under test (in this case, the download_csv
method).您将“模拟”该 function 以返回一个值,该值允许测试被测系统中逻辑的 rest(在本例中为
download_csv
方法)。
Assuming we have a requirements.txt like this,假设我们有一个这样的 requirements.txt,
pytest
mock
with a file test.py
like this, we can mock the decompress_csv
function.使用这样的文件
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"
Note that in a normal situation your test code will likely be in a file different from the code it's testing;请注意,在正常情况下,您的测试代码可能位于与其正在测试的代码不同的文件中; that's why I pointed out that the
module_that_contains_function_to_be_mocked
is critical.这就是为什么我指出
module_that_contains_function_to_be_mocked
很关键。
Turn self.decompress_csv()
into a function such as:将
self.decompress_csv()
变成 function 如:
def decompress_csv(file):
file.decompress_csv()
When you want to test it just call it from download_csv() with self as the file parameter:当你想测试它时,只需从 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.