def test_many_participants(self):
        """Tests whether an appointment can have many participants."""
        add_user()
        db.session.commit()
        user = User.query.first()
        availability = create_availability()
        add_event(user_id=user.id, availability=availability)
        db.session.commit()
        event = Event.query.first()
        name = ['User Jeff', 'Jeff User', 'Reff Usej']
        email = ['*****@*****.**', '*****@*****.**', '*****@*****.**']
        comments = 'I think this whole Jeff and User thing is getting ' \
                   'confusing.'
        add_appointment(event_id=event.id,
                        participants=[
                            create_participant(name[i], email[i])
                            for i in range(2)
                        ],
                        comments=comments)
        db.session.commit()
        participants = db.session.query(Participant).\
            filter(Appointment.comments == comments)

        for j in range(2):
            self.assertEqual(participants[j].name, name[j])
            self.assertEqual(participants[j].email, email[j])
Example #2
0
    def test_appointment_model(self):
        """Tests whether the appointment model is working correctly."""
        add_user()
        db.session.commit()
        user = User.query.first()
        availability = create_availability()
        add_event(user_id=user.id, availability=availability)
        db.session.commit()
        event = Event.query.first()
        participant = create_participant()
        start = dt.datetime(year=2020,
                            month=3,
                            day=1,
                            hour=8,
                            tzinfo=dt.timezone.utc)
        end = start + dt.timedelta(hours=1)
        created = dt.datetime.now(dt.timezone.utc)
        add_appointment(event_id=event.id,
                        participants=[participant],
                        start=start,
                        end=end,
                        created=created)
        db.session.commit()
        appointment = Appointment.query.filter_by(start=start).first()

        self.assertEqual(appointment.end, end)
        self.assertEqual(appointment.created, created)
Example #3
0
    def test_appointment_not_found(self):
        """Tests whether requesting an appointment that doesn't exist returns
        a 404 error."""
        add_user()
        db.session.commit()
        user = User.query.first()
        user_public_id = user.public_id
        add_event(user.id, create_availability())
        db.session.commit()
        event = Event.query.first()
        event_url = event.url
        start = dt.datetime.now(dt.timezone.utc) + dt.timedelta(days=30)
        add_appointment(event_id=event.id,
                        participants=[create_participant()],
                        start=start)
        db.session.commit()

        route = f'/users/{user_public_id}/events/{event_url}/appointments/' \
                f'{(start + dt.timedelta(days=1)).isoformat()}'
        status = False
        response = self.api.patch(route,
                                  data=json.dumps({'status': status}),
                                  content_type='application/json')

        data = json.loads(response.data.decode())
        self.assertEqual(response.status_code, 404)
        self.assertEqual(data['status'], 'fail')
        self.assertEqual(data['message'], 'No appointment was found for that '
                         'start time.')
Example #4
0
    def test_bad_value(self):
        """Tests whether attempting to supply an unsupported value is
        rejected with a 400 response."""
        add_user()
        db.session.commit()
        user = User.query.first()
        user_public_id = user.public_id
        add_event(user.id, create_availability())
        db.session.commit()
        event = Event.query.first()
        event_url = event.url
        start = dt.datetime.now(dt.timezone.utc) + dt.timedelta(days=30)
        add_appointment(event_id=event.id,
                        participants=[create_participant()],
                        start=start)
        db.session.commit()

        route = f'/users/{user_public_id}/events/{event_url}/appointments/' \
                f'{start.isoformat()}'
        status = 'potato'
        response = self.api.patch(route,
                                  data=json.dumps({'status': status}),
                                  content_type='application/json')

        self.assertEqual(response.status_code, 400)

        data = json.loads(response.data.decode())
        self.assertEqual(data['errors']['status'],
                         f"'{status}' is not of type "
                         f"'boolean'")
        self.assertEqual(data['message'], 'Input payload validation failed')
Example #5
0
    def test_bad_params(self):
        """Tests whether a request with both valid and invalid parameters is
        accepted and the valid parameters are used."""
        add_user()
        db.session.commit()
        user = User.query.first()
        user_public_id = user.public_id
        add_event(user.id, create_availability())
        db.session.commit()
        event = Event.query.first()
        event_url = event.url
        start = dt.datetime.now(dt.timezone.utc) + dt.timedelta(days=30)
        add_appointment(event_id=event.id,
                        participants=[create_participant()],
                        start=start,
                        status=True)
        db.session.commit()

        route = f'/users/{user_public_id}/events/{event_url}/appointments/' \
                f'{start.isoformat()}'
        status = False
        response = self.api.patch(route,
                                  data=json.dumps({
                                      'status':
                                      status,
                                      'potato':
                                      'I love potatoes man.'
                                  }),
                                  content_type='application/json')

        self.assertEqual(response.status_code, 200)

        data = json.loads(response.data.decode())
        self.assertEqual(data['message'], 'success')
Example #6
0
    def test_updating_to_same_value(self):
        """Tests whether updating a value to its current value is accepted."""
        add_user()
        db.session.commit()
        user = User.query.first()
        user_public_id = user.public_id
        add_event(user.id, create_availability())
        db.session.commit()
        event = Event.query.first()
        event_url = event.url
        start = dt.datetime.now(dt.timezone.utc) + dt.timedelta(days=30)
        add_appointment(event_id=event.id,
                        participants=[create_participant()],
                        start=start,
                        status=True)
        db.session.commit()

        route = f'/users/{user_public_id}/events/{event_url}/appointments/' \
                f'{start.isoformat()}'
        status = True
        response = self.api.patch(route,
                                  data=json.dumps({'status': status}),
                                  content_type='application/json')

        self.assertEqual(response.status_code, 200)

        data = json.loads(response.data.decode())
        self.assertEqual(data['message'], 'success')

        appointment = Appointment.query.first()
        self.assertEqual(appointment.status, status)
Example #7
0
    def test_get_appointments(self):
        """Tests whether appointments can be successfully requested."""
        add_user()
        db.session.commit()
        user = User.query.first()
        add_event(user_id=user.id, availability=create_availability())
        db.session.commit()
        event = Event.query.first()
        name = 'Jimmy Joe'
        comments = "OMG I haven't seen you in forever Jimmy how has it been?"
        start = dt.datetime.now(dt.timezone.utc)
        add_appointment(event_id=event.id,
                        participants=[create_participant(name=name)],
                        comments=comments,
                        start=start)
        db.session.commit()
        auth_token = user.encode_auth_token(user.id)

        response = self.api.get(
            f'/users/{user.public_id}/events/{event.url}/'
            f'appointments',
            headers={'x-access-token': auth_token},
            content_type='application/json')

        data = json.loads(response.data.decode())
        appointment = data[0]
        participants = appointment['participants'][0]

        self.assertEqual(response.status_code, 200)
        self.assertEqual(appointment['comments'], comments)
        self.assertEqual(participants['name'], name)
        self.assertEqual(parser.isoparse(appointment['start']), start)
Example #8
0
    def test_get_appointment(self):
        """Tests whether an appointment can be successfully requested."""
        add_user()
        db.session.commit()
        user = User.query.first()
        user_public_id = user.public_id
        add_event(user.id, create_availability())
        db.session.commit()
        event = Event.query.first()
        event_url = event.url
        name = 'Big Bob'
        email = '*****@*****.**'
        comments = 'What is this appointment for again?'
        start = dt.datetime(year=2020,
                            month=3,
                            day=2,
                            hour=9,
                            tzinfo=dt.timezone.utc)
        add_appointment(
            event_id=event.id,
            participants=[create_participant(name=name, email=email)],
            start=start,
            comments=comments)
        db.session.commit()

        route = f'/users/{user_public_id}/events/{event_url}/appointments/' \
                f'{start.isoformat()}'
        response = self.api.get(route, content_type='application/json')

        appointment = json.loads(response.data.decode())
        participant = appointment['participants'][0]
        self.assertEqual(response.status_code, 200)
        self.assertEqual(appointment['comments'], comments)
        self.assertEqual(participant['name'], name)
        self.assertEqual(participant['email'], email)
Example #9
0
    def test_bad_token(self):
        """Tests whether a request with an invalid token returns a 403
        response."""
        add_user(email='*****@*****.**')
        add_user(email='*****@*****.**')
        db.session.commit()
        user1 = User.query.filter_by(email='*****@*****.**').first()
        user2 = User.query.filter_by(email='*****@*****.**').first()
        add_event(user1.id, create_availability())
        db.session.commit()
        event1 = Event.query.filter_by(user_id=user1.id).first()
        add_appointment(event_id=event1.id,
                        participants=[create_participant()])
        db.session.commit()

        auth_token2 = user2.encode_auth_token(user2.id)
        route = f'/users/{user1.public_id}/events/{event1.url}/appointments'
        response = self.api.get(route,
                                headers={'x-access-token': auth_token2},
                                content_type='application/json')
        data = json.loads(response.data.decode())

        self.assertEqual(response.status_code, 403)
        self.assertEqual(data['message'],
                         "You do not have permission to access this content")
Example #10
0
    def test_get_all_appointments(self):
        """Test Getting all appointments from a User"""
        add_user()
        db.session.commit()
        user = User.query.first()
        # Create 2 events
        event1 = add_event(user_id=user.id,
                           availability=create_availability(),
                           name="Frist Event",
                           url="my first url")

        event2 = add_event(user_id=user.id,
                           availability=create_availability(),
                           name="Frist Second",
                           url="my second url")
        db.session.commit()
        start = dt.datetime.now(dt.timezone.utc)
        # add appointment to event 1
        add_appointment(event_id=event1.id,
                        participants=[
                            create_participant(name="John",
                                               email="*****@*****.**")
                        ],
                        comments="comments",
                        start=start)
        # add appointment to event 2
        add_appointment(event_id=event2.id,
                        participants=[
                            create_participant(name="Bonnie",
                                               email="*****@*****.**")
                        ],
                        comments="comments",
                        start=start + dt.timedelta(days=1))
        db.session.commit()
        auth_token = user.encode_auth_token(user.id)

        resp_with_query_param = self.api.get(
            f'/users/{user.public_id}/appointments?event_url={event1.url}',
            headers={'x-access-token': auth_token},
            content_type='application/json')
        data_with_query = json.loads(resp_with_query_param.data.decode())

        resp_no_query_param = self.api.get(
            f'/users/{user.public_id}/appointments',
            headers={'x-access-token': auth_token},
            content_type='application/json')

        data_no_query_param = json.loads(resp_no_query_param.data.decode())

        self.assertEqual(len(data_with_query), 1)

        self.assertEqual(len(data_no_query_param), 2)
Example #11
0
    def test_participant_model(self):
        """Tests whether the participant model is working correctly."""
        add_user()
        db.session.commit()
        user = User.query.first()
        availability = create_availability()
        add_event(user_id=user.id, availability=availability)
        db.session.commit()
        event = Event.query.first()
        name = 'User Jeff'
        email = '*****@*****.**'
        add_appointment(
            event_id=event.id,
            participants=[create_participant(name=name, email=email)])
        db.session.commit()
        participant = Participant.query.filter_by(name=name).first()

        self.assertEqual(participant.email, email)
Example #12
0
    def test_missing_token(self):
        """Tests whether a request with a missing token returns a 401
        response"""
        add_user(email='*****@*****.**')
        db.session.commit()
        user = User.query.first()
        add_event(user.id, create_availability())
        db.session.commit()
        event = Event.query.first()
        add_appointment(event_id=event.id, participants=[create_participant()])
        db.session.commit()

        route = f'/users/{user.public_id}/events/{event.url}/appointments'
        response = self.api.get(route, content_type='application/json')
        data = json.loads(response.data.decode())

        self.assertEqual(response.status_code, 401)
        self.assertEqual(data['message'], 'Token is missing!')
Example #13
0
    def test_multiple_participants(self):
        """Tests whether an appointment can have multiple participants."""
        add_user()
        db.session.commit()
        user = User.query.first()
        availability = create_availability()
        add_event(user_id=user.id, availability=availability)
        db.session.commit()
        event = Event.query.first()
        names = ['Rex', 'Fives', 'Echo', 'Dogma', 'Wolffe']
        emails = [f'{name}@trooper.com' for name in names]
        participants = [
            create_participant(name=names[i], email=emails[i])
            for i in range(4)
        ]
        add_appointment(event_id=event.id, participants=participants)
        db.session.commit()
        appointment = Appointment.query.first()

        for i in range(4):
            self.assertEqual(appointment.participants[i].name, names[i])
            self.assertEqual(appointment.participants[i].email, emails[i])
    def post(self, public_id, event_url):
        """Creates an appointment for the specified event."""
        payload = api.payload
        if not start_within_next_x_days(payload['start']):
            raise AppointmentAfterNext_X_DaysError(NEXT_X_DAYS)

        event = db.session.query(Event). \
            filter(Event.url == event_url, User.public_id == public_id). \
            first()

        if not appointment_availability_allowed(
                event.availability, event.duration,
                parser.isoparse(payload['start'])):
            raise AppointmentNotAvailableError

        participant = participant_exists(payload['participant']['name'],
                                         payload['participant']['email'])
        appointment = add_appointment(event_id=event.id,
                                      participants=[participant],
                                      start=parser.isoparse(payload['start']),
                                      end=parser.isoparse(payload['start']) +
                                      dt.timedelta(minutes=event.duration),
                                      comments=payload['comments'])
        db.session.commit()

        response = {'message': 'success'}

        user: User = event.user
        calendar_response = create_google_event(
            creds=user.cred,
            user_email=user.email,
            event_name=event.name,
            location=event.location,
            description=f"{appointment.comments}\n"
            f"\n",
            start=appointment.start,
            end=appointment.end,
            participant_email=participant.email)
        if 'error' in calendar_response.keys():
            response['googleCalendar'] = 'fail'

        gmail_response = send_email(
            user.email,
            appointment,
            'project/resources/templates/'
            'email_template.html',
        )
        if len(gmail_response) > 0:
            response['googleEmail'] = 'fail'

        return response, 201