コード例 #1
0
def test_initial_is_first(request_mock, shippped_count, is_first):
    customer = CustomerFactory()
    for n in range(shippped_count):
        OrderFactory(customer=customer, status=Order.SHIPPED)
    order = OrderFactory(customer=customer)
    handler = OrderProcessing(request_mock, order)
    assert handler.is_first is is_first
コード例 #2
0
def test_remidenrs_if_second_and_next(request_mock):
    first_order = OrderFactory(status=Order.SHIPPED)
    customer = first_order.customer
    OrderFactory(customer=customer, status=Order.SHIPPED)
    order = OrderFactory(customer=customer)
    OrderProcessing(request_mock, order).process()
    assert Reminder.objects.all().count() == 0
コード例 #3
0
def test_next_order_coffee_if_discovery_pack(request_mock):
    order = OrderFactory(discovery_pack=True)
    OrderProcessing(request_mock, order).process()
    new_order = order.customer.orders.exclude(id=order.id).get()
    assert new_order.coffee == order.coffee
    assert (new_order.get_discovery_coffee_ids() !=
            order.get_discovery_coffee_ids())
コード例 #4
0
def test_order_not_recurrent_charge(request_mock, charge_mock, pk,
                                    assert_func):
    order = OrderFactory(id=pk, recurrent=False)
    result = OrderProcessing(request_mock, order).process()
    order.refresh_from_db()
    getattr(charge_mock, assert_func)()
    assert order.status == Order.SHIPPED
    assert 'error' not in result
コード例 #5
0
def test_process_order_by_credits(request_mock, charge_mock):
    order = OrderFactory(recurrent=True, amount=20, customer__amount=25)
    result = OrderProcessing(request_mock, order).process()
    order.refresh_from_db()
    charge_mock.assert_not_called()
    assert order.status == Order.SHIPPED
    assert result['processed_by'] == 'credits'
    assert order.customer.amount == 5
    assert order.amount == 0
コード例 #6
0
def test_process_order_as_present(request_mock, charge_mock):
    order = OrderFactory(recurrent=True,
                         customer__preferences__present_next=True)
    result = OrderProcessing(request_mock, order).process()
    order.refresh_from_db()
    charge_mock.assert_not_called()
    assert order.customer.preferences.present_next is False
    assert result['processed_by'] == 'present'
    assert order.status == Order.SHIPPED
    assert order.amount == 0
コード例 #7
0
def test_process_order_by_charge_unexpected_error(charge_mock, request_mock):
    charge_mock.side_effect = Exception('Error that will never occur ;)')
    order = OrderFactory(recurrent=True)
    result = OrderProcessing(request_mock, order).process()
    order.refresh_from_db()
    charge_mock.assert_called_once()
    assert order.status == Order.ERROR
    assert result.get('processed_by') is None
    assert result['error'] == (
        "Critical Stripe error: Exception(u'Error that will never occur ;)',)")
コード例 #8
0
def test_api_one_coffee_order(charge_mock, admin_json_client):
    order = OrderFactory(id=18052)
    assert order.status == order.ACTIVE
    resp = admin_json_client.post(
        '/manager/api/commands/processOrder/%d' % order.id,
        {'orderType': 'COFFEE'})
    charge_mock.assert_not_called()
    order.refresh_from_db()
    assert order.status == order.SHIPPED
    assert resp.status_code == 200
    assert resp.content.startswith(b'%PDF')
コード例 #9
0
def test_process_order_by_charge(request_mock, charge_mock):
    order = OrderFactory(amount=14.15, recurrent=True)
    result = OrderProcessing(request_mock, order).process()
    order.refresh_from_db()
    charge_mock.assert_called_once_with(amount=1415,
                                        currency='SGD',
                                        customer=order.customer.stripe_id,
                                        description=str(order.coffee),
                                        metadata={'order_id': order.id})
    assert order.status == Order.SHIPPED
    assert result['processed_by'] == 'card'
コード例 #10
0
def test_api_unauthorized(mocker, json_client):
    order = OrderFactory()
    assert order.status == order.ACTIVE
    processing_mock = mocker.patch('manager.utils.OrderProcessing.process')
    resp = json_client.post('/manager/api/commands/processOrder/%d' % order.id,
                            {'orderType': 'COFFEE'})
    processing_mock.assert_not_called()
    order.refresh_from_db()
    assert order.status == order.ACTIVE
    assert resp.status_code == 302
    assert '/manager?next=/' in resp.url
コード例 #11
0
def test_next_order_decaf(request_mock, next_order, expected):
    f_order = OrderFactory(pod_sub_decaf=True, status=Order.SHIPPED)
    customer = f_order.customer
    for _ in range(30):
        order = OrderFactory(customer=customer,
                             different=True,
                             **{next_order: True})
        OrderProcessing(request_mock, order).process()
    assert (customer.orders.filter(
        status=Order.ACTIVE,
        coffee__decaf=True).exclude(id=f_order.id).exists()) is expected
コード例 #12
0
def test_summary_email(request_mock, mailoutbox, shippped, credits, sender,
                       subject, template):
    customer = CustomerFactory(amount=credits)
    for n in range(shippped):
        OrderFactory(customer=customer, status=Order.SHIPPED)
    order = OrderFactory(amount=10, customer=customer)
    OrderProcessing(request_mock, order).process()
    assert len(mailoutbox) == 1
    m = mailoutbox[0]
    assert m.from_email == sender
    assert m.subject == subject
    assert m.template_name == template
コード例 #13
0
def test_api_sub_coffee_order(charge_mock, admin_json_client):
    order = OrderFactory(recurrent=True, amount=14.25)
    assert order.status == order.ACTIVE
    resp = admin_json_client.post(
        '/manager/api/commands/processOrder/%d' % order.id,
        {'orderType': 'COFFEE'})
    charge_mock.assert_called_once_with(amount=1425,
                                        currency='SGD',
                                        customer=order.customer.stripe_id,
                                        description=str(order.coffee),
                                        metadata={'order_id': order.id})
    order.refresh_from_db()
    assert order.status == order.SHIPPED
    assert resp.status_code == 200
    assert resp.content.startswith(b'%PDF')
コード例 #14
0
def test_next_order_processed_by_present(mocker, request_mock):
    order = OrderFactory(recurrent=True,
                         customer__preferences__present_next=True)
    mocker.spy(OrderProcessing, 'create_next_order')
    OrderProcessing(request_mock, order).process()
    assert OrderProcessing.create_next_order.call_count == 1
    assert order.customer.orders.exclude(id=order.id).count() == 1  # new order
コード例 #15
0
def test_order_amount_decrease_after_special_to_usual(request_mock, param):
    order = OrderFactory(**{param: True})
    OrderProcessing(request_mock, order).process()
    new_order = order.customer.orders.exclude(id=order.id).get()
    assert new_order.recurrent is True
    assert new_order.amount < order.amount
    assert new_order.amount == Decimal('14')
コード例 #16
0
def test_shipping_date_exceeding_3_following_days(request_mock, charge_mock):
    now = CTZ.normalize(timezone.now())
    order = OrderFactory(shipping_date=now + timedelta(days=3.1))
    result = OrderProcessing(request_mock, order).process()
    charge_mock.assert_not_called()
    error = 'The order has the shipping date exceeding 3 following days.'
    assert error in result['error']
コード例 #17
0
def test_next_order_diff_coffee_if_special(request_mock, param):
    order = OrderFactory(**{param: True})
    OrderProcessing(request_mock, order).process()
    new_order = order.customer.orders.exclude(id=order.id).get()
    assert new_order.coffee != order.coffee
    assert new_order.coffee.special is False
    assert new_order.coffee.mode is True
コード例 #18
0
def test_next_order_processed_by_credits(mocker, request_mock, credits,
                                         result):
    order = OrderFactory(amount=10, recurrent=True, customer__amount=credits)
    mocker.spy(OrderProcessing, 'create_next_order')
    OrderProcessing(request_mock, order).process()
    assert OrderProcessing.create_next_order.call_count == 1
    assert order.customer.orders.exclude(id=order.id).count() == result
コード例 #19
0
def test_next_order_with_voucher(request_mock, voucher, next_voucher, result):
    order = OrderFactory(amount=14,
                         recurrent=True,
                         voucher=VoucherFactory(name=voucher, discount=20))
    OrderProcessing(request_mock, order).process()
    new_order = order.customer.orders.exclude(id=order.id).get()
    assert new_order.amount == result
    if next_voucher:
        assert new_order.voucher.name == next_voucher
コード例 #20
0
def test_process_order_by_charge_and_credits_declined(request_mock,
                                                      charge_mock):
    charge_mock.side_effect = _raise_card_was_declined
    order = OrderFactory(recurrent=True, amount=20, customer__amount=5)
    result = OrderProcessing(request_mock, order).process()
    order.refresh_from_db()
    order.customer.refresh_from_db()
    charge_mock.assert_called_once_with(amount=1500,
                                        currency='SGD',
                                        customer=order.customer.stripe_id,
                                        description=str(order.coffee),
                                        metadata={'order_id': order.id})
    assert order.status == Order.DECLINED
    assert result.get('processed_by') is None
    # after a declined payment, the amount of credits on customer's account
    # and the order amount needs to be restored to its original value
    assert order.customer.amount == 5
    assert order.amount == 20
コード例 #21
0
def test_grant_points(request_mock, param, key):
    orderPoints = OrderPoints.objects.values().latest('id')
    order = OrderFactory(**{param: True})
    user = order.customer.user
    OrderProcessing(request_mock, order).process()
    user_point = Point.objects.get(user=user)
    log = GrantPointLog.objects.get(user=user)
    assert user_point.points == orderPoints[key]
    assert log.points == orderPoints[key]
コード例 #22
0
def test_process_order_by_charge_declined(charge_mock, request_mock,
                                          mailoutbox):
    charge_mock.side_effect = _raise_card_was_declined
    order = OrderFactory(recurrent=True)
    result = OrderProcessing(request_mock, order).process()
    order.refresh_from_db()
    charge_mock.assert_called_once()
    assert order.status == Order.DECLINED
    assert result.get('processed_by') is None
    assert result['declined'] is True
    assert result['error'] == 'Your card was declined.'

    # check email which sent when card was declined
    assert len(mailoutbox) == 1
    m = mailoutbox[0]
    assert m.subject == OrderProcessing.EMAIL_DECLINED_SUBJECT
    assert m.template_name == OrderProcessing.EMAIL_DECLINED_SUBJECT
    assert m.from_email == 'Hook Coffee <*****@*****.**>'
    assert list(m.to) == [order.customer.user.email]
コード例 #23
0
def test_summary_email_merge_vars(mocker, request_mock, mailoutbox, brew,
                                  package, sent_brew, sent_package):
    dt = datetime(2020, 1, 1, tzinfo=CTZ)
    mocker.patch('django.utils.timezone.now', return_value=dt)
    order = OrderFactory(amount=18,
                         date=dt,
                         shipping_date=dt,
                         brew=BrewMethodFactory(name=brew),
                         package=package)
    order.coffee.roasted_on = dt
    OrderProcessing(request_mock, order).process()
    assert len(mailoutbox) == 1
    m = mailoutbox[0]
    assert m.from_email == OrderProcessing.EMAIL_SUMMARY_FROM_FIRST_BAG
    assert list(m.to) == [order.customer.user.email]
    assert m.merge_vars == {
        order.customer.user.email: {
            'COFFEE':
            order.coffee.name,
            'ROASTED_ON':
            datetime.strftime(order.coffee.roasted_on, '%d/%m/%y'),
            'BREW':
            sent_brew,
            'PACKAGE':
            sent_package,
            'PRICE':
            'S$ %d' % order.amount,
            'SHIPPING_DATE':
            '%s %s' % (ordinal(order.shipping_date.day),
                       datetime.strftime(order.shipping_date, '%B %Y')),
            'ADDRESS_NAME':
            order.shipping_address['name'],
            'LINE1':
            order.shipping_address['line1'],
            'COUNTRY_POSTCODE':
            order.shipping_address['postcode'],
            'NEXT_DELIVERY':
            datetime.strftime(
                order.shipping_date + timedelta(days=order.interval),
                '%d %B %Y'),
            'POINTS':
            50,
            'TOTAL_POINTS':
            50,
            'ESTIMATED_DELIVERY':
            get_estimated_date(order.shipping_date),
            'REFERRAL_CODE':
            order.customer.user.referral_set.get().code,
            'DOMAIN_NAME':
            'testserver',
            'USERNAME':
            order.customer.first_name,
        }
    }
コード例 #24
0
def test_next_order_shipping_date(mocker, request_mock, interval, date):
    dt = datetime(2000, 1, 1, tzinfo=CTZ)  # Saturday
    order = OrderFactory(interval=interval,
                         recurrent=True,
                         different=True,
                         date=dt,
                         shipping_date=dt)
    mocker.patch('django.utils.timezone.now', return_value=dt)
    OrderProcessing(request_mock, order).process()
    new_order = order.customer.orders.exclude(id=order.id).get()
    assert new_order.shipping_date.date() == date
コード例 #25
0
def test_next_order_same_params(request_mock):
    order = OrderFactory(interval=8, recurrent=True, different=False)
    OrderProcessing(request_mock, order).process()
    new_order = order.customer.orders.exclude(id=order.id).get()
    assert new_order.status == Order.ACTIVE
    attrs = [
        'coffee', 'amount', 'customer', 'recurrent', 'brew', 'package',
        'different', 'interval'
    ]
    for attr in attrs:
        assert getattr(new_order, attr) == getattr(order, attr)
コード例 #26
0
def test_api_sub_coffee_order_declined(charge_mock, admin_json_client):
    charge_mock.side_effect = _raise_card_was_declined
    order = OrderFactory(recurrent=True, amount=14.25)
    assert order.status == order.ACTIVE
    resp = admin_json_client.post(
        '/manager/api/commands/processOrder/%d' % order.id,
        {'orderType': 'COFFEE'})
    charge_mock.assert_called_once_with(amount=1425,
                                        currency='SGD',
                                        customer=order.customer.stripe_id,
                                        description=str(order.coffee),
                                        metadata={'order_id': order.id})
    order.refresh_from_db()
    assert order.status == Order.DECLINED
    assert resp.status_code == 402
    error = ('An error occurred while processing the order!\n\n'
             'Order: {pk}\nUsername/Email: {name}\nAccount number: {acc}\n'
             'Error: {err}').format(pk=order.pk,
                                    name=order.customer,
                                    acc=order.customer.stripe_id,
                                    err='Your card was declined.')
    assert resp.json() == {'error': error}
コード例 #27
0
def test_remidenrs_if_first(mocker, request_mock):
    dt = datetime(2020, 1, 1, tzinfo=CTZ)
    mocker.patch('django.utils.timezone.now', return_value=dt)
    order = OrderFactory()
    customer = order.customer
    OrderProcessing(request_mock, order).process()
    reminder = Reminder.objects.get()
    assert reminder.username == customer.first_name.upper()
    assert reminder.email == customer.user.email
    assert reminder.from_email == 'Faye from Hook Coffee <*****@*****.**>'
    assert reminder.subject == 'Welcome to Hook Rewards'
    assert reminder.template_name == 'O3 - Welcome to Hook Rewards (done)'
    assert reminder.scheduled == dt + timedelta(days=5)
コード例 #28
0
def test_concurrent_order_processing(rf, admin_user):
    order = OrderFactory(recurrent=True)
    pool = Pool(processes=2, initializer=_pool_init, initargs=[Lock()])
    responses = pool.map(_run_concurrent_order_processing, [
        (rf, admin_user, order),
        (rf, admin_user, order),
    ])
    pool.close()
    pool.join()
    error = json.loads(responses[1].content)['error']
    assert 'The order is already processed!' in error
    assert order.customer.orders.filter(status=Order.SHIPPED).count() == 1
    assert order.customer.orders.filter(status=Order.ACTIVE).count() == 1
コード例 #29
0
def test_api_sub_coffee_order_unexpected_error(charge_mock, admin_json_client):
    charge_mock.side_effect = Exception('Error that will never occur ;)')
    order = OrderFactory(recurrent=True, amount=14.25)
    assert order.status == order.ACTIVE
    resp = admin_json_client.post(
        '/manager/api/commands/processOrder/%d' % order.id,
        {'orderType': 'COFFEE'})
    charge_mock.assert_called_once_with(amount=1425,
                                        currency='SGD',
                                        customer=order.customer.stripe_id,
                                        description=str(order.coffee),
                                        metadata={'order_id': order.id})
    order.refresh_from_db()
    assert order.status == Order.ERROR
    assert resp.status_code == 406
    error = ('An error occurred while processing the order!\n\n'
             'Order: {pk}\nUsername/Email: {name}\nAccount number: {acc}\n'
             'Error: {err}').format(
                 pk=order.pk,
                 name=order.customer,
                 acc=order.customer.stripe_id,
                 err=("Critical Stripe error: "
                      "Exception(u'Error that will never occur ;)',)"))
    assert resp.json() == {'error': error}
コード例 #30
0
def test_summary_email_if_resent(request_mock, mailoutbox):
    order = OrderFactory(resent=True)
    OrderProcessing(request_mock, order).process()
    assert len(mailoutbox) == 0