sam
sam

Reputation: 873

How do I mock `csv.DictWriter.writeheader()`, which is called from within my custom function?

I have a custom function defined in

custom_file.py


import csv

def write_dict_to_csv(columns=None, file_name=None, data=None):
    try:
        with open(file_name, "w") as f:
            writer = csv.DictWriter(f, fieldnames=columns)
            writer.writeheader()

in test_file.py I want to return a fixed value when writer.writeheader() is called.

from custom_file import write_dict_to_csv

class TestMyFunctions(unittest.TestCase):

    @patch('custom_file.csv.DictWriter.writeheader')
    def test_write_dict_to_csv(self, mock_writeheader):
        custom_file.write_dict_to_csv(file_name='fileName')
        self.assertTrue(mock_writeheader.called)

But this returns TypeError: stat: path should be string, bytes, os.PathLike or integer, not NoneType

How do I mock csv.DictWriter.writeheader() when it's being imported from an external library into a custom_file, which I'm then testing from a separate test_file?

I figured this would be close to correct since we're meant to patch where a thing is looked up, not where it is defined.

Upvotes: 1

Views: 1279

Answers (1)

Pavel Ryvintsev
Pavel Ryvintsev

Reputation: 1008

The code you have provided does not run "as is" because of some missing imports, but after fixing the problems everything seems working (the test passes). Here is the code I ran. I hope it helps.

custom_file.py

import csv


def write_dict_to_csv(columns=None, file_name=None, data=None):
    with open(file_name, "w") as f:
        writer = csv.DictWriter(f, fieldnames=columns)
        writer.writeheader()

test_file.py

import unittest
from unittest.mock import patch

import custom_file


class TestMyFunctions(unittest.TestCase):

    @patch('custom_file.csv.DictWriter.writeheader')
    def test_write_dict_to_csv(self, mock_writeheader):
        print("Hello")
        custom_file.write_dict_to_csv(file_name='fileName')
        self.assertTrue(mock_writeheader.called)

Upvotes: 2

Related Questions