def save(self, validated_data): email = validated_data.get('email') new_user = User( username=email, email=email, is_active=False, ) new_user.save() # Create new salary instance new_salary = Salary(user=new_user) new_salary.save() # Create new adminprofile instance new_adminprofile = AdminProfile(user=new_user) new_adminprofile.save() # Create new company instance and assign admin_profile to new admin_profile, other fields have placeholder values new_company = Company(adminprofile=new_adminprofile) new_company.save() registration = Registration( user=new_user, code_type='RV', profile_type='AP', ) registration.save() email = Email( to=email, subject='Thank you for registering with RazzPay!', content=f'Here is your validation code: {registration.code}') email.save(request=self.context['request']) return new_user
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 signup(request): """ Register the user and log him in """ if request.user.is_authenticated(): return redirect(settings.LOGIN_REDIRECT_URL) if request.method == 'GET': return render_login_page(request, parameters={'signup': 'active'}) if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] email = form.cleaned_data["email"] user = User(username=username, first_name=form.cleaned_data["first_name"], last_name=form.cleaned_data["last_name"], email=email, is_active=False ) user.set_password(password) user.save() registration = Registration(user=user) try: registration.register(request) registration.save() except: print sys.exc_info()[0] user.delete() error = True error_message = ["Unable to Register user"] errors = { 'error': error, 'error_list': True, 'error_message': error_message, 'signup': 'active' } return render_login_page(request, register_form=form, parameters=errors) info = { 'info': True, 'info_message': 'Successfully registered. \ Check %s and activate your account.' % (email)} return render_login_page(request, parameters=info) else: error = True error_message = [] for key, value in form.errors.iteritems(): error_message.append((', '.join(value))) errors = { 'error': error, 'error_list': True, 'error_message': error_message, 'signup': 'active'} return render_login_page(request, register_form=form, parameters=errors) else: raise Http404
def register_user_for_event(request, event, profile): registration = Registration.objects.filter(user_profile=profile, event=event.id) if len(registration) == 0: registration = Registration() registration.user_profile = profile registration.event = event registration.ip_address = request.META['REMOTE_ADDR'] registration.save() request.session['user_registered'] = "True"
def index(request): print(request.method) if request.method == 'POST': name = request.POST.get('fname') email = request.POST.get('email') m_no = request.POST.get('m_no') print(name, email, m_no) s = Registration(name=name, email=email, m_no=m_no) s.save() # sending data to html return render(request, 'index.html')
def save(self, validated_data): # Obtain user info email = validated_data.get('email') first_name = validated_data.get('first_name') last_name = validated_data.get('last_name') company = self.context['request'].user.company # Obtain salary info gross_month = validated_data.get('gross_month') position = validated_data.get('position') new_user = User( username=email, email=email, first_name=first_name, last_name=last_name, company_id=company.id, # Mark as true so that employee user instance can be used immediately without waiting for employee to register via email code is_active=True, ) new_user.save() # Create new employeeprofile instance new_employeeprofile = EmployeeProfile(user=new_user) new_employeeprofile.save() # Create new salary instance new_salary = Salary(user=new_user, position=position, gross_month=round((gross_month), 2), ahv_amount=round((gross_month * 0.05125), 2), alv_amount=round((gross_month * 0.011), 2), pension=round((gross_month * 0.01), 2), net=round( (gross_month - (gross_month * 0.05125) - (gross_month * 0.011) - (gross_month * 0.01)), 2)) new_salary.save() registration = Registration( user=new_user, code_type='RV', profile_type='EP', ) registration.save() email = Email( to=email, subject='Welcome to RazzPay!', content=f'Here is your validation code: {registration.code}') email.save(request=self.context['request']) return new_user
def create(self, validated_data): email = validated_data['email'] new_user = User(email=email, username=email, is_active=False) new_user.save() registration = Registration(user=new_user) registration.save() send_mail( 'Luna Validation code', f'Hello, Please use the following validation code: {registration.code} to continue your' ' registration at http://luna-sagittarius.propulsion-learn.ch .', '*****@*****.**', [new_user.email], fail_silently=False, ) return Response(status=201)
def post(self, request, *args, **kwargs): email = request.data.get('email') new_user = User(username=email, email=email, is_active=False) new_user.save() new_user_profile = UserProfile(user=new_user) new_user_profile.save() registration = Registration(user=new_user_profile) registration.save() send_mail( 'Verification code', f'Please confirm the verification code {registration.code}', '*****@*****.**', [email], fail_silently=False, ) return Response(status=200)
def post(self, request, *args, **kwargs): # Converts the text payload into a python dictionary incoming_message = json.loads(self.request.body.decode('utf-8')) # Facebook recommends going through every entry since they might send # multiple messages in a single call during high load tomorows_date = datetime.date.today() + datetime.timedelta(days=1) for entry in incoming_message['entry']: for message in entry['messaging']: # Check to make sure the received call is a message call # This might be delivery, optin, postback for other events if 'message' in message: # Print the message to the terminal #laikas = message['message']['nlp']['entities']['laikas'] diena = message['message']['nlp']['entities']['diena'] tikrai_diena = diena[0]['confidence'] pprint(tikrai_diena) #tikrai_laikas = laikas[0]['confidence'] #pprint(tikrai_laikas) # Assuming the sender only sends text. Non-text messages like stickers, audio, pictures # are sent as attachments and must be handled accordingly. if tikrai_diena >= 0.75: if diena[0]['value'] == 'siandien' or diena[0][ 'value'] == 'siandiena': post_facebook_message(message['sender']['id'], time.strftime("%Y-%m-%d")) p = Registration( name='n***a', surname='penis', registration_date=time.strftime("%Y-%m-%d"), registration_time='12:00') p.save() elif diena[0]['value'] == 'rytoj': post_facebook_message( message['sender']['id'], tomorows_date.strftime("%Y-%m-%d")) else: post_facebook_message(message['sender']['id'], 'neatpazistu') #elif tikrai_laikas >= 0.95: #post_facebook_message(message['sender']['id'], laikas[0]['value']) else: print('nay') post_facebook_message(message['sender']['id'], 'Tai ne diena') return HttpResponse()
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')
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')
def save(request): if request.method == 'POST': feed = Registration() print(request.POST.get('status')) if request.POST.get('title') and request.POST.get( 'email') and request.POST.get('password'): feed.title = request.POST.get('title') feed.email = request.POST.get('email') feed.description = request.POST.get('description') feed.password = make_password(request.POST.get('password')) feed.status = request.POST.get('status') feed.time = request.POST.get('time') feed.save() messages.success(request, 'To-do created successfully') args = {'message': messages} return render(request, 'create.html', args)
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_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 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 parse_axtime(event, session, results_file): """Expects a Session object and a file object with and iterates through to return either a list of result instances, or a dictionary containing error messages""" validate_error = {} results = [] club = session.club reader = csv.reader(results_file) header = reader.next() header_check = [ 'First', 'Last', 'Reg', 'Class', 'Num', 'Vehicle', 'Pax_Cls', 'Color', "Notes", "Heat" ] if not all([h in header for h in header_check]): validate_error['results_file'] = "your file was missing some columns" return validate_error time_keys = [k for k in header if 'Run' in k] cone_keys = [k for k in header if 'Pyl' in k] pen_keys = [k for k in header if 'Pen' in k] if not all([time_keys, cone_keys, pen_keys]): validate_error[ 'result_file'] = "your file was missing some run results columns" return validate_error keys = header_check + time_keys + cone_keys + pen_keys for line in reader: result = Result() result.session = session result.club = session.club data = dict(zip(header, line)) reg_id = data['Notes'] #find the group class and raceclass: if data['Class'] == data['Pax_Cls']: group = None else: try: group = RaceClass.objects.get(abrv=data['Class'], club=club) except RaceClass.DoesNotExist: validate_error[ 'result_file'] = 'Your Reults for %s %s included a unknown entry, %s in the Class column' % ( data['First'], data['Last'], data['Class']) return validate_error try: race_class = RaceClass.objects.get(abrv=data['Pax_Cls'], club=club) except RaceClass.DoesNotExist: if not data['Pax_Cls']: validate_error[ 'results_file'] = "Your results for %s %s included an blank race class" % ( data['First'], data['Last']) else: validate_error[ 'results_file'] = "Your results for %s %s included an unknown race class: %s" % ( data['First'], data['Last'], data['Pax_Cls']) return validate_error car_data = data['Vehicle'].split() if len(car_data) == 3 and int_check.match(car_data[0]): data['Vehicle_year'] = car_data[0] data['Vehicle_make'] = car_data[1] data['Vehicle_model'] = car_data[2] elif len(car_data) == 2: data['Vehicle_year'] = None data['Vehicle_make'] = car_data[0] data['Vehicle_model'] = car_data[1] else: data['Vehicle_year'] = None data['Vehicle_make'] = None data['Vehicle_model'] = data['Vehicle'] #try REALLY hard to find the registration that maps to this driver try: user = User.objects.filter(username__icontains=data['Mem_Num'], first_name__icontains=data['First'], last_name__icontains=data['Last'])[0] except IndexError: #coudn't find one user = None if user: try: reg = Registration.objects.get( event=event, user_profile__user__username=user.username) if reg.race_class != race_class: reg.race_class = race_class except Registration.DoesNotExist: reg = Registration() reg.user_profile = user.get_profile() reg.number = int(data['Num']) reg.race_class = race_class reg.pax_class = group reg._anon_car = data['Vehicle'] reg.event = event reg.club = club #not sure how this could happen at all... #except Registration.MultipleObjectsReturned: # reg = session.query(model.Registration).join(model.Driver).join(model.Event).\ # filter(model.Event.id==c.event.id).filter(model.Driver.user_name==driver.user_name).all() # for r in reg: # session.delete(r) # # reg = model.Registration() # reg.driver = driver # reg.number = int(data['Num']) # reg.race_class = race_class # reg.anon_car = unicode(data['Vehicle']) # reg.event = c.event else: #try to find a previous anon_reg try: reg = Registration.objects.get(event=event, _anon_f_name=data['First'], _anon_l_name=data['Last']) except Registration.DoesNotExist: reg = Registration() reg.number = int(data['Num']) reg.race_class = race_class reg.pax_class = group reg._anon_f_name = data['First'] reg._anon_l_name = data['Last'] reg._anon_car = data['Vehicle'] reg.event = event reg.club = club try: reg.save() except: validate_error[ 'results_file'] = "%s %s has a duplicate class/number: %d %s" % ( reg.first_name, reg.last_name, reg.number, reg.race_class) return validate_error try: reg.number = int(data['Num']) except Exception: validate_error[ 'results_file'] = 'Problem with car number for entry: %s %s' % ( reg.first_name, reg.last_name) return validate_error result.reg = reg result.save() for r_key, c_key, p_key in zip(time_keys, cone_keys, pen_keys): run = Run() run.result = result run.club = club try: if float(data[r_key]) <= 0.0: continue except ValueError: continue run.base_time = float(data[r_key]) run.cones = int(data[c_key]) if data[p_key].strip(): run.penalty = data[p_key] run.save() #note: not sure why this has to be done here try: reg.save() except Exception: validate_error[ 'results_file'] = "%s %s has a duplicate class/number: %d %s" % ( reg.first_name, reg.last_name, reg.number, reg.race_class) return validate_error results.append(result) return results
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)
def parse_axtime(event, session, results_file): """Expects a Session object and a file object with and iterates through to return either a list of result instances, or a dictionary containing error messages""" validate_error = {} results = [] club = session.club reader = csv.reader(results_file) header = reader.next() header_check = ["First", "Last", "Reg", "Class", "Num", "Vehicle", "Pax_Cls", "Color", "Notes", "Heat"] if not all([h in header for h in header_check]): validate_error["results_file"] = "your file was missing some columns" return validate_error time_keys = [k for k in header if "Run" in k] cone_keys = [k for k in header if "Pyl" in k] pen_keys = [k for k in header if "Pen" in k] if not all([time_keys, cone_keys, pen_keys]): validate_error["result_file"] = "your file was missing some run results columns" return validate_error keys = header_check + time_keys + cone_keys + pen_keys for line in reader: result = Result() result.session = session result.club = session.club data = dict(zip(header, line)) reg_id = data["Notes"] # find the group class and raceclass: if data["Class"] == data["Pax_Cls"]: group = None else: try: group = RaceClass.objects.get(abrv=data["Class"], club=club) except RaceClass.DoesNotExist: validate_error["result_file"] = ( "Your Reults for %s %s included a unknown entry, %s in the Class column" % (data["First"], data["Last"], data["Class"]) ) return validate_error try: race_class = RaceClass.objects.get(abrv=data["Pax_Cls"], club=club) except RaceClass.DoesNotExist: if not data["Pax_Cls"]: validate_error["results_file"] = "Your results for %s %s included an blank race class" % ( data["First"], data["Last"], ) else: validate_error["results_file"] = "Your results for %s %s included an unknown race class: %s" % ( data["First"], data["Last"], data["Pax_Cls"], ) return validate_error car_data = data["Vehicle"].split() if len(car_data) == 3 and int_check.match(car_data[0]): data["Vehicle_year"] = car_data[0] data["Vehicle_make"] = car_data[1] data["Vehicle_model"] = car_data[2] elif len(car_data) == 2: data["Vehicle_year"] = None data["Vehicle_make"] = car_data[0] data["Vehicle_model"] = car_data[1] else: data["Vehicle_year"] = None data["Vehicle_make"] = None data["Vehicle_model"] = data["Vehicle"] # try REALLY hard to find the registration that maps to this driver try: user = User.objects.filter( username__icontains=data["Mem_Num"], first_name__icontains=data["First"], last_name__icontains=data["Last"], )[0] except IndexError: # coudn't find one user = None if user: try: reg = Registration.objects.get(event=event, user_profile__user__username=user.username) if reg.race_class != race_class: reg.race_class = race_class except Registration.DoesNotExist: reg = Registration() reg.user_profile = user.get_profile() reg.number = int(data["Num"]) reg.race_class = race_class reg.pax_class = group reg._anon_car = data["Vehicle"] reg.event = event reg.club = club # not sure how this could happen at all... # except Registration.MultipleObjectsReturned: # reg = session.query(model.Registration).join(model.Driver).join(model.Event).\ # filter(model.Event.id==c.event.id).filter(model.Driver.user_name==driver.user_name).all() # for r in reg: # session.delete(r) # # reg = model.Registration() # reg.driver = driver # reg.number = int(data['Num']) # reg.race_class = race_class # reg.anon_car = unicode(data['Vehicle']) # reg.event = c.event else: # try to find a previous anon_reg try: reg = Registration.objects.get(event=event, _anon_f_name=data["First"], _anon_l_name=data["Last"]) except Registration.DoesNotExist: reg = Registration() reg.number = int(data["Num"]) reg.race_class = race_class reg.pax_class = group reg._anon_f_name = data["First"] reg._anon_l_name = data["Last"] reg._anon_car = data["Vehicle"] reg.event = event reg.club = club try: reg.save() except: validate_error["results_file"] = "%s %s has a duplicate class/number: %d %s" % ( reg.first_name, reg.last_name, reg.number, reg.race_class, ) return validate_error try: reg.number = int(data["Num"]) except Exception: validate_error["results_file"] = "Problem with car number for entry: %s %s" % ( reg.first_name, reg.last_name, ) return validate_error result.reg = reg result.save() for r_key, c_key, p_key in zip(time_keys, cone_keys, pen_keys): run = Run() run.result = result run.club = club try: if float(data[r_key]) <= 0.0: continue except ValueError: continue run.base_time = float(data[r_key]) run.cones = int(data[c_key]) if data[p_key].strip(): run.penalty = data[p_key] run.save() # note: not sure why this has to be done here try: reg.save() except Exception: validate_error["results_file"] = "%s %s has a duplicate class/number: %d %s" % ( reg.first_name, reg.last_name, reg.number, reg.race_class, ) return validate_error results.append(result) return results
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 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 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 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)
def signup(request): """ Register the user and log him in """ if request.user.is_authenticated(): return redirect(settings.LOGIN_REDIRECT_URL) if request.method == 'GET': return render_login_page(request, parameters={'signup': 'active'}) if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] email = form.cleaned_data["email"] user = User(username=username, first_name=form.cleaned_data["first_name"], last_name=form.cleaned_data["last_name"], email=email, is_active=False) user.set_password(password) user.save() registration = Registration(user=user) try: registration.register(request) registration.save() except: print sys.exc_info()[0] user.delete() error = True error_message = ["Unable to Register user"] errors = { 'error': error, 'error_list': True, 'error_message': error_message, 'signup': 'active' } return render_login_page(request, register_form=form, parameters=errors) info = { 'info': True, 'info_message': 'Successfully registered. \ Check %s and activate your account.' % (email) } return render_login_page(request, parameters=info) else: error = True error_message = [] for key, value in form.errors.iteritems(): error_message.append((', '.join(value))) errors = { 'error': error, 'error_list': True, 'error_message': error_message, 'signup': 'active' } return render_login_page(request, register_form=form, parameters=errors) else: raise Http404
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 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)
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)