def setUp(self) -> None: self.organizer = Group(name="organizer") self.organizer.save() self.public = Event( name="Public Event", image=get_image_file(), description="Public Event description", lead="Public Event Lead", start_date_time=make_aware( datetime.datetime(2200, 1, 1, hour=1, minute=20)), end_date_time=make_aware( datetime.datetime(2200, 1, 1, hour=16, minute=36)), member_only=False, location="Common Room", organizer=self.organizer, price=69.69, ) self.public.save() self.member = Event( name="Member Event", image=get_image_file(), description="Member Event description", lead="Member Event Lead", start_date_time=make_aware( datetime.datetime(2200, 1, 1, hour=1, minute=20)), end_date_time=make_aware( datetime.datetime(2200, 1, 1, hour=16, minute=36)), member_only=True, location="Common Room", organizer=self.organizer, price=69.69, ) self.member.save()
def test_queryset_no_upcoming_events(self): """Ensure that the `upcoming` method returns an empty queryset when there are no upcoming events. """ e1 = Event(type=Event.EventType.WORKSHOP, topics=['AI/ML'], start=timezone.now() - timedelta(hours=1, days=1), end=timezone.now() - timedelta(days=1)) e2 = Event(type=Event.EventType.GUEST_SPEAKER, topics=['AI/ML'], start=timezone.now() - timedelta(hours=2, days=1), end=timezone.now() - timedelta(hours=1, days=1)) e1.save() e2.save() self.assertEqual(0, len(Event.objects.upcoming()))
def test_queryset_two_upcoming_events(self): """Ensure that a queryset of length two is returned when there are two upcoming events in the database. """ e1 = Event(type=Event.EventType.PROJECT_MEETING, topics=['AI/ML'], start=timezone.now() + timedelta(hours=1, days=1), end=timezone.now() + timedelta(days=1)) e2 = Event(type=Event.EventType.GUEST_SPEAKER, topics=['AI/ML'], start=timezone.now() + timedelta(hours=2, days=1), end=timezone.now() + timedelta(hours=1, days=1)) e1.save() e2.save() self.assertEqual(2, len(Event.objects.upcoming()))
def test_queryset_one_upcoming_event_one_passed(self): """Ensure that the `upcoming` method returns a queryset of length one when there is one upcoming event. """ e1 = Event(type=Event.EventType.HACKATHON_MEETING, topics=['AI/ML'], start=timezone.now() + timedelta(hours=1, days=1), end=timezone.now() + timedelta(days=1)) e2 = Event(type=Event.EventType.GUEST_SPEAKER, topics=['AI/ML'], start=timezone.now() - timedelta(hours=2, days=1), end=timezone.now() - timedelta(hours=1, days=1)) e1.save() e2.save() self.assertEqual(1, len(Event.objects.upcoming())) self.assertEqual(e1.pk, Event.objects.upcoming()[0].pk)
def test_subscribing_not_loggedin_not_registered(self): ''' tests the creation of a subcription if the user is not registered checks if the anoynomous user creation along with a subscription to this event ''' user = User(**self.user) event = Event(author=user,**self.event) user.save() event.save() ev = Event.objects.filter(title=self.event['title']) response = self.client.post( '/events/'+str(ev[0].id), data={ 'username': '******', 'email': '*****@*****.**', 'comment': 'some absurd comment' }) users = User.objects.filter(username='******',email='*****@*****.**') self.assertEqual(len(users),1) subs = Subscription.objects.all() self.assertEqual(len(subs),1) self.assertEqual(subs[0].subscriber, users[0]) self.assertEqual(subs[0].event.author, user) self.assertTrue(response.url,'/events/'+str(ev[0].id))
def test_str_different_start_and_end_day(self): """Ensure that an object's string representation is correct when its start and end dates are different. An Event that starts and ends on different days should have a string representation of the form: 'EVENT_TYPE_LABEL from MM-DD-YYYY to MM-DD-YYYY' """ event = Event(type=Event.EventType.OTHER, topics=[], start=timezone.datetime(2021, 4, 20, 1, 30, tzinfo=pytz.UTC), end=timezone.datetime(2021, 4, 21, 3, 30, tzinfo=pytz.UTC)) event.save() self.assertEqual( f'{Event.EventType.OTHER.label} from 04-20-2021 to 04-21-2021', str(event))
def insertLocationView(request, id): event = Event.objects.get(id=id) object = Event() locations = Location.objects.filter(event=id) location_form = LocationForm() if request.method == 'POST': location_form = LocationForm(request.POST) if location_form.is_valid: location_repeat = Location.objects.all().filter( event=event).filter(name=location_form['name'].value()) if location_repeat.first() == None: addLocationView(request, event.id, location_form['name'].value(), location_form['cost'].value()) messages.success(request, 'Localidad agregada exitosamente') return HttpResponseRedirect( reverse('location_crear', args=[id])) else: messages.error(request, 'Error, localidad repetida') return HttpResponseRedirect( reverse('location_crear', args=[id])) else: context = { 'event': event, 'location_form': location_form, 'locations': locations } return render(request, 'tickets/generateLocations.html', context)
def writeUnivisEventsInDB(events: list): for event in events: if 'calendar' in event and not event[ 'calendar'] == 'nein' and 'internal' in event and event[ 'internal'] == 'nein' and 'startdate' in event and 'enddate' in event: startdate = datetime.strptime(event['startdate'], "%Y-%m-%d") enddate = datetime.strptime(event['enddate'], "%Y-%m-%d") if (startdate + timedelta(1)) >= enddate: if 'title' in event and 'rooms' in event and 'starttime' in event: # TODO: Add Description in # TODO: Is there a better way to add Objects in DB? event_obj = Event() event_obj.save() event_obj.title = event['title'] locations = getLocationIDs(event) for location in locations: event_obj.locations.add( Location.objects.get(key=location)) event_obj.time = event['starttime'] event_obj.date = event['startdate'] # TODO: Better Category handling event_obj.category = UNIVIS_CATEGORY if 'presenter' in event: event_obj.presenter = event['presenter'] if 'orgname' in event: event_obj.orgname = event['orgname'] try: event_obj.save() except IntegrityError: # TODO: Update DB Object if duplicate detected print("Found Duplicate!") except Exception as err: print(err.args) Event.objects.filter(title="").delete()
def handle(self, *args, **options): # Remove old test data call_command('resetdb') # host = User.objects.get(email='*****@*****.**') host = User(email='*****@*****.**', username='******') host.set_password('password') host.save() details = UserDetails(user=host, display_name="Sam") for i in range(0, 12): name = "Auto Generated Event {}".format(i) date = datetime.now() + timedelta(days=i) description = ''.join(loremipsum.get_sentences(15)) event = Event(name=name, description=description, location="UNSW", host=host, date=date) event.save() # Create a toplevel post post_text = ''.join(loremipsum.get_sentences(15)) post = Post(author=host, eventID=event, date=date, message=post_text) post.save() # Generate some replies for j in range(0, 10): reply_text = ''.join(loremipsum.get_sentences(5)) post = Post(author=host, eventID=event, date=date, message=reply_text) post.save()
def login(): data = request.get_json() if data is None or None in [ data.get('password', None), data.get('email', None) ]: return jsonify({ 'code': NotValidData.code, 'description': NotValidData.description }) user = User.query.filter_by(email=data['email']).first() if user is None: return jsonify({ 'code': WrongPasswordOrEmail.code, 'description': WrongPasswordOrEmail.description }) if User.verify_password(user.password, data['password']): event = Event(user_id=user.id, type_active=Event.TypeActivity.Login) db.session.add(event) db.session.commit() token = user.get_token() return jsonify({'token': token, 'user_id': user.id}) return jsonify({ 'code': WrongPasswordOrEmail.code, 'description': WrongPasswordOrEmail.description })
def createPost(): data = request.get_json() if (data is None or None in [data.get('text', None), data.get('author_id', None)]): return jsonify({ 'code': NotValidData.code, 'description': NotValidData.description }) if User.query.filter_by(id=data['author_id']).first() is None: return jsonify({ 'code': NotValidData.code, 'description': NotValidData.description }) post = Post(author_id=data['author_id'], text=data['text']) event = Event(user_id=data['author_id'], type_active=Event.TypeActivity.Request) db.session.add(post) db.session.add(event) db.session.commit() return jsonify({ 'id': post.id, 'text': post.text, 'author_id': post.author_id })
def test_event_form(self): response = self.client.get('/events/create') html = response.content.decode('utf-8') user = User(**self.user) event = Event(author=user, **self.event) form = EventForm(instance=event)
def test_valid_topics_nonempty_list(self): """Ensure that a ValidationError is not raised for an object with a list of topics containing one valid topic. """ event = Event(type=Event.EventType.OTHER, topics=['Topic 1'], start=timezone.now(), end=timezone.now() + timedelta(days=2)) self.assertNotRaises(ValidationError, event.full_clean)
def test_end_datetime_before_start_datetime(self): """Ensure that a ValidationError is raised for an object whose start falls after its end. """ event = Event(type=Event.EventType.WORKSHOP, topics=['AI/ML'], start=timezone.now(), end=timezone.now() - timedelta(days=1)) self.assertRaises(ValidationError, event.full_clean)
def test_valid_start_and_end(self): """Ensure that a ValidationError is not raised for an object with valid start and end datetimes. """ event = Event(type=Event.EventType.WORKSHOP, topics=['AI/ML'], start=timezone.now(), end=timezone.now() + timedelta(days=2)) self.assertNotRaises(ValidationError, event.full_clean)
def test_start_and_end_equal(self): """Ensure that a ValidationError is raised for an object whose start falls after its end. """ time = timezone.now() event = Event(type=Event.EventType.WORKSHOP, topics=['AI/ML'], start=time, end=time) self.assertRaises(ValidationError, event.full_clean)
def test_upcoming_action(self): """Ensure that appending `/upcoming` to the URL results in the response only containing upcoming events. """ e1 = Event(type=Event.EventType.WORKSHOP, topics=['Topic'], start=timezone.now() - timedelta(hours=1, days=1), end=timezone.now() - timedelta(days=1)) e2 = Event(type=Event.EventType.WORKSHOP, topics=['Topic'], start=timezone.now() + timedelta(days=2), end=timezone.now() + timedelta(days=2, hours=3)) e1.save() e2.save() url = reverse('event-list') response = self.client.get(f'{url}/upcoming') self.assertEqual(status.HTTP_200_OK, response.status_code) self.assertEqual(1, len(response.data))
def test_queryset_event_in_progress(self): """Ensure that an event that has started, but not completed, is not included in the `upcoming` queryset. """ e = Event(type=Event.EventType.WORKSHOP, topics=['Topic'], start=timezone.now() - timedelta(hours=1), end=timezone.now() + timedelta(hours=1)) e.save() self.assertEqual(0, len(Event.objects.upcoming()))
def setUpTestData(cls): """Creates and saves a valid Event object for creating ContactInfo objects in individual tests. """ cls.event = Event( type=Event.EventType.OTHER, topics=['Topic 1'], start=timezone.now(), end=timezone.now() + timedelta(days=2) ) cls.event.save()
def test_invalid_topics_whitespace_string_in_list_with_valid_string(self): """Ensure that a ValidationError is raised for an object with one valid and invalid topic in its list of topics. Topics cannot be represented by strings containing only whitespace characters. """ event = Event(type=Event.EventType.OTHER, topics=['Topic 1', ' \t\f'], start=timezone.now(), end=timezone.now() + timedelta(days=2)) self.assertRaises(ValidationError, event.full_clean)
def test_invalid_topics_empty_string_in_list(self): """Ensure that a ValidationError is raised for an object with a single, invalid topic in its list of topics. Topics cannot be represented by strings of length 0. """ event = Event(type=Event.EventType.OTHER, topics=[''], start=timezone.now(), end=timezone.now() + timedelta(days=2)) self.assertRaises(ValidationError, event.full_clean)
def testEventsRawCreation(self): e = Event(head="hello", body="123452", image="asd.jpg", game="lol", date="2013-09-10") e2 = Event(head="hello2", body="123452", image="asd.jpg", game="lol", date="2013-09-22") e.save() E = Event.objects.filter(head="hello").get() self.assertEqual(e.head, E.head) self.assertNotEqual(e2.head, E.head) E2 = Event.objects.filter(head="hello2") self.assertEqual(0, E2.count()) e2.save() E2 = Event.objects.filter(head="hello2") self.assertEqual(1, E2.count())
def test_list_action_valid_count_less_than_num_in_db(self): """Ensure that specifying a valid count does not cause any issues. """ e = Event(type=Event.EventType.WORKSHOP, topics=['Topic'], start=timezone.now() - timedelta(hours=1, days=1), end=timezone.now() - timedelta(days=1)) e.save() url = reverse('event-list') response = self.client.get(f'{url}?count=1') self.assertEqual(status.HTTP_200_OK, response.status_code) self.assertEqual(1, len(response.data))
def test_event_created(self, event_created): """Ensure that the `event_created` task is run with the correct arguments when a new Event object is created and saved. """ event = Event(type=Event.EventType.WORKSHOP, topics=['AI/ML'], start=timezone.now(), end=timezone.now() + timedelta(days=2)) event.save() self.assertTrue(event_created.called) self.assertEqual( Event.EventType(event.type).label, event_created.call_args[0][0]) self.assertEqual(event.start, event_created.call_args[0][1])
def test_clean_invalid_relation(self): """Ensure that a ValidationError is raised for an object whose `form` is not one of the supported relation types. """ event = Event(type=Event.EventType.WORKSHOP, topics=['AI/ML'], start=timezone.now(), end=timezone.now() + timedelta(days=2)) event.save() comment = AdminComment(first_name='John', last_name='Adams', comment='Comment text', form=event) self.assertRaises(ValidationError, comment.full_clean)
def setUpTestData(cls): """Set up the test data for the test case once when the test case class is being prepared to run. """ cls.event = Event( type=Event.EventType.WORKSHOP, topics=['Autoencoders', 'Gradient boosting'], start=timezone.now(), end=timezone.now() + timedelta(days=2), calendar_link='https://www.google.com', meeting_link='https://www.google.com', ) cls.event.save() cls.contact = ContactInfo(type=ContactInfo.InfoType.EMAIL, preferred=False, value='*****@*****.**', content_object=cls.event) cls.contact.save()
def setUp(self): user = EventViewData.user event = EventViewData.event self.my_user = User.objects.create( username=user['username'], email=user['email'], password=user['password'], ) self.event = Event( title=event['title'], description=event['description'], author=self.my_user, state=event['state'], ) self.event.save()
def unlikePost(): data = request.get_json() if (data is None or None in [ data.get('post_id', None), data.get('user_id', None), data.get('like_id') ]): return jsonify({ 'code': NotValidData.code, 'description': NotValidData.description }) if User.query.filter_by( id=data['user_id']).first() is None or Post.query.filter_by( id=data['post_id']).first() is None: return jsonify({ 'code': NotValidData.code, 'description': NotValidData.description }) like = Like.query.filter_by(user_id=data['user_id'], post_id=data['post_id'], id=data['like_id']).first() if like is None: return jsonify({ 'code': NotValidData.code, 'description': NotValidData.description }) db.session.delete(like) event = Event(user_id=data['user_id'], type_active=Event.TypeActivity.Request) db.session.add(event) db.session.commit() return jsonify({ 'id': like.id, 'user_id': like.user_id, 'post_id': like.post_id, 'date_created': like.created })
def setUp(self): user = EventViewData.user event = EventViewData.event self.my_user = User.objects.create( username=user['username'], email=user['email'], password=user['password'], ) self.my_user.save() event_num = 10 self.events = [] for _ in range(event_num): e = Event( title=event['title'], description=event['description'], author=self.my_user, state=event['state'], ) e.save() self.events.append(e)
def test_subscribing_not_loggedin_registered(self): ''' tests the creation of a subcription if the user is registered and doesn't have a subscription on this event ''' user = User(**self.user) event = Event(author=user,**self.event) user.save() event.save() ev = Event.objects.filter(title=self.event['title']) response = self.client.post( '/events/'+str(ev[0].id), data={ 'username': self.user['username'], 'email': self.user['email'], 'comment': 'some absurd comment' }) sub = Subscription.objects.all() self.assertEqual(len(sub),1) self.assertTrue(response.url,'/events/'+str(ev[0].id))