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.pyindex cd27445e308..cefe38a1cd3 100644--- a/corporate/lib/stripe.py+++ b/corporate/lib/stripe.py@@ -5,7 +5,7 @@ import secretsfrom datetime import datetime, timedeltafrom decimal import Decimalfrom 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, Unionimport orjsonimport stripe@@ -17,6 +17,7 @@ from django.utils.timezone import now as timezone_nowfrom django.utils.translation import gettext as _from django.utils.translation import gettext_lazyfrom django.utils.translation import override as override_language+from typing_extensions import ParamSpecfrom 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 = 30MAX_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_errorsdiff --git a/corporate/tests/test_stripe.py b/corporate/tests/test_stripe.pyindex 6a54d133c91..e2bc2600b99 100644--- a/corporate/tests/test_stripe.py+++ b/corporate/tests/test_stripe.py@@ -9,7 +9,7 @@ from dataclasses import dataclassfrom datetime import datetime, timedelta, timezonefrom decimal import Decimalfrom 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, TypeVarfrom unittest.mock import Mock, patchimport orjson@@ -22,6 +22,7 @@ from django.http import HttpResponsefrom django.urls.resolvers import get_resolverfrom django.utils.crypto import get_random_stringfrom django.utils.timezone import now as timezone_now+from typing_extensions import ParamSpecfrom corporate.lib.stripe import (DEFAULT_INVOICE_DAYS_UNTIL_DUE,@@ -104,6 +105,8 @@ from zerver.models import (from zilencer.models import RemoteZulipServer, RemoteZulipServerAuditLogCallableT = 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 = generateif generate_fixture is None:generate_fixture = settings.GENERATE_STRIPE_FIXTURES@@ -350,17 +353,14 @@ def mock_stripe() # nocoverageelse: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: # nocoveragedelete_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 wrappedreturn _mock_stripe