Permalink
Browse files

add importer and tests

  • Loading branch information...
czue committed Jan 16, 2016
1 parent 5a65b93 commit 8928de5dc266da86aad5d36d01a916103e8278c6
View
@@ -0,0 +1,24 @@
import csv
from guests.models import Party, Guest
def import_guests(path):
with open(path, 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
first_row = True
for row in reader:
if first_row:
first_row = False
continue
party_name, first_name, last_name, email, party_type, is_child = row[:6]
party = Party.objects.get_or_create(name=party_name)[0]
if party.type != party_type:
party.type = party_type
party.save()
if email:
guest = Guest.objects.get_or_create(party=party, email=email)[0]
guest.first_name = first_name
guest.last_name = last_name
guest.save()
else:
Guest.objects.get_or_create(party=party, first_name=first_name, last_name=last_name)
No changes.
No changes.
@@ -0,0 +1,9 @@
from django.core.management import BaseCommand
from guests import csv_import
class Command(BaseCommand):
args = 'filename'
def handle(self, filename, *args, **kwargs):
csv_import.import_guests(filename)
View
@@ -0,0 +1 @@
from .test_importer import *
@@ -0,0 +1,5 @@
Party,First Name,Last Name,email,Category,is child?
The Starks,Ned,Stark,ned@winterfell.gov,formal,
The Starks,Catelyn,Stark,cat@winterfell.gov,formal,
The Starks,Arya,Stark,needle@winterfell.gov,formal,y
Tyrion,Tyrion,Lannister,,fun,n
@@ -0,0 +1,27 @@
import os
from django.test import TestCase
from guests.csv_import import import_guests
from guests.models import Party, Guest
class GuestImporterTest(TestCase):
@classmethod
def setUpClass(cls):
super(GuestImporterTest, cls).setUpClass()
cls.path = os.path.join(os.path.dirname(__file__), 'data', 'guests-test.csv')
def test_import(self):
import_guests(self.path)
self.assertEqual(2, Party.objects.count())
self.assertEqual(4, Guest.objects.count())
the_starks = Guest.objects.filter(party__name='The Starks')
self.assertEqual(3, the_starks.count())
def test_import_idempotent(self):
for i in range(3):
import_guests(self.path)
self.assertEqual(2, Party.objects.count())
self.assertEqual(4, Guest.objects.count())
the_starks = Guest.objects.filter(party__name='The Starks')
self.assertEqual(3, the_starks.count())

0 comments on commit 8928de5

Please sign in to comment.