Beispiel #1
0
    def test_no_transaction_settle_with_only_related_proforma(self):
        proforma = ProformaFactory.create(related_document=None)

        customer = proforma.customer
        PaymentMethodFactory.create(
            payment_processor=triggered_processor, customer=customer,
            canceled=False,
            verified=True,
        )

        proforma.issue()

        transaction = proforma.transactions[0]
        # here transaction.proforma is the same object as the proforma from the
        # DB due to the way transition callbacks and saves are called

        transaction.settle()

        self.assertEqual(proforma.state, proforma.STATES.PAID)

        invoice = proforma.related_document
        self.assertEqual(invoice.state, invoice.STATES.PAID)

        self.assertEqual(list(proforma.transactions),
                         list(invoice.transactions))

        self.assertEqual(len(proforma.transactions), 1)
    def test_get_listing(self):
        PaymentMethodFactory.create(customer=CustomerFactory.create())
        payment_method = self.create_payment_method(customer=self.customer)

        url = reverse('payment-method-list',
                      kwargs={'customer_pk': self.customer.pk})

        self.assert_get_data(url, [payment_method])
Beispiel #3
0
    def test_get_detail(self):
        PaymentMethodFactory.create(customer=CustomerFactory.create())
        payment_method = self.create_payment_method(customer=self.customer)

        url = reverse('payment-method-detail', kwargs={
            'customer_pk': self.customer.pk,
            'payment_method_id': payment_method.pk
        })

        self.assert_get_data(url, payment_method)
Beispiel #4
0
    def test_patch_transaction_not_allowed_fields(self):
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor)
        customer = payment_method.customer
        transaction = TransactionFactory.create(payment_method=payment_method)

        proforma = ProformaFactory.create(state='issued', customer=customer)
        invoice = InvoiceFactory.create(state='issued',
                                        customer=customer,
                                        related_document=proforma)
        proforma.related_document = invoice
        proforma.save()

        invoice_url = reverse('invoice-detail', args=[invoice.pk])
        proforma_url = reverse('proforma-detail', args=[proforma.pk])
        url = reverse('transaction-detail',
                      args=[transaction.customer.pk, transaction.uuid])

        new_payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor, customer=customer)

        new_payment_method_url = reverse('payment-method-detail',
                                         kwargs={
                                             'customer_pk':
                                             new_payment_method.customer.pk,
                                             'payment_method_id':
                                             new_payment_method.pk
                                         })

        data = {
            'proforma': proforma_url,
            'invoice': invoice_url,
            'currency': 'EUR',
            'amount': 1234,
            'payment_method': new_payment_method_url
        }

        response = self.client.patch(url, format='json', data=data)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        self.assertEqual(
            response.data, {
                'proforma': [u'This field may not be modified.'],
                'invoice': [u'This field may not be modified.'],
                'currency': [u'This field may not be modified.'],
                'amount': [u'This field may not be modified.'],
                'payment_method': [u'This field may not be modified.']
            })
Beispiel #5
0
    def test_documents_list_case_1(self):
        """
            One proforma, one invoice, without related documents
        """
        proforma = ProformaFactory.create()
        invoice_entries = DocumentEntryFactory.create_batch(3)
        invoice = InvoiceFactory.create(invoice_entries=invoice_entries)
        invoice.issue()
        payment_method = PaymentMethodFactory.create(customer=invoice.customer)
        transaction = TransactionFactory.create(payment_method=payment_method,
                                                invoice=invoice)

        url = reverse('document-list')

        with patch('silver.utils.payments._get_jwt_token',
                   new=self._jwt_token):
            response = self.client.get(url)

        # ^ there's a bug where specifying format='json' doesn't work
        response_data = response.data

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response_data), 2)

        self.assertIn(self._get_expected_data(invoice, [transaction]),
                      response_data)

        self.assertIn(self._get_expected_data(proforma), response_data)
Beispiel #6
0
    def test_add_transaction_without_documents(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)
        valid_until = datetime.now().replace(microsecond=0)
        url = reverse('payment-method-transaction-list',
                      kwargs={
                          'customer_pk': customer.pk,
                          'payment_method_id': payment_method.pk
                      })
        data = {
            'payment_method':
            reverse('payment-method-detail',
                    kwargs={
                        'customer_pk': customer.pk,
                        'payment_method_id': payment_method.id
                    }),
            'valid_until':
            valid_until,
            'amount':
            200.0,
        }

        response = self.client.post(url, format='json', data=data)

        expected_data = {
            'non_field_errors': [
                u'The transaction must have at least one billing document '
                u'(invoice or proforma).'
            ]
        }
        self.assertEqual(response.data, expected_data)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
    def test_add_transaction_with_amount_greater_than_what_should_be_charged(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)

        proforma = ProformaFactory.create(customer=customer,
                                          state=Proforma.STATES.ISSUED,
                                          issue_date=timezone.now().date())
        proforma.create_invoice()
        invoice = proforma.related_document

        valid_until = datetime.now().replace(microsecond=0)
        url = reverse('payment-method-transaction-list',
                      kwargs={'customer_pk': customer.pk,
                              'payment_method_id': payment_method.pk})

        invoice_url = reverse('invoice-detail', args=[invoice.pk])
        proforma_url = reverse('proforma-detail', args=[proforma.pk])
        data = {
            'payment_method': reverse('payment-method-detail',
                                      kwargs={'customer_pk': customer.pk,
                                              'payment_method_id': payment_method.id}),
            'valid_until': valid_until,
            'amount': invoice.total_in_transaction_currency + 1,
            'invoice': invoice_url,
            'proforma': proforma_url
        }

        response = self.client.post(url, format='json', data=data)

        expected_data = {
            'non_field_errors': ["Amount is greater than the amount that should be charged in "
                                 "order to pay the billing document."]
        }
        self.assertEqual(response.data, expected_data)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
Beispiel #8
0
def test_get_invoice(authenticated_api_client, settings, issued_invoice):
    invoice = issued_invoice
    customer = issued_invoice.customer

    issued_invoice.generate_pdf()

    with mute_signals(pre_save):
        [
            TransactionFactory.create(
                state=state,
                invoice=issued_invoice,
                payment_method=PaymentMethodFactory(customer=customer))
            for state in Transaction.States.as_list() if state not in [
                Transaction.States.Canceled, Transaction.States.Refunded,
                Transaction.States.Failed
            ]
        ]

    url = reverse('invoice-detail', kwargs={'pk': invoice.pk})

    response = authenticated_api_client.get(url, format='json')

    assert response.status_code == status.HTTP_200_OK, response.data

    # Cast IDs to UUID so the comparison check doesn't fail
    data = response.data
    data['transactions'][0]['id'] = UUID(data['transactions'][0]['id'])
    data['transactions'][1]['id'] = UUID(data['transactions'][1]['id'])
    data['transactions'][2]['id'] = UUID(data['transactions'][2]['id'])

    invoice_definition.check_response(invoice, response_data=response.data)
    def test_add_transaction_with_documents_for_a_different_customer(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)

        proforma = ProformaFactory.create()
        proforma.issue()
        proforma.create_invoice()
        proforma.refresh_from_db()
        invoice = proforma.related_document

        valid_until = datetime.now().replace(microsecond=0)
        url = reverse('payment-method-transaction-list',
                      kwargs={'customer_pk': customer.pk,
                              'payment_method_id': payment_method.pk})

        invoice_url = reverse('invoice-detail', args=[invoice.pk])
        proforma_url = reverse('proforma-detail', args=[proforma.pk])
        data = {
            'payment_method': reverse('payment-method-detail',
                                      kwargs={'customer_pk': customer.pk,
                                              'payment_method_id': payment_method.id}),
            'valid_until': valid_until,
            'amount': 200.0,
            'invoice': invoice_url,
            'proforma': proforma_url
        }

        response = self.client.post(url, format='json', data=data)

        expected_data = {
            'non_field_errors': [u"Customer doesn't match with the one in documents."]
        }
        self.assertEqual(response.data, expected_data)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
    def test_transaction_filtering(self):
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor, verified=True)

        transactions = TransactionFactory.create_batch(
            5, payment_method=payment_method)

        filtered_transactions = [
            transactions[0], transactions[2], transactions[4]
        ]

        mock_execute = MagicMock()
        with patch.multiple(TriggeredProcessor,
                            execute_transaction=mock_execute):
            transactions_arg = [
                str(transaction.pk) for transaction in filtered_transactions
            ]
            call_command('execute_transactions',
                         '--transactions=%s' % ','.join(transactions_arg))

            for transaction in filtered_transactions:
                self.assertIn(call(transaction), mock_execute.call_args_list)

            self.assertEqual(mock_execute.call_count,
                             len(filtered_transactions))
    def test_fetch_transaction_status_transactions_filtering(self):
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor)

        transactions = TransactionFactory.create_batch(
            5, payment_method=payment_method, state=Transaction.States.Pending)

        filtered_transactions = [
            transactions[0], transactions[2], transactions[4]
        ]

        mock_fetch_status = MagicMock()
        with patch.multiple(TriggeredProcessor,
                            fetch_transaction_status=mock_fetch_status):
            transactions_arg = [
                str(transaction.pk) for transaction in filtered_transactions
            ]
            call_command('fetch_transactions_status',
                         '--transactions=%s' % ','.join(transactions_arg))

            for transaction in filtered_transactions:
                self.assertIn(call(transaction),
                              mock_fetch_status.call_args_list)

            self.assertEqual(mock_fetch_status.call_count,
                             len(filtered_transactions))
Beispiel #12
0
    def test_add_transaction_without_currency_and_amount(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)

        entries = DocumentEntryFactory.create_batch(2)
        proforma = ProformaFactory.create(customer=customer,
                                          state=Proforma.STATES.ISSUED,
                                          issue_date=timezone.now().date(),
                                          currency='USD',
                                          transaction_currency='RON',
                                          transaction_xe_rate=Decimal('0.25'),
                                          proforma_entries=entries)
        proforma.create_invoice()
        invoice = proforma.related_document

        valid_until = datetime.now().replace(microsecond=0) + timedelta(
            minutes=30)
        url = reverse('payment-method-transaction-list',
                      kwargs={
                          'customer_pk': customer.pk,
                          'payment_method_id': payment_method.pk
                      })

        payment_method_url = reverse('payment-method-detail',
                                     kwargs={
                                         'customer_pk': customer.pk,
                                         'payment_method_id': payment_method.id
                                     })
        invoice_url = reverse('invoice-detail', args=[invoice.pk])
        proforma_url = reverse('proforma-detail', args=[proforma.pk])
        data = {
            'payment_method':
            reverse('payment-method-detail',
                    kwargs={
                        'customer_pk': customer.pk,
                        'payment_method_id': payment_method.id
                    }),
            'valid_until':
            valid_until,
            'invoice':
            invoice_url,
            'proforma':
            proforma_url
        }

        response = self.client.post(url, format='json', data=data)

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        self.assertEqual(response.data['payment_method'], payment_method_url)
        self.assertEqual(response.data['valid_until'][:-1],
                         valid_until.isoformat())
        self.assertEqual(response.data['can_be_consumed'], True)
        self.assertEqual(response.data['amount'],
                         force_str(invoice.total_in_transaction_currency))
        self.assertEqual(response.data['invoice'], invoice_url)
        self.assertEqual(response.data['proforma'], proforma_url)
        self.assertEqual(response.data['currency'],
                         invoice.transaction_currency)
Beispiel #13
0
    def test_filter_min_max_amount(self):
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor, )
        customer = payment_method.customer

        entry = DocumentEntryFactory(quantity=1, unit_price=100)
        invoice = InvoiceFactory.create(invoice_entries=[entry],
                                        customer=customer)
        invoice.issue()

        transaction = TransactionFactory.create(payment_method=payment_method,
                                                invoice=invoice)

        transaction_data = self._transaction_data(transaction)

        urls = [
            reverse('payment-method-transaction-list',
                    kwargs={
                        'customer_pk': customer.pk,
                        'payment_method_id': payment_method.pk
                    }),
            reverse('transaction-list', kwargs={'customer_pk': customer.pk})
        ]

        for url in urls:
            url_with_filterable_data = url + '?min_amount=10'
            url_no_output = url + '?min_amount=150'

            with patch('silver.utils.payments._get_jwt_token') as mocked_token:
                mocked_token.return_value = 'token'

                response = self.client.get(url_with_filterable_data,
                                           format='json')

                transaction.refresh_from_db()
                transaction_data['updated_at'] = response.data[0]['updated_at']

                self.assertEqual(response.status_code, status.HTTP_200_OK)
                self.assertEqual(response.data[0], transaction_data)

                response = self.client.get(url_no_output, format='json')
                self.assertEqual(response.status_code, status.HTTP_200_OK)
                self.assertEqual(response.data, [])

                url_with_filterable_data = url + '?max_amount=1050'
                url_no_output = url + '?max_amount=10'

                response = self.client.get(url_with_filterable_data,
                                           format='json')

                transaction.refresh_from_db()
                transaction_data['updated_at'] = response.data[0]['updated_at']

                self.assertEqual(response.status_code, status.HTTP_200_OK)
                self.assertEqual(response.data[0], transaction_data)

                response = self.client.get(url_no_output, format='json')
                self.assertEqual(response.status_code, status.HTTP_200_OK)
                self.assertEqual(response.data, [])
Beispiel #14
0
    def test_no_transaction_creation_at_proforma_pay(self):
        proforma = ProformaFactory.create(related_document=None)

        customer = proforma.customer
        PaymentMethodFactory.create(
            payment_processor=triggered_processor, customer=customer,
            canceled=False,
            verified=True,
        )

        proforma.issue()
        proforma.pay()

        invoice = proforma.related_document

        self.assertEqual(len(Transaction.objects.filter(proforma=proforma)), 1)

        transaction = Transaction.objects.filter(proforma=proforma)[0]
        self.assertEqual(transaction.invoice, invoice)
Beispiel #15
0
    def test_transaction_creation_for_issued_documents(self):
        """
            The happy case.
        """
        invoice = InvoiceFactory.create()
        customer = invoice.customer

        PaymentMethodFactory.create(
            payment_processor=triggered_processor, customer=customer,
            canceled=False,
            verified=True,
        )

        invoice.issue()

        transactions = Transaction.objects.filter(
            invoice=invoice, proforma=invoice.related_document
        )
        self.assertEqual(len(transactions), 1)
Beispiel #16
0
    def test_no_transaction_creation_for_issued_documents_case2(self):
        """
            The payment method is not usable
        """
        invoice = InvoiceFactory.create()
        customer = invoice.customer
        PaymentMethodFactory.create(
            payment_processor=triggered_processor, customer=customer,
            canceled=False
        )

        mock_execute = MagicMock()
        with patch.multiple(TriggeredProcessor, execute_transaction=mock_execute):
            invoice.issue()

            transactions = Transaction.objects.filter(
                invoice=invoice, proforma=invoice.related_document
            )
            self.assertEqual(len(transactions), 0)
    def test_skip_transaction_with_unverified_payment_method(self):
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor, verified=False)

        TransactionFactory.create(payment_method=payment_method)

        mock_execute = MagicMock()
        with patch.multiple(TriggeredProcessor,
                            execute_transaction=mock_execute):
            call_command('execute_transactions')

            self.assertEqual(mock_execute.call_count, 0)
    def test_add_transaction(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)

        entry = DocumentEntryFactory(quantity=1, unit_price=200)
        proforma = ProformaFactory.create(customer=customer,
                                          proforma_entries=[entry])
        proforma.issue()
        proforma.create_invoice()
        proforma.refresh_from_db()
        invoice = proforma.related_document

        payment_method_url = reverse('payment-method-detail',
                                     kwargs={'customer_pk': customer.pk,
                                             'payment_method_id': payment_method.id})

        invoice_url = reverse('invoice-detail', args=[invoice.pk])
        proforma_url = reverse('proforma-detail', args=[proforma.pk])

        url = reverse('payment-method-transaction-list',
                      kwargs={'customer_pk': customer.pk,
                              'payment_method_id': payment_method.pk})

        valid_until = datetime.now().replace(microsecond=0) + timedelta(minutes=30)

        currency = invoice.transaction_currency

        data = {
            'payment_method': reverse('payment-method-detail',
                                      kwargs={'customer_pk': customer.pk,
                                              'payment_method_id': payment_method.id}),
            'amount': invoice.total_in_transaction_currency,
            'invoice': invoice_url,
            'proforma': proforma_url,
            'valid_until': valid_until,
            'currency': currency,
        }

        response = self.client.post(url, format='json', data=data)

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        self.assertEqual(response.data['payment_method'], payment_method_url)
        self.assertEqual(response.data['valid_until'][:-1], valid_until.isoformat())
        self.assertEqual(response.data['can_be_consumed'], True)
        self.assertEqual(response.data['amount'],
                         force_text(invoice.total_in_transaction_currency))
        self.assertEqual(response.data['invoice'], invoice_url)
        self.assertEqual(response.data['proforma'], proforma_url)
        self.assertEqual(response.data['currency'], currency)

        self.assertTrue(Transaction.objects.filter(uuid=response.data['id']))
    def test_filter_payment_method(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor,
            customer=customer
        )

        transaction1 = TransactionFactory.create(
            payment_method=payment_method
        )
        transaction_data_1 = self._transaction_data(transaction1)

        transaction2 = TransactionFactory.create(
            payment_method=payment_method
        )
        transaction_data_2 = self._transaction_data(transaction2)

        urls = [
            reverse(
                'payment-method-transaction-list', kwargs={
                    'customer_pk': customer.pk,
                    'payment_method_id': payment_method.pk}),
            reverse(
                'transaction-list', kwargs={'customer_pk': customer.pk})]

        for url in urls:
            url_method_someprocessor = (
                url + '?payment_processor=' + triggered_processor
            )

            url_no_output = url + '?payment_processor=Random'

            with patch('silver.utils.payments._get_jwt_token') as mocked_token:
                mocked_token.return_value = 'token'

                response = self.client.get(url_method_someprocessor, format='json')
                self.assertEqual(response.status_code, status.HTTP_200_OK)

                transaction1.refresh_from_db()
                transaction_data_1['updated_at'] = response.data[1]['updated_at']

                transaction1.refresh_from_db()
                transaction_data_2['updated_at'] = response.data[0]['updated_at']

                self.assertEqual(response.data[1], transaction_data_1)
                self.assertEqual(response.data[0], transaction_data_2)

                response = self.client.get(url_no_output, format='json')
                self.assertEqual(response.status_code, status.HTTP_200_OK)
                self.assertEqual(response.data, [])
Beispiel #20
0
    def test_add_transaction_with_currency_different_from_document(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)

        proforma = ProformaFactory.create(customer=customer,
                                          state=Proforma.STATES.ISSUED,
                                          issue_date=timezone.now().date())
        proforma.create_invoice()
        invoice = proforma.related_document

        valid_until = datetime.now().replace(microsecond=0)
        url = reverse('payment-method-transaction-list',
                      kwargs={
                          'customer_pk': customer.pk,
                          'payment_method_id': payment_method.pk
                      })

        invoice_url = reverse('invoice-detail', args=[invoice.pk])
        proforma_url = reverse('proforma-detail', args=[proforma.pk])
        data = {
            'payment_method':
            reverse('payment-method-detail',
                    kwargs={
                        'customer_pk': customer.pk,
                        'payment_method_id': payment_method.id
                    }),
            'valid_until':
            valid_until,
            'currency':
            'EUR',
            'amount':
            invoice.total_in_transaction_currency,
            'invoice':
            invoice_url,
            'proforma':
            proforma_url
        }

        response = self.client.post(url, format='json', data=data)

        expected_data = {
            'non_field_errors': [
                u"Transaction currency is different from it's "
                u"document's transaction_currency."
            ]
        }
        self.assertEqual(response.data, expected_data)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
    def test_transaction_executing(self):
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor, verified=True)

        transactions = TransactionFactory.create_batch(
            5, payment_method=payment_method)

        mock_execute = MagicMock()
        with patch.multiple(TriggeredProcessor,
                            execute_transaction=mock_execute):
            call_command('execute_transactions')

            for transaction in transactions:
                self.assertIn(call(transaction), mock_execute.call_args_list)

            self.assertEqual(mock_execute.call_count, len(transactions))
    def test_get_transaction(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)

        transaction = TransactionFactory.create(payment_method=payment_method)
        expected = self._transaction_data(transaction)

        with patch('silver.utils.payments._get_jwt_token') as mocked_token:
            mocked_token.return_value = 'token'

            url = reverse('transaction-detail',
                          kwargs={'customer_pk': customer.pk,
                                  'transaction_uuid': transaction.uuid})
            response = self.client.get(url, format='json')

            self.assertEqual(response.data, dict(expected))
    def test_not_allowed_methods(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)
        transaction_1 = TransactionFactory.create(payment_method=payment_method)
        valid_until = datetime.now().replace(microsecond=0)
        url = reverse('transaction-detail',
                      kwargs={'customer_pk': customer.id,
                              'transaction_uuid': transaction_1.uuid})
        data = {
            'valid_until': valid_until
        }

        response = self.client.put(url, format='json', data=data)
        self.assertEqual(response.data['detail'], 'Method "PUT" not allowed.')

        response = self.client.post(url, format='json', data=data)
        self.assertEqual(response.data['detail'], 'Method "POST" not allowed.')
Beispiel #24
0
    def test_create_one_without_required_fields(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)
        valid_until = datetime.now().replace(microsecond=0)

        data = {'valid_until': valid_until}

        url = reverse('payment-method-transaction-list',
                      kwargs={
                          'customer_pk': customer.id,
                          'payment_method_id': payment_method.id
                      })

        response = self.client.post(url, format='json', data=data)

        self.assertEqual(response.data['payment_method'],
                         ['This field is required.'])
    def test_encoding(self):
        now = timezone.now().replace(microsecond=0)
        payment_method = PaymentMethodFactory.create(added_at=now)

        factory = APIRequestFactory()
        url = reverse('payment-method-detail',
                      kwargs={
                          'payment_method_id': payment_method.pk,
                          'customer_pk': payment_method.customer.pk
                      })
        request = factory.get(url, format='json')

        serializer = PaymentMethodSerializer(payment_method,
                                             context={'request': request})

        self_url = build_absolute_test_url(url)
        transactions_url = build_absolute_test_url(
            reverse('payment-method-transaction-list',
                    kwargs={
                        "payment_method_id": payment_method.pk,
                        "customer_pk": payment_method.customer.pk
                    }))
        customer_url = build_absolute_test_url(
            reverse('customer-detail', [payment_method.customer.pk]))
        expected_data = OrderedDict([
            ('url', self_url),
            ('transactions', transactions_url),
            ('customer', customer_url),
            ('payment_processor_name', manual_processor),
            ('payment_processor',
             OrderedDict([("type", ManualProcessor.type),
                          ("name", manual_processor),
                          ("allowed_currencies", []),
                          ("url",
                           build_absolute_test_url(
                               reverse('payment-processor-detail',
                                       ['manual'])))])),
            ('added_at', payment_method.added_at),
            ('verified', False),
            ('canceled', False),
            ('valid_until', None),
            ('display_info', None),
        ])

        json = JSONRenderer().render(serializer.data)
        self.assertEqual(json, JSONRenderer().render(expected_data))
    def test_fetch_transaction_status_call(self):
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor)

        transactions = TransactionFactory.create_batch(
            5, payment_method=payment_method, state=Transaction.States.Pending)

        mock_fetch_status = MagicMock()
        with patch.multiple(TriggeredProcessor,
                            fetch_transaction_status=mock_fetch_status):
            call_command('fetch_transactions_status')

            for transaction in transactions:
                self.assertIn(call(transaction),
                              mock_fetch_status.call_args_list)

            self.assertEqual(mock_fetch_status.call_count, len(transactions))
Beispiel #27
0
    def test_no_transaction_creation_for_issued_documents_case3(self):
        """
            There are 1 pending and 1 settled transactions that together cover the document amount.
        """
        entry = DocumentEntryFactory(quantity=1, unit_price=100)
        invoice = InvoiceFactory.create(invoice_entries=[entry])
        invoice.issue()

        customer = invoice.customer
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor, customer=customer,
            canceled=False,
            verified=False,
        )

        TransactionFactory.create(invoice=invoice,
                                  payment_method=payment_method,
                                  amount=invoice.total_in_transaction_currency / 2,
                                  state=Transaction.States.Settled)

        TransactionFactory.create(invoice=invoice,
                                  payment_method=payment_method,
                                  amount=invoice.total_in_transaction_currency / 2,
                                  state=Transaction.States.Pending)

        mock_execute = MagicMock()
        with patch.multiple(TriggeredProcessor, execute_transaction=mock_execute):
            expected_exception = ValidationError
            expected_message = "Amount is greater than the amount that should be " \
                               "charged in order to pay the billing document."
            try:
                TransactionFactory.create(invoice=invoice,
                                          payment_method=payment_method,
                                          amount=1)

                self.fail('{} not raised.'.format(str(expected_exception)))
            except expected_exception as e:
                self.assertTrue(expected_message in str(e))

            transactions = Transaction.objects.filter(
                payment_method=payment_method, invoice=invoice,
            )
            self.assertEqual(len(transactions), 2)

            self.assertEqual(mock_execute.call_count, 0)
    def test_exception_logging(self, mock_logger):
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor, verified=True)

        transaction = TransactionFactory.create(payment_method=payment_method)

        mock_execute = MagicMock()
        mock_execute.side_effect = Exception('This happened.')

        with patch.multiple(TriggeredProcessor,
                            execute_transaction=mock_execute):
            call_command('execute_transactions')
            expected_call = call(
                'Encountered exception while executing transaction with id=%s.',
                transaction.id,
                exc_info=True)

            self.assertEqual(expected_call, mock_logger.call_args)
    def test_list_transactions(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)

        transaction_1 = TransactionFactory.create(payment_method=payment_method)
        expected_t1 = self._transaction_data(transaction_1)
        transaction_2 = TransactionFactory.create(payment_method=payment_method)
        expected_t2 = self._transaction_data(transaction_2)

        with patch('silver.utils.payments._get_jwt_token') as mocked_token:
            mocked_token.return_value = 'token'

            url = reverse('transaction-list',
                          kwargs={'customer_pk': customer.pk})

            response = self.client.get(url, format='json')

            self.assertEqual(response.data[1], expected_t1)
            self.assertEqual(response.data[0], expected_t2)
    def test_transaction_update_status_exception_logging(self, mock_logger):
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor)

        transaction = TransactionFactory.create(
            payment_method=payment_method, state=Transaction.States.Pending)

        mock_fetch_status = MagicMock()
        mock_fetch_status.side_effect = Exception('This happened.')

        with patch.multiple(TriggeredProcessor,
                            fetch_transaction_status=mock_fetch_status):
            call_command('fetch_transactions_status')
            expected_call = call(
                'Encountered exception while updating transaction with id=%s.',
                transaction.id,
                exc_info=True)

            self.assertEqual(expected_call, mock_logger.call_args)