diff --git a/.release-please-manifest.json b/.release-please-manifest.json
index 4bab9967..bd115b20 100644
--- a/.release-please-manifest.json
+++ b/.release-please-manifest.json
@@ -1,3 +1,3 @@
{
- ".": "0.121.0"
+ ".": "0.122.0"
}
\ No newline at end of file
diff --git a/.stats.yml b/.stats.yml
index 586a5f55..4645bd0f 100644
--- a/.stats.yml
+++ b/.stats.yml
@@ -1,4 +1,4 @@
-configured_endpoints: 189
-openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/lithic%2Flithic-fd53f07a8b1f148011972d7eba834d5995778d707ff8ef1ead92580b44142a15.yml
-openapi_spec_hash: 45892e6361542824364d82181d4eb80d
-config_hash: 5eca052bb23d273fa970eac3127dd919
+configured_endpoints: 190
+openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/lithic%2Flithic-d29b68bb85936070878d8badaa8a7c5991313285e70a990bc812c838eba85373.yml
+openapi_spec_hash: 54b44da68df22eb0ea99f2bc564667a2
+config_hash: ac8326134e692f3f3bdec82396bbec80
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a37879dd..3760e200 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,20 @@
# Changelog
+## 0.122.0 (2026-04-20)
+
+Full Changelog: [v0.121.0...v0.122.0](https://github.com/lithic-com/lithic-python/compare/v0.121.0...v0.122.0)
+
+### Features
+
+* **api:** add card_authorization.challenge_response webhook event ([78f2c4c](https://github.com/lithic-com/lithic-python/commit/78f2c4c93def51d76abab01e41c5d80f6fe146e5))
+* **api:** Add card/account/business account signals endpoints and behavioral rule attributes ([aa44c45](https://github.com/lithic-com/lithic-python/commit/aa44c45ae060d6350d56dd72e1ca7bf55d16a7e3))
+* **api:** add set_verification_method to external_bank_accounts ([2645172](https://github.com/lithic-com/lithic-python/commit/26451722203cc8c6f88ec720d6529847ac09b2fd))
+
+
+### Performance Improvements
+
+* **client:** optimize file structure copying in multipart requests ([5504230](https://github.com/lithic-com/lithic-python/commit/55042302360bdca2a67d23f2d835bdb3d072d071))
+
## 0.121.0 (2026-04-13)
Full Changelog: [v0.120.0...v0.121.0](https://github.com/lithic-com/lithic-python/compare/v0.120.0...v0.121.0)
diff --git a/api.md b/api.md
index 754f24b2..d1c47871 100644
--- a/api.md
+++ b/api.md
@@ -577,6 +577,7 @@ Methods:
- client.external_bank_accounts.list(\*\*params) -> SyncCursorPage[ExternalBankAccountListResponse]
- client.external_bank_accounts.retry_micro_deposits(external_bank_account_token, \*\*params) -> ExternalBankAccountRetryMicroDepositsResponse
- client.external_bank_accounts.retry_prenote(external_bank_account_token, \*\*params) -> ExternalBankAccount
+- client.external_bank_accounts.set_verification_method(external_bank_account_token, \*\*params) -> ExternalBankAccount
- client.external_bank_accounts.unpause(external_bank_account_token) -> ExternalBankAccount
## MicroDeposits
@@ -888,6 +889,7 @@ from lithic.types import (
AccountHolderVerificationWebhookEvent,
AccountHolderDocumentUpdatedWebhookEvent,
CardAuthorizationApprovalRequestWebhookEvent,
+ CardAuthorizationChallengeResponseWebhookEvent,
AuthRulesBacktestReportCreatedWebhookEvent,
BalanceUpdatedWebhookEvent,
BookTransferTransactionCreatedWebhookEvent,
diff --git a/pyproject.toml b/pyproject.toml
index 3eb30e09..d67ac65f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "lithic"
-version = "0.121.0"
+version = "0.122.0"
description = "The official Python library for the lithic API"
dynamic = ["readme"]
license = "Apache-2.0"
diff --git a/src/lithic/_files.py b/src/lithic/_files.py
index cc14c14f..0fdce17b 100644
--- a/src/lithic/_files.py
+++ b/src/lithic/_files.py
@@ -3,8 +3,8 @@
import io
import os
import pathlib
-from typing import overload
-from typing_extensions import TypeGuard
+from typing import Sequence, cast, overload
+from typing_extensions import TypeVar, TypeGuard
import anyio
@@ -17,7 +17,9 @@
HttpxFileContent,
HttpxRequestFiles,
)
-from ._utils import is_tuple_t, is_mapping_t, is_sequence_t
+from ._utils import is_list, is_mapping, is_tuple_t, is_mapping_t, is_sequence_t
+
+_T = TypeVar("_T")
def is_base64_file_input(obj: object) -> TypeGuard[Base64FileInput]:
@@ -121,3 +123,51 @@ async def async_read_file_content(file: FileContent) -> HttpxFileContent:
return await anyio.Path(file).read_bytes()
return file
+
+
+def deepcopy_with_paths(item: _T, paths: Sequence[Sequence[str]]) -> _T:
+ """Copy only the containers along the given paths.
+
+ Used to guard against mutation by extract_files without copying the entire structure.
+ Only dicts and lists that lie on a path are copied; everything else
+ is returned by reference.
+
+ For example, given paths=[["foo", "files", "file"]] and the structure:
+ {
+ "foo": {
+ "bar": {"baz": {}},
+ "files": {"file": }
+ }
+ }
+ The root dict, "foo", and "files" are copied (they lie on the path).
+ "bar" and "baz" are returned by reference (off the path).
+ """
+ return _deepcopy_with_paths(item, paths, 0)
+
+
+def _deepcopy_with_paths(item: _T, paths: Sequence[Sequence[str]], index: int) -> _T:
+ if not paths:
+ return item
+ if is_mapping(item):
+ key_to_paths: dict[str, list[Sequence[str]]] = {}
+ for path in paths:
+ if index < len(path):
+ key_to_paths.setdefault(path[index], []).append(path)
+
+ # if no path continues through this mapping, it won't be mutated and copying it is redundant
+ if not key_to_paths:
+ return item
+
+ result = dict(item)
+ for key, subpaths in key_to_paths.items():
+ if key in result:
+ result[key] = _deepcopy_with_paths(result[key], subpaths, index + 1)
+ return cast(_T, result)
+ if is_list(item):
+ array_paths = [path for path in paths if index < len(path) and path[index] == ""]
+
+ # if no path expects a list here, nothing will be mutated inside it - return by reference
+ if not array_paths:
+ return cast(_T, item)
+ return cast(_T, [_deepcopy_with_paths(entry, array_paths, index + 1) for entry in item])
+ return item
diff --git a/src/lithic/_utils/__init__.py b/src/lithic/_utils/__init__.py
index 10cb66d2..1c090e51 100644
--- a/src/lithic/_utils/__init__.py
+++ b/src/lithic/_utils/__init__.py
@@ -24,7 +24,6 @@
coerce_integer as coerce_integer,
file_from_path as file_from_path,
strip_not_given as strip_not_given,
- deepcopy_minimal as deepcopy_minimal,
get_async_library as get_async_library,
maybe_coerce_float as maybe_coerce_float,
get_required_header as get_required_header,
diff --git a/src/lithic/_utils/_utils.py b/src/lithic/_utils/_utils.py
index 63b8cd60..771859f5 100644
--- a/src/lithic/_utils/_utils.py
+++ b/src/lithic/_utils/_utils.py
@@ -177,21 +177,6 @@ def is_iterable(obj: object) -> TypeGuard[Iterable[object]]:
return isinstance(obj, Iterable)
-def deepcopy_minimal(item: _T) -> _T:
- """Minimal reimplementation of copy.deepcopy() that will only copy certain object types:
-
- - mappings, e.g. `dict`
- - list
-
- This is done for performance reasons.
- """
- if is_mapping(item):
- return cast(_T, {k: deepcopy_minimal(v) for k, v in item.items()})
- if is_list(item):
- return cast(_T, [deepcopy_minimal(entry) for entry in item])
- return item
-
-
# copied from https://github.com/Rapptz/RoboDanny
def human_join(seq: Sequence[str], *, delim: str = ", ", final: str = "or") -> str:
size = len(seq)
diff --git a/src/lithic/_version.py b/src/lithic/_version.py
index c5edd576..d7da7751 100644
--- a/src/lithic/_version.py
+++ b/src/lithic/_version.py
@@ -1,4 +1,4 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
__title__ = "lithic"
-__version__ = "0.121.0" # x-release-please-version
+__version__ = "0.122.0" # x-release-please-version
diff --git a/src/lithic/resources/events/events.py b/src/lithic/resources/events/events.py
index 984d63f4..9ce8f012 100644
--- a/src/lithic/resources/events/events.py
+++ b/src/lithic/resources/events/events.py
@@ -116,6 +116,7 @@ def list(
"balance.updated",
"book_transfer_transaction.created",
"book_transfer_transaction.updated",
+ "card_authorization.challenge_response",
"card_transaction.enhanced_data.created",
"card_transaction.enhanced_data.updated",
"card_transaction.updated",
@@ -390,6 +391,7 @@ def list(
"balance.updated",
"book_transfer_transaction.created",
"book_transfer_transaction.updated",
+ "card_authorization.challenge_response",
"card_transaction.enhanced_data.created",
"card_transaction.enhanced_data.updated",
"card_transaction.updated",
diff --git a/src/lithic/resources/events/subscriptions.py b/src/lithic/resources/events/subscriptions.py
index 96ad2287..e1a8af38 100644
--- a/src/lithic/resources/events/subscriptions.py
+++ b/src/lithic/resources/events/subscriptions.py
@@ -68,6 +68,7 @@ def create(
"balance.updated",
"book_transfer_transaction.created",
"book_transfer_transaction.updated",
+ "card_authorization.challenge_response",
"card_transaction.enhanced_data.created",
"card_transaction.enhanced_data.updated",
"card_transaction.updated",
@@ -214,6 +215,7 @@ def update(
"balance.updated",
"book_transfer_transaction.created",
"book_transfer_transaction.updated",
+ "card_authorization.challenge_response",
"card_transaction.enhanced_data.created",
"card_transaction.enhanced_data.updated",
"card_transaction.updated",
@@ -683,6 +685,7 @@ def send_simulated_example(
"balance.updated",
"book_transfer_transaction.created",
"book_transfer_transaction.updated",
+ "card_authorization.challenge_response",
"card_transaction.enhanced_data.created",
"card_transaction.enhanced_data.updated",
"card_transaction.updated",
@@ -806,6 +809,7 @@ async def create(
"balance.updated",
"book_transfer_transaction.created",
"book_transfer_transaction.updated",
+ "card_authorization.challenge_response",
"card_transaction.enhanced_data.created",
"card_transaction.enhanced_data.updated",
"card_transaction.updated",
@@ -952,6 +956,7 @@ async def update(
"balance.updated",
"book_transfer_transaction.created",
"book_transfer_transaction.updated",
+ "card_authorization.challenge_response",
"card_transaction.enhanced_data.created",
"card_transaction.enhanced_data.updated",
"card_transaction.updated",
@@ -1421,6 +1426,7 @@ async def send_simulated_example(
"balance.updated",
"book_transfer_transaction.created",
"book_transfer_transaction.updated",
+ "card_authorization.challenge_response",
"card_transaction.enhanced_data.created",
"card_transaction.enhanced_data.updated",
"card_transaction.updated",
diff --git a/src/lithic/resources/external_bank_accounts/external_bank_accounts.py b/src/lithic/resources/external_bank_accounts/external_bank_accounts.py
index f386c48d..d2d5e5aa 100644
--- a/src/lithic/resources/external_bank_accounts/external_bank_accounts.py
+++ b/src/lithic/resources/external_bank_accounts/external_bank_accounts.py
@@ -17,6 +17,7 @@
external_bank_account_update_params,
external_bank_account_retry_prenote_params,
external_bank_account_retry_micro_deposits_params,
+ external_bank_account_set_verification_method_params,
)
from ..._types import Body, Omit, Query, Headers, NotGiven, SequenceNotStr, omit, not_given
from ..._utils import path_template, required_args, maybe_transform, async_maybe_transform
@@ -644,6 +645,60 @@ def retry_prenote(
cast_to=ExternalBankAccount,
)
+ def set_verification_method(
+ self,
+ external_bank_account_token: str,
+ *,
+ verification_method: Literal["MICRO_DEPOSIT", "PRENOTE", "EXTERNALLY_VERIFIED"],
+ financial_account_token: str | Omit = omit,
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
+ # The extra values given here take precedence over values defined on the client or passed to this method.
+ extra_headers: Headers | None = None,
+ extra_query: Query | None = None,
+ extra_body: Body | None = None,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ ) -> ExternalBankAccount:
+ """Update the verification method for an external bank account.
+
+ Verification method
+ can only be updated if the `verification_state` is `PENDING`.
+
+ Args:
+ verification_method: The verification method to set for the external bank account
+
+ financial_account_token: The financial account token of the operating account to fund the micro deposits.
+ Required when verification_method is MICRO_DEPOSIT or PRENOTE.
+
+ extra_headers: Send extra headers
+
+ extra_query: Add additional query parameters to the request
+
+ extra_body: Add additional JSON properties to the request
+
+ timeout: Override the client-level default timeout for this request, in seconds
+ """
+ if not external_bank_account_token:
+ raise ValueError(
+ f"Expected a non-empty value for `external_bank_account_token` but received {external_bank_account_token!r}"
+ )
+ return self._post(
+ path_template(
+ "/v1/external_bank_accounts/{external_bank_account_token}/set_verification_method",
+ external_bank_account_token=external_bank_account_token,
+ ),
+ body=maybe_transform(
+ {
+ "verification_method": verification_method,
+ "financial_account_token": financial_account_token,
+ },
+ external_bank_account_set_verification_method_params.ExternalBankAccountSetVerificationMethodParams,
+ ),
+ options=make_request_options(
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
+ ),
+ cast_to=ExternalBankAccount,
+ )
+
def unpause(
self,
external_bank_account_token: str,
@@ -1281,6 +1336,60 @@ async def retry_prenote(
cast_to=ExternalBankAccount,
)
+ async def set_verification_method(
+ self,
+ external_bank_account_token: str,
+ *,
+ verification_method: Literal["MICRO_DEPOSIT", "PRENOTE", "EXTERNALLY_VERIFIED"],
+ financial_account_token: str | Omit = omit,
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
+ # The extra values given here take precedence over values defined on the client or passed to this method.
+ extra_headers: Headers | None = None,
+ extra_query: Query | None = None,
+ extra_body: Body | None = None,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ ) -> ExternalBankAccount:
+ """Update the verification method for an external bank account.
+
+ Verification method
+ can only be updated if the `verification_state` is `PENDING`.
+
+ Args:
+ verification_method: The verification method to set for the external bank account
+
+ financial_account_token: The financial account token of the operating account to fund the micro deposits.
+ Required when verification_method is MICRO_DEPOSIT or PRENOTE.
+
+ extra_headers: Send extra headers
+
+ extra_query: Add additional query parameters to the request
+
+ extra_body: Add additional JSON properties to the request
+
+ timeout: Override the client-level default timeout for this request, in seconds
+ """
+ if not external_bank_account_token:
+ raise ValueError(
+ f"Expected a non-empty value for `external_bank_account_token` but received {external_bank_account_token!r}"
+ )
+ return await self._post(
+ path_template(
+ "/v1/external_bank_accounts/{external_bank_account_token}/set_verification_method",
+ external_bank_account_token=external_bank_account_token,
+ ),
+ body=await async_maybe_transform(
+ {
+ "verification_method": verification_method,
+ "financial_account_token": financial_account_token,
+ },
+ external_bank_account_set_verification_method_params.ExternalBankAccountSetVerificationMethodParams,
+ ),
+ options=make_request_options(
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
+ ),
+ cast_to=ExternalBankAccount,
+ )
+
async def unpause(
self,
external_bank_account_token: str,
@@ -1342,6 +1451,9 @@ def __init__(self, external_bank_accounts: ExternalBankAccounts) -> None:
self.retry_prenote = _legacy_response.to_raw_response_wrapper(
external_bank_accounts.retry_prenote,
)
+ self.set_verification_method = _legacy_response.to_raw_response_wrapper(
+ external_bank_accounts.set_verification_method,
+ )
self.unpause = _legacy_response.to_raw_response_wrapper(
external_bank_accounts.unpause,
)
@@ -1373,6 +1485,9 @@ def __init__(self, external_bank_accounts: AsyncExternalBankAccounts) -> None:
self.retry_prenote = _legacy_response.async_to_raw_response_wrapper(
external_bank_accounts.retry_prenote,
)
+ self.set_verification_method = _legacy_response.async_to_raw_response_wrapper(
+ external_bank_accounts.set_verification_method,
+ )
self.unpause = _legacy_response.async_to_raw_response_wrapper(
external_bank_accounts.unpause,
)
@@ -1404,6 +1519,9 @@ def __init__(self, external_bank_accounts: ExternalBankAccounts) -> None:
self.retry_prenote = to_streamed_response_wrapper(
external_bank_accounts.retry_prenote,
)
+ self.set_verification_method = to_streamed_response_wrapper(
+ external_bank_accounts.set_verification_method,
+ )
self.unpause = to_streamed_response_wrapper(
external_bank_accounts.unpause,
)
@@ -1435,6 +1553,9 @@ def __init__(self, external_bank_accounts: AsyncExternalBankAccounts) -> None:
self.retry_prenote = async_to_streamed_response_wrapper(
external_bank_accounts.retry_prenote,
)
+ self.set_verification_method = async_to_streamed_response_wrapper(
+ external_bank_accounts.set_verification_method,
+ )
self.unpause = async_to_streamed_response_wrapper(
external_bank_accounts.unpause,
)
diff --git a/src/lithic/types/__init__.py b/src/lithic/types/__init__.py
index a78b5f11..0f829753 100644
--- a/src/lithic/types/__init__.py
+++ b/src/lithic/types/__init__.py
@@ -354,6 +354,9 @@
from .transaction_simulate_credit_authorization_response import (
TransactionSimulateCreditAuthorizationResponse as TransactionSimulateCreditAuthorizationResponse,
)
+from .card_authorization_challenge_response_webhook_event import (
+ CardAuthorizationChallengeResponseWebhookEvent as CardAuthorizationChallengeResponseWebhookEvent,
+)
from .external_bank_account_retry_micro_deposits_response import (
ExternalBankAccountRetryMicroDepositsResponse as ExternalBankAccountRetryMicroDepositsResponse,
)
@@ -363,6 +366,9 @@
from .card_transaction_enhanced_data_updated_webhook_event import (
CardTransactionEnhancedDataUpdatedWebhookEvent as CardTransactionEnhancedDataUpdatedWebhookEvent,
)
+from .external_bank_account_set_verification_method_params import (
+ ExternalBankAccountSetVerificationMethodParams as ExternalBankAccountSetVerificationMethodParams,
+)
from .three_ds_authentication_approval_request_webhook_event import (
ThreeDSAuthenticationApprovalRequestWebhookEvent as ThreeDSAuthenticationApprovalRequestWebhookEvent,
)
diff --git a/src/lithic/types/auth_rules/conditional_authorization_action_parameters.py b/src/lithic/types/auth_rules/conditional_authorization_action_parameters.py
index e2a4fb93..4f8d73e6 100644
--- a/src/lithic/types/auth_rules/conditional_authorization_action_parameters.py
+++ b/src/lithic/types/auth_rules/conditional_authorization_action_parameters.py
@@ -1,13 +1,34 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import List
+from typing import List, Optional
from typing_extensions import Literal
from ..._models import BaseModel
from .conditional_value import ConditionalValue
from .conditional_operation import ConditionalOperation
-__all__ = ["ConditionalAuthorizationActionParameters", "Condition"]
+__all__ = ["ConditionalAuthorizationActionParameters", "Condition", "ConditionParameters"]
+
+
+class ConditionParameters(BaseModel):
+ """Additional parameters required for transaction history signal attributes.
+
+ Required when
+ `attribute` is one of `AMOUNT_Z_SCORE`, `AVG_TRANSACTION_AMOUNT`,
+ `STDEV_TRANSACTION_AMOUNT`, `IS_NEW_COUNTRY`, `IS_NEW_MCC`, `IS_FIRST_TRANSACTION`,
+ `CONSECUTIVE_DECLINES`, `TIME_SINCE_LAST_TRANSACTION`, or `DISTINCT_COUNTRY_COUNT`.
+ Not used for other attributes.
+ """
+
+ interval: Optional[Literal["LIFETIME", "7D", "30D", "90D"]] = None
+ """
+ The time window for statistical attributes (`AMOUNT_Z_SCORE`,
+ `AVG_TRANSACTION_AMOUNT`, `STDEV_TRANSACTION_AMOUNT`). Use `LIFETIME` for
+ all-time history or a specific window (`7D`, `30D`, `90D`).
+ """
+
+ scope: Optional[Literal["CARD", "ACCOUNT", "BUSINESS_ACCOUNT"]] = None
+ """The entity scope to evaluate the attribute against."""
class Condition(BaseModel):
@@ -38,6 +59,16 @@ class Condition(BaseModel):
"SERVICE_LOCATION_POSTAL_CODE",
"CARD_AGE",
"ACCOUNT_AGE",
+ "AMOUNT_Z_SCORE",
+ "AVG_TRANSACTION_AMOUNT",
+ "STDEV_TRANSACTION_AMOUNT",
+ "IS_NEW_COUNTRY",
+ "IS_NEW_MCC",
+ "IS_FIRST_TRANSACTION",
+ "CONSECUTIVE_DECLINES",
+ "TIME_SINCE_LAST_TRANSACTION",
+ "DISTINCT_COUNTRY_COUNT",
+ "THREE_DS_SUCCESS_RATE",
]
"""The attribute to target.
@@ -110,6 +141,33 @@ class Condition(BaseModel):
- `CARD_AGE`: The age of the card in seconds at the time of the authorization.
- `ACCOUNT_AGE`: The age of the account holder's account in seconds at the time
of the authorization.
+ - `AMOUNT_Z_SCORE`: The z-score of the transaction amount relative to the
+ entity's transaction history. Null if fewer than 30 approved transactions in
+ the specified window. Requires `parameters.scope` and `parameters.interval`.
+ - `AVG_TRANSACTION_AMOUNT`: The average approved transaction amount for the
+ entity over the specified window, in cents. Requires `parameters.scope` and
+ `parameters.interval`.
+ - `STDEV_TRANSACTION_AMOUNT`: The standard deviation of approved transaction
+ amounts for the entity over the specified window, in cents. Null if fewer than
+ 30 approved transactions in the specified window. Requires `parameters.scope`
+ and `parameters.interval`.
+ - `IS_NEW_COUNTRY`: Whether the transaction's merchant country has not been seen
+ in the entity's transaction history. Valid values are `TRUE`, `FALSE`.
+ Requires `parameters.scope`.
+ - `IS_NEW_MCC`: Whether the transaction's MCC has not been seen in the entity's
+ transaction history. Valid values are `TRUE`, `FALSE`. Requires
+ `parameters.scope`.
+ - `IS_FIRST_TRANSACTION`: Whether this is the first transaction for the entity.
+ Valid values are `TRUE`, `FALSE`. Requires `parameters.scope`.
+ - `CONSECUTIVE_DECLINES`: The number of consecutive declined transactions for
+ the entity over the last 30 days (rolling). Requires `parameters.scope`. Not
+ supported for `BUSINESS_ACCOUNT` scope.
+ - `TIME_SINCE_LAST_TRANSACTION`: The number of days since the last approved
+ transaction for the entity. Requires `parameters.scope`.
+ - `DISTINCT_COUNTRY_COUNT`: The number of distinct merchant countries seen in
+ the entity's transaction history. Requires `parameters.scope`.
+ - `THREE_DS_SUCCESS_RATE`: The 3DS authentication success rate for the card, as
+ a percentage from 0.0 to 100.0. Card-scoped only; no `parameters` required.
"""
operation: ConditionalOperation
@@ -118,6 +176,15 @@ class Condition(BaseModel):
value: ConditionalValue
"""A regex string, to be used with `MATCHES` or `DOES_NOT_MATCH`"""
+ parameters: Optional[ConditionParameters] = None
+ """Additional parameters required for transaction history signal attributes.
+
+ Required when `attribute` is one of `AMOUNT_Z_SCORE`, `AVG_TRANSACTION_AMOUNT`,
+ `STDEV_TRANSACTION_AMOUNT`, `IS_NEW_COUNTRY`, `IS_NEW_MCC`,
+ `IS_FIRST_TRANSACTION`, `CONSECUTIVE_DECLINES`, `TIME_SINCE_LAST_TRANSACTION`,
+ or `DISTINCT_COUNTRY_COUNT`. Not used for other attributes.
+ """
+
class ConditionalAuthorizationActionParameters(BaseModel):
action: Literal["DECLINE", "CHALLENGE"]
diff --git a/src/lithic/types/auth_rules/conditional_authorization_action_parameters_param.py b/src/lithic/types/auth_rules/conditional_authorization_action_parameters_param.py
index 11a1c220..0a9373f7 100644
--- a/src/lithic/types/auth_rules/conditional_authorization_action_parameters_param.py
+++ b/src/lithic/types/auth_rules/conditional_authorization_action_parameters_param.py
@@ -9,7 +9,28 @@
from .conditional_operation import ConditionalOperation
from .conditional_value_param import ConditionalValueParam
-__all__ = ["ConditionalAuthorizationActionParametersParam", "Condition"]
+__all__ = ["ConditionalAuthorizationActionParametersParam", "Condition", "ConditionParameters"]
+
+
+class ConditionParameters(TypedDict, total=False):
+ """Additional parameters required for transaction history signal attributes.
+
+ Required when
+ `attribute` is one of `AMOUNT_Z_SCORE`, `AVG_TRANSACTION_AMOUNT`,
+ `STDEV_TRANSACTION_AMOUNT`, `IS_NEW_COUNTRY`, `IS_NEW_MCC`, `IS_FIRST_TRANSACTION`,
+ `CONSECUTIVE_DECLINES`, `TIME_SINCE_LAST_TRANSACTION`, or `DISTINCT_COUNTRY_COUNT`.
+ Not used for other attributes.
+ """
+
+ interval: Literal["LIFETIME", "7D", "30D", "90D"]
+ """
+ The time window for statistical attributes (`AMOUNT_Z_SCORE`,
+ `AVG_TRANSACTION_AMOUNT`, `STDEV_TRANSACTION_AMOUNT`). Use `LIFETIME` for
+ all-time history or a specific window (`7D`, `30D`, `90D`).
+ """
+
+ scope: Literal["CARD", "ACCOUNT", "BUSINESS_ACCOUNT"]
+ """The entity scope to evaluate the attribute against."""
class Condition(TypedDict, total=False):
@@ -41,6 +62,16 @@ class Condition(TypedDict, total=False):
"SERVICE_LOCATION_POSTAL_CODE",
"CARD_AGE",
"ACCOUNT_AGE",
+ "AMOUNT_Z_SCORE",
+ "AVG_TRANSACTION_AMOUNT",
+ "STDEV_TRANSACTION_AMOUNT",
+ "IS_NEW_COUNTRY",
+ "IS_NEW_MCC",
+ "IS_FIRST_TRANSACTION",
+ "CONSECUTIVE_DECLINES",
+ "TIME_SINCE_LAST_TRANSACTION",
+ "DISTINCT_COUNTRY_COUNT",
+ "THREE_DS_SUCCESS_RATE",
]
]
"""The attribute to target.
@@ -114,6 +145,33 @@ class Condition(TypedDict, total=False):
- `CARD_AGE`: The age of the card in seconds at the time of the authorization.
- `ACCOUNT_AGE`: The age of the account holder's account in seconds at the time
of the authorization.
+ - `AMOUNT_Z_SCORE`: The z-score of the transaction amount relative to the
+ entity's transaction history. Null if fewer than 30 approved transactions in
+ the specified window. Requires `parameters.scope` and `parameters.interval`.
+ - `AVG_TRANSACTION_AMOUNT`: The average approved transaction amount for the
+ entity over the specified window, in cents. Requires `parameters.scope` and
+ `parameters.interval`.
+ - `STDEV_TRANSACTION_AMOUNT`: The standard deviation of approved transaction
+ amounts for the entity over the specified window, in cents. Null if fewer than
+ 30 approved transactions in the specified window. Requires `parameters.scope`
+ and `parameters.interval`.
+ - `IS_NEW_COUNTRY`: Whether the transaction's merchant country has not been seen
+ in the entity's transaction history. Valid values are `TRUE`, `FALSE`.
+ Requires `parameters.scope`.
+ - `IS_NEW_MCC`: Whether the transaction's MCC has not been seen in the entity's
+ transaction history. Valid values are `TRUE`, `FALSE`. Requires
+ `parameters.scope`.
+ - `IS_FIRST_TRANSACTION`: Whether this is the first transaction for the entity.
+ Valid values are `TRUE`, `FALSE`. Requires `parameters.scope`.
+ - `CONSECUTIVE_DECLINES`: The number of consecutive declined transactions for
+ the entity over the last 30 days (rolling). Requires `parameters.scope`. Not
+ supported for `BUSINESS_ACCOUNT` scope.
+ - `TIME_SINCE_LAST_TRANSACTION`: The number of days since the last approved
+ transaction for the entity. Requires `parameters.scope`.
+ - `DISTINCT_COUNTRY_COUNT`: The number of distinct merchant countries seen in
+ the entity's transaction history. Requires `parameters.scope`.
+ - `THREE_DS_SUCCESS_RATE`: The 3DS authentication success rate for the card, as
+ a percentage from 0.0 to 100.0. Card-scoped only; no `parameters` required.
"""
operation: Required[ConditionalOperation]
@@ -122,6 +180,15 @@ class Condition(TypedDict, total=False):
value: Required[Annotated[ConditionalValueParam, PropertyInfo(format="iso8601")]]
"""A regex string, to be used with `MATCHES` or `DOES_NOT_MATCH`"""
+ parameters: ConditionParameters
+ """Additional parameters required for transaction history signal attributes.
+
+ Required when `attribute` is one of `AMOUNT_Z_SCORE`, `AVG_TRANSACTION_AMOUNT`,
+ `STDEV_TRANSACTION_AMOUNT`, `IS_NEW_COUNTRY`, `IS_NEW_MCC`,
+ `IS_FIRST_TRANSACTION`, `CONSECUTIVE_DECLINES`, `TIME_SINCE_LAST_TRANSACTION`,
+ or `DISTINCT_COUNTRY_COUNT`. Not used for other attributes.
+ """
+
class ConditionalAuthorizationActionParametersParam(TypedDict, total=False):
action: Required[Literal["DECLINE", "CHALLENGE"]]
diff --git a/src/lithic/types/auth_rules/rule_feature.py b/src/lithic/types/auth_rules/rule_feature.py
index 40fffc14..5a218be6 100644
--- a/src/lithic/types/auth_rules/rule_feature.py
+++ b/src/lithic/types/auth_rules/rule_feature.py
@@ -17,6 +17,7 @@
"AccountHolderFeature",
"IPMetadataFeature",
"SpendVelocityFeature",
+ "TransactionHistorySignalsFeature",
]
@@ -84,6 +85,16 @@ class SpendVelocityFeature(BaseModel):
"""The variable name for this feature in the rule function signature"""
+class TransactionHistorySignalsFeature(BaseModel):
+ scope: Literal["CARD", "ACCOUNT", "BUSINESS_ACCOUNT"]
+ """The entity scope to load transaction history signals for."""
+
+ type: Literal["TRANSACTION_HISTORY_SIGNALS"]
+
+ name: Optional[str] = None
+ """The variable name for this feature in the rule function signature"""
+
+
RuleFeature: TypeAlias = Union[
AuthorizationFeature,
AuthenticationFeature,
@@ -93,4 +104,5 @@ class SpendVelocityFeature(BaseModel):
AccountHolderFeature,
IPMetadataFeature,
SpendVelocityFeature,
+ TransactionHistorySignalsFeature,
]
diff --git a/src/lithic/types/auth_rules/rule_feature_param.py b/src/lithic/types/auth_rules/rule_feature_param.py
index 0d32b726..a26c9766 100644
--- a/src/lithic/types/auth_rules/rule_feature_param.py
+++ b/src/lithic/types/auth_rules/rule_feature_param.py
@@ -18,6 +18,7 @@
"AccountHolderFeature",
"IPMetadataFeature",
"SpendVelocityFeature",
+ "TransactionHistorySignalsFeature",
]
@@ -85,6 +86,16 @@ class SpendVelocityFeature(TypedDict, total=False):
"""The variable name for this feature in the rule function signature"""
+class TransactionHistorySignalsFeature(TypedDict, total=False):
+ scope: Required[Literal["CARD", "ACCOUNT", "BUSINESS_ACCOUNT"]]
+ """The entity scope to load transaction history signals for."""
+
+ type: Required[Literal["TRANSACTION_HISTORY_SIGNALS"]]
+
+ name: str
+ """The variable name for this feature in the rule function signature"""
+
+
RuleFeatureParam: TypeAlias = Union[
AuthorizationFeature,
AuthenticationFeature,
@@ -94,4 +105,5 @@ class SpendVelocityFeature(TypedDict, total=False):
AccountHolderFeature,
IPMetadataFeature,
SpendVelocityFeature,
+ TransactionHistorySignalsFeature,
]
diff --git a/src/lithic/types/card_authorization_challenge_response_webhook_event.py b/src/lithic/types/card_authorization_challenge_response_webhook_event.py
new file mode 100644
index 00000000..97ed32a5
--- /dev/null
+++ b/src/lithic/types/card_authorization_challenge_response_webhook_event.py
@@ -0,0 +1,38 @@
+# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
+
+from typing import Optional
+from datetime import datetime
+from typing_extensions import Literal
+
+from .._models import BaseModel
+
+__all__ = ["CardAuthorizationChallengeResponseWebhookEvent"]
+
+
+class CardAuthorizationChallengeResponseWebhookEvent(BaseModel):
+ card_token: Optional[str] = None
+ """The token of the card associated with the challenge"""
+
+ challenge_method: Literal["SMS"]
+ """The method used to deliver the challenge to the cardholder"""
+
+ completed: Optional[datetime] = None
+ """The timestamp of when the challenge was completed"""
+
+ created: datetime
+ """The timestamp of when the challenge was created"""
+
+ event_token: str
+ """Globally unique identifier for the event"""
+
+ event_type: Literal["card_authorization.challenge_response"]
+ """Event type"""
+
+ response: Literal["APPROVE", "DECLINE"]
+ """The cardholder's response to the challenge"""
+
+ transaction_token: Optional[str] = None
+ """
+ The token of the transaction associated with the authorization event being
+ challenged
+ """
diff --git a/src/lithic/types/event.py b/src/lithic/types/event.py
index 188a46d8..97d8ce22 100644
--- a/src/lithic/types/event.py
+++ b/src/lithic/types/event.py
@@ -30,6 +30,7 @@ class Event(BaseModel):
"balance.updated",
"book_transfer_transaction.created",
"book_transfer_transaction.updated",
+ "card_authorization.challenge_response",
"card_transaction.enhanced_data.created",
"card_transaction.enhanced_data.updated",
"card_transaction.updated",
@@ -89,6 +90,8 @@ class Event(BaseModel):
created.
- book_transfer_transaction.updated: Occurs when a book transfer transaction is
updated.
+ - card_authorization.challenge_response: Occurs when a cardholder responds to an
+ SMS challenge during card authorization.
- card_transaction.enhanced_data.created: Occurs when L2/L3 enhanced commercial
data is processed for a transaction event.
- card_transaction.enhanced_data.updated: Occurs when L2/L3 enhanced commercial
diff --git a/src/lithic/types/event_list_params.py b/src/lithic/types/event_list_params.py
index 24daebfb..ec270300 100644
--- a/src/lithic/types/event_list_params.py
+++ b/src/lithic/types/event_list_params.py
@@ -40,6 +40,7 @@ class EventListParams(TypedDict, total=False):
"balance.updated",
"book_transfer_transaction.created",
"book_transfer_transaction.updated",
+ "card_authorization.challenge_response",
"card_transaction.enhanced_data.created",
"card_transaction.enhanced_data.updated",
"card_transaction.updated",
diff --git a/src/lithic/types/event_subscription.py b/src/lithic/types/event_subscription.py
index 2c59189e..4f4dd071 100644
--- a/src/lithic/types/event_subscription.py
+++ b/src/lithic/types/event_subscription.py
@@ -33,6 +33,7 @@ class EventSubscription(BaseModel):
"balance.updated",
"book_transfer_transaction.created",
"book_transfer_transaction.updated",
+ "card_authorization.challenge_response",
"card_transaction.enhanced_data.created",
"card_transaction.enhanced_data.updated",
"card_transaction.updated",
diff --git a/src/lithic/types/events/subscription_create_params.py b/src/lithic/types/events/subscription_create_params.py
index 7d1caebf..fbdeea9c 100644
--- a/src/lithic/types/events/subscription_create_params.py
+++ b/src/lithic/types/events/subscription_create_params.py
@@ -28,6 +28,7 @@ class SubscriptionCreateParams(TypedDict, total=False):
"balance.updated",
"book_transfer_transaction.created",
"book_transfer_transaction.updated",
+ "card_authorization.challenge_response",
"card_transaction.enhanced_data.created",
"card_transaction.enhanced_data.updated",
"card_transaction.updated",
diff --git a/src/lithic/types/events/subscription_send_simulated_example_params.py b/src/lithic/types/events/subscription_send_simulated_example_params.py
index 4cdc1f72..08489d80 100644
--- a/src/lithic/types/events/subscription_send_simulated_example_params.py
+++ b/src/lithic/types/events/subscription_send_simulated_example_params.py
@@ -17,6 +17,7 @@ class SubscriptionSendSimulatedExampleParams(TypedDict, total=False):
"balance.updated",
"book_transfer_transaction.created",
"book_transfer_transaction.updated",
+ "card_authorization.challenge_response",
"card_transaction.enhanced_data.created",
"card_transaction.enhanced_data.updated",
"card_transaction.updated",
diff --git a/src/lithic/types/events/subscription_update_params.py b/src/lithic/types/events/subscription_update_params.py
index dac70887..3bcdd6c7 100644
--- a/src/lithic/types/events/subscription_update_params.py
+++ b/src/lithic/types/events/subscription_update_params.py
@@ -28,6 +28,7 @@ class SubscriptionUpdateParams(TypedDict, total=False):
"balance.updated",
"book_transfer_transaction.created",
"book_transfer_transaction.updated",
+ "card_authorization.challenge_response",
"card_transaction.enhanced_data.created",
"card_transaction.enhanced_data.updated",
"card_transaction.updated",
diff --git a/src/lithic/types/external_bank_account_set_verification_method_params.py b/src/lithic/types/external_bank_account_set_verification_method_params.py
new file mode 100644
index 00000000..2fded7f1
--- /dev/null
+++ b/src/lithic/types/external_bank_account_set_verification_method_params.py
@@ -0,0 +1,18 @@
+# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
+
+from __future__ import annotations
+
+from typing_extensions import Literal, Required, TypedDict
+
+__all__ = ["ExternalBankAccountSetVerificationMethodParams"]
+
+
+class ExternalBankAccountSetVerificationMethodParams(TypedDict, total=False):
+ verification_method: Required[Literal["MICRO_DEPOSIT", "PRENOTE", "EXTERNALLY_VERIFIED"]]
+ """The verification method to set for the external bank account"""
+
+ financial_account_token: str
+ """The financial account token of the operating account to fund the micro deposits.
+
+ Required when verification_method is MICRO_DEPOSIT or PRENOTE.
+ """
diff --git a/src/lithic/types/parsed_webhook_event.py b/src/lithic/types/parsed_webhook_event.py
index ae66c886..d355b7d2 100644
--- a/src/lithic/types/parsed_webhook_event.py
+++ b/src/lithic/types/parsed_webhook_event.py
@@ -52,6 +52,7 @@
from .digital_wallet_tokenization_result_webhook_event import DigitalWalletTokenizationResultWebhookEvent
from .card_authorization_approval_request_webhook_event import CardAuthorizationApprovalRequestWebhookEvent
from .digital_wallet_tokenization_updated_webhook_event import DigitalWalletTokenizationUpdatedWebhookEvent
+from .card_authorization_challenge_response_webhook_event import CardAuthorizationChallengeResponseWebhookEvent
from .card_transaction_enhanced_data_created_webhook_event import CardTransactionEnhancedDataCreatedWebhookEvent
from .card_transaction_enhanced_data_updated_webhook_event import CardTransactionEnhancedDataUpdatedWebhookEvent
from .three_ds_authentication_approval_request_webhook_event import ThreeDSAuthenticationApprovalRequestWebhookEvent
@@ -431,6 +432,7 @@ class LegacyPayload(BaseModel):
AccountHolderVerificationWebhookEvent,
AccountHolderDocumentUpdatedWebhookEvent,
CardAuthorizationApprovalRequestWebhookEvent,
+ CardAuthorizationChallengeResponseWebhookEvent,
AuthRulesBacktestReportCreatedWebhookEvent,
BalanceUpdatedWebhookEvent,
BookTransferTransactionCreatedWebhookEvent,
diff --git a/tests/api_resources/test_external_bank_accounts.py b/tests/api_resources/test_external_bank_accounts.py
index 9418e6bc..f04b517f 100644
--- a/tests/api_resources/test_external_bank_accounts.py
+++ b/tests/api_resources/test_external_bank_accounts.py
@@ -512,6 +512,59 @@ def test_path_params_retry_prenote(self, client: Lithic) -> None:
external_bank_account_token="",
)
+ @parametrize
+ def test_method_set_verification_method(self, client: Lithic) -> None:
+ external_bank_account = client.external_bank_accounts.set_verification_method(
+ external_bank_account_token="182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e",
+ verification_method="MICRO_DEPOSIT",
+ )
+ assert_matches_type(ExternalBankAccount, external_bank_account, path=["response"])
+
+ @parametrize
+ def test_method_set_verification_method_with_all_params(self, client: Lithic) -> None:
+ external_bank_account = client.external_bank_accounts.set_verification_method(
+ external_bank_account_token="182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e",
+ verification_method="MICRO_DEPOSIT",
+ financial_account_token="182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e",
+ )
+ assert_matches_type(ExternalBankAccount, external_bank_account, path=["response"])
+
+ @parametrize
+ def test_raw_response_set_verification_method(self, client: Lithic) -> None:
+ response = client.external_bank_accounts.with_raw_response.set_verification_method(
+ external_bank_account_token="182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e",
+ verification_method="MICRO_DEPOSIT",
+ )
+
+ assert response.is_closed is True
+ assert response.http_request.headers.get("X-Stainless-Lang") == "python"
+ external_bank_account = response.parse()
+ assert_matches_type(ExternalBankAccount, external_bank_account, path=["response"])
+
+ @parametrize
+ def test_streaming_response_set_verification_method(self, client: Lithic) -> None:
+ with client.external_bank_accounts.with_streaming_response.set_verification_method(
+ external_bank_account_token="182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e",
+ verification_method="MICRO_DEPOSIT",
+ ) as response:
+ assert not response.is_closed
+ assert response.http_request.headers.get("X-Stainless-Lang") == "python"
+
+ external_bank_account = response.parse()
+ assert_matches_type(ExternalBankAccount, external_bank_account, path=["response"])
+
+ assert cast(Any, response.is_closed) is True
+
+ @parametrize
+ def test_path_params_set_verification_method(self, client: Lithic) -> None:
+ with pytest.raises(
+ ValueError, match=r"Expected a non-empty value for `external_bank_account_token` but received ''"
+ ):
+ client.external_bank_accounts.with_raw_response.set_verification_method(
+ external_bank_account_token="",
+ verification_method="MICRO_DEPOSIT",
+ )
+
@parametrize
def test_method_unpause(self, client: Lithic) -> None:
external_bank_account = client.external_bank_accounts.unpause(
@@ -1044,6 +1097,59 @@ async def test_path_params_retry_prenote(self, async_client: AsyncLithic) -> Non
external_bank_account_token="",
)
+ @parametrize
+ async def test_method_set_verification_method(self, async_client: AsyncLithic) -> None:
+ external_bank_account = await async_client.external_bank_accounts.set_verification_method(
+ external_bank_account_token="182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e",
+ verification_method="MICRO_DEPOSIT",
+ )
+ assert_matches_type(ExternalBankAccount, external_bank_account, path=["response"])
+
+ @parametrize
+ async def test_method_set_verification_method_with_all_params(self, async_client: AsyncLithic) -> None:
+ external_bank_account = await async_client.external_bank_accounts.set_verification_method(
+ external_bank_account_token="182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e",
+ verification_method="MICRO_DEPOSIT",
+ financial_account_token="182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e",
+ )
+ assert_matches_type(ExternalBankAccount, external_bank_account, path=["response"])
+
+ @parametrize
+ async def test_raw_response_set_verification_method(self, async_client: AsyncLithic) -> None:
+ response = await async_client.external_bank_accounts.with_raw_response.set_verification_method(
+ external_bank_account_token="182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e",
+ verification_method="MICRO_DEPOSIT",
+ )
+
+ assert response.is_closed is True
+ assert response.http_request.headers.get("X-Stainless-Lang") == "python"
+ external_bank_account = response.parse()
+ assert_matches_type(ExternalBankAccount, external_bank_account, path=["response"])
+
+ @parametrize
+ async def test_streaming_response_set_verification_method(self, async_client: AsyncLithic) -> None:
+ async with async_client.external_bank_accounts.with_streaming_response.set_verification_method(
+ external_bank_account_token="182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e",
+ verification_method="MICRO_DEPOSIT",
+ ) as response:
+ assert not response.is_closed
+ assert response.http_request.headers.get("X-Stainless-Lang") == "python"
+
+ external_bank_account = await response.parse()
+ assert_matches_type(ExternalBankAccount, external_bank_account, path=["response"])
+
+ assert cast(Any, response.is_closed) is True
+
+ @parametrize
+ async def test_path_params_set_verification_method(self, async_client: AsyncLithic) -> None:
+ with pytest.raises(
+ ValueError, match=r"Expected a non-empty value for `external_bank_account_token` but received ''"
+ ):
+ await async_client.external_bank_accounts.with_raw_response.set_verification_method(
+ external_bank_account_token="",
+ verification_method="MICRO_DEPOSIT",
+ )
+
@parametrize
async def test_method_unpause(self, async_client: AsyncLithic) -> None:
external_bank_account = await async_client.external_bank_accounts.unpause(
diff --git a/tests/test_deepcopy.py b/tests/test_deepcopy.py
deleted file mode 100644
index b513e83a..00000000
--- a/tests/test_deepcopy.py
+++ /dev/null
@@ -1,58 +0,0 @@
-from lithic._utils import deepcopy_minimal
-
-
-def assert_different_identities(obj1: object, obj2: object) -> None:
- assert obj1 == obj2
- assert id(obj1) != id(obj2)
-
-
-def test_simple_dict() -> None:
- obj1 = {"foo": "bar"}
- obj2 = deepcopy_minimal(obj1)
- assert_different_identities(obj1, obj2)
-
-
-def test_nested_dict() -> None:
- obj1 = {"foo": {"bar": True}}
- obj2 = deepcopy_minimal(obj1)
- assert_different_identities(obj1, obj2)
- assert_different_identities(obj1["foo"], obj2["foo"])
-
-
-def test_complex_nested_dict() -> None:
- obj1 = {"foo": {"bar": [{"hello": "world"}]}}
- obj2 = deepcopy_minimal(obj1)
- assert_different_identities(obj1, obj2)
- assert_different_identities(obj1["foo"], obj2["foo"])
- assert_different_identities(obj1["foo"]["bar"], obj2["foo"]["bar"])
- assert_different_identities(obj1["foo"]["bar"][0], obj2["foo"]["bar"][0])
-
-
-def test_simple_list() -> None:
- obj1 = ["a", "b", "c"]
- obj2 = deepcopy_minimal(obj1)
- assert_different_identities(obj1, obj2)
-
-
-def test_nested_list() -> None:
- obj1 = ["a", [1, 2, 3]]
- obj2 = deepcopy_minimal(obj1)
- assert_different_identities(obj1, obj2)
- assert_different_identities(obj1[1], obj2[1])
-
-
-class MyObject: ...
-
-
-def test_ignores_other_types() -> None:
- # custom classes
- my_obj = MyObject()
- obj1 = {"foo": my_obj}
- obj2 = deepcopy_minimal(obj1)
- assert_different_identities(obj1, obj2)
- assert obj1["foo"] is my_obj
-
- # tuples
- obj3 = ("a", "b")
- obj4 = deepcopy_minimal(obj3)
- assert obj3 is obj4
diff --git a/tests/test_files.py b/tests/test_files.py
index 70b2ddcb..9f7be408 100644
--- a/tests/test_files.py
+++ b/tests/test_files.py
@@ -4,7 +4,8 @@
import pytest
from dirty_equals import IsDict, IsList, IsBytes, IsTuple
-from lithic._files import to_httpx_files, async_to_httpx_files
+from lithic._files import to_httpx_files, deepcopy_with_paths, async_to_httpx_files
+from lithic._utils import extract_files
readme_path = Path(__file__).parent.parent.joinpath("README.md")
@@ -49,3 +50,99 @@ def test_string_not_allowed() -> None:
"file": "foo", # type: ignore
}
)
+
+
+def assert_different_identities(obj1: object, obj2: object) -> None:
+ assert obj1 == obj2
+ assert obj1 is not obj2
+
+
+class TestDeepcopyWithPaths:
+ def test_copies_top_level_dict(self) -> None:
+ original = {"file": b"data", "other": "value"}
+ result = deepcopy_with_paths(original, [["file"]])
+ assert_different_identities(result, original)
+
+ def test_file_value_is_same_reference(self) -> None:
+ file_bytes = b"contents"
+ original = {"file": file_bytes}
+ result = deepcopy_with_paths(original, [["file"]])
+ assert_different_identities(result, original)
+ assert result["file"] is file_bytes
+
+ def test_list_popped_wholesale(self) -> None:
+ files = [b"f1", b"f2"]
+ original = {"files": files, "title": "t"}
+ result = deepcopy_with_paths(original, [["files", ""]])
+ assert_different_identities(result, original)
+ result_files = result["files"]
+ assert isinstance(result_files, list)
+ assert_different_identities(result_files, files)
+
+ def test_nested_array_path_copies_list_and_elements(self) -> None:
+ elem1 = {"file": b"f1", "extra": 1}
+ elem2 = {"file": b"f2", "extra": 2}
+ original = {"items": [elem1, elem2]}
+ result = deepcopy_with_paths(original, [["items", "", "file"]])
+ assert_different_identities(result, original)
+ result_items = result["items"]
+ assert isinstance(result_items, list)
+ assert_different_identities(result_items, original["items"])
+ assert_different_identities(result_items[0], elem1)
+ assert_different_identities(result_items[1], elem2)
+
+ def test_empty_paths_returns_same_object(self) -> None:
+ original = {"foo": "bar"}
+ result = deepcopy_with_paths(original, [])
+ assert result is original
+
+ def test_multiple_paths(self) -> None:
+ f1 = b"file1"
+ f2 = b"file2"
+ original = {"a": f1, "b": f2, "c": "unchanged"}
+ result = deepcopy_with_paths(original, [["a"], ["b"]])
+ assert_different_identities(result, original)
+ assert result["a"] is f1
+ assert result["b"] is f2
+ assert result["c"] is original["c"]
+
+ def test_extract_files_does_not_mutate_original_top_level(self) -> None:
+ file_bytes = b"contents"
+ original = {"file": file_bytes, "other": "value"}
+
+ copied = deepcopy_with_paths(original, [["file"]])
+ extracted = extract_files(copied, paths=[["file"]])
+
+ assert extracted == [("file", file_bytes)]
+ assert original == {"file": file_bytes, "other": "value"}
+ assert copied == {"other": "value"}
+
+ def test_extract_files_does_not_mutate_original_nested_array_path(self) -> None:
+ file1 = b"f1"
+ file2 = b"f2"
+ original = {
+ "items": [
+ {"file": file1, "extra": 1},
+ {"file": file2, "extra": 2},
+ ],
+ "title": "example",
+ }
+
+ copied = deepcopy_with_paths(original, [["items", "", "file"]])
+ extracted = extract_files(copied, paths=[["items", "", "file"]])
+
+ assert extracted == [("items[][file]", file1), ("items[][file]", file2)]
+ assert original == {
+ "items": [
+ {"file": file1, "extra": 1},
+ {"file": file2, "extra": 2},
+ ],
+ "title": "example",
+ }
+ assert copied == {
+ "items": [
+ {"extra": 1},
+ {"extra": 2},
+ ],
+ "title": "example",
+ }