Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Moved raw_request functions from stripe module to StripeClient class #1399

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions stripe/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,6 @@ def _warn_if_mismatched_proxy():
WebhookSignature as WebhookSignature,
)

from stripe._raw_request import raw_request as raw_request # noqa
from stripe._raw_request import deserialize as deserialize # noqa

# StripeClient
from stripe._stripe_client import StripeClient as StripeClient # noqa

Expand Down
8 changes: 4 additions & 4 deletions stripe/_api_requestor.py
Original file line number Diff line number Diff line change
Expand Up @@ -529,7 +529,7 @@ def _args_for_request_with_retries(
usage: Optional[List[str]] = None,
):
"""
Mechanism for issuing an API call
Mechanism for issuing an API call. Used by request_raw and request_raw_async.
"""
request_options = merge_options(self._options, options)

Expand Down Expand Up @@ -800,7 +800,7 @@ def _interpret_response(
rbody: object,
rcode: int,
rheaders: Mapping[str, str],
api_mode: Optional[ApiMode],
api_mode: ApiMode,
) -> StripeResponse:
try:
if hasattr(rbody, "decode"):
Expand Down Expand Up @@ -831,7 +831,7 @@ def _interpret_streaming_response(
stream: IOBase,
rcode: int,
rheaders: Mapping[str, str],
api_mode: Optional[ApiMode],
api_mode: ApiMode,
) -> StripeStreamResponse:
# Streaming response are handled with minimal processing for the success
# case (ie. we don't want to read the content). When an error is
Expand Down Expand Up @@ -862,7 +862,7 @@ async def _interpret_streaming_response_async(
stream: AsyncIterable[bytes],
rcode: int,
rheaders: Mapping[str, str],
api_mode: Optional[ApiMode],
api_mode: ApiMode,
) -> StripeStreamResponseAsync:
if self._should_handle_code_as_error(rcode):
json_content = b"".join([chunk async for chunk in stream])
Expand Down
50 changes: 0 additions & 50 deletions stripe/_raw_request.py

This file was deleted.

68 changes: 67 additions & 1 deletion stripe/_stripe_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@
DEFAULT_METER_EVENTS_API_BASE,
)

from stripe._api_mode import ApiMode
from stripe._error import AuthenticationError
from stripe._api_requestor import _APIRequestor
from stripe._request_options import extract_options_from_dict
from stripe._requestor_options import RequestorOptions, BaseAddresses
from stripe._client_options import _ClientOptions
from stripe._http_client import (
Expand All @@ -20,11 +22,14 @@
new_http_client_async_fallback,
)
from stripe._api_version import _ApiVersion
from stripe._stripe_object import StripeObject
from stripe._stripe_response import StripeResponse
from stripe._util import _convert_to_stripe_object, get_api_mode
from stripe._webhook import Webhook, WebhookSignature
from stripe._event import Event
from stripe.v2._event import ThinEvent

from typing import Optional, Union, cast
from typing import Any, Dict, Optional, Union, cast

# Non-generated services
from stripe._oauth_service import OAuthService
Expand Down Expand Up @@ -298,3 +303,64 @@ def parse_snapshot_event(
)

return event

def raw_request(self, method_: str, url_: str, **params):
params = params.copy()
options, params = extract_options_from_dict(params)
api_mode = get_api_mode(url_)
base_address = params.pop("base", "api")

stripe_context = params.pop("stripe_context", None)

# stripe-context goes *here* and not in api_requestor. Properties
# go on api_requestor when you want them to persist onto requests
# made when you call instance methods on APIResources that come from
# the first request. No need for that here, as we aren't deserializing APIResources
if stripe_context is not None:
options["headers"] = options.get("headers", {})
assert isinstance(options["headers"], dict)
options["headers"].update({"Stripe-Context": stripe_context})

rbody, rcode, rheaders = self._requestor.request_raw(
method_,
url_,
params=params,
options=options,
base_address=base_address,
api_mode=api_mode,
usage=["raw_request"],
)

return self._requestor._interpret_response(rbody, rcode, rheaders, api_mode)

async def raw_request_async(self, method_: str, url_: str, **params):
params = params.copy()
options, params = extract_options_from_dict(params)
api_mode = get_api_mode(url_)
base_address = params.pop("base", "api")

rbody, rcode, rheaders = await self._requestor.request_raw_async(
method_,
url_,
params=params,
options=options,
base_address=base_address,
api_mode=api_mode,
usage=["raw_request"],
)

return self._requestor._interpret_response(rbody, rcode, rheaders, api_mode)

def deserialize(
self,
resp: Union[StripeResponse, Dict[str, Any]],
params: Optional[Dict[str, Any]] = None,
*,
api_mode: ApiMode
) -> StripeObject:
return _convert_to_stripe_object(
resp=resp,
params=params,
requestor=self._requestor,
api_mode=api_mode,
)
68 changes: 53 additions & 15 deletions tests/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
from collections import defaultdict
from typing import List, Dict, Tuple, Optional

from stripe._stripe_client import StripeClient

if platform.python_implementation() == "PyPy":
pytest.skip("skip integration tests with PyPy", allow_module_level=True)

Expand Down Expand Up @@ -347,7 +349,9 @@ async def async_http_client(self, request, anyio_backend):
async def set_global_async_http_client(self, async_http_client):
stripe.default_http_client = async_http_client

async def test_async_success(self, set_global_async_http_client):
async def test_async_raw_request_success(
self, set_global_async_http_client
):
class MockServerRequestHandler(MyTestHandler):
default_body = '{"id": "cus_123", "object": "customer"}'.encode(
"utf-8"
Expand All @@ -356,11 +360,16 @@ class MockServerRequestHandler(MyTestHandler):

self.setup_mock_server(MockServerRequestHandler)

stripe.api_base = "http://localhost:%s" % self.mock_server_port

cus = await stripe.Customer.create_async(
description="My test customer"
client = StripeClient(
"sk_test_123",
base_addresses={
"api": "http://localhost:%s" % self.mock_server_port
},
)
resp = await client.raw_request_async(
"post", "/v1/customers", description="My test customer"
)
cus = client.deserialize(resp.data, api_mode="V1")

reqs = MockServerRequestHandler.get_requests(1)
req = reqs[0]
Expand All @@ -369,14 +378,15 @@ class MockServerRequestHandler(MyTestHandler):
assert req.command == "POST"
assert isinstance(cus, stripe.Customer)

async def test_async_timeout(self, set_global_async_http_client):
async def test_async_raw_request_timeout(
self, set_global_async_http_client
):
class MockServerRequestHandler(MyTestHandler):
def do_request(self, n):
time.sleep(0.02)
return super().do_request(n)

self.setup_mock_server(MockServerRequestHandler)
stripe.api_base = "http://localhost:%s" % self.mock_server_port
# If we set HTTPX's generic timeout the test is flaky (sometimes it's a ReadTimeout, sometimes its a ConnectTimeout)
# so we set only the read timeout specifically.
hc = stripe.default_http_client
Expand All @@ -390,19 +400,30 @@ def do_request(self, n):
expected_message = "A ServerTimeoutError was raised"
else:
raise ValueError(f"Unknown http client: {hc.name}")
stripe.max_network_retries = 0

exception = None
try:
await stripe.Customer.create_async(description="My test customer")
client = StripeClient(
"sk_test_123",
http_client=hc,
base_addresses={
"api": "http://localhost:%s" % self.mock_server_port
},
max_network_retries=0,
)
await client.raw_request_async(
"post", "/v1/customers", description="My test customer"
)
except stripe.APIConnectionError as e:
exception = e

assert exception is not None

assert expected_message in str(exception.user_message)

async def test_async_retries(self, set_global_async_http_client):
async def test_async_raw_request_retries(
self, set_global_async_http_client
):
class MockServerRequestHandler(MyTestHandler):
def do_request(self, n):
if n == 0:
Expand All @@ -416,16 +437,26 @@ def do_request(self, n):
pass

self.setup_mock_server(MockServerRequestHandler)
stripe.api_base = "http://localhost:%s" % self.mock_server_port

await stripe.Customer.create_async(description="My test customer")
client = StripeClient(
"sk_test_123",
base_addresses={
"api": "http://localhost:%s" % self.mock_server_port
},
max_network_retries=stripe.max_network_retries,
)
await client.raw_request_async(
"post", "/v1/customers", description="My test customer"
)

reqs = MockServerRequestHandler.get_requests(2)
req = reqs[0]

assert req.path == "/v1/customers"

async def test_async_unretryable(self, set_global_async_http_client):
async def test_async_raw_request_unretryable(
self, set_global_async_http_client
):
class MockServerRequestHandler(MyTestHandler):
def do_request(self, n):
return (
Expand All @@ -437,11 +468,18 @@ def do_request(self, n):
pass

self.setup_mock_server(MockServerRequestHandler)
stripe.api_base = "http://localhost:%s" % self.mock_server_port

exception = None
try:
await stripe.Customer.create_async(description="My test customer")
client = StripeClient(
"sk_test_123",
base_addresses={
"api": "http://localhost:%s" % self.mock_server_port
},
)
await client.raw_request_async(
"post", "/v1/customers", description="My test customer"
)
except stripe.AuthenticationError as e:
exception = e

Expand Down
Loading