Skip to content

Commit

Permalink
mas tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mariofix committed Dec 13, 2024
1 parent 26b9e62 commit f2dd3bb
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 22 deletions.
38 changes: 23 additions & 15 deletions django_payments_chile/FlowProvider.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
from dataclasses import asdict
from typing import Any, Optional
from urllib import request
import requests

from django.http import HttpResponseBadRequest, JsonResponse
from payments import PaymentError, PaymentStatus, RedirectNeeded
from payments.core import BasicProvider, get_base_url
from payments.forms import PaymentForm as BasePaymentForm
from pyflowcl import Payment as FlowPayment
from pyflowcl import Refund as FlowRefund
from pyflowcl.Clients import ApiClient

# from pyflowcl import Payment as FlowPayment
# from pyflowcl import Refund as FlowRefund
# from pyflowcl.Clients import ApiClient


class FlowProvider(BasicProvider):
Expand All @@ -28,13 +31,12 @@ class FlowProvider(BasicProvider):
api_key: str = None
api_secret: str = None
api_medio: int
_client: Any = None

def __init__(
self,
api_endpoint: str,
api_key: str,
api_secret: str,
api_endpoint: str = "live",
api_medio: int = 9,
**kwargs: int,
):
Expand All @@ -47,7 +49,6 @@ def __init__(
self.api_endpoint = "https://www.flow.cl/api"
elif self.api_endpoint == "sandbox":
self.api_endpoint = "https://sandbox.flow.cl/api"
self._client = ApiClient(self.api_endpoint, self.api_key, self.api_secret)

def get_form(self, payment, data: Optional[dict] = None) -> Any:
"""
Expand Down Expand Up @@ -87,23 +88,27 @@ def get_form(self, payment, data: Optional[dict] = None) -> Any:
except Exception as e:
raise PaymentError(f"Ocurrió un error al guardar attrs.datos_flow: {e}")

firma_datos = ...
datos_para_flow.update({"s": firma_datos})
try:
pago = FlowPayment.create(self._client, datos_para_flow)
pago_req = requests.post(f"{self.api_endpoint}/payment/create", data=datos_para_flow)
pago_req.raise_for_status()

except Exception as pe:
payment.change_status(PaymentStatus.ERROR, str(pe))
raise PaymentError(pe)
else:
payment.transaction_id = pago.token
pago = pago_req.json()
payment.transaction_id = pago["token"]
payment.attrs.respuesta_flow = {
"url": pago.url,
"token": pago.token,
"flowOrder": pago.flowOrder,
"url": pago["url"],
"token": pago["token"],
"flowOrder": pago["flowOrder"],
}
payment.save()
payment.change_status(PaymentStatus.WAITING)

raise RedirectNeeded(f"{pago.url}?token={pago.token}")
raise RedirectNeeded(f"{pago['url']}?token={pago['token']}")

def process_data(self, payment, request) -> JsonResponse:
"""
Expand All @@ -120,11 +125,10 @@ def process_data(self, payment, request) -> JsonResponse:
if "token" not in request.POST:
raise HttpResponseBadRequest("token no está en post")

data = {"status": "ok"}
if payment.status in [PaymentStatus.WAITING, PaymentStatus.PREAUTH]:
self.actualiza_estado(payment=payment)

return JsonResponse(data)
return JsonResponse({"status": "ok"})

def actualiza_estado(self, payment) -> dict:
"""Actualiza el estado del pago con Flow
Expand All @@ -136,10 +140,14 @@ def actualiza_estado(self, payment) -> dict:
dict: Diccionario con valores del objeto `PaymentStatus`.
"""
try:
status = FlowPayment.getStatus(self._client, payment.transaction_id)
# status = FlowPayment.getStatus(self._client, payment.transaction_id)
estado_req = requests.post(f"{self.api_endpoint}/payment/getStatus")
estado_req.raise_for_status()

except Exception as e:
raise e
else:
status = estado_req.json()
if status.status == 2:
payment.change_status(PaymentStatus.CONFIRMED)
elif status.status == 3:
Expand Down
58 changes: 51 additions & 7 deletions tests/test_flowprovider.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from payments import PaymentStatus
from payments import RedirectNeeded

from django_payments_chile import FlowProvider
from django_payments_chile.FlowProvider import FlowProvider

API_KEY = "flow_test_key"
API_SECRET = "flow_test_secret"
Expand Down Expand Up @@ -46,14 +46,58 @@ def get_success_url(self):
return "http://mi-app.cl/exito"


class TestStripeProviderV3(TestCase):
class TestFlowProviderV3(TestCase):
def test_provider_create_session_success(self):
payment = Payment()
provider = FlowProvider(api_key=API_KEY, api_secret=API_SECRET)
return_value = {"url": "https://flow.cl", "token": "TOKEN_ID", "flowOrder": "ORDER_ID"}
with patch("stripe.checkout.Session.create", return_value=return_value):
with patch("django_payments_chile.FlowProvider.requests.post") as mock_post:
# Configure mock response
mock_response = Mock()
mock_response.raise_for_status.return_value = None # Simulates no exception raised
mock_response.json.return_value = {"url": "https://flow.cl", "token": "TOKEN_ID", "flowOrder": "ORDER_ID"}
mock_post.return_value = mock_response

with self.assertRaises(RedirectNeeded):
provider.get_form(payment)

self.assertEqual(payment.status, PaymentStatus.WAITING)
self.assertEqual(payment.attrs.respuesta_flow["url"], "https://flow.cl")
self.assertEqual(payment.attrs.respuesta_flow["token"], "TOKEN_ID")
self.assertEqual(payment.attrs.respuesta_flow["flowOrder"], "ORDER_ID")

def test_provider_create_session_error(self):
payment = Payment()
provider = FlowProvider(api_key=API_KEY, api_secret=API_SECRET)
with patch("django_payments_chile.FlowProvider.requests.post") as mock_post:
# Simulate an error response
mock_response = Mock()
mock_response.raise_for_status.side_effect = Exception("Error occurred")
mock_post.return_value = mock_response

with self.assertRaises(Exception):
provider.get_form(payment)

self.assertEqual(payment.status, PaymentStatus.ERROR)
self.assertIn("Error occurred", payment.message)

def test_provider_change_status(self):
payment = Payment()
payment.change_status(PaymentStatus.CONFIRMED, "Payment successful")

self.assertEqual(payment.status, PaymentStatus.CONFIRMED)
self.assertEqual(payment.message, "Payment successful")

def test_provider_transaction_id_set(self):
payment = Payment()
provider = FlowProvider(api_key=API_KEY, api_secret=API_SECRET)
with patch("django_payments_chile.FlowProvider.requests.post") as mock_post:
# Configure mock response with transaction ID
mock_response = Mock()
mock_response.raise_for_status.return_value = None
mock_response.json.return_value = {"url": "https://flow.cl", "token": "TOKEN_ID", "flowOrder": "ORDER_ID"}
mock_post.return_value = mock_response

with self.assertRaises(RedirectNeeded):
provider.get_form(payment)
self.assertTrue("url" in payment.attrs.session)
self.assertTrue("token" in payment.attrs.session)
self.assertEqual(payment.status, PaymentStatus.WAITING)

self.assertEqual(payment.transaction_id, "TOKEN_ID")

0 comments on commit f2dd3bb

Please sign in to comment.