Skip to content

Instantly share code, notes, and snippets.

@jmcarp
Created April 8, 2018 19:53
Show Gist options
  • Save jmcarp/3032687c4201a7272136ce3801105724 to your computer and use it in GitHub Desktop.
Save jmcarp/3032687c4201a7272136ce3801105724 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
import datetime
import collections
import pytest
def ledger(path, cutoff=None):
with open(path) as csvfile:
result = collections.defaultdict(int)
reader = csv.DictReader(csvfile, fieldnames=['date', 'payor', 'payee', 'amount'])
for row in reader:
amount = float(row['amount'])
if cutoff is not None:
date = datetime.datetime.strptime(row['date'], '%Y-%m-%d')
if date > cutoff:
continue
result[row['payor']] -= amount
result[row['payee']] += amount
return result
class TestLedger:
@pytest.fixture
def data(self, tmpdir):
path = tmpdir.join('data.csv')
with path.open('w') as csvfile:
csvfile.write('2010-10-01,john,mary,50\n')
csvfile.write('2011-10-01,mary,store,25\n')
csvfile.write('2012-10-01,mary,store,100\n')
csvfile.write('2013-10-01,sarah,mary,75\n')
return path
@pytest.fixture
def bad_date_data(self, tmpdir):
path = tmpdir.join('data.csv')
with path.open('w') as csvfile:
csvfile.write('2010-ten-one,john,mary,50\n')
return path
@pytest.fixture
def bad_amount_data(self, tmpdir):
path = tmpdir.join('data.csv')
with path.open('w') as csvfile:
csvfile.write('2010-10-01,john,mary,fifty\n')
return path
def test_no_date(self, data):
assert ledger(data) == {
'john': -50,
'mary': 0,
'sarah': -75,
'store': 125,
}
def test_date(self, data):
assert ledger(data, datetime.datetime(2012, 1, 1)) == {
'john': -50,
'mary': 25,
'store': 25,
}
def test_bad_date(self, bad_date_data):
with pytest.raises(ValueError):
ledger(bad_date_data, datetime.datetime(2012, 1, 1))
def test_bad_amount(self, bad_amount_data):
with pytest.raises(ValueError):
ledger(bad_amount_data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment