예제 #1
0
    def test_calculate_balance(self):
        available_calendar = CalendarFactory(
            activity__organizer=self.organizer)
        available_orders = OrderFactory.create_batch(
            size=3,
            calendar=available_calendar,
            status='approved',
            fee=0,
            amount=factory.Iterator([20000, 30000]))

        unavailable_calendar = CalendarFactory(
            activity__organizer=self.organizer)
        unavailable_orders = OrderFactory.create_batch(
            size=4,
            calendar=unavailable_calendar,
            status='approved',
            fee=0,
            amount=factory.Iterator([20000, 30000]))

        status = [*['available'] * 3, *['unavailable'] * 4]

        BalanceLogFactory.create_batch(
            size=7,
            order=factory.Iterator([*available_orders, *unavailable_orders]),
            organizer=self.organizer,
            status=factory.Iterator(status))

        task = CalculateOrganizerBalanceTask()
        task.delay(organizer_ids=[self.organizer.id])

        balance = Balance.objects.get(id=self.organizer.balance.id)
        self.assertEqual(balance.available, 70000)
        self.assertEqual(balance.unavailable, 100000)
예제 #2
0
    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})
예제 #3
0
    def setUp(self):
        super(ReferrerCouponTaskTest, self).setUp()

        # Arrangement
        self.referral = mommy.make(Referral,
                                   referrer=self.student,
                                   referred=self.another_student)
        self.calendar = CalendarFactory(activity__published=True,
                                        available_capacity=10)
        self.coupon_type = mommy.make(CouponType, name='referrer')
        self.order = mommy.make(Order,
                                student=self.another_student,
                                status=Order.ORDER_APPROVED_STATUS,
                                calendar=self.calendar)
예제 #4
0
 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)
예제 #5
0
    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)
예제 #6
0
    def test_create_other_package_in_update(self):
        """
        If the serializer receive one more package in the update method
        the package should be created
        """
        calendar = CalendarFactory(activity__is_open=True)
        packages = CalendarPackageFactory.create_batch(2, calendar=calendar)

        data = {
            'packages':[{
                'id': p.id,
                'quantity': p.quantity,
                'price': p.price,
            } for p in packages]
        }

        # The new package
        data['packages'].append({
            'quantity': 16,
            'price': 183740,
            'type': 1,
        })

        packages_counter = CalendarPackage.objects.count()

        serializer = CalendarSerializer(calendar, data=data, partial=True)
        self.assertTrue(serializer.is_valid(raise_exception=True))
        serializer.save()
        self.assertEqual(CalendarPackage.objects.count(), packages_counter + 1)
예제 #7
0
    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)
예제 #8
0
 def setUp(self):
     self.organizer = OrganizerFactory()
     self.student = StudentFactory()
     self.calendar = CalendarFactory(activity__organizer=self.organizer)
     self.organizer_message = OrganizerMessageFactory(
         calendar=self.calendar)
     self.assistants = AssistantFactory.create_batch(
         size=3,
         order__calendar=self.calendar,
         order__student=self.student,
         order__status=Order.ORDER_APPROVED_STATUS,
         enrolled=True)
예제 #9
0
    def setUp(self):
        super(OrdersSerializerTest, self).setUp()

        # Arrangement
        self.referral = mommy.make(Referral,
                                   referrer=self.student,
                                   referred=self.another_student)
        self.coupon_type = mommy.make(CouponType, name='referrer')
        self.calendar = CalendarFactory(activity__published=True,
                                        available_capacity=10)
        self.data = self.get_data()
        self.context = self.get_context()
예제 #10
0
 def setUp(self):
     super(ListAndCreateOrganizerMessageViewTest, self).setUp()
     self.url = reverse('messages:list_and_create')
     self.calendar = CalendarFactory(activity__organizer=self.organizer)
     self.orders = OrderFactory.create_batch(3, calendar=self.calendar,
                                             status=Order.ORDER_APPROVED_STATUS)
     self.organizer_messages = OrganizerMessageFactory.create_batch(3, organizer=self.organizer,
                                                                    calendar=self.calendar)
     self.organizer_message_relation = OrganizerMessageStudentRelationFactory(
         organizer_message=self.organizer_messages[0],
         student=self.student,
     )
예제 #11
0
    def test_balance_not_yet_available(self):
        calendar = CalendarFactory(activity__organizer=self.organizer,
                                   initial_date=now().date())
        order = OrderFactory(calendar=calendar)
        balance_log = BalanceLogFactory(organizer=self.organizer, order=order)

        task = BalanceLogToAvailableTask()
        result = task.delay()

        self.assertEqual(
            BalanceLog.objects.get(id=balance_log.id).status, 'unavailable')
        self.assertEqual(result.result, [])
예제 #12
0
    def test_balance_log_available(self):
        last_week = (now() - timedelta(days=5)).date()
        calendar = CalendarFactory(activity__organizer=self.organizer,
                                   initial_date=last_week)
        order = OrderFactory(calendar=calendar)
        balance_log = BalanceLogFactory(organizer=self.organizer, order=order)

        task = BalanceLogToAvailableTask()
        result = task.delay()

        self.assertEqual(
            BalanceLog.objects.get(id=balance_log.id).status, 'available')
        self.assertEqual(result.result, [self.organizer.id])
예제 #13
0
    def setUp(self):
        self.organizer = OrganizerFactory()
        self.calendar = CalendarFactory(activity__organizer=self.organizer)
        self.organizer_message = OrganizerMessageFactory(
            calendar=self.calendar)
        self.orders = OrderFactory.create_batch(
            size=3, calendar=self.calendar, status=Order.ORDER_APPROVED_STATUS)

        self.assistants = []
        for order in self.orders:
            self.assistants.append(
                AssistantFactory(order=order,
                                 email=order.student.user.email,
                                 enrolled=True))
예제 #14
0
    def create_calendars(self):
        self.stdout.write('Creando calendars')
        calendars = list()
        for activity in self.activities:
            quantity = self.get_quantity()
            calendars.append(
                CalendarFactory.create_batch(
                    quantity,
                    activity=activity,
                    enroll_open=factory.Faker('boolean'),
                    is_weekend=factory.Faker('boolean'),
                    is_free=factory.Faker('boolean',
                                          chance_of_getting_true=20)))

        return self.flat_list(calendars)
예제 #15
0
    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)
예제 #16
0
    def test_free_activity_fee(self):
        """
        Test no fee in the order because is a free activity
        """

        # Arrangement
        calendar = CalendarFactory(activity__published=True,
                                   is_free=True,
                                   available_capacity=10)
        self.data['calendar'] = calendar.id

        serializer = OrdersSerializer(data=self.data)
        serializer.context = self.context
        serializer.is_valid(raise_exception=True)
        order = serializer.save()

        self.assertEqual(order.fee, 0)
예제 #17
0
    def setUp(self):
        super(PaymentWebHookTest, self).setUp()

        # Arrangement
        self.calendar = CalendarFactory(activity__published=True,
                                        available_capacity=10)
        self.payment = mommy.make(Payment,
                                  payment_type=Payment.CC_PAYMENT_TYPE)
        self.order = mommy.make(Order,
                                calendar=self.calendar,
                                student=self.another_student,
                                payment=self.payment)
        self.referral = mommy.make(Referral,
                                   referrer=self.student,
                                   referred=self.another_student)
        self.coupon_type = mommy.make(CouponType, name='referrer')

        # URLs
        self.payu_callback_url = reverse('payments:notification')
예제 #18
0
    def setUp(self):
        super(PaymentCreditCardWithCouponTest, self).setUp()

        # Objects
        self.calendar = CalendarFactory(session_price=100000.0,
                                        available_capacity=20,
                                        activity__published=True)
        self.redeem = mommy.make(Redeem,
                                 student=self.student,
                                 coupon__coupon_type__amount=50000)
        self.payment = mommy.make(Payment)
        self.post_data = self.get_post_data()

        # URLs
        self.create_read_url = reverse(
            'orders:create_or_list_by_activity',
            kwargs={'activity_pk': self.calendar.activity.id})

        # Set permissions
        permission = Permission.objects.get_by_natural_key(
            'add_order', 'orders', 'order')
        permission.user_set.add(self.student.user)
        permission.user_set.add(self.another_student.user)
예제 #19
0
    def setUp(self):
        super(PaymentWebHookWithCouponTest, self).setUp()

        # Objects
        self.calendar = CalendarFactory(session_price=100000.0,
                                        available_capacity=20,
                                        activity__published=True)
        self.redeem = mommy.make(Redeem,
                                 student=self.student,
                                 coupon__coupon_type__amount=50000)
        self.payment = mommy.make(Payment,
                                  payment_type=Payment.CC_PAYMENT_TYPE)
        self.order = mommy.make(Order,
                                status=Order.ORDER_PENDING_STATUS,
                                payment=self.payment,
                                coupon=self.redeem.coupon,
                                calendar=self.calendar,
                                student=self.student)
        self.assistants = AssistantFactory.create_batch(3, order=self.order)

        self.post_data = self.get_post_data()

        # URLs
        self.payu_callback_url = reverse('payments:notification')
예제 #20
0
class ReferrerCouponTaskTest(BaseAPITestCase):
    """
    Class to test ReferrerCouponTask
    """
    def setUp(self):
        super(ReferrerCouponTaskTest, self).setUp()

        # Arrangement
        self.referral = mommy.make(Referral,
                                   referrer=self.student,
                                   referred=self.another_student)
        self.calendar = CalendarFactory(activity__published=True,
                                        available_capacity=10)
        self.coupon_type = mommy.make(CouponType, name='referrer')
        self.order = mommy.make(Order,
                                student=self.another_student,
                                status=Order.ORDER_APPROVED_STATUS,
                                calendar=self.calendar)

    @mock.patch('referrals.tasks.SendCouponEmailTask.delay')
    def test_create(self, delay):
        """
        Test create a referrer coupon
        """

        # Counter
        coupon_counter = Coupon.objects.count()
        redeem_counter = Redeem.objects.count()

        # Call the task
        task = ReferrerCouponTask()
        task.delay(student_id=self.another_student.id, order_id=self.order.id)

        self.assertEqual(Coupon.objects.count(), coupon_counter + 1)
        self.assertEqual(Redeem.objects.count(), redeem_counter + 1)
        self.assertTrue(
            Redeem.objects.filter(
                student=self.student,
                coupon__coupon_type=self.coupon_type).exists())

    def test_with_an_payed_activity(self):
        """
        Test case when shouldn't create a referrer coupon
        because the student already has a payed activity
        """

        # Arrangement
        OrderFactory(student=self.another_student)

        # Counter
        coupon_counter = Coupon.objects.count()
        redeem_counter = Redeem.objects.count()

        # Call the task
        task = ReferrerCouponTask()
        task.delay(student_id=self.another_student.id, order_id=self.order.id)

        self.assertEqual(Coupon.objects.count(), coupon_counter)
        self.assertEqual(Redeem.objects.count(), redeem_counter)
        self.assertFalse(
            Redeem.objects.filter(
                student=self.student,
                coupon__coupon_type=self.coupon_type).exists())

    @mock.patch('referrals.tasks.SendCouponEmailTask.delay')
    def test_having_an_free_activity(self, delay):
        """
        Test case should create the coupon
        because the student has a free activity
        """

        # Arrangement
        OrderFactory(student=self.another_student, calendar__is_free=True)

        # Counter
        coupon_counter = Coupon.objects.count()
        redeem_counter = Redeem.objects.count()

        # Call the task
        task = ReferrerCouponTask()
        task.delay(student_id=self.another_student.id, order_id=self.order.id)

        self.assertEqual(Coupon.objects.count(), coupon_counter + 1)
        self.assertTrue(
            Coupon.objects.filter(coupon_type=self.coupon_type).exists())
        self.assertEqual(Redeem.objects.count(), redeem_counter + 1)
        self.assertTrue(
            Redeem.objects.filter(
                student=self.student,
                coupon__coupon_type=self.coupon_type).exists())

    def test_enrolling_to_a_free_activity(self):
        """
        Test case shouldn't create a coupon
        because is a free activity
        """

        # Arrangement
        self.calendar.is_free = True
        self.calendar.save(update_fields=['is_free'])

        # Counter
        coupon_counter = Coupon.objects.count()
        redeem_counter = Redeem.objects.count()

        # Call the task
        task = ReferrerCouponTask()
        task.delay(student_id=self.another_student.id, order_id=self.order.id)

        self.assertEqual(Coupon.objects.count(), coupon_counter)
        self.assertEqual(Redeem.objects.count(), redeem_counter)
        self.assertFalse(
            Redeem.objects.filter(
                student=self.student,
                coupon__coupon_type=self.coupon_type).exists())

    def test_without_referral(self):
        """
        Test shouldn't create the coupon because it doesn't have a referral
        """

        # Arrangement
        self.referral.delete()

        # Counter
        coupon_counter = Coupon.objects.count()
        redeem_counter = Redeem.objects.count()

        # Call the task
        task = ReferrerCouponTask()
        task.delay(student_id=self.another_student.id, order_id=self.order.id)

        self.assertEqual(Coupon.objects.count(), coupon_counter)
        self.assertEqual(Redeem.objects.count(), redeem_counter)
        self.assertFalse(
            Redeem.objects.filter(
                student=self.student,
                coupon__coupon_type=self.coupon_type).exists())

    def test_with_declined_order(self):
        """
        Test shouldn't create the coupon because the order was declined
        """

        # Arrangement
        self.order.status = Order.ORDER_DECLINED_STATUS
        self.order.save(update_fields=['status'])

        # Counter
        coupon_counter = Coupon.objects.count()
        redeem_counter = Redeem.objects.count()

        # Call the task
        task = ReferrerCouponTask()
        task.delay(student_id=self.another_student.id, order_id=self.order.id)

        self.assertEqual(Coupon.objects.count(), coupon_counter)
        self.assertEqual(Redeem.objects.count(), redeem_counter)
        self.assertFalse(
            Redeem.objects.filter(
                student=self.student,
                coupon__coupon_type=self.coupon_type).exists())

    def test_with_pending_order(self):
        """
        Test should't create the coupon because the order isn't approved yet
        """

        # Arrangement
        self.calendar.is_free = True
        self.calendar.save(update_fields=['is_free'])

        # Counter
        coupon_counter = Coupon.objects.count()
        redeem_counter = Redeem.objects.count()

        # Call the task
        task = ReferrerCouponTask()
        task.delay(student_id=self.another_student.id, order_id=self.order.id)

        self.assertEqual(Coupon.objects.count(), coupon_counter)
        self.assertEqual(Redeem.objects.count(), redeem_counter)
        self.assertFalse(
            Redeem.objects.filter(
                student=self.student,
                coupon__coupon_type=self.coupon_type).exists())
예제 #21
0
class CalendarSerializerTest(APITestCase):
    """
    Test cases for CalendarSerializer
    """

    def setUp(self):
        self.calendar = CalendarFactory(session_price=100000)
        self.order = mommy.make(Order, status=Order.ORDER_APPROVED_STATUS, calendar=self.calendar,
                                quantity=3)
        self.assistants = mommy.make(Assistant, order=self.order, _quantity=2)

    def test_read(self):
        """
        Test the serialize data
        """
        epoch = UnixEpochDateField()

        mommy.make(Assistant, order=self.order, enrolled=False)
        package = CalendarPackageFactory(calendar=self.calendar, type=1)
        serializer = CalendarSerializer(self.calendar)

        content = {
            'id': self.calendar.id,
            'activity': self.calendar.activity.id,
            'initial_date': epoch.to_representation(self.calendar.initial_date),
            'enroll_open': True,
            'session_price': self.calendar.session_price,
            'schedules': '<p><strong>Lunes - Viernes</strong></p><p>6:00pm - 9:00pm</p>',
            'assistants': AssistantsSerializer(self.calendar.get_assistants(), many=True,
                                               remove_fields=['student']).data,
            'is_weekend': self.calendar.is_weekend,
            'is_free': self.calendar.is_free,
            'available_capacity': self.calendar.available_capacity,
            'packages': [{
                'id': package.id,
                'quantity': package.quantity,
                'price': package.price,
                'type': 1,
                'type_name': 'Mes(es)',
            }],

        }
        self.assertTrue(all(item in serializer.data.items() for item in content.items()))

    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_update(self):
        """
        The serializer should update the data even the packages data
        """
        package = CalendarPackageFactory(calendar=self.calendar, price=100000, quantity=4)

        data = {
            'session_price': 500000,
            'packages': [{
                'id': package.id,
                'quantity': 6,
            }]
        }

        serializer = CalendarSerializer(self.calendar, data=data, partial=True)
        self.assertTrue(serializer.is_valid(raise_exception=True))
        serializer.save()
        calendar = Calendar.objects.get(id=self.calendar.id)
        package = CalendarPackage.objects.get(id=package.id)
        self.assertEqual(calendar.session_price, 500000)
        self.assertEqual(package.quantity, 6)

    def test_create_other_package_in_update(self):
        """
        If the serializer receive one more package in the update method
        the package should be created
        """
        calendar = CalendarFactory(activity__is_open=True)
        packages = CalendarPackageFactory.create_batch(2, calendar=calendar)

        data = {
            'packages':[{
                'id': p.id,
                'quantity': p.quantity,
                'price': p.price,
            } for p in packages]
        }

        # The new package
        data['packages'].append({
            'quantity': 16,
            'price': 183740,
            'type': 1,
        })

        packages_counter = CalendarPackage.objects.count()

        serializer = CalendarSerializer(calendar, data=data, partial=True)
        self.assertTrue(serializer.is_valid(raise_exception=True))
        serializer.save()
        self.assertEqual(CalendarPackage.objects.count(), packages_counter + 1)

    def test_should_not_update_schedule_if_there_are_orders(self):
        """
        The serializer shouldn't allow to update the schedules field
        if there are orders associated to the calendar
        """
        data = {'schedules': '<p>No Schedule!</p>'}
        msg = 'No se puede cambiar el horario debido a que existen ordenes relacionadas.'
        serializer = CalendarSerializer(self.calendar, data=data, partial=True)
        with self.assertRaisesMessage(ValidationError, "{'schedules': ['%s']}" % msg):
            serializer.is_valid(raise_exception=True)

    def test_if_activity_is_closed_session_price_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=False)
        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, "{'session_price': ['Este campo es"
                                                       " requerido.']}"):
            serializer.is_valid(raise_exception=True)

    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 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)
예제 #22
0
    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)
예제 #23
0
 def setUp(self):
     self.calendar = CalendarFactory(available_capacity=10)
     self.orders = self.create_orders()
     self.assistants = self.create_assistants()
예제 #24
0
class CalendarTestCase(APITestCase):
    """
    Class to test the model Calendar
    """
    def setUp(self):
        self.calendar = CalendarFactory(available_capacity=10)
        self.orders = self.create_orders()
        self.assistants = self.create_assistants()

    def create_orders(self):
        statuses = [
            Order.ORDER_APPROVED_STATUS, Order.ORDER_PENDING_STATUS,
            Order.ORDER_DECLINED_STATUS, Order.ORDER_CANCELLED_STATUS
        ]
        orders = mommy.make(Order,
                            calendar=self.calendar,
                            status=cycle(statuses),
                            quantity=4,
                            _quantity=4)
        return orders

    def create_assistants(self):
        enrolled = [True, False]
        return mommy.make(Assistant,
                          order=cycle(self.orders),
                          enrolled=cycle(enrolled),
                          _quantity=16)

    def test_available_capacity(self):
        """
        Test the available capacity property
        """

        # Capacity = 10
        # Num enrolled assistants  = 4
        # Available capacity = 10 - 4 = 6

        self.assertEqual(self.calendar.available_capacity, 6)

        # Capacity = 10
        # Num enrolled assistants  = 4
        # Available capacity = 10 - 4 = 6
        # Cancel assistant
        # Num enrolled assistants  = 4 - 1 = 3
        # Available capacity = 10 - 3  = 7

        approved_order = self.orders[0]
        assistants = approved_order.assistants.all()
        first_assistant = assistants[0]
        first_assistant.enrolled = False
        first_assistant.save()

        self.assertEqual(self.calendar.available_capacity, 7)

        # Capacity = 10
        # Num enrolled assistants  = 4
        # Available capacity = 10 - 4 = 6
        # Cancel assistant
        # Num enrolled assistants  = 4 - 1 = 3
        # Available capacity = 10 - 3  = 7
        # Cancel order
        # Num enrolled assistants  = 3 - 3 = 0
        # Available capacity = 10 - 0  = 10

        approved_order.change_status(Order.ORDER_CANCELLED_STATUS)

        self.assertEqual(self.calendar.available_capacity, 10)

        # Capacity = 10
        # Num enrolled assistants  = 4
        # Available capacity = 10 - 4 = 6
        # Cancel assistant
        # Num enrolled assistants  = 4 - 1 = 3
        # Available capacity = 10 - 3  = 7
        # Cancel order
        # Num enrolled assistants  = 3 - 3 = 0
        # Available capacity = 10 - 0  = 10
        # Approve order
        # Num enrolled assistants  = 0 + 3 = 0
        # Available capacity = 10 - 3  = 7
        approved_order.change_status(Order.ORDER_APPROVED_STATUS)

        self.assertEqual(self.calendar.available_capacity, 7)

    def test_permissions(self):
        """
        When an instance is created should set the permissions
        """

        user = self.calendar.activity.organizer.user

        self.assertTrue(
            user.has_perm('activities.change_calendar', self.calendar))
        self.assertTrue(
            user.has_perm('activities.delete_calendar', self.calendar))

    def test_get_assistants(self):
        """
        Test the method get_assistants
        """

        assistants = Assistant.objects.filter(order__calendar=self.calendar,
                                              order__status__in=[
                                                  Order.ORDER_APPROVED_STATUS,
                                                  Order.ORDER_PENDING_STATUS
                                              ],
                                              enrolled=True)
        self.assertEqual(self.calendar.get_assistants(), list(assistants))
예제 #25
0
 def setUp(self):
     self.calendar = CalendarFactory(session_price=100000)
     self.order = mommy.make(Order, status=Order.ORDER_APPROVED_STATUS, calendar=self.calendar,
                             quantity=3)
     self.assistants = mommy.make(Assistant, order=self.order, _quantity=2)
예제 #26
0
 def setUp(self):
     self.calendar = CalendarFactory()
     self.order = OrderFactory(calendar=self.calendar, status='approved')
예제 #27
0
 def setUp(self):
     self.calendar = CalendarFactory()
     self.order = OrderFactory(calendar=self.calendar, status=Order.ORDER_APPROVED_STATUS)
     self.assistants = AssistantFactory.create_batch(2, order=self.order)
예제 #28
0
 def setUp(self):
     self.organizer = OrganizerFactory()
     self.students = StudentFactory.create_batch(2)
     self.calendar = CalendarFactory(activity__organizer=self.organizer)