def setUp(self): super(OrganizerActivitiesViewTest, self).setUp() # get organizer organizer = self.organizer # create organizer activities today = now() yesterday = today - timedelta(1) self.unpublished_activities = \ ActivityFactory.create_batch(2, organizer=organizer) # Open activities self.opened_activities = \ ActivityFactory.create_batch(2, published=True, organizer=organizer) CalendarFactory.create_batch(size=2, initial_date=now() + timedelta(days=20), enroll_open=True, activity=factory.Iterator( self.opened_activities)) self.closed_activities = \ ActivityFactory.create_batch(2, published=True, organizer=organizer) self.activities = self.organizer.activity_set.all() # set url self.url = reverse('organizers:activities', kwargs={'organizer_pk': organizer.id}) self.autocomplete_url = reverse('organizers:activities_autocomplete', kwargs={'organizer_pk': organizer.id})
def setUp(self): super(ActivitiesByStudentViewTest, self).setUp() # get student student = self.student # create student activities today = datetime.today().date() yesterday = today - timedelta(1) tomorrow = today + timedelta(1) month_ago = today - timedelta(days=31) # create current activities self.current_activities = \ ActivityFactory.create_batch(2) self._create_calendars(self.current_activities, yesterday) # create next activities self.next_activities = \ ActivityFactory.create_batch(2) self._create_calendars(self.next_activities, tomorrow) # create past activities self.past_activities = \ ActivityFactory.create_batch(2) self._create_calendars(self.past_activities, month_ago) self.activities = Activity.objects.filter(calendars__orders__student=student) self.url = reverse('students:activities', kwargs={'pk': student.id}) self.url_autocomplete = reverse('students:activities_autocomplete', kwargs={'pk': student.id})
def setUp(self): self.user = UserFactory() self.activity = ActivityFactory(rating=4) self.calendar = CalendarFactory(activity=self.activity, initial_date=(now() + timedelta(days=5)).date()) self.cover = ActivityPhotoFactory(activity=self.activity, main_photo=True) self.location = LocationFactory(organizer=self.activity.organizer)
def test_create(self): """ The serializer should create the calendar with the data passed """ today = now() epoch = UnixEpochDateField() activity = ActivityFactory() data = { 'activity': activity.id, 'initial_date': epoch.to_representation(today), 'session_price': 300000, 'available_capacity': 10, 'note': 'Note', 'schedules': '<p><strong>Lunes - Viernes</strong></p><p>6:00pm - 9:00pm</p>', 'packages': [{ 'quantity': 16, 'price': 100000, 'type': 1, }] } calendar_counter = Calendar.objects.count() package_counter = CalendarPackage.objects.count() serializer = CalendarSerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() self.assertEqual(Calendar.objects.count(), calendar_counter + 1) self.assertEqual(CalendarPackage.objects.count(), package_counter + 1)
def test_only_one_calendar_activity_open(self): """ If the activity is open the serializer shouldn't let create more than 1 calendar """ today = now() epoch = UnixEpochDateField() activity = ActivityFactory(is_open=True) CalendarFactory(activity=activity) data = { 'activity': activity.id, 'initial_date': epoch.to_representation(today), 'available_capacity': 10, 'note': 'Note', 'schedules': '<p><strong>Lunes - Viernes</strong></p><p>6:00pm - 9:00pm</p>', 'packages': [{ 'quantity': 3, 'price': 123843, 'type': 1, }] } serializer = CalendarSerializer(data=data) with self.assertRaisesMessage(ValidationError, "{'non_field_errors': ['No se puede crear" " más de un calendario cuando la actividad" " es de horario abierto']}"): serializer.is_valid(raise_exception=True)
def create_activities(self, num_activities: int): self.stdout.write('Creando activities') activities = list() size = None if num_activities: size = num_activities // len(self.organizers) for organizer in self.organizers: quantity = size if size else self.get_quantity() instructors = list(organizer.instructors.all()) instructors_sample = self.get_sample(instructors, 1) params = { 'organizer': organizer, 'published': True, 'sub_category': factory.Iterator(self.subcategories, cycle=True), 'instructors': instructors_sample, 'location': factory.Iterator(self.locations, cycle=True), 'certification': factory.Faker('boolean'), } activities.append(ActivityFactory.create_batch(quantity, **params)) activities = self.flat_list(activities) self.create_main_photo(activities) self.create_tags(activities) return activities
def setUp(self): super(PayUPSETest, self).setUp() self.activity = ActivityFactory(published=True) self.calendar = CalendarFactory(activity=self.activity) self.url = reverse('orders:create_or_list_by_activity', kwargs={'activity_pk': self.activity.id}) # Permissions permissions = Permission.objects.filter( Q(codename='add_order') | Q(codename='add_assistant')) self.student.user.user_permissions.add(*permissions)
def setUp(self): self.activity = ActivityFactory() self.author = mommy.make(Student) self.order = OrderFactory(status=Order.ORDER_APPROVED_STATUS, calendar__activity=self.activity, calendar__initial_date=now() - timedelta(days=3), student=self.author) self.data = { 'rating': 5, 'activity': self.activity.id, } self.context = self.get_context()
def test_should_not_update_is_open_if_there_are_calendars(self): """ The serializer should not allow update is_open if there is any calendar """ activity = ActivityFactory() CalendarFactory(activity=activity) data = {'is_open': True} request = mock.MagicMock() request.user = activity.organizer.user serializer = ActivitiesSerializer(activity, data=data, partial=True, context={'request': request}) msg = 'No se puede cambiar el tipo de horario porque existen calendarios relacionados.' with self.assertRaisesMessage(ValidationError, "{'is_open': ['%s']}" % msg): serializer.is_valid(raise_exception=True)
def test_remove_activity_from_wish_list(self): """ Test removing an activity from the wish list """ activity = ActivityFactory() wish_list = WishListFactory(student=self.student, activity=activity) # Anonymous should get a 401 unauthorized response = self.client.post(self.url) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # Organizer should get a 403 forbidden response = self.organizer_client.post(self.url) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # Student should be able to add an activity response = self.student_client.post(self.url, data={'activity_id': activity.id}) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertNotIn(activity, self.student.wish_list.all())
def test_if_activity_is_open_packages_should_be_required(self): """ If the activity is_open is False the CalendarSerializer should require the session price and not the packages """ today = now() epoch = UnixEpochDateField() activity = ActivityFactory(is_open=True) data = { 'activity': activity.id, 'initial_date': epoch.to_representation(today), 'available_capacity': 10, 'note': 'Note', 'schedules': '<p><strong>Lunes - Viernes</strong></p><p>6:00pm - 9:00pm</p>', } serializer = CalendarSerializer(data=data) with self.assertRaisesMessage(ValidationError, "{'packages': ['Este campo es" " requerido.']}"): serializer.is_valid(raise_exception=True)
def setUp(self): self.activity = ActivityFactory()
class ActivitySerializerTest(APITestCase): """ Test for ActivitySerializer """ def setUp(self): self.activity = ActivityFactory() def test_read(self): """ Test the serializer data """ category_data = CategoriesSerializer(instance=self.activity.sub_category.category, remove_fields=['subcategories']).data # location_data = LocationsSerializer(self.activity.location).data organizer_data = OrganizersSerializer(self.activity.organizer).data content = { 'id': self.activity.id, 'title': self.activity.title, 'short_description': self.activity.short_description, 'sub_category': self.activity.sub_category.id, 'sub_category_display': self.activity.sub_category.name, 'level': self.activity.level, 'level_display': self.activity.get_level_display(), 'category': category_data, 'content': self.activity.content, 'requirements': self.activity.requirements, 'return_policy': self.activity.return_policy, 'extra_info': self.activity.extra_info, 'audience': self.activity.audience, 'goals': self.activity.goals, 'methodology': self.activity.methodology, 'youtube_video_url': self.activity.youtube_video_url, 'published': self.activity.published, 'certification': self.activity.certification, 'calendars': [], 'steps': activities_constants.ACTIVITY_STEPS, 'organizer': organizer_data, 'instructors': [], 'score': self.activity.score, 'rating': self.activity.rating, 'is_open': False, } serializer = ActivitiesSerializer(self.activity) self.assertTrue(all(item in serializer.data.items() for item in content.items())) def test_create(self): """ Test the creation of the instance with the serializer """ organizer = OrganizerFactory() data = { 'sub_category': SubCategoryFactory().id, 'organizer': organizer.id, 'title': 'Clase de conducción', 'short_description': 'Clase de conducción', 'level': 'P', 'goals': 'Conducir', 'methodology': 'Por la derecha', 'content': 'Poco la verdad', 'audience': 'Ciegos y ancianos', 'requirements': 'No saber conducir', 'return_policy': 'Ninguna', 'location': LocationFactory().id, } request = mock.MagicMock() request.user = organizer.user activities_counter = Activity.objects.count() serializer = ActivitiesSerializer(data=data, context={'request': request}) serializer.is_valid(raise_exception=True) serializer.save() self.assertEqual(Activity.objects.count(), activities_counter + 1) def test_should_not_update_is_open_if_there_are_calendars(self): """ The serializer should not allow update is_open if there is any calendar """ activity = ActivityFactory() CalendarFactory(activity=activity) data = {'is_open': True} request = mock.MagicMock() request.user = activity.organizer.user serializer = ActivitiesSerializer(activity, data=data, partial=True, context={'request': request}) msg = 'No se puede cambiar el tipo de horario porque existen calendarios relacionados.' with self.assertRaisesMessage(ValidationError, "{'is_open': ['%s']}" % msg): serializer.is_valid(raise_exception=True)
def setUp(self): self.activity = ActivityFactory() self.user = UserFactory()
class SendEmailShareActivityTaskTest(APITestCase): """ Class to test the SendEmailShareActivityTask task """ def setUp(self): self.user = UserFactory() self.activity = ActivityFactory(rating=4) self.calendar = CalendarFactory(activity=self.activity, initial_date=(now() + timedelta(days=5)).date()) self.cover = ActivityPhotoFactory(activity=self.activity, main_photo=True) self.location = LocationFactory(organizer=self.activity.organizer) @mock.patch('utils.tasks.SendEmailTaskMixin.send_mail') def test_success(self, send_mail): """ Test send the email to share the activity when it's success """ emails = [mommy.generators.gen_email() for _ in range(0, 3)] message = 'Hey checa esto!' send_mail.return_value = [{ 'email': e, 'status': 'sent', 'reject_reason': None } for e in emails] task = SendEmailShareActivityTask() task_id = task.delay(user_id=self.user.id, activity_id=self.activity.id, emails=emails, message=message) context = { 'name': self.user.first_name, 'activity': { 'cover_url': self.cover.photo.url, 'title': self.activity.title, 'initial_date': self.activity.closest_calendar().initial_date.isoformat(), }, 'category': { 'color': self.activity.sub_category.category.color, 'name': self.activity.sub_category.category.name, }, 'message': message, 'organizer': { 'name': self.activity.organizer.name, 'city': self.location.city.name, }, 'rating': self.activity.rating, # TODO quitar duration del template - FIXED # 'duration': self.activity.closest_calendar().duration // 3600, 'price': self.activity.closest_calendar().session_price, 'url': '%sactivities/%s/' % (settings.FRONT_SERVER_URL, self.activity.id), } for email in emails: self.assertTrue(EmailTaskRecord.objects.filter( task_id=task_id, to=email, status='sent', data=context, template_name='activities/email/share_activity.html').exists()) @mock.patch('utils.tasks.SendEmailTaskMixin.send_mail') def test_rejected(self, send_mail): """ Test send the email to share the activity when it's rejected """ emails = [mommy.generators.gen_email() for _ in range(0, 3)] message = 'Hey checa esto!' send_mail.return_value = [{ 'email': e, 'status': 'rejected', 'reject_reason': 'invalid-sender' } for e in emails] task = SendEmailShareActivityTask() task_id = task.delay(user_id=self.user.id, activity_id=self.activity.id, emails=emails, message=message) for email in emails: self.assertTrue(EmailTaskRecord.objects.filter( task_id=task_id, to=email, status='rejected', reject_reason='invalid-sender').exists()) @mock.patch('utils.tasks.SendEmailTaskMixin.send_mail') @override_settings(CELERY_EAGER_PROPAGATES_EXCEPTIONS=False) def test_error(self, send_mail): """ Test send the email to share the activity when it's error """ emails = [mommy.generators.gen_email() for _ in range(0, 3)] message = 'Hey checa esto!' send_mail.side_effect = Exception('No subaccount exists with the id customer-123') task = SendEmailShareActivityTask() task_id = task.delay(user_id=self.user.id, activity_id=self.activity.id, emails=emails, message=message) for email in emails: self.assertTrue(EmailTaskRecord.objects.filter( task_id=task_id, to=email, status='error', reject_reason='No subaccount exists with the id customer-123').exists()) @mock.patch('utils.tasks.SendEmailTaskMixin.send_mail') def test_anonymous_user(self, send_mail): """ Test the task if the user is anonymous """ emails = [mommy.generators.gen_email() for _ in range(0, 3)] message = 'Hey checa esto!' send_mail.return_value = [{ 'email': e, 'status': 'sent', 'reject_reason': None } for e in emails] task = SendEmailShareActivityTask() task_id = task.delay(activity_id=self.activity.id, user_name='Harvey', emails=emails, message=message) for email in emails: self.assertTrue(EmailTaskRecord.objects.filter( task_id=task_id, to=email, status='sent', data__name='Harvey', template_name='activities/email/share_activity.html').exists())
def setUp(self): self.organizer = OrganizerFactory() self.activities = ActivityFactory.create_batch( organizer=self.organizer, size=2)
def setUp(self): self.user = UserFactory() self.activity = ActivityFactory(organizer__user=self.user)
def setUp(self): # Calling the super (initialization) super(ReviewAPITest, self).setUp() # Objects needed self.activity = ActivityFactory(organizer=self.organizer, published=True) self.calendar = CalendarFactory( activity=self.activity, initial_date=(now() - timedelta(days=2)).date()) self.order = OrderFactory(student=self.student, calendar=self.calendar, status=Order.ORDER_APPROVED_STATUS) self.post = {'rating': 4, 'comment': 'First comment!'} self.read_review_post = {'rating': 4, 'comment': 'Im a read review!'} self.unread_review_post = { 'rating': 4, 'comment': 'Im an unread review!' } self.put = {'rating': 2, 'reply': 'Thank you!'} self.review = mommy.make(Review, author=self.student, activity=self.activity, **self.post) self.read_review = mommy.make(Review, author=self.student, activity=self.activity, read=True, **self.read_review_post) self.unread_review = mommy.make(Review, author=self.student, activity=self.activity, read=False, **self.unread_review_post) # URLs self.list_by_organizer_url = reverse( 'reviews:list_by_organizer', kwargs={'organizer_pk': self.organizer.id}) self.list_by_student_url = reverse( 'reviews:list_by_student', kwargs={'student_pk': self.student.id}) self.create_url = reverse('reviews:create', kwargs={'activity_pk': self.activity.id}) self.retrieve_update_delete_url = reverse( 'reviews:reply', kwargs={'pk': self.review.id}) self.report_url = reverse('reviews:report', kwargs={'pk': self.review.id}) self.read_url = reverse('reviews:read', kwargs={'pk': self.review.id}) # Counters self.review_count = Review.objects.count() self.activity_reviews = self.activity.reviews.count() # Set permissions add_review = Permission.objects.get_by_natural_key( 'add_review', 'reviews', 'review') add_review.user_set.add(self.student.user, self.another_student.user) change_review = Permission.objects.get_by_natural_key( 'change_review', 'reviews', 'review') change_review.user_set.add(self.organizer.user, self.another_organizer.user) assign_perm('reviews.reply_review', user_or_group=self.organizer.user, obj=self.review) assign_perm('reviews.report_review', user_or_group=self.organizer.user, obj=self.review) assign_perm('reviews.read_review', user_or_group=self.organizer.user, obj=self.review)
class SendEmailLocationTaskTest(APITestCase): def setUp(self): self.activity = ActivityFactory() self.calendar = CalendarFactory(activity=self.activity) self.order = OrderFactory(calendar=self.calendar, status=Order.ORDER_APPROVED_STATUS) self.assistants = AssistantFactory.create_batch(2, order=self.order) @mock.patch('utils.tasks.SendEmailTaskMixin.send_mail') def test_task_dispatch_if_there_is_not_other_task(self, send_mail): send_mail.return_value = [{ 'email': assistant.email, 'status': 'sent', 'reject_reason': None } for assistant in self.assistants] task = SendEmailLocationTask() task_id = task.delay(self.activity.id) context = { 'organizer': self.activity.organizer.name, 'activity': self.activity.title, 'address': self.activity.location.address, 'detail_url': self.activity.get_frontend_url(), } for assistant in self.assistants: data = {**context, 'name': assistant.first_name} self.assertTrue(EmailTaskRecord.objects.filter( task_id=task_id, to=assistant.email, status='sent', data=data, template_name='activities/email/change_location_data.html').exists()) def test_ignore_task_if_there_is_a_pending_task(self): ActivityCeleryTaskEditActivity.objects.create( task_id='05b9d438-821c-4506-9fa5-e958f3af406b', state=states.PENDING, activity=self.activity) task = SendEmailLocationTask() task_id = task.delay(self.activity.id) self.assertEqual(task_id.result, None) for assistant in self.assistants: self.assertFalse(EmailTaskRecord.objects.filter( task_id=task_id, to=assistant.email, status='sent').exists()) @mock.patch('utils.tasks.SendEmailTaskMixin.send_mail') def test_task_should_delete_on_success(self, send_mail): send_mail.return_value = [{ 'email': assistant.email, 'status': 'sent', 'reject_reason': None } for assistant in self.assistants] task = SendEmailLocationTask() task.delay(self.activity.id) self.assertEqual(ActivityCeleryTaskEditActivity.objects.count(), 0) @mock.patch('utils.tasks.SendEmailTaskMixin.send_mail') @override_settings(CELERY_EAGER_PROPAGATES_EXCEPTIONS=False) def test_task_should_update_error_on_failure(self, send_mail): send_mail.side_effect = Exception('This could be a mandrill exception') task = SendEmailLocationTask() task_id = task.delay(self.activity.id) self.assertTrue(ActivityCeleryTaskEditActivity.objects.filter( task_id=task_id, state=states.FAILURE, activity=self.activity).exists())
def setUp(self): self.activity = ActivityFactory() self.calendar = CalendarFactory(activity=self.activity) self.order = OrderFactory(calendar=self.calendar, status=Order.ORDER_APPROVED_STATUS) self.assistants = AssistantFactory.create_batch(2, order=self.order)
def setUp(self): super(OrdersAPITest, self).setUp() # Create Activities objects self.activity = ActivityFactory(organizer=self.organizer, published=True) self.other_activity = ActivityFactory(organizer=self.organizer, published=True) self.active_activity = ActivityFactory(published=True) self.inactive_activity = ActivityFactory() # Create Calendards objects self.calendar = mommy.make(Calendar, activity=self.activity) self.other_calendar = mommy.make(Calendar, activity=self.other_activity) self.free_calendar = mommy.make(Calendar, is_free=True, activity=self.active_activity, available_capacity=10) self.inactive_calendar = mommy.make(Calendar, activity=self.inactive_activity) self.full_calendar = mommy.make(Calendar, activity=self.active_activity, available_capacity=0) self.closed_enroll_calendar = mommy.make(Calendar, activity=self.active_activity, enroll_open=False) # Create Orders objects OrderFactory.create_batch(student=self.student, size=2) OrderFactory.create_batch(calendar=self.calendar, size=2) OrderFactory.create_batch(calendar=self.other_calendar, size=2) self.order = OrderFactory(student=self.student) self.another_other = OrderFactory() # URLs self.orders_by_activity_url = reverse( 'orders:create_or_list_by_activity', kwargs={'activity_pk': self.activity.id}) self.orders_by_student_url = reverse( 'orders:list_by_student', kwargs={'student_pk': self.student.id}) self.orders_by_organizer_url = reverse( 'orders:list_by_organizer', kwargs={'organizer_pk': self.organizer.id}) self.order_retrieve_url = reverse('orders:retrieve', kwargs={'order_pk': self.order.id}) self.another_order_retrieve_url = reverse( 'orders:retrieve', kwargs={'order_pk': self.another_other.id}) self.create_order_url = reverse( 'orders:create_or_list_by_activity', kwargs={'activity_pk': self.active_activity.id}) self.create_inactive_activity_order_url = reverse( 'orders:create_or_list_by_activity', kwargs={'activity_pk': self.inactive_activity.id}) # Set permissions permission = Permission.objects.get_by_natural_key( 'add_order', 'orders', 'order') permission.user_set.add(self.student.user) # counts self.orders_count = Order.objects.all().count() self.student_orders_count = Order.objects.filter( student=self.student).count() self.activity_orders_count = Order.objects.filter( calendar=self.calendar).count() self.organizer_orders_count = Order.objects. \ filter(calendar__activity__organizer=self.organizer).count()