模拟CSV DictReader

时间:2015-10-23 21:47:38

标签: python python-2.7 csv mocking

有没有办法模拟DictReader进行单元测试而不必实际编写文件然后重新打开它。

我的函数接受一个DictReader实例,所以我可以轻松地将它们传递给一个来测试它们的功能,但是如果没有打开文件似乎无法获得它。

目前我手动编写CSV文件,然后在每次测试时删除它。

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)

3 个答案:

答案 0 :(得分:4)

您可以使用内存 StringIO 对象来存储/读取Unicode /字符串:

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)

要读回来:

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

如果您想使用内存缓冲区,您也可以使用 io.StringIO

答案 1 :(得分:0)

如果您正在寻找计算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)

答案 2 :(得分:0)

如果有人正在寻找模拟 writerow 并想检查数据是否成功传递到csv编写器:

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