Jared Mackey
Jared Mackey

Reputation: 4158

Mock CSV DictReader

Is there a way to mock the DictReader for unit testing without actually having to write a file and then re-open it.

My functions accept a DictReader instance, so I could just easily pass them one to test their functionality, but cannot seem to get one without opening a file.

Currently I am manually writing a CSV file and then deleting it each test.

class TestRowsStuff(unittest.TestCase):
    def write_csv(self, path, iterable):
        with open(path, 'wb') as f:
            writer = csv.DictWriter(f, [PP, SN, TN])
            writer.writeheader()
            writer.writerows(iterable)

    def setUp(self):
        ...
        self.test_file = os.path.join('test.csv')
        self.write_csv(self.test_file, test_values)

    def tearDown(self):
        os.remove(self.test_file)

Upvotes: 4

Views: 6808

Answers (3)

Degim
Degim

Reputation: 71

In case that someone is looking for mocking writerow and wants to check if data was successfully passed to the csv writer:

from unittest import mock

@mock.patch('csv.writer')
def test_csv_writer_writerow(self, csv_writer_mock):
    (do your stuff...)
    csv_writer_mock.writerow.assert_has_calls([mock.call(expected_data_here)])

Upvotes: 3

Danil
Danil

Reputation: 5181

Can be halpful if you are looking a way to count writerow

from mock import Mock, patch
from where.you.do.stuff import do
@patch('where.you.do.stuff.csv')
def test846(self, m_csv):
    m_csv.writer = Mock(writerow=Mock())
    do()
    self.assertEqual(m_csv.writer.call_count, 1)
    self.assertEqual(m_csv.writer().writerow.call_count, 999)



import csv
from io import StringIO
def do():
    w = csv.writer(StringIO)
    for i in range(1, 999):
        w.writerow(i)

Upvotes: 1

Anzel
Anzel

Reputation: 20563

You may use in-memory StringIO object to store/read the Unicode/strings:

In [10]: from StringIO import StringIO

In [11]: import csv

In [12]: csvfile = StringIO()

In [13]: csvfile.seek(0)

# sample taken from [here](https://docs.python.org/2/library/csv.html)    
In [14]: fieldnames = ['first_name', 'last_name']

In [15]: writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

In [16]: writer.writeheader()

In [17]: writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})

In [18]: writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})

In [19]: writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})

In [20]: csvfile.seek(0)

To read it back:

In [21]: csvfile.readlines()
Out[21]: 
['first_name,last_name\r\n',
 'Baked,Beans\r\n',
 'Lovely,Spam\r\n',
 'Wonderful,Spam\r\n']

If you want to use in-memory buffer instead you may also use io.StringIO.

Upvotes: 5

Related Questions