r/pythonhelp • • Aug 24 '22

Am I mocking correctly?

In my test I have:

def test_should_convert_csv_headers_to_array(mocker):

    expected = [ 'ID', 'Name', 'Image', 'SKU' ]
    mock_csv_dict_writer = mocker.MagicMock()
    mock_csv_dict_writer.fieldnames.return_value = [ 'ID', 'Name', 'Image', 'SKU' ]

assert expected == headers_to_config_map(mock_csv_dict_writer)

All headers_to_config_map does is call fieldnames on csv.DictWriter

I've mocked the csv dictwriter so the return value of calling feildnames returns the array I expect.

I'm just wondering if I'm moving in the right direction in terms of unit testing.

I can't help but think, this doesn't need to be tested because DictWriter.fieldnames() is already tested by the creators of the csv package. My function just wraps that so do I still need to test my function?

3 Upvotes

4 comments sorted by

1

u/Goobyalus Aug 24 '22

I've mocked the csv dictwriter so the return value of calling feildnames returns the array I expect.

You can do

dictwriter = DictWriter(Mock(), ['ID', 'Name', 'Image', 'SKU'])

or

dictwriter = DictWriter(StringIO(), ['ID', 'Name', 'Image', 'SKU'])

to mock out a smaller set of functionality.

My function just wraps that so do I still need to test my function?

Well, this will catch if you messed up the wrapper.

All headers_to_config_map does is call fieldnames on csv.DictWriter

This raises the question of why your wrapper function exists at all - just replace headers_to_config_map(dictwriter) with dictwriter.fieldnames, right?

1

u/Status_Ad6549 Aug 24 '22 edited Aug 24 '22

Thank you. Where does `Mock()` come from?

Mock is a part of unittest, can I mix unittest and Pytest?

1

u/Goobyalus Aug 24 '22

Yep, the fact that this is mocked isn't really visible to pytest, and it's normal to use unittest features in your pytest tests if they're useful.

e.g.: https://github.com/pytest-dev/pytest/blob/f28421cc7068b13ba63c1f60cc21f898cccea36c/testing/example_scripts/acceptance/fixture_mock_integration.py

1

u/Status_Ad6549 Aug 24 '22

Thank you. You've been very helpful!