So I have function in my Django app business logic I want to test:
def parse_sectors_from_csv():
sectors_csv = open(os.path.join(settings.BASE_DIR, 'sector', 'fixtures', 'sectors.csv'))
sectors_csv_reader = csv.DictReader(sectors_csv)
return [
{
'model': 'sector.sector',
'id': index,
'fields': {
'name': row.get('Sector'),
'slug': slugify(row['Sector']),
'type_id': row.get('Type_Id')
}
}
for index, row in enumerate(sectors_csv_reader, 1)
]
I already test it for file existence and for existence of heading row.
Now I want to mock
open(os.path.join(settings.BASE_DIR, 'sector', 'fixtures', 'sectors.csv'))
In my test.py I wrote
with patch('__builtin__.open', mock_open(read_data=sectors_csv_mock), create=True) as m:
sectors = service.parse_sectors_from_csv()
print('Sectors:', sectors)
self.assertEqual(expected_sectors, sectors)
But as I understand, it's passes empty file to function as it prints Sectors: []
I read mock_open dock for a few times and still can't figure it out.
>>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
... with open('foo') as h: # what's happening here?
... result = h.read() # here?
...
>>> m.assert_called_once_with('foo') # and here?
>>> assert result == 'bibble'