def testEventisRegd(self): 
     
     self.e.save()
     
     u = User()
     u.first_name = "Justin" 
     u.last_name = "Gray"
     u.username = "******"
     
     u.save()
     
     rc = RaceClass()
     rc.abrv = "CSP"
     rc.name = "CSP"
     rc.pax = 1
     rc.club = self.c
     rc.save()
             
     self.assertFalse(self.e.is_regd(u))        
     
     r = Registration()
     r.event = self.e
     r.number = 11
     r.race_class = rc
     r.user_profile = u.get_profile()
     r.club = self.c
     r.save()
     
     self.assertTrue(self.e.is_regd(u))
    def testMoveToBumpClass(self):
        bump_class = RaceClass()
        bump_class.name = "Index"
        bump_class.pax = 1.0
        bump_class.club = self.c
        bump_class.save()

        self.r.bump_class = bump_class
        self.r.save()

        self.assertEqual(self.r.race_class, self.race_class)
        self.assertEqual(self.r.bump_class, bump_class)
    def testMoveToBumpClass(self):
        bump_class = RaceClass()
        bump_class.name = "Index"
        bump_class.pax = 1.0
        bump_class.club = self.c
        bump_class.save()

        self.r.bump_class = bump_class
        self.r.save()

        self.assertEqual(self.r.race_class, self.race_class)
        self.assertEqual(self.r.bump_class, bump_class)
    def test_default_pax_class(self):

        pax_class = RaceClass()
        pax_class.name = "Street Tire"
        pax_class.abrv = "T"
        pax_class.pax = 1
        pax_class.club = self.c
        pax_class.pax_class = True
        pax_class.hidden = True
        pax_class.save()

        other_pax_class = RaceClass()
        other_pax_class.name = "Pro"
        other_pax_class.abrv = "X"
        other_pax_class.pax = 1
        other_pax_class.club = self.c
        other_pax_class.pax_class = True
        other_pax_class.hidden = False
        other_pax_class.save()

        race_class = RaceClass()
        race_class.name = "HS"
        race_class.abrv = "HS"
        race_class.pax = 0.5
        race_class.club = self.c
        race_class.default_pax_class = pax_class
        race_class.save()

        self.r.race_class = race_class
        self.r.save()

        self.assertEqual(self.r.pax_class, pax_class)

        # set it back to CSP
        self.r.race_class = self.race_class
        self.r.save()
        self.assertEqual(self.r.pax_class, None)

        # make sure pax_class does not change
        self.r.pax_class = other_pax_class
        self.r.save()
        self.assertEqual(self.r.pax_class, other_pax_class)
        self.r.race_class = race_class
        self.r.save()
        self.assertEqual(self.r.pax_class, other_pax_class)
    def test_default_pax_class(self):

        pax_class = RaceClass()
        pax_class.name = "Street Tire"
        pax_class.abrv = "T"
        pax_class.pax = 1
        pax_class.club = self.c
        pax_class.pax_class = True
        pax_class.hidden = True
        pax_class.save()

        other_pax_class = RaceClass()
        other_pax_class.name = "Pro"
        other_pax_class.abrv = "X"
        other_pax_class.pax = 1
        other_pax_class.club = self.c
        other_pax_class.pax_class = True
        other_pax_class.hidden = False
        other_pax_class.save()

        race_class = RaceClass()
        race_class.name = "HS"
        race_class.abrv = "HS"
        race_class.pax = .5
        race_class.club = self.c
        race_class.default_pax_class = pax_class
        race_class.save()

        self.r.race_class = race_class
        self.r.save()

        self.assertEqual(self.r.pax_class, pax_class)

        #set it back to CSP
        self.r.race_class = self.race_class
        self.r.save()
        self.assertEqual(self.r.pax_class, None)

        #make sure pax_class does not change
        self.r.pax_class = other_pax_class
        self.r.save()
        self.assertEqual(self.r.pax_class, other_pax_class)
        self.r.race_class = race_class
        self.r.save()
        self.assertEqual(self.r.pax_class, other_pax_class)
class TestRegistration(unittest.TestCase):
    def setUp(self):
        self.c = Club()
        self.c.name = "test club"
        self.c.full_clean()
        self.c.save()

        self.season = Season()
        self.season.club = self.c
        self.season.year = 2011
        self.season.save()

        self.race_class = RaceClass()
        self.race_class.name = "CSP"
        self.race_class.abrv = "CSP"
        self.race_class.pax = .875
        self.race_class.club = self.c
        self.race_class.save()

        self.e = Event()
        self.e.name = "test event"
        self.e.date = datetime.date.today()
        self.e.season = self.season
        self.e.club = self.c
        self.e.save()

        self.user = User()
        self.user.first_name = "Justin"
        self.user.last_name = "Gray"
        self.user.username = "******"
        self.user.save()

        self.user2 = User()
        self.user2.first_name = "Eli"
        self.user2.last_name = "Gray"
        self.user2.username = "******"
        self.user2.save()

        self.car = Car()
        self.car.year = 1990
        self.car.make = "Mazda"
        self.car.model = "Miata"
        self.car.user_profile = self.user.get_profile()
        self.car.save()

        self.r = Registration()
        self.r.number = 11
        self.r.race_class = self.race_class
        self.r.pax_class = None
        self.r.club = self.c
        self.r.event = self.e

        self.user_profile = UserProfile.objects.get(user=self.user)
        self.user_profile2 = UserProfile.objects.get(user=self.user2)

    def tearDown(self):

        clear_db()

    def test_default_pax_class(self):

        pax_class = RaceClass()
        pax_class.name = "Street Tire"
        pax_class.abrv = "T"
        pax_class.pax = 1
        pax_class.club = self.c
        pax_class.pax_class = True
        pax_class.hidden = True
        pax_class.save()

        other_pax_class = RaceClass()
        other_pax_class.name = "Pro"
        other_pax_class.abrv = "X"
        other_pax_class.pax = 1
        other_pax_class.club = self.c
        other_pax_class.pax_class = True
        other_pax_class.hidden = False
        other_pax_class.save()

        race_class = RaceClass()
        race_class.name = "HS"
        race_class.abrv = "HS"
        race_class.pax = .5
        race_class.club = self.c
        race_class.default_pax_class = pax_class
        race_class.save()

        self.r.race_class = race_class
        self.r.save()

        self.assertEqual(self.r.pax_class, pax_class)

        #set it back to CSP
        self.r.race_class = self.race_class
        self.r.save()
        self.assertEqual(self.r.pax_class, None)

        #make sure pax_class does not change
        self.r.pax_class = other_pax_class
        self.r.save()
        self.assertEqual(self.r.pax_class, other_pax_class)
        self.r.race_class = race_class
        self.r.save()
        self.assertEqual(self.r.pax_class, other_pax_class)

    def test_calc_times_empty_results(self):
        self.r.save()

        self.r.calc_times()

        self.assertEqual(self.r.total_raw_time, 0)
        self.assertEqual(self.r.total_index_time, 0)

    def test_calc_times(self):
        self.r.save()

        sess = Session()
        sess.name = "AM"
        sess.event = self.e
        sess.club = self.c
        sess.save()

        res = Result()
        res.reg = self.r
        res.session = sess
        res.club = self.c
        res.save()

        r = Run()
        r.base_time = 10.0
        r.result = res
        r.club = self.c
        r.save()

        res = Result()
        res.reg = self.r
        res.session = sess
        res.club = self.c
        res.save()

        r = Run()
        r.base_time = 10.0
        r.result = res
        r.club = self.c
        r.save()

        self.r.save()
        self.r.calc_times()

        self.assertEqual(self.r.total_raw_time, 20.0)
        self.assertEqual(self.r.total_index_time,
                         self.r.total_raw_time * self.race_class.pax)

    def testAnon(self):

        self.r._anon_f_name = "Justin"
        self.r._anon_l_name = "Gray"
        self.r._anon_car = "1990 Mazda Miata"

        self.r.save()

        self.assertEqual("Justin", self.r.first_name)
        self.assertEqual("Gray", self.r.last_name)
        self.assertEqual("1990 Mazda Miata", self.r.car_name)

        self.r.associate_with_user(self.user2.username)
        self.r.save()

        self.assertEqual("Eli", self.r.first_name)
        self.assertEqual("Gray", self.r.last_name)
        self.assertEqual("1990 Mazda Miata", self.r.car_name)

    def testWithCar(self):

        self.r.car = self.car
        self.r.user_profile = self.user_profile
        self.r.save()

        self.assertEqual("Justin", self.r.first_name)
        self.assertEqual("Gray", self.r.last_name)
        self.assertEqual("1990 Mazda Miata", self.r.car_name)

    def testAllowedNumberRaceClass(self):

        self.r.car = self.car
        self.r.user_profile = self.user_profile
        self.r.save()

        self.r2 = Registration()
        self.r2.number = 11
        self.r2.race_class = self.race_class
        self.r2.pax_class = None
        self.r2.club = self.c
        self.r2.event = self.e

        try:
            self.r2.full_clean()
        except ValidationError as err:
            self.assertEqual(
                "{'__all__': [u'11 CSP is already taken, pick another number.']}",
                str(err))
        else:
            self.fail("ValidationError expected")

        #make sure you can save an existing reg
        self.r2.number = 12
        self.r2.save()

        self.r.number = 12
        #self.r.save()

        try:
            self.r.full_clean()
        except ValidationError as err:
            self.assertEqual(
                "{'__all__': [u'12 CSP is already taken, pick another number.']}",
                str(err))
        else:
            self.fail("ValidationError expected")

        self.e2 = Event()
        self.e2.name = "test event 2"
        self.e2.date = datetime.date.today()
        self.e2.season = self.season
        self.e2.club = self.c
        self.e2.save()

        self.r3 = Registration()
        self.r3.number = 77
        self.r3.race_class = self.race_class
        self.r3.pax_class = None
        self.r3.event = self.e2
        self.r3.club = self.c
        self.r3.save()

        self.e.child_events.add(self.e2)
        self.e.save()

        self.r2.number = 77

        try:
            self.r2.full_clean()
        except ValidationError as err:
            self.assertEqual(
                "{'__all__': [u'77 CSP is already taken, pick another number.']}",
                str(err))
        else:
            self.fail("ValidationError expected")

    def testMaxUserRegLimit(self):
        self.e2 = Event()
        self.e2.name = "test event 2"
        self.e2.date = datetime.date.today()
        self.e2.season = self.season
        self.e2.club = self.c
        self.e2.save()

        self.race_class.user_reg_limit = 1
        self.race_class.save()

        self.r.car = self.car
        self.r.user_profile = self.user_profile
        self.r.event = self.e
        self.r.save()

        self.r2 = Registration()
        self.r2.number = 11
        self.r2.race_class = self.race_class
        self.r2.pax_class = None
        self.r2.event = self.e2
        self.r2.club = self.c
        self.r2.user_profile = self.user_profile

        try:
            self.r2.full_clean()
        except ValidationError as err:
            self.assertEqual(
                "{'__all__': [u'You have reached the registration limit for CSP.']}",
                str(err))
        else:
            self.fail("ValidationError expected")

    def testEventRegLimit(self):
        self.race_class.event_reg_limit = 1
        self.race_class.save()

        self.r.car = self.car
        self.r.event = self.e
        self.r.user_profile = self.user_profile
        self.r.save()

        self.r2 = Registration()
        self.r2.number = 21
        self.r2.race_class = self.race_class
        self.r2.pax_class = None
        self.r2.club = self.c
        self.r2.event = self.e

        try:
            self.r2.full_clean()
        except ValidationError as err:
            self.assertEqual(
                "{'__all__': [u'Only 1 registrations for CSP are "
                "allowed for an event. The class is full']}", str(err))
        else:
            self.fail("ValidationError expected")

        #test that a user can only register once, regardless of class
        self.race_class.event_reg_limit = 10
        self.race_class.save()

        self.r2.number = 111
        self.r2.race_class = self.race_class
        self.r2.pax_class = None
        self.r2.event = self.e
        self.r2.user_profile = self.user_profile

        try:
            self.r2.full_clean()
        except ValidationError as err:
            self.assertEqual(
                "{'__all__': [u'You have already registered to run as 11 CSP']}",
                str(err))
        else:
            self.fail("ValidationError expected")

    def testCarDeleteFromReg(self):
        """Check to make sure reg_car gets set to null if a car gets deleted"""

        self.r.car = self.car

        self.r.save()

        self.assertEqual(self.r.car, self.car)

        self.car.delete()
        reg = Registration.objects.filter(number=11).get()

        self.assertIsNone(reg.car)

    def testMoveToBumpClass(self):
        bump_class = RaceClass()
        bump_class.name = "Index"
        bump_class.pax = 1.0
        bump_class.club = self.c
        bump_class.save()

        self.r.bump_class = bump_class
        self.r.save()

        self.assertEqual(self.r.race_class, self.race_class)
        self.assertEqual(self.r.bump_class, bump_class)

    def testMakeAssocRegs(self):
        e2 = Event()
        e2.name = "test event 2"
        e2.date = datetime.date.today()
        e2.season = self.season
        e2.club = self.c
        e2.save()

        self.e.child_events.add(e2)
        self.e.save()

        self.r.make_assoc_regs()
        regs = Registration.objects.filter(event=e2).all()
        self.assertEqual(len(regs), 1)

    def testUpdateAssocRegs(self):
        e2 = Event()
        e2.name = "test event 2"
        e2.date = datetime.date.today()
        e2.season = self.season
        e2.club = self.c
        e2.save()

        self.e.child_events.add(e2)
        self.e.save()

        self.r.make_assoc_regs()

        self.r.number = 10
        self.r.save()
        self.r.update_assoc_regs()

        reg = Registration.objects.filter(event=e2).get()
        self.assertEqual(reg.number, self.r.number)
class TestOrder(unittest.TestCase):
    def tearDown(self):
        clear_db()

    def setUp(self):
        self.c = Club()
        self.c.name = "test club"
        self.c.full_clean()
        self.c.save()

        self.season = Season()
        self.season.club = self.c
        self.season.year = 2011
        self.season.save()

        self.race_class = RaceClass()
        self.race_class.name = "CSP"
        self.race_class.pax = .875
        self.race_class.club = self.c
        self.race_class.save()

        self.e = Event()
        self.e.name = "test event"
        self.e.date = datetime.date.today()
        self.e.season = self.season
        self.e.club = self.c
        self.e.save()

        self.user = User()
        self.user.first_name = "justin"
        self.user.last_name = "gray"
        self.user.username = "******"
        self.user.save()

        self.user2 = User()
        self.user2.first_name = "sirius"
        self.user2.last_name = "gray"
        self.user2.username = "******"
        self.user2.save()

    def test_total_price(self):
        self.o = Order()
        self.o.user_prof = self.user.get_profile()
        self.o.save()

        item1 = Registration()
        item1.number = 11
        item1.race_class = self.race_class
        item1.pax_class = None
        item1.event = self.e
        item1.price = "40.00"
        item1.order = self.o
        item1.club = self.c
        item1.save()

        item2 = Membership()
        item2.user_prof = self.user.get_profile()
        item2.club = self.c
        item2.num = 1
        item2.start = datetime.date.today() - datetime.timedelta(days=300)
        item2.valid_thru = datetime.date.today() + datetime.timedelta(days=1)
        item2.price = "60.00"
        item2.order = self.o
        item2.save()

        self.o.calc_total_price()
        self.assertEqual(self.o.total_price, "100.00")

        club = Club()
        club.name = "test-test"
        club.save()

        c = Coupon()
        c.discount_amount = "10.00"
        c.permanent = True
        c.code = "aaa"
        c.expires = datetime.date.today() + datetime.timedelta(days=1)
        c.club = club
        c.save()

        self.o.coupon = c
        self.o.calc_total_price()
        self.assertEqual(self.o.total_price, '90.00')
Exemple #8
0
class TestResult(unittest.TestCase): 
    
    def setUp(self): 
        
        self.c = Club()
        self.c.name = "test club"
        self.c.save()
        
        self.season = Season()
        self.season.club = self.c
        self.season.year = 2011
        self.season.save()
        
        self.race_class = RaceClass()
        self.race_class.name = "CSP"
        self.race_class.pax = .875
        self.race_class.club = self.c
        self.race_class.save()
        
        self.e = Event()
        self.e.name = "test event"
        self.e.date = datetime.date.today()
        self.e.season = self.season
        self.e.club = self.c
        self.e.save()
        
        self.sess = Session()
        self.sess.name = "AM"
        self.sess.event = self.e
        self.sess.club = self.c
        self.sess.save()
        
        self.r = Registration()
        self.r.number = 11
        self.r.race_class = self.race_class
        self.r.pax_class = None
        self.r.event = self.e
        self.r.club = self.c
        self.r.save()
        
        self.result = Result()
        self.result.reg = self.r
        self.result.session = self.sess
        self.result.club = self.c
        self.result.save()
        
    def tearDown(self): 
        
        Club.objects.all().delete()
        Season.objects.all().delete()
        RaceClass.objects.all().delete()
        Event.objects.all().delete()
        Session.objects.all().delete()
        Registration.objects.all().delete()
        Result.objects.all().delete()
        Run.objects.all().delete()
    
    def test_best_run1(self): 
        
        r1 = Run()
        r1.base_time = 10.0
        r1.result = self.result
        r1.club = self.c
        r1.save()
        
        r2 = Run()
        r2.base_time = 11.0
        r2.result = self.result
        r2.club = self.c
        r2.save()
        
        r3 = Run()
        r3.base_time = 9.0
        r3.cones = 1
        r3.result = self.result
        r3.club = self.c
        r3.save()
        
        r4 = Run()
        r4.base_time = 10.0
        r4.result = self.result
        r4.penalty = "DNF"
        r4.club = self.c
        r4.save()
        
        best_run = self.result.find_best_run()
        
        self.assertEqual(best_run, r1)
        
    def test_best_run2(self): 
        
        r1 = Run()
        r1.base_time = 10.0
        r1.result = self.result
        r1.club = self.c
        r1.save()
        
        best_run = self.result.find_best_run() 
        
        self.assertEqual(best_run, r1)   
        
    def test_best_run3(self): 
        
        r1 = Run()
        r1.base_time = 10.0
        r1.result = self.result
        r1.club = self.c
        r1.save()
        
        r2 = Run()
        r2.base_time = 9.0
        r2.result = self.result
        r2.club = self.c
        r2.save()
        
        r3 = Run()
        r3.base_time = 10.5
        r3.result = self.result
        r3.club = self.c
        r3.save()
        
        best_run = self.result.find_best_run() 
        
        self.assertEqual(best_run, r2) 
        
    def test_best_run_no_clean_runs(self): 
        
        r1 = Run()
        r1.base_time = 10.0
        r1.result = self.result
        r1.penalty = "DNF"
        r1.club = self.c
        r1.save()
        
        r2 = Run()
        r2.base_time = 0.1
        r2.result = self.result
        r2.penalty = "O/C"
        r2.club = self.c
        r2.save()
        
        best_run = self.result.find_best_run() 
        
        self.assertEqual(best_run, None)        
class TestParseAxtime(TestCase):
    def setUp(self):
        self.data = [
            '"First","Last","Reg","Class","Num","BC","Vehicle","Addr","City_St","Zip","Heat","Wrk_Ht","Wrk_Asgn","Notes","Mem_Num","Pax_Cls","Color","Sponsor","Tires","Co_Drvr","In_Pts","DL_Num","DL_St","DL_Exp","Fee","Pd_by","Run1_1","Pyl1_1","Pen1_1","Run2_1","Pyl2_1","Pen2_1","Run3_1","Pyl3_1","Pen3_1","Run4_1","Pyl4_1","Pen4_1","Run5_1","Pyl5_1","Pen5_1","Best_1","Run1_2","Pyl1_2","Pen1_2","Run2_2","Pyl2_2","Pen2_2","Run3_2","Pyl3_2","Pen3_2","Run4_2","Pyl4_2","Pen4_2","Run5_2","Pyl5_2","Pen5_2","Best_2","Pts_1","Pts_2","Pts_3","Pts_4","Pts_5","Pts_6","Pts_7","Pts_8","Pts_9","Pts_10","Pts_11","Pts_12","Pts_13","Pts_14","Pts_15","Pts_Bon","Indx_1","Indx_2","Indx_3","Indx_4","Indx_5","Indx_6","Indx_7","Indx_8","Indx_9","Indx_10","Indx_11","Indx_12","Indx_13","Indx_14","Indx_15","Indx_Bon"',
            '"CHRIS","BRUBAKER","NORA","STS","73","","97 MAZDA MIATA","","   ","     ","  1","  2","","22906","BRUBAKER","STS","","","","","Y","","  ","","   ","  ","  55.531"," 0","   ","  55.436"," 0","   ","  53.677"," 0","   ","  54.566"," 0","   ","   0.000"," 0","   ","  53.677","  53.873"," 0","   ","  54.056"," 0","   ","  53.792"," 0","   ","  53.803"," 0","   ","   0.000"," 0","   ","  53.792","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    "'
        ]

        self.c = Club()
        self.c.name = "test"
        self.c.save()

        self.s = Season()
        self.s.year = 2011
        self.s.club = self.c
        self.s.save()

        self.e = Event()
        self.e.name = "test event"
        self.e.date = datetime.date.today()
        self.e.season = self.s
        self.e.club = self.c
        self.e.save()

        self.session = Session()
        self.session.name = "am"
        self.session.club = self.c
        self.session.event = self.e
        self.session.save()

        self.rc = RaceClass()
        self.rc.name = "STS"
        self.rc.abrv = "STS"
        self.rc.pax = .95
        self.rc.club = self.c
        self.rc.save()

        self.rc2 = RaceClass()
        self.rc2.name = "Rookie"
        self.rc2.abrv = "R"
        self.rc2.pax = 1
        self.rc2.club = self.c
        self.rc2.pax_class = True
        self.rc2.save()

        self.rc3 = RaceClass()
        self.rc3.name = "STC"
        self.rc3.abrv = "STC"
        self.rc3.pax = .95
        self.rc3.club = self.c
        self.rc3.save()

        user = User.objects.create_user('admin', '*****@*****.**',
                                        'admin')

    def tearDown(self):

        models = [Registration, RaceClass, Club, Season, Event, Session, User]
        for model in models:
            model.objects.all().delete()

    def test_missing_raceclass(self):
        RaceClass.objects.all().delete()

        f = StringIO.StringIO("\n".join(self.data))

        results = parse_axtime(self.e, self.session, f)

        self.assertEqual(
            results, {
                'results_file':
                'Your results for CHRIS BRUBAKER included an unknown race class: STS'
            })

    def test_with_raceclass_anon(self):
        f = StringIO.StringIO("\n".join(self.data))

        results = parse_axtime(self.e, self.session, f)

        result = results[0]
        runs = result.runs.all()

        self.assertEqual(len(runs), 8)
        self.assertEqual(result.best_run, runs[2])

        self.assertEqual(result.reg._anon_f_name, 'CHRIS')
        self.assertEqual(result.reg._anon_l_name, 'BRUBAKER')
        self.assertEqual(result.reg.user, AnonymousUser())

    def test_with_raceclass(self):
        f = StringIO.StringIO("\n".join(self.data))

        user = User()
        user.first_name = "CHRIS"
        user.last_name = "brubaker"
        user.username = "******"
        user.save()

        self.r = Registration()
        self.r.number = 11
        self.r.race_class = self.rc
        self.r.pax_class = None
        self.r.club = self.c
        self.r.event = self.e

        result = parse_axtime(self.e, self.session, f)[0]
        runs = result.runs.all()

        self.assertEqual(len(runs), 8)
        self.assertEqual(result.best_run, runs[2])

        reg = result.reg
        self.assertEqual(reg.user, user)

        self.assertEqual(reg.number, 73)

    def test_multi_results(self):
        self.data.append(
            '"CHRIS","MCPHERSON","NORA","R","13","","90 HONDA CIVIC SI","","   ","     ","  1","  2","","22929","SUMMERNIGH","STC","","","","","Y","","  ","","   ","  ","  59.740"," 0","   ","  58.399"," 0","   ","  56.798"," 2","   ","  57.131"," 0","   ","  55.374"," 0","   ","  55.374","  56.671"," 0","   ","  56.519"," 0","   ","  56.225"," 0","   ","  55.629"," 0","   ","   0.000"," 0","   ","  55.629","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    "'
        )
        f = StringIO.StringIO("\n".join(self.data))

        results = parse_axtime(self.e, self.session, f)

        self.assertEqual(len(results), 2)

        result = results[0]
        self.assertEqual(result.reg.race_class, self.rc)
        self.assertEqual(result.reg.pax_class, None)

        result = results[1]
        self.assertEqual(result.reg.race_class, self.rc3)
        self.assertEqual(result.reg.pax_class, self.rc2)

    def base_upload_results(self):

        c = Client()
        c.login(username='******', password='******')

        self.data.append(
            '"CHRIS","MCPHERSON","NORA","R","13","","90 HONDA CIVIC SI","","   ","     ","  1","  2","","22929","SUMMERNIGH","STC","","","","","Y","","  ","","   ","  ","  59.740"," 0","   ","  58.399"," 0","   ","  56.798"," 2","   ","  57.131"," 0","   ","  55.374"," 0","   ","  55.374","  56.671"," 0","   ","  56.519"," 0","   ","  56.225"," 0","   ","  55.629"," 0","   ","   0.000"," 0","   ","  55.629","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    "'
        )
        f = StringIO.StringIO("\n".join(self.data))
        f.name = "results.csv"

        url = "/garage/event/%d/results" % self.e.id

        post_data = {'name': 'AM', 'results_file': f}

        response = c.post(url, post_data)

        return response

    def test_upload_with_error1(self):
        """make sure things work if the first result line is an error"""
        RaceClass.objects.all().delete()
        Session.objects.all().delete()

        response = self.base_upload_results()

        self.assertEqual(
            json.loads(response.content), {
                'results_file':
                'Your results for CHRIS BRUBAKER included an unknown race class: STS'
            })

        runs = Run.objects.all()
        self.assertEqual(len(runs), 0)

        results = Result.objects.all()
        self.assertEqual(len(results), 0)

        sessions = Session.objects.all()
        self.assertEqual(len(sessions), 0)

    def test_upload_with_error2(self):
        """make sure things work if the second result line is an error"""
        RaceClass.objects.exclude(abrv='STS').delete()
        Session.objects.all().delete()

        response = self.base_upload_results()

        self.assertEqual(
            json.loads(response.content), {
                u'result_file':
                u'Your Reults for CHRIS MCPHERSON included a unknown entry, R in the Class column'
            })

        runs = Run.objects.all()
        self.assertEqual(len(runs), 0)

        results = Result.objects.all()
        self.assertEqual(len(results), 0)

        sessions = Session.objects.all()
        self.assertEqual(len(sessions), 0)

    def test_upload_clean(self):
        Session.objects.all().delete()

        response = self.base_upload_results()

        self.assertEqual(response.status_code, 200)

        runs = Run.objects.all()
        self.assertEqual(len(runs), 17)

        results = Result.objects.all()
        self.assertEqual(len(results), 2)

        sessions = Session.objects.all()
        self.assertEqual(len(sessions), 1)
    def handle(self, *args, **options):
        clear_db()

        
        s = Site.objects.all()[0]
        s.domain = "dev.racerslane.com" 
        s.name = "Racerslane.com" 
        s.save()

        print "Loading users"
        reader = csv.DictReader(open('old_data/driver.csv', 'rU'))
        for line in reader: 
            """user_name","email","verified","activation_code",
            "f_name","l_name","address","city","state",
            "zip_code","_password"""
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None   
                             
            u = User()
            u.username = line['user_name']
            u.email = line['email']
            u.password = "******"%line['_password']
            u.first_name = line['f_name']
            u.last_name = line['l_name']
            u.is_active = True
            u.save()
            
            up = u.get_profile()
            up.address = line['address']
            up.city = line['city']
            up.state = line['state']
            up.zip_code = line['zip_code']
            up.save()
            db.reset_queries()

            
        #dev to make it so I can login to any account    
        justin = User.objects.get(username="******")   
        password = justin.password
        
        #User.objects.all().update(password=password)

        print "Loading Cars"
        car_map = {}
        reader = csv.DictReader(open('old_data/car.csv', 'rb'))
        for line in reader:     
            """id","nickname","make","model","color","avatar_file_loc",
            "avatar_thumb_loc","year","owner_user_name"""
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None            
            if line['owner_user_name']: 
                try: 
                    c = Car()
                    c.provisional = False
                    c.name = line['nickname']
                    c.make = line['make']
                    c.model = line['model']
                    if line['color']: 
                        c.color = line['color']
                    c.year = line['year']
                    c.user_profile = User.objects.get(username=line['owner_user_name']).get_profile()
                    s_car_id = (line['owner_user_name'], line['nickname'])
                    if exists('old_data/avatars/%s_%s_avatar'%s_car_id): 
                        c.avatar.save('%s_%s_avatar'%s_car_id, File(open('old_data/avatars/%s_%s_avatar'%s_car_id)))
                        c.thumb.save('%s_%s_thumb'%s_car_id, File(open('old_data/avatars/%s_%s_thumb'%s_car_id)))
                    c.save()
                    db.reset_queries()
                    car_map[line['id']] = c.pk
                except:
                    continue         
     
        print "Loading Clubs"
        #read in clubs
        club_map = {}
        for line in csv.DictReader(open('old_data/club.csv', 'rU')): 
            """"name","web_link","process_payments","points_calc_type",
            "membership_cost","renewal_cost","membership_terms","paypal_email",
            "index_point_method","address","city","state","zip_code","""
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None            
            c = Club()
            c.city = line['city']
            c.address = line['address']
            c.zip_code = line['zip_code']
            c.state = line['state']
            c.name = line['name']
            c.process_payments = line['process_payments']
            c.paypal_email = line['paypal_email']
            c.membership_terms = line['membership_terms']
            c.new_member_cost = line['membership_cost']
            c.renew_cost = line['renewal_cost']

            c.save()

            club_map[line['name']] = c
            db.reset_queries()  

        print "loading coupons"
        for line in csv.DictReader(open('old_data/coupon.csv')):    
            """coupon_code","club_name","discount_amount","uses_left","expires",
            "permanent","driver_user_name","registration_id"""    
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None
            
            c = Coupon()
            c.code = line['coupon_code']
            c.permanent = bool(line['permanent'])
            c.club = club_map[line['club_name']]
            c.uses_left = line['uses_left']
            c.discount_amount = line['discount_amount']
            if line['expires']: 
                c.expires = datetime.datetime.strptime(line['expires'], '%Y-%m-%d %H:%M:%S')
            if line['driver_user_name']:
                c.user_prof = User.objects.get(username=line['driver_user_name']).get_profile()
            c.save()    
            db.reset_queries()

        print "loading memberships"
        reader = csv.DictReader(open('old_data/membership.csv', 'rb'))
        for line in reader: 
            """"id","club_name","number","start_date","valid_thru_date",
            "price","paid","token","payer_id","transaction_id","anon_f_name",
            "anon_l_name","driver_user_name"""
            
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None 

            m = Membership()
            m.num = line['number']

            m.start = datetime.datetime.strptime(line['start_date'], '%Y-%m-%d %H:%M:%S')
            m.valid_thru = datetime.datetime.strptime(line['valid_thru_date'], '%Y-%m-%d %H:%M:%S')
            m.paid = bool(line['paid'])
            if line['price']!=None:
                m.price = float(line['price'])

            try: 
                m.user_prof = User.objects.get(username=line['driver_user_name']).get_profile()
            except User.DoesNotExist: 
                continue    
            m.club = club_map[line['club_name']]
            
            m._anon_f_name = line['anon_f_name']
            m._anon_l_name = line['anon_l_name']

            m.save()
            db.reset_queries()

        print "loading locations"
        location_map = {}    
        for line in csv.DictReader(open("old_data/location.csv")):    
            """id","name","address","lat","lng","club_name"""
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None                
            club = Club.objects.get(name=line['club_name'])        
            
            l = Location()
            l.name = line['name']
            l.address = line['address']
            #l.lat = line['lat']
            #l.lon = line['lng']
            l.club = club
            
            l.save()      
            
            location_map[line['id']] = l
            db.reset_queries()

        print "loading seasons"      
        season_map = {}    
        for line in csv.DictReader(open('old_data/season.csv')): 
            s = Season()
            """"id","year","active","club_name","drop_lowest_events"""
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None            
            club = Club.objects.get(name=line['club_name'])
            s.club = club
            s.year = int(line['year'])
            s.drop_lowest_events = int(line['drop_lowest_events'])
            s.save()
                        
            season_map[line['id']] = s
            db.reset_queries()

        print "loading events"
        event_map = {}
        for line in csv.DictReader(open('old_data/event.csv', 'rU')):
            
            """id","name","note","date","registration_close","member_cost",
            "non_member_cost","pay_at_event_cost","location_id","club_name",
            "season_id","multiplier","count_points"""
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None            
            
            e = Event()
            e.name = line['name']
            e.note = line['note']
            e.date = datetime.datetime.strptime(line['date'], '%Y-%m-%d %H:%M:%S')
            e.reg_close = line['registration_close']+"-05:00"
            e.member_price = float(line['member_cost'])
            e.non_member_price = float(line['non_member_cost'])
            e.non_pre_pay_penalty = float(line['pay_at_event_cost'])
            e.season = season_map[line['season_id']]
            e.club = e.season.club
            e.count_points = int(line['count_points'])
            e.multiplier = int(line['multiplier'])
            
            if line['location_id']:
                e.location = location_map[line['location_id']]
            
            e.save()
            
            event_map[line['id']] = e
            db.reset_queries()

        print "loading race_classes" 
        race_class_map = {}
        for line in csv.DictReader(open('old_data/raceclass.csv')):
            """id","pax","name","club_name"""
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None            
            
            club = Club.objects.get(name=line['club_name'])                        
            r = RaceClass()
            r.name = line['name']
            r.abrv = line['name']
            r.pax = float(line['pax'])
            r.club = club
            r.save()
            db.reset_queries()
            
            race_class_map[line['id']] = r
            
        index_class = RaceClass()
        index_class.name = 'Index'
        index_class.bump_class = True
        index_class.abrv = "i"
        index_class.pax = 1.0
        index_class.club = club
        index_class.save()
        
        print "loading reg_types" 
        reg_type_map = {}    
        for line in csv.DictReader(open('old_data/regtype.csv')):
            """id","name","class_letters","reg_limit","index",
            "description","club_name"""
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None            
            club = Club.objects.get(name=line['club_name']) 
            r = RaceClass()
            r.pax_class = True
            r.description = line['description']
            r.name = line['name']
            r.abrv = line['class_letters']
            if line['reg_limit']: 
                r.user_reg_limit=line['reg_limit']
            r.pax = 1.0
            r.club = club
            r.save()
            
            reg_type_map[line['id']] = r
            db.reset_queries()

        print "loading registrations" 
        registration_map = {}  
        for line in csv.DictReader(open('old_data/registration.csv')): 
            
            """id","number","paid","token","payer_id","transaction_id",
            "price","class_points","index_points","index_flag","anon_f_name",
            "anon_l_name","anon_car","driver_user_name","event_id","reg_type_id",
            "car_id","race_class_id"""
            
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None            
                
            if not line['event_id']: 
                continue            
            
            rc = race_class_map[line['race_class_id']]

            r = Registration()

            r.paid = bool(line['paid'])
            if line['price']!=None:
                r.price = float(line['price'])
            
            if line['driver_user_name']: 
                user = User.objects.get(username=line['driver_user_name'])
                r.user_profile = user.get_profile()
            r.number = int(line['number'])
            r.paid = int(line['paid'])
            r.index_points = line['index_points']
            r.class_points = line['class_points']
            if line['price']:
                r.price = float(line['price'])
            else: 
                r.price = 0.00
            r.index_points = int(line['index_points'])
            r.class_points = int(line['class_points'])
            if line['anon_car']: 
                r._anon_car=line['anon_car'].strip()
            if line['anon_l_name']: 
                r._anon_l_name=line['anon_l_name'].strip()
            if line['anon_f_name']: 
                r._anon_f_name=line['anon_f_name'].strip()
            r.race_class = rc
            r.event = event_map[line['event_id']]
            r.club = r.event.club
            try: 
                if line['reg_type_id']: 
                    r.pax_class=reg_type_map[line['reg_type_id']]
            except: 
                pass
            
            if line['index_flag']: 
                r.bump_class=index_class
            try: 
                if line['car_id']:
                    r.car=Car.objects.get(pk=car_map[line['car_id']])
            except: 
                pass
            #TODO race_class_id
            #TODO remove reg_detail class, and associate reg with UserProfile directly
            #TODO registrations can be siblings for joint update
            
            try: 
                r.save()
            except: 
                r.number += 100
                try: 
                    r.save()
                except: 
                    continue   

            registration_map[line['id']] = r.pk
            db.reset_queries()

        print "loading sessions"     
        session_map = {}
        for line in csv.DictReader(open('old_data/session.csv')):
            """id", "name", "event_id", "course_id"""
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None             
            
            try: 
                event_map[line['event_id']]
            except: 
                continue
            
            s = Session()
            s.name = line['name']
            s.event = event_map[line['event_id']]
            s.club = s.event.club
            s.save()
            
            session_map[line['id']] = s
            db.reset_queries()

        print "loading results"   
        result_map = {}    
        for line in csv.DictReader(open('old_data/result.csv')):        
            """id","registration_id","event_id","sess_id"""
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None                        
    
            try: 
                registration_map[line['registration_id']]
                session_map[line['sess_id']]
            except: 
                continue
            
            r = Result()
            reg = Registration.objects.get(pk=registration_map[line['registration_id']])
            r.reg = reg 

            r.session = session_map[line['sess_id']]
            r.club = r.session.club
            try: 
                r.save()
            except Exception as err: 
                print registration_map[line['registration_id']].pk
                print str(err)
                print registration_map[line['registration_id']]
            
            result_map[line['id']] = r.id
            db.reset_queries()

        print "loading runs" 
        for line in csv.DictReader(open('old_data/run.csv')):
            """id","base_time","calc_time","index_time","cones",
            "penalty","result_id","result_2_id"""
            for k, v in line.iteritems(): 
                if v == "NULL": 
                    line[k] = None
                    
            if line['base_time'] == None: 
                continue
            try: 
                r = Run()
                r.base_time = float(line['base_time'])
                r.cones = int(line['cones'])
                if line['penalty']:
                    r.penalty = line['penalty']
                result = Result.objects.get(pk=result_map[line['result_id']])
                r.result = result
                r.club = r.result.club
                r.save()
                db.reset_queries()
            except KeyError: 
                continue

        print "calculating reg times"
        for reg in Registration.objects.select_related('results').all().iterator(): 
            reg.calc_times()


        #House keeping
        nora = Club.objects.get(safe_name='noraascc')
        user = User.objects.get(username="******")
        nora.group.user_set.add(user)
Exemple #11
0
class TestPostForms(ResourceTestCase):
    def setUp(self):
        super(TestPostForms, self).setUp()

        self.c = Club()
        self.c.name = "test club"
        self.c.full_clean()
        self.c.save()

        self.season = Season()
        self.season.club = self.c
        self.season.year = 2011
        self.season.save()

        self.race_class = RaceClass()
        self.race_class.name = "CSP"
        self.race_class.abrv = "CSP"
        self.race_class.pax = .875
        self.race_class.club = self.c
        self.race_class.save()

        self.e = Event()
        self.e.name = "test event"
        self.e.date = datetime.date.today()
        self.e.season = self.season
        self.e.club = self.c
        self.e.save()

        self.user = User()
        self.user.first_name = "Justin"
        self.user.last_name = "Gray"
        self.user.username = "******"
        self.user.save()

        self.c.group.user_set.add(self.user)
        self.c.save()

        self.user.set_password("test")
        self.user.save()

        self.r = Registration()
        self.r.number = 11
        self.r.race_class = self.race_class
        self.r.pax_class = None
        self.r.club = self.c
        self.r.event = self.e

    def get_credentials(self):
        resp = self.api_client.client.login(username='******',
                                            password='******')
        return resp

    def test_assoc_reg_user(self):

        self.r.save()

        data = {
            "username": "******",
        }

        self.get_credentials()

        resp = self.api_client.client.post('/garage/reg/%s/driver' % self.r.pk,
                                           data)

        self.assertValidJSONResponse(resp)
        post_data = self.deserialize(resp)

        resp = self.api_client.get('/garage/api/v1/registration/%d/' %
                                   self.r.pk)
        self.assertValidJSONResponse(resp)

        get_data = self.deserialize(resp)

        self.assertEqual(post_data, get_data)
class TestEventPointsCalc(unittest.TestCase): 
    
    def setUp(self): 
        self.c = Club()
        self.c.name = "test club"
        self.c.full_clean()
        self.c.save()
        
        self.season = Season()
        self.season.club = self.c
        self.season.year = 2011
        self.season.save()
        
        self.e = Event()
        self.e.name = "test event"
        self.e.date = datetime.date.today()
        self.e.season = self.season
        self.e.club = self.c
        self.e.save()
        
        self.sess = Session()
        self.sess.name = "AM"
        self.sess.event = self.e
        self.sess.club = self.c
        self.sess.save()
        
        self.classes = ["A", "B", "C", "D", "E", "F", "G", "H"]
        self.paxes   = [1.0, .98, .96, .94, .92, .90, .88, .86]
        for klass, pax in zip(self.classes, self.paxes): 
            self.race_class = RaceClass()
            self.race_class.name = klass
            self.race_class.pax = pax
            self.race_class.club = self.c
            self.race_class.save()
            
            for i in range(0, 10): 
                self.r = Registration()
                self.r.number = i
                self.r.race_class = self.race_class
                self.r._anon_f_name = "%s%d"%(self.race_class.name, i)
                self.r.pax_class = None
                self.r.event = self.e
                self.r.club = self.c
                self.r.save()
                
                #make two regs with empty runs for each class
                if self.race_class.name!="H" and i < 8: #one race class with no results
                    self.result = Result()
                    self.result.reg = self.r
                    self.result.session = self.sess
                    self.result.club = self.c
                    self.result.save()
                    for j in range(0, 3): 
                        run = Run()
                        run.base_time = 100.0-i-j #91.0 is lowest raw time (*0.88 for index)
                        run.result = self.result
                        run.club = self.c
                        run.save()        
                            
    def tearDown(self): 
        clear_db()

    def test_no_index_classes_one_result(self): 
        
        race_classes = self.e.calc_results()
        self.assertEqual(["A", "B", "C", "D", "E", "F", "G"], [rc.name for rc in race_classes])
                
        #make sure the results come back sorted
        for rc, regs in race_classes.iteritems(): #all race_classes should have 8 regs in the results    
            self.assertEqual(regs, sorted(regs, key=lambda x: x.total_index_time))

            self.assertEqual(class_point_ladder[:8], [reg.class_points for reg in regs])
            
            self.assertEqual(8, len(regs))
            
        regs = self.e.get_results()
        self.assertEqual(regs[0].total_index_time, (91.0)*.88)
        self.assertEqual(index_point_ladder[:56], [reg.index_points for reg in regs])
        
    def test_no_index_classes_two_result(self): 
        
        self.sess = Session()
        self.sess.name = "PM"
        self.sess.event = self.e
        self.sess.club = self.c
        self.sess.save()

        for klass, pax in zip(self.classes, self.paxes): 
            self.race_class = RaceClass.objects.filter(name=klass).get()            
            for i in range(0, 10): 
                self.r = Registration.objects.filter(_anon_f_name="%s%d"%(self.race_class.name, i)).get()
                
                #make  regs with empty runs for each class
                if self.race_class.name!="H" and i < 8: #one race class with no results
                    self.result = Result()
                    self.result.reg = self.r
                    self.result.session = self.sess
                    self.result.club = self.c
                    self.result.save()
                    for j in range(0, 3): 
                        run = Run()
                        run.base_time = 100.0-i-j
                        run.result = self.result
                        run.club = self.c
                        run.save()   
                self.r = Registration.objects.filter(_anon_f_name="%s%d"%(self.race_class.name, i)).get()        
                
        race_classes = self.e.calc_results()
        self.assertEqual(["A", "B", "C", "D", "E", "F", "G"], [rc.name for rc in race_classes])
                
        #make sure the results come back sorted
        for rc, regs in race_classes.iteritems(): #all race_classes should have 8 regs in the results    
            self.assertEqual(regs, sorted(regs, key=lambda x: x.total_index_time))

            self.assertEqual(class_point_ladder[:8], [reg.class_points for reg in regs])
            
            self.assertEqual(8, len(regs))
            
        regs = self.e.get_results()
        self.assertEqual(regs[0].total_index_time, 2*(91.0)*.88)
        self.assertEqual(index_point_ladder[:56], [reg.index_points for reg in regs])
        
    def test_pax_class_one_result(self): 
        
        self.race_class = RaceClass()
        self.race_class.name = "Pro"
        self.race_class.abrv ="X"
        self.race_class.pax = 1.0
        self.race_class.pax_class=True
        self.race_class.club = self.c
        self.race_class.save()

        for i, pax_name in zip(range(0, 7), self.classes): 
            
            rc = RaceClass.objects.filter(name=pax_name).get()
            
            self.r = Registration()
            self.r.number = 10*(1+i)
            self.r.race_class = rc
            self.r._anon_f_name = "%s_%d"%(self.race_class.name, i)
            self.r.pax_class = self.race_class
            self.r.event = self.e
            self.r.club = self.c
            self.r.save()
            
            #make  regs with runs for each class
            if rc.name!="H": 
                self.result = Result()
                self.result.reg = self.r
                self.result.session = self.sess
                self.result.club = self.c
                self.result.save()
                for j in range(0, 3): 
                    run = Run()
                    run.base_time = 100.0-i-j
                    run.result = self.result
                    run.club = self.c
                    run.save()   
                
        race_classes = self.e.calc_results()
        self.assertEqual([u"A", u"B", u"C", u"D", u"E", u"F", u"G", u"Pro"], [rc.name for rc in race_classes])
                
        #make sure the results come back sorted
        for rc, regs in race_classes.iteritems(): #all race_classes should have 8 regs in the results    
            self.assertEqual(regs, sorted(regs, key=lambda x: x.total_index_time))

            if rc.name != "Pro": 
                self.assertEqual(class_point_ladder[:8], [reg.class_points for reg in regs])
                self.assertEqual(8, len(regs))
            else: 
                self.assertEqual(class_point_ladder[:7], [reg.class_points for reg in regs])
                self.assertEqual(7, len(regs))
                
        regs = self.e.get_results()
        self.assertEqual(regs[0].total_index_time, (91.0)*.88)
        self.assertEqual(index_point_ladder[:63], [reg.index_points for reg in regs])  
        
    def test_one_bump_class_one_result(self): 
        
        self.race_class = RaceClass()
        self.race_class.name = "index"
        self.race_class.pax = 1.0
        self.race_class.club = self.c
        self.race_class.save()

        for i, pax_name in zip(range(0, 7), self.classes): 
            
            rc = RaceClass.objects.filter(name=pax_name).get()
            
            self.r = Registration()
            self.r.number = 10*(1+i)
            self.r.race_class = rc
            self.r._anon_f_name = "%s_%d"%(self.race_class.name, i)
            self.r.bump_class = self.race_class
            self.r.event = self.e
            self.r.club = self.c
            self.r.save()
            
            #make  regs with empty runs for each class
            if rc.name!="H": 
                self.result = Result()
                self.result.reg = self.r
                self.result.session = self.sess
                self.result.club = self.c
                self.result.save()
                for j in range(0, 3): 
                    run = Run()
                    run.base_time = 100.0-i-j
                    run.result = self.result
                    run.club = self.c
                    run.save()   
                
        race_classes = self.e.calc_results()
        self.assertEqual(["A", "B", "C", "D", "E", "F", "G", "index"], [rc.name for rc in race_classes])
                
        #make sure the results come back sorted
        for rc, regs in race_classes.iteritems(): #all race_classes should have 8 regs in the results    
            self.assertEqual(regs, sorted(regs, key=lambda x: x.total_index_time))

            if rc.name != "index": 
                self.assertEqual(class_point_ladder[:8], [reg.class_points for reg in regs])
                self.assertEqual(8, len(regs))
            else: 
                self.assertEqual(class_point_ladder[:7], [reg.class_points for reg in regs])
                self.assertEqual(7, len(regs))
            
        regs = self.e.get_results()
        self.assertEqual(regs[0].total_index_time, (91.0)*.88)
        self.assertEqual(index_point_ladder[:63], [reg.index_points for reg in regs])  
        
    def test_two_bump_class_one_result(self): 
        
        self.race_class1 = RaceClass()
        self.race_class1.name = "index1"
        self.race_class1.pax = 1.0
        self.race_class1.club = self.c
        self.race_class1.save()
        
        self.race_class2 = RaceClass()
        self.race_class2.name = "index2"
        self.race_class2.pax = 1.0
        self.race_class2.club = self.c
        self.race_class2.save()

        for i, pax_name in zip(range(0, 7), self.classes): 
            
            pax_class = RaceClass.objects.filter(name=pax_name).get()
            
            self.r = Registration()
            self.r.number = 10*(1+i)
            self.r.race_class = pax_class
            self.r._anon_f_name = "%s_%d"%(self.race_class2.name, i)
            self.r.bump_class = self.race_class1
            self.r.event = self.e
            self.r.club = self.c
            self.r.save()
            
            #make  regs with empty runs for each class
            if pax_class.name!="H": 
                self.result = Result()
                self.result.reg = self.r
                self.result.session = self.sess
                self.result.club = self.c
                self.result.save()
                for j in range(0, 3): 
                    run = Run()
                    run.base_time = 100.0-i-j
                    run.result = self.result
                    run.club = self.c
                    run.save()  
                    
                self.r = Registration()
                self.r.number = 60*(1+i)
                self.r.race_class = pax_class
                self.r._anon_f_name = "%s_%d"%(self.race_class2.name, i)
                self.r.bump_class = self.race_class2
                self.r.event = self.e
                self.r.club = self.c
                self.r.save()
                
                #make  regs with empty runs for each class
                if pax_class.name!="H": 
                    self.result = Result()
                    self.result.reg = self.r
                    self.result.session = self.sess
                    self.result.club = self.c
                    self.result.save()
                    for j in range(0, 3): 
                        run = Run()
                        run.base_time = 100.0-i-j
                        run.result = self.result
                        run.club = self.c
                        run.save()               
                    
        race_classes = self.e.calc_results()
        self.assertEqual(set(["A", "B", "C", "D", "E", "F", "G", "index1", "index2"]), set([rc.name for rc in race_classes]))
                
        #make sure the results come back sorted
        for rc, regs in race_classes.iteritems(): #all race_classes should have 8 regs in the results    
            self.assertEqual(regs, sorted(regs, key=lambda x: x.total_index_time))

            if "index" not in rc.name: 
                self.assertEqual(class_point_ladder[:8], [reg.class_points for reg in regs])
                self.assertEqual(8, len(regs))
            else: 
                self.assertEqual(class_point_ladder[:7], [reg.class_points for reg in regs])
                self.assertEqual(7, len(regs))
                
        regs = self.e.get_results()
        self.assertEqual(regs[0].total_index_time, (91.0)*.88)
        self.assertEqual(index_point_ladder[:70], [reg.index_points for reg in regs])      
        
        
class TestRegistration(unittest.TestCase):
    def setUp(self):
        self.c = Club()
        self.c.name = "test club"
        self.c.full_clean()
        self.c.save()

        self.season = Season()
        self.season.club = self.c
        self.season.year = 2011
        self.season.save()

        self.race_class = RaceClass()
        self.race_class.name = "CSP"
        self.race_class.abrv = "CSP"
        self.race_class.pax = 0.875
        self.race_class.club = self.c
        self.race_class.save()

        self.e = Event()
        self.e.name = "test event"
        self.e.date = datetime.date.today()
        self.e.season = self.season
        self.e.club = self.c
        self.e.save()

        self.user = User()
        self.user.first_name = "Justin"
        self.user.last_name = "Gray"
        self.user.username = "******"
        self.user.save()

        self.user2 = User()
        self.user2.first_name = "Eli"
        self.user2.last_name = "Gray"
        self.user2.username = "******"
        self.user2.save()

        self.car = Car()
        self.car.year = 1990
        self.car.make = "Mazda"
        self.car.model = "Miata"
        self.car.user_profile = self.user.get_profile()
        self.car.save()

        self.r = Registration()
        self.r.number = 11
        self.r.race_class = self.race_class
        self.r.pax_class = None
        self.r.club = self.c
        self.r.event = self.e

        self.user_profile = UserProfile.objects.get(user=self.user)
        self.user_profile2 = UserProfile.objects.get(user=self.user2)

    def tearDown(self):

        clear_db()

    def test_default_pax_class(self):

        pax_class = RaceClass()
        pax_class.name = "Street Tire"
        pax_class.abrv = "T"
        pax_class.pax = 1
        pax_class.club = self.c
        pax_class.pax_class = True
        pax_class.hidden = True
        pax_class.save()

        other_pax_class = RaceClass()
        other_pax_class.name = "Pro"
        other_pax_class.abrv = "X"
        other_pax_class.pax = 1
        other_pax_class.club = self.c
        other_pax_class.pax_class = True
        other_pax_class.hidden = False
        other_pax_class.save()

        race_class = RaceClass()
        race_class.name = "HS"
        race_class.abrv = "HS"
        race_class.pax = 0.5
        race_class.club = self.c
        race_class.default_pax_class = pax_class
        race_class.save()

        self.r.race_class = race_class
        self.r.save()

        self.assertEqual(self.r.pax_class, pax_class)

        # set it back to CSP
        self.r.race_class = self.race_class
        self.r.save()
        self.assertEqual(self.r.pax_class, None)

        # make sure pax_class does not change
        self.r.pax_class = other_pax_class
        self.r.save()
        self.assertEqual(self.r.pax_class, other_pax_class)
        self.r.race_class = race_class
        self.r.save()
        self.assertEqual(self.r.pax_class, other_pax_class)

    def test_calc_times_empty_results(self):
        self.r.save()

        self.r.calc_times()

        self.assertEqual(self.r.total_raw_time, 0)
        self.assertEqual(self.r.total_index_time, 0)

    def test_calc_times(self):
        self.r.save()

        sess = Session()
        sess.name = "AM"
        sess.event = self.e
        sess.club = self.c
        sess.save()

        res = Result()
        res.reg = self.r
        res.session = sess
        res.club = self.c
        res.save()

        r = Run()
        r.base_time = 10.0
        r.result = res
        r.club = self.c
        r.save()

        res = Result()
        res.reg = self.r
        res.session = sess
        res.club = self.c
        res.save()

        r = Run()
        r.base_time = 10.0
        r.result = res
        r.club = self.c
        r.save()

        self.r.save()
        self.r.calc_times()

        self.assertEqual(self.r.total_raw_time, 20.0)
        self.assertEqual(self.r.total_index_time, self.r.total_raw_time * self.race_class.pax)

    def testAnon(self):

        self.r._anon_f_name = "Justin"
        self.r._anon_l_name = "Gray"
        self.r._anon_car = "1990 Mazda Miata"

        self.r.save()

        self.assertEqual("Justin", self.r.first_name)
        self.assertEqual("Gray", self.r.last_name)
        self.assertEqual("1990 Mazda Miata", self.r.car_name)

        self.r.associate_with_user(self.user2.username)
        self.r.save()

        self.assertEqual("Eli", self.r.first_name)
        self.assertEqual("Gray", self.r.last_name)
        self.assertEqual("1990 Mazda Miata", self.r.car_name)

    def testWithCar(self):

        self.r.car = self.car
        self.r.user_profile = self.user_profile
        self.r.save()

        self.assertEqual("Justin", self.r.first_name)
        self.assertEqual("Gray", self.r.last_name)
        self.assertEqual("1990 Mazda Miata", self.r.car_name)

    def testAllowedNumberRaceClass(self):

        self.r.car = self.car
        self.r.user_profile = self.user_profile
        self.r.save()

        self.r2 = Registration()
        self.r2.number = 11
        self.r2.race_class = self.race_class
        self.r2.pax_class = None
        self.r2.club = self.c
        self.r2.event = self.e

        try:
            self.r2.full_clean()
        except ValidationError as err:
            self.assertEqual("{'__all__': [u'11 CSP is already taken, pick another number.']}", str(err))
        else:
            self.fail("ValidationError expected")

        # make sure you can save an existing reg
        self.r2.number = 12
        self.r2.save()

        self.r.number = 12
        # self.r.save()

        try:
            self.r.full_clean()
        except ValidationError as err:
            self.assertEqual("{'__all__': [u'12 CSP is already taken, pick another number.']}", str(err))
        else:
            self.fail("ValidationError expected")

        self.e2 = Event()
        self.e2.name = "test event 2"
        self.e2.date = datetime.date.today()
        self.e2.season = self.season
        self.e2.club = self.c
        self.e2.save()

        self.r3 = Registration()
        self.r3.number = 77
        self.r3.race_class = self.race_class
        self.r3.pax_class = None
        self.r3.event = self.e2
        self.r3.club = self.c
        self.r3.save()

        self.e.child_events.add(self.e2)
        self.e.save()

        self.r2.number = 77

        try:
            self.r2.full_clean()
        except ValidationError as err:
            self.assertEqual("{'__all__': [u'77 CSP is already taken, pick another number.']}", str(err))
        else:
            self.fail("ValidationError expected")

    def testMaxUserRegLimit(self):
        self.e2 = Event()
        self.e2.name = "test event 2"
        self.e2.date = datetime.date.today()
        self.e2.season = self.season
        self.e2.club = self.c
        self.e2.save()

        self.race_class.user_reg_limit = 1
        self.race_class.save()

        self.r.car = self.car
        self.r.user_profile = self.user_profile
        self.r.event = self.e
        self.r.save()

        self.r2 = Registration()
        self.r2.number = 11
        self.r2.race_class = self.race_class
        self.r2.pax_class = None
        self.r2.event = self.e2
        self.r2.club = self.c
        self.r2.user_profile = self.user_profile

        try:
            self.r2.full_clean()
        except ValidationError as err:
            self.assertEqual("{'__all__': [u'You have reached the registration limit for CSP.']}", str(err))
        else:
            self.fail("ValidationError expected")

    def testEventRegLimit(self):
        self.race_class.event_reg_limit = 1
        self.race_class.save()

        self.r.car = self.car
        self.r.event = self.e
        self.r.user_profile = self.user_profile
        self.r.save()

        self.r2 = Registration()
        self.r2.number = 21
        self.r2.race_class = self.race_class
        self.r2.pax_class = None
        self.r2.club = self.c
        self.r2.event = self.e

        try:
            self.r2.full_clean()
        except ValidationError as err:
            self.assertEqual(
                "{'__all__': [u'Only 1 registrations for CSP are " "allowed for an event. The class is full']}",
                str(err),
            )
        else:
            self.fail("ValidationError expected")

        # test that a user can only register once, regardless of class
        self.race_class.event_reg_limit = 10
        self.race_class.save()

        self.r2.number = 111
        self.r2.race_class = self.race_class
        self.r2.pax_class = None
        self.r2.event = self.e
        self.r2.user_profile = self.user_profile

        try:
            self.r2.full_clean()
        except ValidationError as err:
            self.assertEqual("{'__all__': [u'You have already registered to run as 11 CSP']}", str(err))
        else:
            self.fail("ValidationError expected")

    def testCarDeleteFromReg(self):
        """Check to make sure reg_car gets set to null if a car gets deleted"""

        self.r.car = self.car

        self.r.save()

        self.assertEqual(self.r.car, self.car)

        self.car.delete()
        reg = Registration.objects.filter(number=11).get()

        self.assertIsNone(reg.car)

    def testMoveToBumpClass(self):
        bump_class = RaceClass()
        bump_class.name = "Index"
        bump_class.pax = 1.0
        bump_class.club = self.c
        bump_class.save()

        self.r.bump_class = bump_class
        self.r.save()

        self.assertEqual(self.r.race_class, self.race_class)
        self.assertEqual(self.r.bump_class, bump_class)

    def testMakeAssocRegs(self):
        e2 = Event()
        e2.name = "test event 2"
        e2.date = datetime.date.today()
        e2.season = self.season
        e2.club = self.c
        e2.save()

        self.e.child_events.add(e2)
        self.e.save()

        self.r.make_assoc_regs()
        regs = Registration.objects.filter(event=e2).all()
        self.assertEqual(len(regs), 1)

    def testUpdateAssocRegs(self):
        e2 = Event()
        e2.name = "test event 2"
        e2.date = datetime.date.today()
        e2.season = self.season
        e2.club = self.c
        e2.save()

        self.e.child_events.add(e2)
        self.e.save()

        self.r.make_assoc_regs()

        self.r.number = 10
        self.r.save()
        self.r.update_assoc_regs()

        reg = Registration.objects.filter(event=e2).get()
        self.assertEqual(reg.number, self.r.number)
class TestParseAxtime(TestCase): 

    def setUp(self): 
        self.data = ['"First","Last","Reg","Class","Num","BC","Vehicle","Addr","City_St","Zip","Heat","Wrk_Ht","Wrk_Asgn","Notes","Mem_Num","Pax_Cls","Color","Sponsor","Tires","Co_Drvr","In_Pts","DL_Num","DL_St","DL_Exp","Fee","Pd_by","Run1_1","Pyl1_1","Pen1_1","Run2_1","Pyl2_1","Pen2_1","Run3_1","Pyl3_1","Pen3_1","Run4_1","Pyl4_1","Pen4_1","Run5_1","Pyl5_1","Pen5_1","Best_1","Run1_2","Pyl1_2","Pen1_2","Run2_2","Pyl2_2","Pen2_2","Run3_2","Pyl3_2","Pen3_2","Run4_2","Pyl4_2","Pen4_2","Run5_2","Pyl5_2","Pen5_2","Best_2","Pts_1","Pts_2","Pts_3","Pts_4","Pts_5","Pts_6","Pts_7","Pts_8","Pts_9","Pts_10","Pts_11","Pts_12","Pts_13","Pts_14","Pts_15","Pts_Bon","Indx_1","Indx_2","Indx_3","Indx_4","Indx_5","Indx_6","Indx_7","Indx_8","Indx_9","Indx_10","Indx_11","Indx_12","Indx_13","Indx_14","Indx_15","Indx_Bon"',
                     '"CHRIS","BRUBAKER","NORA","STS","73","","97 MAZDA MIATA","","   ","     ","  1","  2","","22906","BRUBAKER","STS","","","","","Y","","  ","","   ","  ","  55.531"," 0","   ","  55.436"," 0","   ","  53.677"," 0","   ","  54.566"," 0","   ","   0.000"," 0","   ","  53.677","  53.873"," 0","   ","  54.056"," 0","   ","  53.792"," 0","   ","  53.803"," 0","   ","   0.000"," 0","   ","  53.792","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    "'
                    ]

        self.c = Club()
        self.c.name = "test"
        self.c.save()
        
        self.s = Season()
        self.s.year = 2011
        self.s.club = self.c
        self.s.save()
        
        self.e = Event()
        self.e.name = "test event"
        self.e.date = datetime.date.today()
        self.e.season = self.s
        self.e.club = self.c
        self.e.save()

        self.session = Session()
        self.session.name = "am"
        self.session.club = self.c
        self.session.event = self.e
        self.session.save()

        self.rc = RaceClass()
        self.rc.name = "STS"
        self.rc.abrv = "STS"
        self.rc.pax = .95
        self.rc.club = self.c
        self.rc.save()

        self.rc2 = RaceClass()
        self.rc2.name = "Rookie"
        self.rc2.abrv = "R"
        self.rc2.pax = 1
        self.rc2.club = self.c
        self.rc2.pax_class = True
        self.rc2.save()

        self.rc3 = RaceClass()
        self.rc3.name = "STC"
        self.rc3.abrv = "STC"
        self.rc3.pax = .95
        self.rc3.club = self.c
        self.rc3.save()

        user = User.objects.create_user('admin', '*****@*****.**', 'admin')

    def tearDown(self): 

        models = [Registration, RaceClass, Club, Season, Event, Session, User]
        for model in models: 
            model.objects.all().delete()

    def test_missing_raceclass(self): 
        RaceClass.objects.all().delete()

        f = StringIO.StringIO("\n".join(self.data))

        results = parse_axtime(self.e, self.session, f)

        self.assertEqual(results, 
                        {'results_file': 'Your results for CHRIS BRUBAKER included an unknown race class: STS'})
        
    def test_with_raceclass_anon(self):
        f = StringIO.StringIO("\n".join(self.data))

        results = parse_axtime(self.e, self.session, f)
        
        result = results[0]
        runs = result.runs.all()

        self.assertEqual(len(runs), 8)
        self.assertEqual(result.best_run, runs[2])

        self.assertEqual(result.reg._anon_f_name, 'CHRIS')
        self.assertEqual(result.reg._anon_l_name, 'BRUBAKER')
        self.assertEqual(result.reg.user, AnonymousUser())

    def test_with_raceclass(self):
        f = StringIO.StringIO("\n".join(self.data))

        user = User()
        user.first_name = "CHRIS"
        user.last_name = "brubaker"
        user.username = "******"
        user.save()

        self.r = Registration()
        self.r.number = 11
        self.r.race_class = self.rc
        self.r.pax_class = None
        self.r.club = self.c
        self.r.event = self.e

        result = parse_axtime(self.e, self.session, f)[0]
        runs = result.runs.all()
        
        self.assertEqual(len(runs), 8)
        self.assertEqual(result.best_run, runs[2])

        reg = result.reg
        self.assertEqual(reg.user, user)

        self.assertEqual(reg.number, 73)

    def test_multi_results(self): 
        self.data.append('"CHRIS","MCPHERSON","NORA","R","13","","90 HONDA CIVIC SI","","   ","     ","  1","  2","","22929","SUMMERNIGH","STC","","","","","Y","","  ","","   ","  ","  59.740"," 0","   ","  58.399"," 0","   ","  56.798"," 2","   ","  57.131"," 0","   ","  55.374"," 0","   ","  55.374","  56.671"," 0","   ","  56.519"," 0","   ","  56.225"," 0","   ","  55.629"," 0","   ","   0.000"," 0","   ","  55.629","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    "')
        f = StringIO.StringIO("\n".join(self.data))

        results = parse_axtime(self.e, self.session, f)

        self.assertEqual(len(results), 2)

        result = results[0]
        self.assertEqual(result.reg.race_class, self.rc)
        self.assertEqual(result.reg.pax_class, None)

        result = results[1]
        self.assertEqual(result.reg.race_class, self.rc3)
        self.assertEqual(result.reg.pax_class, self.rc2)

    def base_upload_results(self): 
        
        c = Client()
        c.login(username='******', password='******')

        self.data.append('"CHRIS","MCPHERSON","NORA","R","13","","90 HONDA CIVIC SI","","   ","     ","  1","  2","","22929","SUMMERNIGH","STC","","","","","Y","","  ","","   ","  ","  59.740"," 0","   ","  58.399"," 0","   ","  56.798"," 2","   ","  57.131"," 0","   ","  55.374"," 0","   ","  55.374","  56.671"," 0","   ","  56.519"," 0","   ","  56.225"," 0","   ","  55.629"," 0","   ","   0.000"," 0","   ","  55.629","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    ","    "')
        f = StringIO.StringIO("\n".join(self.data))
        f.name = "results.csv"

        url = "/garage/event/%d/results"%self.e.id

        post_data = {'name': 'AM', 'results_file': f}

        response = c.post(url, post_data)

        return response
    
    def test_upload_with_error1(self): 
        """make sure things work if the first result line is an error"""
        RaceClass.objects.all().delete()
        Session.objects.all().delete()

        response = self.base_upload_results()

        self.assertEqual(json.loads(response.content), 
                         {'results_file': 'Your results for CHRIS BRUBAKER included an unknown race class: STS'})

        runs = Run.objects.all()
        self.assertEqual(len(runs), 0)

        results = Result.objects.all()
        self.assertEqual(len(results), 0)

        sessions = Session.objects.all()
        self.assertEqual(len(sessions), 0)

    def test_upload_with_error2(self): 
        """make sure things work if the second result line is an error"""
        RaceClass.objects.exclude(abrv='STS').delete()
        Session.objects.all().delete()

        response = self.base_upload_results()

        self.assertEqual(json.loads(response.content),
                         {u'result_file': u'Your Reults for CHRIS MCPHERSON included a unknown entry, R in the Class column'})

        runs = Run.objects.all()
        self.assertEqual(len(runs), 0)

        results = Result.objects.all()
        self.assertEqual(len(results), 0)

        sessions = Session.objects.all()
        self.assertEqual(len(sessions), 0)    

    def test_upload_clean(self): 
        Session.objects.all().delete()

        response = self.base_upload_results()

        self.assertEqual(response.status_code, 200)

        runs = Run.objects.all()
        self.assertEqual(len(runs), 17)

        results = Result.objects.all()
        self.assertEqual(len(results), 2)

        sessions = Session.objects.all()
        self.assertEqual(len(sessions), 1)    
class TestOrder(unittest.TestCase): 
    
    def tearDown(self): 
        clear_db()
            
    def setUp(self): 
        self.c = Club()
        self.c.name = "test club"
        self.c.full_clean()
        self.c.save()
        
        self.season = Season()
        self.season.club = self.c
        self.season.year = 2011
        self.season.save()
        
        self.race_class = RaceClass()
        self.race_class.name = "CSP"
        self.race_class.pax = .875
        self.race_class.club = self.c
        self.race_class.save()
        
        self.e = Event()
        self.e.name = "test event"
        self.e.date = datetime.date.today()
        self.e.season = self.season
        self.e.club = self.c
        self.e.save()        
        
        self.user = User()
        self.user.first_name = "justin"
        self.user.last_name = "gray"
        self.user.username = "******"
        self.user.save()
        
        self.user2 = User()
        self.user2.first_name = "sirius"
        self.user2.last_name = "gray"
        self.user2.username = "******"
        self.user2.save()
    
    def test_total_price(self): 
        self.o = Order()
        self.o.user_prof = self.user.get_profile()
        self.o.save()        
        
        item1 = Registration()
        item1.number = 11
        item1.race_class = self.race_class
        item1.pax_class = None
        item1.event = self.e
        item1.price = "40.00"
        item1.order = self.o
        item1.club = self.c
        item1.save()
        
        item2 = Membership()
        item2.user_prof = self.user.get_profile()
        item2.club = self.c
        item2.num = 1
        item2.start = datetime.date.today() - datetime.timedelta(days=300)
        item2.valid_thru = datetime.date.today()+datetime.timedelta(days=1)
        item2.price = "60.00"
        item2.order = self.o
        item2.save()
        
        self.o.calc_total_price()
        self.assertEqual(self.o.total_price, "100.00")

        club = Club()
        club.name ="test-test"
        club.save()
        
        c = Coupon()
        c.discount_amount = "10.00"
        c.permanent = True
        c.code = "aaa"
        c.expires = datetime.date.today() + datetime.timedelta(days=1)
        c.club = club
        c.save()
        
        self.o.coupon = c
        self.o.calc_total_price()
        self.assertEqual(self.o.total_price, '90.00')        
Exemple #16
0
class TestPostForms(ResourceTestCase): 

    def setUp(self): 
        super(TestPostForms, self).setUp()

        self.c = Club()
        self.c.name = "test club"
        self.c.full_clean()
        self.c.save()
        
        self.season = Season()
        self.season.club = self.c
        self.season.year = 2011
        self.season.save()
        
        self.race_class = RaceClass()
        self.race_class.name = "CSP"
        self.race_class.abrv = "CSP"
        self.race_class.pax = .875
        self.race_class.club = self.c
        self.race_class.save()
        
        self.e = Event()
        self.e.name = "test event"
        self.e.date = datetime.date.today()
        self.e.season = self.season
        self.e.club = self.c
        self.e.save()
        
        self.user = User()
        self.user.first_name = "Justin"
        self.user.last_name = "Gray"
        self.user.username = "******"
        self.user.save()

        self.c.group.user_set.add(self.user)
        self.c.save()

        self.user.set_password("test")
        self.user.save()
          
        
        self.r = Registration()
        self.r.number = 11
        self.r.race_class = self.race_class
        self.r.pax_class = None
        self.r.club = self.c
        self.r.event = self.e

    def get_credentials(self):
        resp = self.api_client.client.login(username='******',
                                              password='******')
        return resp

    def test_assoc_reg_user(self): 

        self.r.save()


        data = {"username": "******",}

        self.get_credentials()
        
        resp = self.api_client.client.post('/garage/reg/%s/driver'%self.r.pk, data)    

        self.assertValidJSONResponse(resp)
        post_data = self.deserialize(resp)

        resp = self.api_client.get('/garage/api/v1/registration/%d/'%self.r.pk)
        self.assertValidJSONResponse(resp)

        get_data = self.deserialize(resp)

        self.assertEqual(post_data,get_data)
class TestDibs(unittest.TestCase): 
    
    def setUp(self): 
        
        self.today = datetime.date.today()
        
        self.c = Club()
        self.c.name = "test"
        self.c.events_for_dibs = 2
        self.c.save()
        
        self.race_class = RaceClass()
        self.race_class.name = "CSP"
        self.race_class.pax = .875
        self.race_class.club = self.c
        self.race_class.save()
        
        self.s = Season()
        self.s.year = 2011
        self.s.club = self.c
        self.s.save()
        
        self.e1 = Event()
        self.e1.name = "event1"
        self.e1.date = self.today-datetime.timedelta(days=10)
        self.e1.season = self.s
        self.e1.club = self.c
        self.e1.save()
        
        self.e2 = Event()
        self.e2.name = "event2"
        self.e2.date = self.today-datetime.timedelta(days=8)
        self.e2.season = self.s
        self.e2.club = self.c
        self.e2.save()
        
        self.e3 = Event()
        self.e3.name = "event3"
        self.e3.date = self.today-datetime.timedelta(days=5)
        self.e3.season = self.s
        self.e3.club = self.c
        self.e3.save()
        
        self.e4 = Event()
        self.e4.name = "event4"
        self.e4.date = self.today+datetime.timedelta(days=10)
        self.e4.season = self.s
        self.e4.club = self.c
        self.e4.save()
        
        self.events = [self.e1, self.e2, self.e3]       
        
        for event in self.events: 
            s = Session()
            s.event = event
            s.name = "AM"
            s.club = self.c
            s.save()
        
        self.u1 = User()
        self.u1.username = "******"
        self.u1.save()
        
        self.u2 = User()
        self.u2.username = "******"
        self.u2.save()
        
        self.u3 = User()
        self.u3.username = "******"
        self.u3.save()
        
        self.users = [self.u1, self.u2, self.u3]
        
        for i, user in enumerate(self.users): 
            up = user.get_profile()
            for j, event in enumerate(self.events): 
                if j<=i: 
                    r = Registration()
                    r.number = "%d"%(i+1)
                    r.race_class = self.race_class
                    r.pax_class = None
                    r.event = event    
                    r.user_profile = up
                    r.club = self.c
                    r.save()
                    
                    result = Result()
                    result.reg = r
                    result.session = event.sessions.all()[0]
                    result.club = self.c
                    result.save()
                    
                    for k in range(0, 3):
                        r = Run()
                        r.base_time = 10.0
                        r.calc_time = 10.0
                        r.index_time = 10.0
                        r.result = result
                        r.club = self.c
                        r.save()
   
    def tearDown(self): 
        self.u3.delete()
        self.u2.delete()
        self.u1.delete()
        self.s.delete()
        self.c.delete()
        
    def test_1_dibs(self): 
        
        self.c.assign_dibs()
        
        self.assertEqual(len(self.c.dibs.filter(club=self.c, user_profile=self.u3.get_profile()).all()), 1) 
        dibs = Dibs.objects.filter(club=self.c, user_profile=self.u3.get_profile()).get()
        self.assertEqual(dibs.number, 3)
        self.assertEqual(dibs.race_class, self.race_class)
        self.assertEqual(dibs.expires, self.e4.date+datetime.timedelta(days=30))
        
        Dibs.objects.all().delete()
        
    def test_no_dibs(self): 
        reg = Registration()
        up = UserProfile.objects.get(user=self.u1)
        reg.user_profile = up
        reg.number = 15
        reg.race_class = self.race_class
        reg.pax_class = None
        reg.event = self.e4
        reg.club = self.c
        reg.save()   
        
        s = Session()
        s.event = self.e4
        s.name = "AM"
        s.club = self.c
        s.save()
        
        result = Result()
        result.reg = reg
        result.session = s
        result.club = self.c
        result.save()
        
        for k in range(0, 3):
            r = Run()
            r.base_time = 10.0
            r.calc_time = 10.0
            r.index_time = 10.0
            r.result = result
            r.club = self.c
            r.save()        
        
        self.c.assign_dibs()
        self.assertEqual(len(Dibs.objects.all()), 0) 
                        
        reg.delete()
        s.delete()
        
    def test_no_result_reg_dibs(self): 
        reg = Registration()
        up = UserProfile.objects.get(user=self.u2)
        reg.user_profile = up
        reg.number = 15
        reg.race_class = self.race_class
        reg.pax_class = None
        reg.event = self.e3
        reg.club = self.c
        reg.save() 
        
        self.c.assign_dibs()
        
        self.assertEqual(len(self.c.dibs.filter(club=self.c, user_profile=self.u3.get_profile()).all()), 1) 
        dibs = Dibs.objects.filter(club=self.c, user_profile=self.u3.get_profile).get()
        self.assertEqual(dibs.number, 3)
        self.assertEqual(dibs.race_class, self.race_class)
        self.assertEqual(dibs.expires, self.e4.date+datetime.timedelta(days=30))
        
        reg.delete()
        Dibs.objects.all().delete()
        
    def test_update_existing_dibs(self):
        
        dibs = Dibs()
        dibs.club = self.c
        dibs.user_profile = self.u3.get_profile()
        dibs.race_class = self.race_class
        dibs.number = 3
        dibs.duration = 30
        dibs.expires = self.today+datetime.timedelta(days=5)
        dibs.save()
        dibs.created = self.today-datetime.timedelta(days=60)
        dibs.save()
        
        self.c.assign_dibs()       
        self.assertEqual(len(self.c.dibs.filter(club=self.c, user_profile=self.u3.get_profile()).all()), 1) 
        dibs = Dibs.objects.filter(club=self.c, user_profile=self.u3.get_profile()).get()
        self.assertEqual(dibs.duration, 60)
        self.assertEqual(dibs.expires, self.e3.date+datetime.timedelta(days=60))
        
        dibs.delete()
        
    def test_dont_update_old_dibs(self): 
        
        dibs = Dibs()
        dibs.club = self.c
        dibs.user_profile = self.u1.get_profile()
        dibs.race_class = self.race_class
        dibs.number = 3
        dibs.duration = 30
        dibs.expires = self.today-datetime.timedelta(days=5)
        dibs.save()
        dibs.created = self.today-datetime.timedelta(days=60)
        dibs.save()
        
        self.c.assign_dibs()  
        
        dibs = Dibs.objects.filter(user_profile=self.u1.get_profile()).get()
        
        self.assertEqual(dibs.expires, self.today-datetime.timedelta(days=5))
        self.assertEqual(dibs.duration, 30)
        
    def test_race_class_allow_dibs(self): 
        
        self.race_class.allow_dibs = False
        self.race_class.save()
        
        self.c.assign_dibs()
        
        self.assertEqual(len(Dibs.objects.all()), 0)
        
    def test_clean_dibs(self): 
        
        dibs = Dibs()
        dibs.club = self.c
        dibs.expires = datetime.date.today()-datetime.timedelta(days=10)
        dibs.duration = 30
        dibs.number = 99
        dibs.race_class = self.race_class
        dibs.user_profile = self.u2.get_profile()
        
        dibs.save()

        clean_dibs()
        
        self.assertEqual(len(self.c.dibs.filter(club=self.c, user_profile=self.u3.get_profile()).all()), 1) 
        dibs = Dibs.objects.filter(club=self.c, user_profile=self.u3.get_profile()).get()
        self.assertEqual(dibs.number, 3)
        self.assertEqual(dibs.race_class, self.race_class)
        self.assertEqual(dibs.expires, self.e4.date+datetime.timedelta(days=30))
        
        self.assertEqual(len(self.c.dibs.filter(club=self.c, user_profile=self.u2.get_profile()).all()), 0) 
class TestEvent(unittest.TestCase): 
    
    def setUp(self): 
        self.c = Club()
        self.c.name = "test"
        self.c.save()
        
        self.s = Season()
        self.s.year = 2011
        self.s.club = self.c
        self.s.save()
        
        self.e = Event()
        self.e.name = "test event"
        self.e.date = datetime.date.today()
        self.e.season = self.s
        self.e.club = self.c
        
    def tearDown(self): 
        clear_db()
               
        
    def testEventSafeName(self): 
        pass
    
    def testEventisRegd(self): 
        
        self.e.save()
        
        u = User()
        u.first_name = "Justin" 
        u.last_name = "Gray"
        u.username = "******"
        
        u.save()
        
        rc = RaceClass()
        rc.abrv = "CSP"
        rc.name = "CSP"
        rc.pax = 1
        rc.club = self.c
        rc.save()
                
        self.assertFalse(self.e.is_regd(u))        
        
        r = Registration()
        r.event = self.e
        r.number = 11
        r.race_class = rc
        r.user_profile = u.get_profile()
        r.club = self.c
        r.save()
        
        self.assertTrue(self.e.is_regd(u))
    
    def testValidRegClose(self): 
        
        try: 
            self.e.reg_close = datetime.datetime.today()+datetime.timedelta(days=1)
            self.e.full_clean()
        except ValidationError as err: 
            self.assertEqual("{'__all__': [u'Registration must close before the date of the event.']}", str(err))
        else: 
            self.fail("ValidationError expected")     
                
    def test_event_reg_limit(self): 
        self.e.save()
        self.sess = Session()
        self.sess.name = "AM"
        self.sess.event = self.e
        self.sess.club = self.c
        self.sess.save()
                
        self.race_class = RaceClass()
        self.race_class.name = "A"
        self.race_class.pax = 1
        self.race_class.club = self.c
        self.race_class.save()        
        
        self.e.reg_limit = 3
        self.e.save()
        
        for i in range(0, 4): 
            try: 
                self.r = Registration()
                self.r.number = i
                self.r.race_class = self.race_class
                self.r._anon_f_name = "random_%d"%(i,)
                self.r.pax_class = None
                self.r.event = self.e
                self.r.club = self.c
                self.r.save()
                
            except ValidationError as err: #don't error untill the limit is reached  
                self.assertEqual(i, 3)
            else: 
                self.assertLess(i, 3)
class TestResult(unittest.TestCase):
    def setUp(self):

        self.c = Club()
        self.c.name = "test club"
        self.c.save()

        self.season = Season()
        self.season.club = self.c
        self.season.year = 2011
        self.season.save()

        self.race_class = RaceClass()
        self.race_class.name = "CSP"
        self.race_class.pax = 0.875
        self.race_class.club = self.c
        self.race_class.save()

        self.e = Event()
        self.e.name = "test event"
        self.e.date = datetime.date.today()
        self.e.season = self.season
        self.e.club = self.c
        self.e.save()

        self.sess = Session()
        self.sess.name = "AM"
        self.sess.event = self.e
        self.sess.club = self.c
        self.sess.save()

        self.r = Registration()
        self.r.number = 11
        self.r.race_class = self.race_class
        self.r.pax_class = None
        self.r.event = self.e
        self.r.club = self.c
        self.r.save()

        self.result = Result()
        self.result.reg = self.r
        self.result.session = self.sess
        self.result.club = self.c
        self.result.save()

    def tearDown(self):

        Club.objects.all().delete()
        Season.objects.all().delete()
        RaceClass.objects.all().delete()
        Event.objects.all().delete()
        Session.objects.all().delete()
        Registration.objects.all().delete()
        Result.objects.all().delete()
        Run.objects.all().delete()

    def test_best_run1(self):

        r1 = Run()
        r1.base_time = 10.0
        r1.result = self.result
        r1.club = self.c
        r1.save()

        r2 = Run()
        r2.base_time = 11.0
        r2.result = self.result
        r2.club = self.c
        r2.save()

        r3 = Run()
        r3.base_time = 9.0
        r3.cones = 1
        r3.result = self.result
        r3.club = self.c
        r3.save()

        r4 = Run()
        r4.base_time = 10.0
        r4.result = self.result
        r4.penalty = "DNF"
        r4.club = self.c
        r4.save()

        best_run = self.result.find_best_run()

        self.assertEqual(best_run, r1)

    def test_best_run2(self):

        r1 = Run()
        r1.base_time = 10.0
        r1.result = self.result
        r1.club = self.c
        r1.save()

        best_run = self.result.find_best_run()

        self.assertEqual(best_run, r1)

    def test_best_run3(self):

        r1 = Run()
        r1.base_time = 10.0
        r1.result = self.result
        r1.club = self.c
        r1.save()

        r2 = Run()
        r2.base_time = 9.0
        r2.result = self.result
        r2.club = self.c
        r2.save()

        r3 = Run()
        r3.base_time = 10.5
        r3.result = self.result
        r3.club = self.c
        r3.save()

        best_run = self.result.find_best_run()

        self.assertEqual(best_run, r2)

    def test_best_run_no_clean_runs(self):

        r1 = Run()
        r1.base_time = 10.0
        r1.result = self.result
        r1.penalty = "DNF"
        r1.club = self.c
        r1.save()

        r2 = Run()
        r2.base_time = 0.1
        r2.result = self.result
        r2.penalty = "O/C"
        r2.club = self.c
        r2.save()

        best_run = self.result.find_best_run()

        self.assertEqual(best_run, None)
    def handle(self, *args, **options):
        clear_db()

        s = Site.objects.all()[0]
        s.domain = "dev.racerslane.com"
        s.name = "Racerslane.com"
        s.save()

        print "Loading users"
        reader = csv.DictReader(open('old_data/driver.csv', 'rU'))
        for line in reader:
            """user_name","email","verified","activation_code",
            "f_name","l_name","address","city","state",
            "zip_code","_password"""
            for k, v in line.iteritems():
                if v == "NULL":
                    line[k] = None

            u = User()
            u.username = line['user_name']
            u.email = line['email']
            u.password = "******" % line['_password']
            u.first_name = line['f_name']
            u.last_name = line['l_name']
            u.is_active = True
            u.save()

            up = u.get_profile()
            up.address = line['address']
            up.city = line['city']
            up.state = line['state']
            up.zip_code = line['zip_code']
            up.save()
            db.reset_queries()

        #dev to make it so I can login to any account
        justin = User.objects.get(username="******")
        password = justin.password

        #User.objects.all().update(password=password)

        print "Loading Cars"
        car_map = {}
        reader = csv.DictReader(open('old_data/car.csv', 'rb'))
        for line in reader:
            """id","nickname","make","model","color","avatar_file_loc",
            "avatar_thumb_loc","year","owner_user_name"""
            for k, v in line.iteritems():
                if v == "NULL":
                    line[k] = None
            if line['owner_user_name']:
                try:
                    c = Car()
                    c.provisional = False
                    c.name = line['nickname']
                    c.make = line['make']
                    c.model = line['model']
                    if line['color']:
                        c.color = line['color']
                    c.year = line['year']
                    c.user_profile = User.objects.get(
                        username=line['owner_user_name']).get_profile()
                    s_car_id = (line['owner_user_name'], line['nickname'])
                    if exists('old_data/avatars/%s_%s_avatar' % s_car_id):
                        c.avatar.save(
                            '%s_%s_avatar' % s_car_id,
                            File(
                                open('old_data/avatars/%s_%s_avatar' %
                                     s_car_id)))
                        c.thumb.save(
                            '%s_%s_thumb' % s_car_id,
                            File(
                                open('old_data/avatars/%s_%s_thumb' %
                                     s_car_id)))
                    c.save()
                    db.reset_queries()
                    car_map[line['id']] = c.pk
                except:
                    continue

        print "Loading Clubs"
        #read in clubs
        club_map = {}
        for line in csv.DictReader(open('old_data/club.csv', 'rU')):
            """"name","web_link","process_payments","points_calc_type",
            "membership_cost","renewal_cost","membership_terms","paypal_email",
            "index_point_method","address","city","state","zip_code","""
            for k, v in line.iteritems():
                if v == "NULL":
                    line[k] = None
            c = Club()
            c.city = line['city']
            c.address = line['address']
            c.zip_code = line['zip_code']
            c.state = line['state']
            c.name = line['name']
            c.process_payments = line['process_payments']
            c.paypal_email = line['paypal_email']
            c.membership_terms = line['membership_terms']
            c.new_member_cost = line['membership_cost']
            c.renew_cost = line['renewal_cost']

            c.save()

            club_map[line['name']] = c
            db.reset_queries()

        print "loading coupons"
        for line in csv.DictReader(open('old_data/coupon.csv')):
            """coupon_code","club_name","discount_amount","uses_left","expires",
            "permanent","driver_user_name","registration_id"""
            for k, v in line.iteritems():
                if v == "NULL":
                    line[k] = None

            c = Coupon()
            c.code = line['coupon_code']
            c.permanent = bool(line['permanent'])
            c.club = club_map[line['club_name']]
            c.uses_left = line['uses_left']
            c.discount_amount = line['discount_amount']
            if line['expires']:
                c.expires = datetime.datetime.strptime(line['expires'],
                                                       '%Y-%m-%d %H:%M:%S')
            if line['driver_user_name']:
                c.user_prof = User.objects.get(
                    username=line['driver_user_name']).get_profile()
            c.save()
            db.reset_queries()

        print "loading memberships"
        reader = csv.DictReader(open('old_data/membership.csv', 'rb'))
        for line in reader:
            """"id","club_name","number","start_date","valid_thru_date",
            "price","paid","token","payer_id","transaction_id","anon_f_name",
            "anon_l_name","driver_user_name"""

            for k, v in line.iteritems():
                if v == "NULL":
                    line[k] = None

            m = Membership()
            m.num = line['number']

            m.start = datetime.datetime.strptime(line['start_date'],
                                                 '%Y-%m-%d %H:%M:%S')
            m.valid_thru = datetime.datetime.strptime(line['valid_thru_date'],
                                                      '%Y-%m-%d %H:%M:%S')
            m.paid = bool(line['paid'])
            if line['price'] != None:
                m.price = float(line['price'])

            try:
                m.user_prof = User.objects.get(
                    username=line['driver_user_name']).get_profile()
            except User.DoesNotExist:
                continue
            m.club = club_map[line['club_name']]

            m._anon_f_name = line['anon_f_name']
            m._anon_l_name = line['anon_l_name']

            m.save()
            db.reset_queries()

        print "loading locations"
        location_map = {}
        for line in csv.DictReader(open("old_data/location.csv")):
            """id","name","address","lat","lng","club_name"""
            for k, v in line.iteritems():
                if v == "NULL":
                    line[k] = None
            club = Club.objects.get(name=line['club_name'])

            l = Location()
            l.name = line['name']
            l.address = line['address']
            #l.lat = line['lat']
            #l.lon = line['lng']
            l.club = club

            l.save()

            location_map[line['id']] = l
            db.reset_queries()

        print "loading seasons"
        season_map = {}
        for line in csv.DictReader(open('old_data/season.csv')):
            s = Season()
            """"id","year","active","club_name","drop_lowest_events"""
            for k, v in line.iteritems():
                if v == "NULL":
                    line[k] = None
            club = Club.objects.get(name=line['club_name'])
            s.club = club
            s.year = int(line['year'])
            s.drop_lowest_events = int(line['drop_lowest_events'])
            s.save()

            season_map[line['id']] = s
            db.reset_queries()

        print "loading events"
        event_map = {}
        for line in csv.DictReader(open('old_data/event.csv', 'rU')):
            """id","name","note","date","registration_close","member_cost",
            "non_member_cost","pay_at_event_cost","location_id","club_name",
            "season_id","multiplier","count_points"""
            for k, v in line.iteritems():
                if v == "NULL":
                    line[k] = None

            e = Event()
            e.name = line['name']
            e.note = line['note']
            e.date = datetime.datetime.strptime(line['date'],
                                                '%Y-%m-%d %H:%M:%S')
            e.reg_close = line['registration_close'] + "-05:00"
            e.member_price = float(line['member_cost'])
            e.non_member_price = float(line['non_member_cost'])
            e.non_pre_pay_penalty = float(line['pay_at_event_cost'])
            e.season = season_map[line['season_id']]
            e.club = e.season.club
            e.count_points = int(line['count_points'])
            e.multiplier = int(line['multiplier'])

            if line['location_id']:
                e.location = location_map[line['location_id']]

            e.save()

            event_map[line['id']] = e
            db.reset_queries()

        print "loading race_classes"
        race_class_map = {}
        for line in csv.DictReader(open('old_data/raceclass.csv')):
            """id","pax","name","club_name"""
            for k, v in line.iteritems():
                if v == "NULL":
                    line[k] = None

            club = Club.objects.get(name=line['club_name'])
            r = RaceClass()
            r.name = line['name']
            r.abrv = line['name']
            r.pax = float(line['pax'])
            r.club = club
            r.save()
            db.reset_queries()

            race_class_map[line['id']] = r

        index_class = RaceClass()
        index_class.name = 'Index'
        index_class.bump_class = True
        index_class.abrv = "i"
        index_class.pax = 1.0
        index_class.club = club
        index_class.save()

        print "loading reg_types"
        reg_type_map = {}
        for line in csv.DictReader(open('old_data/regtype.csv')):
            """id","name","class_letters","reg_limit","index",
            "description","club_name"""
            for k, v in line.iteritems():
                if v == "NULL":
                    line[k] = None
            club = Club.objects.get(name=line['club_name'])
            r = RaceClass()
            r.pax_class = True
            r.description = line['description']
            r.name = line['name']
            r.abrv = line['class_letters']
            if line['reg_limit']:
                r.user_reg_limit = line['reg_limit']
            r.pax = 1.0
            r.club = club
            r.save()

            reg_type_map[line['id']] = r
            db.reset_queries()

        print "loading registrations"
        registration_map = {}
        for line in csv.DictReader(open('old_data/registration.csv')):
            """id","number","paid","token","payer_id","transaction_id",
            "price","class_points","index_points","index_flag","anon_f_name",
            "anon_l_name","anon_car","driver_user_name","event_id","reg_type_id",
            "car_id","race_class_id"""

            for k, v in line.iteritems():
                if v == "NULL":
                    line[k] = None

            if not line['event_id']:
                continue

            rc = race_class_map[line['race_class_id']]

            r = Registration()

            r.paid = bool(line['paid'])
            if line['price'] != None:
                r.price = float(line['price'])

            if line['driver_user_name']:
                user = User.objects.get(username=line['driver_user_name'])
                r.user_profile = user.get_profile()
            r.number = int(line['number'])
            r.paid = int(line['paid'])
            r.index_points = line['index_points']
            r.class_points = line['class_points']
            if line['price']:
                r.price = float(line['price'])
            else:
                r.price = 0.00
            r.index_points = int(line['index_points'])
            r.class_points = int(line['class_points'])
            if line['anon_car']:
                r._anon_car = line['anon_car'].strip()
            if line['anon_l_name']:
                r._anon_l_name = line['anon_l_name'].strip()
            if line['anon_f_name']:
                r._anon_f_name = line['anon_f_name'].strip()
            r.race_class = rc
            r.event = event_map[line['event_id']]
            r.club = r.event.club
            try:
                if line['reg_type_id']:
                    r.pax_class = reg_type_map[line['reg_type_id']]
            except:
                pass

            if line['index_flag']:
                r.bump_class = index_class
            try:
                if line['car_id']:
                    r.car = Car.objects.get(pk=car_map[line['car_id']])
            except:
                pass
            #TODO race_class_id
            #TODO remove reg_detail class, and associate reg with UserProfile directly
            #TODO registrations can be siblings for joint update

            try:
                r.save()
            except:
                r.number += 100
                try:
                    r.save()
                except:
                    continue

            registration_map[line['id']] = r.pk
            db.reset_queries()

        print "loading sessions"
        session_map = {}
        for line in csv.DictReader(open('old_data/session.csv')):
            """id", "name", "event_id", "course_id"""
            for k, v in line.iteritems():
                if v == "NULL":
                    line[k] = None

            try:
                event_map[line['event_id']]
            except:
                continue

            s = Session()
            s.name = line['name']
            s.event = event_map[line['event_id']]
            s.club = s.event.club
            s.save()

            session_map[line['id']] = s
            db.reset_queries()

        print "loading results"
        result_map = {}
        for line in csv.DictReader(open('old_data/result.csv')):
            """id","registration_id","event_id","sess_id"""
            for k, v in line.iteritems():
                if v == "NULL":
                    line[k] = None

            try:
                registration_map[line['registration_id']]
                session_map[line['sess_id']]
            except:
                continue

            r = Result()
            reg = Registration.objects.get(
                pk=registration_map[line['registration_id']])
            r.reg = reg

            r.session = session_map[line['sess_id']]
            r.club = r.session.club
            try:
                r.save()
            except Exception as err:
                print registration_map[line['registration_id']].pk
                print str(err)
                print registration_map[line['registration_id']]

            result_map[line['id']] = r.id
            db.reset_queries()

        print "loading runs"
        for line in csv.DictReader(open('old_data/run.csv')):
            """id","base_time","calc_time","index_time","cones",
            "penalty","result_id","result_2_id"""
            for k, v in line.iteritems():
                if v == "NULL":
                    line[k] = None

            if line['base_time'] == None:
                continue
            try:
                r = Run()
                r.base_time = float(line['base_time'])
                r.cones = int(line['cones'])
                if line['penalty']:
                    r.penalty = line['penalty']
                result = Result.objects.get(pk=result_map[line['result_id']])
                r.result = result
                r.club = r.result.club
                r.save()
                db.reset_queries()
            except KeyError:
                continue

        print "calculating reg times"
        for reg in Registration.objects.select_related(
                'results').all().iterator():
            reg.calc_times()

        #House keeping
        nora = Club.objects.get(safe_name='noraascc')
        user = User.objects.get(username="******")
        nora.group.user_set.add(user)