class UpdateEffectiveContractDiscountTests(TestCase): """ Tests the enrollment code creation command. """ def setUp(self): """ Create test data. """ super(UpdateEffectiveContractDiscountTests, self).setUp() # Set up orders with a enterprise_customer self.enterprise_customer_uuid = '123e4567-e89b-12d3-a456-426655440000' self.unit_price = 100 self.condition = ManualEnrollmentOrderDiscountConditionFactory( enterprise_customer_uuid=self.enterprise_customer_uuid ) self.offer = ConditionalOfferFactory(condition=self.condition, id=9999) self.order = OrderFactory() self.order_discount = OrderDiscountFactory(offer_id=self.offer.id, order=self.order) self.line = OrderLineFactory(order=self.order, unit_price_excl_tax=self.unit_price) self.line.save() self.order_discount = OrderDiscountFactory(offer_id=self.offer.id, order=self.order) self.order.save() self.offer.save() self.condition.save() def test_discount_update(self): discount_percentage = 20 call_command( 'update_effective_contract_discount', '--enterprise-customer={}'.format(self.enterprise_customer_uuid), '--discount-percentage={}'.format(discount_percentage) ) assert self.line.order == self.order
def test_check_deprecated_hash_verification(self): order = OrderFactory(number='100001') # Check that check_deprecated_verification_hash validates the hash self.assertTrue( order.check_deprecated_verification_hash('3efd0339e8c789447469f37851cbaaaf') ) # Check that check_verification_hash calls it correctly self.assertTrue(order.check_verification_hash('3efd0339e8c789447469f37851cbaaaf'))
def test_invalid_user(self): """ Verify an unauthorized request is redirected to the LMS dashboard. """ order = OrderFactory() order.user = self.create_user() response = self.client.get(reverse(self.path, args=[order.number])) self.assertEqual(response.status_code, 302) self.assertEqual(response['location'], get_lms_url('dashboard'))
def test_invalid_user(self): """ Verify an unauthorized request is redirected to the LMS dashboard. """ order = OrderFactory() order.user = self.create_user() response = self.client.get(reverse(self.path, args=[order.number])) self.assertEqual(response.status_code, 302) redirect_location = get_lms_url('dashboard') self.assertEqual(response['location'], redirect_location)
def test_num_orders(self): voucherset = VoucherSetFactory() assert voucherset.num_orders == 0 order = OrderFactory() user, order = UserFactory(), OrderFactory() voucher = voucherset.vouchers.first() voucher.record_usage(order, user) assert voucherset.num_orders == 1
def test_migrate_partner(self): """ Test that command successfully add partner to orders.""" initial_count = 4 SiteConfigurationFactory() OrderFactory.create_batch(initial_count, partner=None) self.assertEqual( Order.objects.filter(partner__isnull=True).count(), initial_count) call_command('migrate_partner_to_orders', batch_size=2, sleep_time=1) self.assertEqual(Order.objects.filter(partner__isnull=True).count(), 0)
def setUp(self): # Timestamp in the middle of the time window time_delta = (DEFAULT_START_DELTA_TIME + DEFAULT_END_DELTA_TIME) / 2 self.timestamp = datetime.datetime.now( pytz.utc) - datetime.timedelta(minutes=time_delta) self.payevent = PaymentEventType.objects.get_or_create( name=PaymentEventTypeName.PAID) self.refundevent = PaymentEventType.objects.get_or_create( name=PaymentEventTypeName.REFUNDED) self.order = OrderFactory(total_incl_tax=90, date_placed=self.timestamp) self.order.save()
def setUp(self): # Timestamp in the middle of the time window time_delta = (DEFAULT_START_DELTA_TIME + DEFAULT_END_DELTA_TIME) / 2 self.timestamp = datetime.datetime.now(pytz.utc) - datetime.timedelta(minutes=time_delta) self.payevent, __ = PaymentEventType.objects.get_or_create(name=PaymentEventTypeName.PAID) self.refundevent, __ = PaymentEventType.objects.get_or_create(name=PaymentEventTypeName.REFUNDED) self.seat_product_class, __ = ProductClass.objects.get_or_create(name=SEAT_PRODUCT_CLASS_NAME) self.order = OrderFactory(total_incl_tax=90, date_placed=self.timestamp) self.product = ProductFactory(product_class=self.seat_product_class, categories=None) self.line = OrderLineFactory(order=self.order, product=self.product, partner_sku='test_sku') self.line.save() self.product.save() self.order.save()
def test_generate_coupon_report_for_query_coupon_with_multi_line_order( self): """ Test that coupon report for a query coupon that was used on multi-line order contains ids from all courses in that order. """ course1 = CourseFactory() course2 = CourseFactory() order = OrderFactory(number='TESTORDER') order.lines.add( OrderLineFactory(product=course1.create_or_update_seat( 'verified', False, 101), partner_sku=self.partner_sku)) order.lines.add( OrderLineFactory(product=course2.create_or_update_seat( 'verified', False, 110), partner_sku=self.partner_sku)) query_coupon = self.create_catalog_coupon(catalog_query='*:*') voucher = query_coupon.attr.coupon_vouchers.vouchers.first() voucher.record_usage(order, self.user) field_names, rows = generate_coupon_report( [query_coupon.attr.coupon_vouchers]) expected_redemed_course_ids = '{}, {}'.format(course1.id, course2.id) self.assertEqual(rows[-1]['Redeemed For Course IDs'], expected_redemed_course_ids) self.assertEqual(rows[-1].get('Redeemed For Course ID'), None) self.assertIn('Redeemed For Course ID', field_names) self.assertIn('Redeemed For Course IDs', field_names)
def use_voucher(self, order_num, voucher, user, add_entitlement=False, product=None): """ Mark voucher as used by provided users Args: order_num (string): Order number voucher (Voucher): voucher to be marked as used users (list): list of users """ order = OrderFactory(number=order_num) if add_entitlement: order_line = OrderLineFactory(product=self.entitlement, partner_sku=self.partner_sku) order.lines.add(order_line) product = product if product else self.verified_seat order_line = OrderLineFactory(product=product, partner_sku=self.partner_sku) order.lines.add(order_line) voucher.record_usage(order, user) voucher.offers.first().record_usage(discount={ 'freq': 1, 'discount': 1 })
def test_is_available_to_same_user_multiple_times(self): user, order = UserFactory(), OrderFactory() for i in range(10): self.voucher.record_usage(order, user) is_voucher_available_to_user, __ = self.voucher.is_available_to_user( user=user) self.assertTrue(is_voucher_available_to_user)
def test_offer_availability_with_max_user_discount(self, discount_type, num_prev_orders, is_satisfied): """ Verify that enterprise offer with discount type percentage and absolute, condition returns correct result based on user limits in the offer. """ benefits = { Benefit.PERCENTAGE: factories.EnterprisePercentageDiscountBenefitFactory(value=50), Benefit.FIXED: factories.EnterpriseAbsoluteDiscountBenefitFactory(value=50), } offer = factories.EnterpriseOfferFactory( partner=self.partner, benefit=benefits[discount_type], max_user_discount=100) for _ in range(num_prev_orders): order = OrderFactory(user=self.user, status=ORDER.COMPLETE) OrderDiscountFactory(order=order, offer_id=offer.id, amount=10) basket = BasketFactory(site=self.site, owner=self.user) basket.add_product(self.course_run.seat_products[0]) self.mock_catalog_contains_course_runs( [self.course_run.id], self.condition.enterprise_customer_uuid, self.site.siteconfiguration.enterprise_api_url, enterprise_customer_catalog_uuid=self.condition. enterprise_customer_catalog_uuid, ) self.assertEqual(self.condition.is_satisfied(offer, basket), is_satisfied)
def test_max_user_discount_clean_with_refunded_enrollments(self): """ Verify that `clean` for `max_user_discount` and `max_user_applications` does not raise error when total consumed discount and total max user applications after refund is still less than the value, and the existing offer updates with new per user limit and max user application values. """ current_refund_count = 0 data = self.generate_data(max_user_applications=3, max_user_discount=300) self.mock_specific_enterprise_customer_api( data['enterprise_customer_uuid']) # create an enterprise offer that can provide max $500 discount and consume $400 offer = factories.EnterpriseOfferFactory(max_user_applications=5, max_user_discount=500) for _ in range(4): order = OrderFactory(user=self.user, status=ORDER.COMPLETE) OrderDiscountFactory(order=order, offer_id=offer.id, amount=100) # create a refund of $200 so the total consumed discount becomes $200 if current_refund_count < 2: RefundFactory(order=order, user=self.user, status=REFUND.COMPLETE) current_refund_count += 1 # now try to update the offer with max_user_discount set to $300 # which is still greater than the consumed discount after refund $200 form = EnterpriseOfferForm(request=self.request, data=data, instance=offer) self.assertTrue(form.is_valid()) offer = form.save() self.assertEqual(offer.max_user_applications, data['max_user_applications']) self.assertEqual(offer.max_user_discount, data['max_user_discount'])
def test_shipping_status(self): order = OrderFactory() line_1 = OrderLineFactory(order=order, partner_sku='SKU1234', quantity=2) line_2 = OrderLineFactory(order=order, partner_sku='SKU5678', quantity=1) self.assertEqual(order.shipping_status, '') event_1 = ShippingEventFactory(order=order, event_type__name='Shipped') event_2 = ShippingEventFactory(order=order, event_type__name='Returned') # Default status self.assertEqual(order.shipping_status, _('In progress')) # Set first line to shipped event_1.line_quantities.create(line=line_1, quantity=2) self.assertEqual(order.shipping_status, _('In progress')) # Set first line to returned event_2.line_quantities.create(line=line_1, quantity=2) self.assertEqual(order.shipping_status, _('In progress')) # Set second line to shipped event_1.line_quantities.create(line=line_2, quantity=1) self.assertEqual(order.shipping_status, _('Shipped')) # Set second line to returned event_2.line_quantities.create(line=line_2, quantity=1) self.assertEqual(order.shipping_status, _('Returned'))
def test_clean_history(self): initial_count = 5 OrderFactory.create_batch(initial_count) cutoff_date = now() + datetime.timedelta(days=1) self.assertEqual( Order.history.filter(history_date__lte=cutoff_date).count(), initial_count) QuerySet.delete = counter(QuerySet.delete) call_command('clean_history', '--cutoff_date={}'.format( cutoff_date.strftime('%Y-%m-%d')), batch_size=1, sleep_time=1) self.assertEqual(QuerySet.delete.invocations, initial_count) self.assertEqual( Order.history.filter(history_date__lte=cutoff_date).count(), 0)
def test_threshold(self): """Test verify_transactions only fails if there are too many anomolies""" for i in range(3): # Create some "good" orders w/ payments order = OrderFactory(total_incl_tax=50 + i, date_placed=self.timestamp) line = OrderLineFactory(order=order, product=self.product, partner_sku='test_sku') payment = PaymentEventFactory(order=order, amount=50 + i, event_type_id=self.payevent.id, date_created=self.timestamp) payment.save() line.save() order.save() # self.order fixture should still have no payment with self.assertRaises(CommandError) as cm: call_command('verify_transactions') exception = six.text_type(cm.exception) self.assertIn("The following orders are without payments", exception) self.assertIn(str(self.order.id), exception) try: call_command('verify_transactions', '--threshold=1') # allow 1 anomoly except CommandError as e: self.fail( "Failed to verify transactions when no failure was expected. {}" .format(e)) try: call_command( 'verify_transactions', '--threshold=0.25') # 1-in-4 should be just on the line except CommandError as e: self.fail( "Failed to verify transactions when no failure was expected. {}" .format(e)) with self.assertRaises(CommandError) as cm: call_command('verify_transactions', '--threshold=0.2') exception = six.text_type(cm.exception) self.assertIn("The following orders are without payments", exception) self.assertIn(str(self.order.id), exception)
def test_used_voucher(self): """ Verify voucher_is_valid() assess that the voucher is unavailable. """ voucher, product = prepare_voucher(code=COUPON_CODE) user = self.create_user() order = OrderFactory() VoucherApplication.objects.create(voucher=voucher, user=user, order=order) error_msg = _('This coupon has already been used') self.assert_error_messages(voucher, product, user, error_msg)
def test_used_voucher(self): """Used voucher should not be available.""" voucher, product = prepare_voucher() user = self.create_user() order = OrderFactory() VoucherApplication.objects.create(voucher=voucher, user=user, order=order) error_msg = 'This coupon has already been used' self.assert_error_messages(voucher, product, user, error_msg)
def test_used_voucher(self): """ Verify voucher_is_valid() assess that the voucher is unavailable. """ voucher, product = self.prepare_voucher() order = OrderFactory() user = self.create_user() VoucherApplication.objects.create(voucher=voucher, user=user, order=order) request = RequestFactory().request() valid, msg = voucher_is_valid(voucher=voucher, product=product, request=request) self.assertFalse(valid) self.assertEqual(msg, _('This coupon has already been used'))
def test_successful_response(self): """ Verify a successful response is returned. """ voucher = VoucherFactory(code='ENROLLMENT') order = OrderFactory(user=self.user) line = OrderLineFactory(order=order) order_line_vouchers = OrderLineVouchers.objects.create(line=line) order_line_vouchers.vouchers.add(voucher) response = self.client.get(reverse(self.path, args=[order.number])) self.assertEqual(response.status_code, 200) self.assertEqual(response['content-type'], 'text/csv')
def test_is_available_to_a_user_once(self): user, order = UserFactory(), OrderFactory() is_voucher_available_to_user, __ = self.voucher.is_available_to_user( user=user) self.assertTrue(is_voucher_available_to_user) self.voucher.record_usage(order, user) is_voucher_available_to_user, __ = self.voucher.is_available_to_user( user=user) self.assertFalse(is_voucher_available_to_user)
def test_is_available_to_different_users(self): users, order = [UserFactory(), UserFactory()], OrderFactory() for user in users: is_voucher_available_to_user, __ = self.voucher.is_available_to_user( user=user) self.assertTrue(is_voucher_available_to_user) self.voucher.record_usage(order, user) is_voucher_available_to_user, __ = self.voucher.is_available_to_user( user=user) self.assertFalse(is_voucher_available_to_user)
def test_omitting_already_bought_credit_seat(self): """ Verify a seat that the user bought is omitted from offer page results. """ products, request, voucher = self.prepare_get_offers_response(quantity=2, seat_type='credit') self.mock_eligibility_api(request, self.user, 'a/b/c', eligible=True) offers = VoucherViewSet().get_offers(request=request, voucher=voucher)['results'] self.assertEqual(len(offers), 2) order = OrderFactory(user=self.user) order.lines.add(OrderLineFactory(product=products[0])) offers = VoucherViewSet().get_offers(request=request, voucher=voucher)['results'] self.assertEqual(len(offers), 1)
def test_successful_response(self, product_title): """ Verify a successful response is returned. """ voucher = VoucherFactory() order = OrderFactory(user=self.user) product = ProductFactory(title=product_title, categories=[]) line = OrderLineFactory(order=order, product=product) order_line_vouchers = OrderLineVouchers.objects.create(line=line) order_line_vouchers.vouchers.add(voucher) response = self.client.get(reverse(self.path, args=[order.number])) self.assertEqual(response.status_code, 200) self.assertEqual(response['content-type'], 'text/csv')
def setUp(self): """ Create test data. """ super(UpdateEffectiveContractDiscountTests, self).setUp() # Set up orders with a enterprise_customer self.enterprise_customer_uuid = '123e4567-e89b-12d3-a456-426655440000' self.unit_price = 100 self.condition = ManualEnrollmentOrderDiscountConditionFactory( enterprise_customer_uuid=self.enterprise_customer_uuid ) self.offer = ConditionalOfferFactory(condition=self.condition, id=9999) self.order = OrderFactory() self.order_discount = OrderDiscountFactory(offer_id=self.offer.id, order=self.order) self.line = OrderLineFactory(order=self.order, unit_price_excl_tax=self.unit_price) self.line.save() self.order_discount = OrderDiscountFactory(offer_id=self.offer.id, order=self.order) self.order.save() self.offer.save() self.condition.save()
def test_average_paid_order_costs(self): """ Verify the stats contain average_paid_order_costs. """ password = '******' user = UserFactory(is_staff=True, password=password) self.client.login(username=user.username, password=password) response = self.client.get(reverse('dashboard:index')) actual = response.context['average_paid_order_costs'] self.assertEqual(actual, 0) order = OrderFactory() actual = response.context['average_paid_order_costs'] self.assertEqual(actual, order.total_incl_tax)
def use_voucher(self, voucher, user): """ Mark voucher as used by provided user """ partner = PartnerFactory(short_code='testX') course = CourseFactory(id='course-v1:test-org+course+run', partner=partner) verified_seat = course.create_or_update_seat('verified', False, 100) order = OrderFactory() order_line = OrderLineFactory(product=verified_seat, partner_sku='test_sku') order.lines.add(order_line) voucher.record_usage(order, user) voucher.offers.first().record_usage(discount={'freq': 1, 'discount': 1})
def test_analytics_event_triggered_only_on_first_view(self): order = OrderFactory() session = self.client.session # Put the order ID in the session, mimicking a completed order, # so that we can reach the thank you page. session['checkout_order_id'] = order.pk session.save() r1 = self.client.get(reverse('checkout:thank-you')) self.assertTrue(r1.context['send_analytics_event']) # Request the view a second time r2 = self.client.get(reverse('checkout:thank-you')) self.assertFalse(r2.context['send_analytics_event'])
def test_max_user_discount_clean_with_incorrect_value(self): """ Verify that `clean` for `max_user_discount` field raises correct error for values less than consumed discount. """ expected_errors = { 'max_user_discount': [ 'Ensure new value must be greater than or equal to consumed(400.00) value.' ] } # create an enterprise offer that can provide max $500 discount and has already consumed $400 offer = factories.EnterpriseOfferFactory(max_user_applications=50, max_user_discount=500) for _ in range(4): order = OrderFactory(user=self.user, status=ORDER.COMPLETE) OrderDiscountFactory(order=order, offer_id=offer.id, amount=100) # now try to update the offer with max_discount set to 300 which is less than the already consumed discount data = self.generate_data(max_user_applications=50, max_user_discount=300) self.assert_form_errors(data, expected_errors, instance=offer)
def test_offer_availability_with_max_user_discount_including_refunds( self, discount_type, num_prev_orders, benefit_value, refund_count, is_satisfied): """ Verify that enterprise offer with discount type percentage and absolute, condition returns correct result based on user limits in the offer, even when user has refund history. """ current_refund_count = 0 benefits = { Benefit.PERCENTAGE: factories.EnterprisePercentageDiscountBenefitFactory( value=benefit_value), Benefit.FIXED: factories.EnterpriseAbsoluteDiscountBenefitFactory( value=benefit_value), } offer = factories.EnterpriseOfferFactory( partner=self.partner, benefit=benefits[discount_type], max_user_discount=150) for _ in range(num_prev_orders): order = OrderFactory(user=self.user, status=ORDER.COMPLETE) OrderDiscountFactory(order=order, offer_id=offer.id, amount=10) if current_refund_count < refund_count: RefundFactory(order=order, user=self.user, status=REFUND.COMPLETE) current_refund_count += 1 basket = BasketFactory(site=self.site, owner=self.user) basket.add_product(self.course_run.seat_products[0]) basket.add_product(self.entitlement) self.mock_course_detail_endpoint( discovery_api_url=self.site_configuration.discovery_api_url, course=self.entitlement) self.mock_catalog_contains_course_runs( [self.course_run.id], self.condition.enterprise_customer_uuid, enterprise_customer_catalog_uuid=self.condition. enterprise_customer_catalog_uuid, ) self.assertEqual(self.condition.is_satisfied(offer, basket), is_satisfied)
def test_max_user_applications_clean(self): """ Verify that `clean` for `max_user_applications` field is working as expected. """ num_applications = 3 expected_errors = { 'max_user_applications': [ 'Ensure new value must be greater than or equal to consumed({}) value.'.format(num_applications) ] } # create an enterprise offer that can be used upto 5 times and has already been used 3 times offer = factories.EnterpriseOfferFactory(max_user_applications=5, max_user_discount=500) for _ in range(num_applications): order = OrderFactory(user=self.user, status=ORDER.COMPLETE) OrderDiscountFactory(order=order, offer_id=offer.id, amount=10) # now try to update the offer with max_user_applications set to 2 # which is less than the number of times this offer has already been used data = self.generate_data(max_user_applications=2) self.assert_form_errors(data, expected_errors, instance=offer)
def test_check_deprecated_hash_verification_old_key_matches_new(self): order = OrderFactory(number='100001') # OSCAR_DEPRECATED_ORDER_VERIFY_KEY must not be equal to SECRET_KEY. with self.assertRaises(ImproperlyConfigured): order.check_deprecated_verification_hash('3efd0339e8c789447469f37851cbaaaf')
def test_check_deprecated_hash_verification_without_old_key(self): order = OrderFactory(number='100001') # Check that check_deprecated_verification_hash validates the hash self.assertFalse( order.check_deprecated_verification_hash('3efd0339e8c789447469f37851cbaaaf') )
def test_check_verification_hash_valid_signature_but_wrong_number(self): order = OrderFactory(number='111000') # Hash is valid, but it is for a different order number self.assertFalse(order.check_verification_hash('222000:knvoMB1KAiJu8meWtGce00Y88j4'))
def test_check_verification_hash_invalid_signature(self): order = OrderFactory(number='111000') self.assertFalse(order.check_verification_hash('111000:HKDZWNPLsq7589517c3v1Q6DHKD'))
def test_check_verification_hash_valid(self): order = OrderFactory(number='111000') self.assertTrue(order.check_verification_hash('111000:UJrZWNPLsq7zf1r17c3v1Q6DUmE'))
def test_verification_hash_generation(self): order = OrderFactory(number='111000') self.assertEqual(order.verification_hash(), '111000:UJrZWNPLsq7zf1r17c3v1Q6DUmE')