def setUp(self): self.ev = Event(name='Test Event', event_date=datetime.date.today()) self.ev.save() self.a = {'invitation': 4, 'pfx': 'Mr', 'first': ' mitchell', 'last': 'stoutin ', 'plusOne': 1, 'orderer': 0, 'event': self.ev, 'status':1} self.b = EventGuest(**self.a) self.b.save()
def create(self, validated_data): guests = [EventGuest(**item) for item in validated_data] self.validate_same_invitation(guests) inviteNumber = EventGuest.nextFreeInvitation( guests[0].event if len(guests) > 0 else None) for guest in guests: guest.invitation = inviteNumber return EventGuest.objects.bulk_create(guests)
def test_nextFreeInvite_incriments(self): ev = Event(name='Test Event', event_date=datetime.date.today()) ev.save() defaults = {'event': ev, 'first': 'FirstName', 'last': 'Last Name'} latest = 0 for x in range(10): guest = EventGuest(invitation=EventGuest.nextFreeInvitation(ev), **defaults) guest.save() self.assertTrue(guest.invitation > latest) latest = guest.invitation
def test_will_update_from_public_fields(self): a = {'invitation': 4, 'pfx': 'Mr', 'first': ' mitchell', 'last': 'stoutin ', 'plusOne': 1, 'orderer': 0} b = EventGuest(event=self.ev, **a) b.save() a['first'] = 'Daylen' a['event'] = self.ev.pk c = GuestPublicSerializer(b, data=a) self.assertTrue(c.is_valid()) c.save() self.assertEqual(b.first, 'Daylen')
def create(self, validated_data): guests = [EventGuest(**item) for item in validated_data] self.validate_same_invitation(guests) inviteNumber = EventGuest.nextFreeInvitation(guests[0].event if len(guests) > 0 else None) for guest in guests: guest.invitation = inviteNumber return EventGuest.objects.bulk_create(guests)
class TestGuestSerializersFromPythonObjects(TestCase): def setUp(self): self.ev = Event(name='Test Event', event_date=datetime.date.today()) self.ev.save() self.a = {'invitation': 4, 'pfx': 'Mr', 'first': ' mitchell', 'last': 'stoutin ', 'plusOne': 1, 'orderer': 0, 'event': self.ev, 'status':1} self.b = EventGuest(**self.a) self.b.save() def test_guest_public_hides_attendance(self): c = GuestPublicSerializer(self.b) self.assertFalse('status' in c.data.keys()) def test_invitation_public_hides_status(self): c = InvitationPublicSerializer(self.b) self.assertFalse('status' in c.data.keys())
def test_appropriate_prefixes_receive_dot_on_clean(self): for x in ['mr', 'Mrs', 'Ms', 'Dr', 'mdm']: a = EventGuest(pfx=x, first='FirstName', last='Last Name') a.clean() self.assertEqual(a.pfx[-1], '.') a.pfx = 'Miss' #make sure it doesn't dot everything. a.clean() self.assertNotEqual(a.pfx[-1], '.')
def test_cleaner_handles_nonetype(self): a = EventGuest(pfx=None, first='mitchell ') a.clean() self.assertEqual(a.pfx, None)
def test_names_and_pfxs_stripped_on_clean(self): a = EventGuest(pfx='mr. ', first='mitchell ', last=' stoutin') a.clean() self.assertEqual(a.pfx, 'mr.') self.assertEqual(a.first, 'mitchell') self.assertEqual(a.last, 'stoutin')
def test_nextFreeInvitation_method_raises_exception_on_noEvent(self): with self.assertRaises(NoEventError): EventGuest.nextFreeInvitation(None)
def many_init(cls, *args, **kwargs): """ Here's where we'll validate that all the invitations are the same, or assign them. When passing many=True with a data kwarg, we need to make sure the representations are not orphaned from their event. Representations must either each have a dict key "event" which corresponds to the integer primary key, or you must pass the event as a keyword argument to the serializer along with many=True. """ if 'data' in kwargs: #validate data is a list. data = kwargs.pop('data') assert type(data) == list, ( '''Invitation Serializer with many=True and non-empty data expects a list in the data representation, not a dict or other type.''') eventNumber = kwargs.pop('event', None) if eventNumber is None: try: eventNumber = data[0]['event'] except KeyError: raise NoEventError( '''No event information associated with this list of guests. Try passing `event` keyword arg to the serializer or guest representations with event attributes''') #build invitations list to analyze invitations = [obj.pop('invitation', None) for obj in data] for inx, val in enumerate(invitations): if type(val) == str: #some data cleaning for types. val = val.strip() if val == '': invitations[inx] = None else: try: intval = int(val) invitations[inx] = intval except ValueError: pass integerInvitations = [x for x in invitations if type(x) == int] if integerInvitations: #isn't epmty allsame = map(lambda x: x == integerInvitations[0], integerInvitations) if not all(allsame): raise MixedInvitationError( 'All Numbered invitations must be same.') numberToAssign = integerInvitations[0] else: #usually means invitations == [None,]*len(data): numberToAssign = EventGuest.nextFreeInvitation(eventNumber) for representation in data: representation['invitation'] = numberToAssign # put our work back in the keyword args dict, which we'll use below. kwargs['data'] = data else: instance_queryset = [ args[0], ] if isinstance(args[0], EventGuest) else args[0] #per the serializer API. allsame = map( lambda x: x.invitation == instance_queryset[0].invitation, instance_queryset) if not all(allsame): raise MixedInvitationError # finally make the serializer, knowing the above is done. child = cls(*args, **kwargs) list_kwargs = { 'child': child, } list_kwargs.update({ key: value for key, value in kwargs.items() if key in serializers.LIST_SERIALIZER_KWARGS }) return InvitationListSerializer(*args, **list_kwargs)
def many_init(cls, *args, **kwargs): """ Here's where we'll validate that all the invitations are the same, or assign them. When passing many=True with a data kwarg, we need to make sure the representations are not orphaned from their event. Representations must either each have a dict key "event" which corresponds to the integer primary key, or you must pass the event as a keyword argument to the serializer along with many=True. """ if 'data' in kwargs: #validate data is a list. data = kwargs.pop('data') assert type(data) == list, ( '''Invitation Serializer with many=True and non-empty data expects a list in the data representation, not a dict or other type.''' ) eventNumber = kwargs.pop('event', None) if eventNumber is None: try: eventNumber = data[0]['event'] except KeyError: raise NoEventError( '''No event information associated with this list of guests. Try passing `event` keyword arg to the serializer or guest representations with event attributes''' ) #build invitations list to analyze invitations = [obj.pop('invitation', None) for obj in data] for inx, val in enumerate(invitations): if type(val) == str: #some data cleaning for types. val = val.strip() if val == '': invitations[inx] = None else: try: intval = int(val) invitations[inx] = intval except ValueError: pass integerInvitations = [x for x in invitations if type(x)==int] if integerInvitations: #isn't epmty allsame = map(lambda x: x==integerInvitations[0], integerInvitations) if not all(allsame): raise MixedInvitationError('All Numbered invitations must be same.') numberToAssign = integerInvitations[0] else: #usually means invitations == [None,]*len(data): numberToAssign = EventGuest.nextFreeInvitation(eventNumber) for representation in data: representation['invitation'] = numberToAssign # put our work back in the keyword args dict, which we'll use below. kwargs['data'] = data else: instance_queryset = [args[0],] if isinstance(args[0], EventGuest) else args[0] #per the serializer API. allsame = map(lambda x: x.invitation==instance_queryset[0].invitation, instance_queryset) if not all(allsame): raise MixedInvitationError # finally make the serializer, knowing the above is done. child = cls(*args, **kwargs) list_kwargs = {'child': child,} list_kwargs.update({ key: value for key, value in kwargs.items() if key in serializers.LIST_SERIALIZER_KWARGS }) return InvitationListSerializer(*args, **list_kwargs)