def test_get_all_events(self): now = datetime.now() Event.createOne(name="new_event", date_time=now.isoformat(), description="description", image="https://blob.knighthacks.org/somelogo.png", link="https://blob.knighthacks.org/somelogo.png", end_date_time=now.isoformat(), attendees_count=10, event_status="status") Event.createOne(name="another_new_event", date_time=now.isoformat(), description="description", image="https://blob.knighthacks.org/somelogo.png", link="https://blob.knighthacks.org/somelogo.png", end_date_time=now.isoformat(), attendees_count=10, event_status="status") res = self.client.get("api/events/get_all_events/") data = json.loads(res.data.decode()) self.assertEqual(res.status_code, 201) self.assertEqual(data["events"][0]["name"], "new_event") self.assertEqual(data["events"][1]["name"], "another_new_event")
def test_update_event(self): now = datetime.now() Event.createOne(name="new_event", date_time=now.isoformat(), description="description", image="https://blob.knighthacks.org/somelogo.png", link="https://blob.knighthacks.org/somelogo.png", end_date_time=now.isoformat(), attendees_count=10, event_status="status") res = self.client.put("api/events/update_event/new_event/", data=json.dumps({ "date_time": now.isoformat(), "description": "another_description", "image": "https://blob.knighthacks.org/somelogo.png", "link": "https://blob.knighthacks.org/somelogo.png", "end_date_time": now.isoformat(), "attendees_count": 20, "event_status": "ongoing", }), content_type="application/json") self.assertEqual(res.status_code, 201) self.assertEqual(Event.objects.first().event_status, "ongoing")
def test_remove_from_db(self): event = Event("Test", "lk", "virtual", 10, datetime.now(), datetime.now()) event.save_to_db() try: event.remove_from_db() except NoSuchEventExistException: self.fail("Error occurred when tried to delete existing event")
def test_create_event_not_unique(self): now = datetime.now() Event.createOne(name="new_event", date_time=now.isoformat(), description="description", image="https://blob.knighthacks.org/somelogo.png", link="https://blob.knighthacks.org/somelogo.png", end_date_time=now.isoformat(), attendees_count=10, event_status="status") res = self.client.post("api/events/create_event/", data=json.dumps({ "name": "new_event", "date_time": now.isoformat(), "description": "description", "image": "https://blob.knighthacks.org/somelogo.png", "link": "https://blob.knighthacks.org/somelogo.png", "end_date_time": now.isoformat(), "attendees_count": 10, "event_status": "status" }), content_type="application/json") data = json.loads(res.data.decode()) self.assertEqual(res.status_code, 409) self.assertEqual(data["name"], "Conflict")
def test_user_attended(self): user = "******" event = Event( title="Test event", description="Test description", start=datetime.datetime.utcnow().strftime('%m/%d/%Y %I:%M %p'), end=(datetime.datetime.utcnow() + datetime.timedelta(hours=1)).strftime('%m/%d/%Y %I:%M %p'), event_type="action", points=10) event.save_to_db() EventRegister.register_for_event(user, event.get_id()) EventRegister.set_user_attended(user, event.get_id().hex) self.assertEquals( EventRegister.get_user_attended(user, event.get_id().hex), True) EventRegister.set_user_attended(user, event.get_id().hex) self.assertEquals( EventRegister.get_user_attended(user, event.get_id().hex), False) Database.remove(Event.COLLECTION, {'_id': event.get_id()})
def test_is_synced(self): event = Event("Test", "lk", "virtual", 10, datetime.now(), datetime.now()) event.save_to_db() event.set_title("TestUpdated") event.sync_to_db() self.assertTrue(event.is_synced(), "event marked un-synced when it is") event.remove_from_db()
def test_not_synced(self): event = Event("Test", "lk", "virtual", 10, datetime.now(), datetime.now()) event.save_to_db() event.set_title("TestUpdated") self.assertFalse(event.is_synced(), "event marked synced when it is not") event.remove_from_db()
def create_event(): """ Creates a new event. --- tags: - event summary: Creates event requestBody: content: application/json: schema: $ref: '#/components/schemas/Event' description: Created event object required: true responses: 201: description: OK 400: description: Bad request. 5XX: description: Unexpected error (the API issue). """ data = request.get_json() if not data: raise BadRequest() if data.get("date_time"): try: data["date_time"] = dateutil.parser.parse(data["date_time"]) except ParserError: raise BadRequest() if data.get("end_date_time"): try: data["end_date_time"] = dateutil.parser.parse( data["end_date_time"]) # noqa: E501 except ParserError: raise BadRequest() new_data = {} for field in EVENT_FIELDS: new_data[field] = data.pop(field, None) try: Event.createOne(**new_data) except NotUniqueError: raise Conflict("The event name already exists.") res = {"status": "success", "message": "Event was created!"} return res, 201
def test_to_json(self): dt = datetime.now() id_ = uuid.uuid4() event = Event("Test", "lk", "virtual", 10, dt, dt, id_) self.equal = self.assertEqual( event.to_json(), { 'title': 'Test', 'description': 'lk', "event_type": "virtual", "points": 10, 'start': dt, 'end': dt, '_id': id_ })
def test_update_event_invalid_datatypes(self): now = datetime.now() Event.createOne(name="new_event", date_time=now.isoformat(), description="description", image="https://blob.knighthacks.org/somelogo.png", link="https://blob.knighthacks.org/somelogo.png", end_date_time=now.isoformat(), attendees_count=10, event_status="status") res = self.client.put("api/events/update_event/new_event/", data=json.dumps({ "date_time": "datetime", "description": "another_description", "image": "https://blob.knighthacks.org/somelogo.png", "link": "https://blob.knighthacks.org/somelogo.png", "end_date_time": now.isoformat(), "attendees_count": 20, "event_status": "ongoing", }), content_type="application/json") data = json.loads(res.data.decode()) self.assertEqual(res.status_code, 400) self.assertEqual(data["name"], "Bad Request") res = self.client.put("api/events/update_event/new_event/", data=json.dumps({ "date_time": now.isoformat(), "description": "another_description", "image": "https://blob.knighthacks.org/somelogo.png", "link": "https://blob.knighthacks.org/somelogo.png", "end_date_time": "end_date_time", "attendees_count": 20, "event_status": "ongoing", }), content_type="application/json") data = json.loads(res.data.decode()) self.assertEqual(res.status_code, 400) self.assertEqual(data["name"], "Bad Request")
def event_add_post(): try: start = datetime.strptime(request.form.get('start'), '%m/%d/%Y %I:%M %p') end = datetime.strptime(request.form.get('end'), '%m/%d/%Y %I:%M %p') new_event = Event(request.form.get('title'), request.form.get('description'), request.form.get('event_type'), int(request.form.get('points')), start, end) if not new_event.is_valid_model(): abort(500) new_event.save_to_db() return "Done" except ValueError: abort(500)
def event_delete_delete(event_id): try: old_event = Event.get_by_id(event_id) old_event.remove_from_db() return jsonify({"message": "Done"}), 200 except NoSuchEventExistException: abort(404)
def add(): if not current_user.is_authenticated: flash("Please login") return redirect(url_for('account.login')) form = AddEventForm() datetime1 = datetime.strptime("2019-04-25 22:37", '%Y-%m-%d %H:%M') form.eventtype.choices = [(t.id, t.event_type) for t in Type.query.all()] if request.method == 'POST': v = Venue(venuename=form.venue.data, locationaddress=form.location.data) # db.session.bulk_save_objects(multi) db.session.add(v) db.session.commit() print('*******', current_user.id) e = Event(title=form.title.data, description=form.description.data, organizer_id=current_user.id, venue_id=v.id, eventtype_id=form.eventtype.data, end_time=datetime1, start_time=datetime1, img_link=form.imglink.data, event_owner=form.eventowner.data) db.session.add(e) db.session.commit() flash('Successfully added') return render_template('add_event.html', form=form)
def test_to_json(self): dt = datetime.now() id_ = uuid.uuid4() event = Event("Test", "lk", "virtual", 10, dt, dt, id_) self.equal = self.assertEqual( event.to_json(), { "title": "Test", "description": "lk", "event_type": "virtual", "points": 10, "start": dt, "end": dt, "_id": id_, }, )
def event_edit_get(event_id): try: event = Event.get_by_id(event_id) return render_template('items/event_edit.html', event=event.to_json(), action_type="Edit", event_types=Constants.EVENT_TYPES) except NoSuchEventExistException: abort(404)
def update_event(event_name: str): """ Updates an event that has already been created. --- tags: - event summary: Updates event parameters: - id: event_name in: path description: event name required: true schema: type: string requestBody: content: application/json: schema: $ref: '#/components/schemas/Event' description: Updated event object required: true responses: 201: description: OK 400: description: Bad request. 5XX: description: Unexpected error (the API issue). """ data = request.get_json() if not data: raise BadRequest() if data.get("date_time"): try: data["date_time"] = dateutil.parser.parse(data["date_time"]) except ParserError: raise BadRequest() if data.get("end_date_time"): try: data["end_date_time"] = dateutil.parser.parse( data["end_date_time"]) # noqa: E501 except ParserError: raise BadRequest() event = Event.objects(name=event_name).first() if not event: raise NotFound() event.modify(**data) res = {"status": "success", "message": "Event was updated!"} return res, 201
def event_add_get(): try: return render_template('items/event_edit.html', event=Event("", "", "", "", datetime.now(), datetime.now()).to_json(), action_type="Add", event_types=Constants.EVENT_TYPES) except NoSuchEventExistException: abort(404)
def test_save_to_db(self): event = Event("Test", "lk", "virtual", 10, datetime.now(), datetime.now()) event.save_to_db() try: test_result = Event.get_by_id(event.get_id()) except NoSuchEventExistException: self.fail() event.remove_from_db() self.assertEqual(test_result, event, "Saved and retrieved event is not the same")
def register_for_event(user, event): event_to_use = Event.get_by_id(event) Database.insert( "registrations", { "user": user, "event": event, "title": event_to_use.get_title(), "date": time.strftime("%d/%m/%Y"), "attended": "No" })
def event_get(event_id): try: old_event = Event.get_by_id(event_id) registered = None if session.contains('email') and session['email'] is not None: registered = EventRegister.check_if_registered(session['email'], event_id) date = datetime.now() ff = old_event._end < date return render_template('items/event.html', event=old_event.to_json(), registered=registered, date=date) except NoSuchEventExistException: abort(404)
def add(): # print("Hello") form = AddEventForm() # print(form) form.organizer.choices = [(u.id, u.email) for u in User.query.all()] if form.validate_on_submit(): e = Event(description=form.description.data, user_id=form.organizer.data) db.session.add(e) db.session.commit() return redirect(url_for('ticket')) return render_template('add_event.html', form=form)
def test_create_event(self): now = datetime.now() event = Event.createOne(name="foobar", date_time=now, link="https://foobar.com", end_date_time=now) self.assertTrue(event.id) self.assertEqual(event.name, "foobar") self.assertEqual(event.date_time, now) self.assertEqual(event.link, "https://foobar.com") self.assertEqual(event.end_date_time, now)
def update_attended(user, event_id): id_ = uuid.UUID(event_id) event = Event.get_by_id(id_) category = event.get_event_type() points = event.get_points() if EventRegister.get_user_attended(user, event_id): EventRegister.set_user_attended(user, event_id) User.update_user_points(user, category, -points) else: User.update_user_points(user, category, points) EventRegister.set_user_attended(user, event_id) return jsonify({"message": "ok"}), 200
def show_create_event(): if request.method == "POST": print('create event') new_events = Event(event_name=request.form['event_name'], user_id=current_user.id, location=request.form['event_location'], address=request.form['event_address'], event_type=request.form.get('event_dropdown'), img_pic=request.form['event_img'], time=request.form['event_date']) db.session.add(new_events) db.session.commit() return redirect(url_for('event.render_event', id=new_events.id)) return render_template('event/create_event.html')
def test_user_attended(self): user = "******" event = Event(title="Test event", description="Test description", start=datetime.datetime.utcnow().strftime('%m/%d/%Y %I:%M %p'), end=(datetime.datetime.utcnow() + datetime.timedelta(hours=1)).strftime('%m/%d/%Y %I:%M %p'), event_type="action", points=10) event.save_to_db() EventRegister.register_for_event(user, event.get_id()) EventRegister.set_user_attended(user, event.get_id().hex) self.assertEquals(EventRegister.get_user_attended(user, event.get_id().hex), True) EventRegister.set_user_attended(user, event.get_id().hex) self.assertEquals(EventRegister.get_user_attended(user, event.get_id().hex), False) Database.remove(Event.COLLECTION, {'_id': event.get_id()})
def event_get(event_id): try: old_event = Event.get_by_id(event_id) registered = None if session.contains('email') and session['email'] is not None: registered = EventRegister.check_if_registered( session['email'], event_id) date = datetime.now() ff = old_event._end < date return render_template('items/event.html', event=old_event.to_json(), registered=registered, date=date) except NoSuchEventExistException: abort(404)
def test_event_register(self): user = "******" event = Event(title="Test event", description="Test description", start=datetime.datetime.utcnow().strftime('%m/%d/%Y %I:%M %p'), end=(datetime.datetime.utcnow() + datetime.timedelta(hours=1)).strftime('%m/%d/%Y %I:%M %p'), event_type="action", points=10) event.save_to_db() EventRegister.register_for_event(user, event.get_id()) self.assertIsNotNone(EventRegister.check_if_registered(user, event.get_id())) Database.remove("registrations", {"user": user, "event": event.get_id()}) Database.remove(Event.COLLECTION, {'_id': event.get_id()})
def add(): form = AddForm() if form.validate_on_submit(): name = form.name.data description = form.description.data image_url = form.image_url.data price = form.price.data address = form.address.data time = form.time.data # Add new Event to database new_pup = Event(name, description, image_url, price, address, time) db.session.add(new_pup) db.session.commit() return redirect(url_for('events.list')) return render_template('add.html', form=form)
def test_event_unregister(self): user = "******" event = Event( title="Test event", description="Test description", start=datetime.datetime.utcnow().strftime('%m/%d/%Y %I:%M %p'), end=(datetime.datetime.utcnow() + datetime.timedelta(hours=1)).strftime('%m/%d/%Y %I:%M %p'), event_type="action", points=10) event.save_to_db() EventRegister.register_for_event(user, event.get_id()) EventRegister.unregister_for_event(user, event.get_id()) self.assertIsNone( EventRegister.check_if_registered(user, event.get_id())) Database.remove(Event.COLLECTION, {'_id': event.get_id()})
def get_all_events(): """ Returns an array of event documents. --- tags: - event summary: returns an array of event documents responses: 201: description: OK 5XX: description: Unexpected error (the API issue). """ events = Event.objects() if not events: raise NotFound("There are no events created.") res = {"events": events, "status": "success"} return res, 201
def add(): form = AddForm() formtype = AddType() if request.method == 'POST': if form.validate_on_submit(): newevent = Event( name=form.name.data, description=form.description.data, image_url=form.image_url.data, address=form.address.data, datetimestart=datetime.strptime(form.datetimestart.data, "%m/%d/%Y %H:%M"), created=datetime.now(), datetimeend=None if not form.datetimeend.data else datetime.strptime(form.datetimeend.data, "%m/%d/%Y %H:%M")) current_user.event.append(newevent) db.session.add(newevent) db.session.commit() return redirect(url_for('tickettypes.addtype', id=newevent.id)) else: for field_name, errors in form.errors.items(): flash(errors) return render_template('add.html', form=form)
def test_from_json(self): event = Event.from_json(self, self.event) self.assertIsInstance(event, Event) self.assertTrue(hasattr(event, "id")) self.assertIs(event.id, 2)
def register_for_event(user, event): event_to_use = Event.get_by_id(event) Database.insert("registrations", {"user": user, "event": event, "title": event_to_use.get_title(), "date": time.strftime("%d/%m/%Y"), "attended": "No"})
def test_sync_to_db(self): event = Event("Test", "lk", "virtual", 10, datetime.now(), datetime.now()) event.save_to_db() event.set_title("TestUpdated") event.sync_to_db() try: test_result = Event.get_by_id(event.get_id()) except NoSuchEventExistException: self.fail() event.remove_from_db() self.assertEqual(test_result, event, "Sync event with database failed")
def test_is_not_valid_model(self): event = Event(12, 12, "virtual", 10, "hello", "sd") self.assertFalse(event.is_valid_model(), "Invalid model is valid")
def test_is_valid_model(self): event = Event("Test", "lk", "virtual", 10, datetime.now(), datetime.now(), uuid.uuid4()) self.assertTrue(event.is_valid_model(), "Valid model is invalid")
def test_remove_non_existing_event_from_db(self): event = Event("Test", "lk", "virtual", 10, datetime.now(), datetime.now(), uuid.uuid4()) self.assertRaises(NoSuchEventExistException, event.remove_from_db())
def get_events(self): statement = self._event_table.select() results = self._engine.execute(statement) return list(map(lambda q: Event.init_from_query(q), results))
def test_factory_form_json(self): event = Event("Test", "lk", "virtual", 10, datetime.now(), datetime.now()) self.assertEqual(event, Event.factory_form_json(event.to_json()), "Creating event object from json failed")