Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

stripe: Strengthen decorator types using ParamSpec.

Zixuan James Lib1fbba057789
diff --git a/corporate/lib/stripe.py b/corporate/lib/stripe.py
index cd27445e308..cefe38a1cd3 100644
--- a/corporate/lib/stripe.py
+++ b/corporate/lib/stripe.py
@@ -5,7 +5,7 @@ import secrets
from datetime import datetime, timedelta
from decimal import Decimal
from functools import wraps
-from typing import Any, Callable, Dict, Generator, Optional, Tuple, TypeVar, Union, cast
+from typing import Any, Callable, Dict, Generator, Optional, Tuple, TypeVar, Union
import orjson
import stripe
@@ -17,6 +17,7 @@ from django.utils.timezone import now as timezone_now
from django.utils.translation import gettext as _
from django.utils.translation import gettext_lazy
from django.utils.translation import override as override_language
+from typing_extensions import ParamSpec
from corporate.models import (
Customer,
@@ -45,7 +46,8 @@ billing_logger = logging.getLogger("corporate.stripe")
log_to_file(billing_logger, BILLING_LOG_PATH)
log_to_file(logging.getLogger("stripe"), BILLING_LOG_PATH)
-CallableT = TypeVar("CallableT", bound=Callable[..., object])
+ParamT = ParamSpec("ParamT")
+ReturnT = TypeVar("ReturnT")
MIN_INVOICED_LICENSES = 30
MAX_INVOICED_LICENSES = 1000
@@ -243,9 +245,9 @@ class InvalidTier(Exception):
super().__init__(self.message)
-def catch_stripe_errors(func: CallableT) -> CallableT:
+def catch_stripe_errors(func: Callable[ParamT, ReturnT]) -> Callable[ParamT, ReturnT]:
@wraps(func)
- def wrapped(*args: object, **kwargs: object) -> object:
+ def wrapped(*args: ParamT.args, **kwargs: ParamT.kwargs) -> ReturnT:
try:
return func(*args, **kwargs)
# See https://stripe.com/docs/api/python#error_handling, though
@@ -279,7 +281,7 @@ def catch_stripe_errors(func: CallableT) -> CallableT:
)
raise BillingError("other stripe error")
- return cast(CallableT, wrapped)
+ return wrapped
@catch_stripe_errors
diff --git a/corporate/tests/test_stripe.py b/corporate/tests/test_stripe.py
index 6a54d133c91..e2bc2600b99 100644
--- a/corporate/tests/test_stripe.py
+++ b/corporate/tests/test_stripe.py
@@ -9,7 +9,7 @@ from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from decimal import Decimal
from functools import wraps
-from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, TypeVar, cast
+from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, TypeVar
from unittest.mock import Mock, patch
import orjson
@@ -22,6 +22,7 @@ from django.http import HttpResponse
from django.urls.resolvers import get_resolver
from django.utils.crypto import get_random_string
from django.utils.timezone import now as timezone_now
+from typing_extensions import ParamSpec
from corporate.lib.stripe import (
DEFAULT_INVOICE_DAYS_UNTIL_DUE,
@@ -104,6 +105,8 @@ from zerver.models import (
from zilencer.models import RemoteZulipServer, RemoteZulipServerAuditLog
CallableT = TypeVar("CallableT", bound=Callable[..., Any])
+ParamT = ParamSpec("ParamT")
+ReturnT = TypeVar("ReturnT")
STRIPE_FIXTURES_DIR = "corporate/tests/stripe_fixtures"
@@ -335,8 +338,8 @@ MOCKED_STRIPE_FUNCTION_NAMES = [
def mock_stripe(
tested_timestamp_fields: Sequence[str] = [], generate: Optional[bool] = None
-) -> Callable[[CallableT], CallableT]:
- def _mock_stripe(decorated_function: CallableT) -> CallableT:
+) -> Callable[[Callable[ParamT, ReturnT]], Callable[ParamT, ReturnT]]:
+ def _mock_stripe(decorated_function: Callable[ParamT, ReturnT]) -> Callable[ParamT, ReturnT]:
generate_fixture = generate
if generate_fixture is None:
generate_fixture = settings.GENERATE_STRIPE_FIXTURES
@@ -350,17 +353,14 @@ def mock_stripe(
) # nocoverage
else:
side_effect = read_stripe_fixture(decorated_function.__name__, mocked_function_name)
- decorated_function = cast(
- CallableT,
- patch(
- mocked_function_name,
- side_effect=side_effect,
- autospec=mocked_function_name.endswith(".refresh"),
- )(decorated_function),
- )
+ decorated_function = patch(
+ mocked_function_name,
+ side_effect=side_effect,
+ autospec=mocked_function_name.endswith(".refresh"),
+ )(decorated_function)
@wraps(decorated_function)
- def wrapped(*args: object, **kwargs: object) -> object:
+ def wrapped(*args: ParamT.args, **kwargs: ParamT.kwargs) -> ReturnT:
if generate_fixture: # nocoverage
delete_fixture_data(decorated_function)
val = decorated_function(*args, **kwargs)
@@ -369,7 +369,7 @@ def mock_stripe(
else:
return decorated_function(*args, **kwargs)
- return cast(CallableT, wrapped)
+ return wrapped
return _mock_stripe