如何测试一个函数调用i中的另一个函数

2024-04-19 16:34:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我在用模块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

Tags: 模块csvto函数testselfherepytest
1条回答
网友
1楼 · 发布于 2024-04-19 16:34:11

您可以“模拟”该函数以返回一个值,该值允许测试被测系统中的其余逻辑(在本例中是download_csv方法)。你知道吗

假设我们有一个要求.txt像这样

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"

请注意,在正常情况下,您的测试代码可能位于与其测试的代码不同的文件中;这就是为什么我指出module_that_contains_function_to_be_mocked是关键的。你知道吗

相关问题 更多 >