How to test one function that calls another function inside of it

Viewed 4406

I'm using module pytest to do testing

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

e.g.

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
1 Answers

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).

Assuming we have a requirements.txt like this,

pytest
mock

with a file test.py like this, we can mock the 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.

Related