repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
saleor
saleor/webhook/transport/__init__.py
.py
import hashlib import hmac from ...core.jwt_manager import get_jwt_manager def signature_for_payload(body: bytes, secret_key: str | None): if not secret_key: return get_jwt_manager().jws_encode(body) hash = hmac.new(bytes(secret_key, "utf-8"), body, hashlib.sha256) return hash.hexdigest()
12
313
saleor
saleor/webhook/transport/payment.py
.py
import decimal from typing import Any from ...app.models import App from ...payment.interface import ( GatewayResponse, PaymentData, PaymentGateway, PaymentMethodInfo, ) from .utils import to_payment_app_id def parse_list_payment_gateways_response( response_data: Any, app: "App" ) -> list["Paymen...
83
2,682
saleor
saleor/webhook/transport/metrics.py
.py
from datetime import UTC, datetime from urllib.parse import urlparse from opentelemetry.semconv.attributes import error_attributes, server_attributes from ...app.models import App from ...core.models import EventDeliveryStatus from ...core.telemetry import ( DEFAULT_DURATION_BUCKETS, MetricType, Scope, ...
116
3,258
saleor
saleor/webhook/transport/list_stored_payment_methods.py
.py
import logging from typing import cast import graphene from django.core.cache import cache from pydantic import ValidationError from ...app.models import App from ...payment.interface import ( JSONValue, PaymentGateway, PaymentGatewayInitializeTokenizationResponseData, PaymentGatewayInitializeTokeniza...
215
7,840
saleor
saleor/webhook/transport/shipping_helpers.py
.py
import base64 from ...app.models import App from ..const import APP_ID_PREFIX def to_shipping_app_id(app: App, shipping_method_id: str) -> str: app_identifier = app.identifier or app.id return base64.b64encode( str.encode(f"{APP_ID_PREFIX}:{app_identifier}:{shipping_method_id}") ).decode("utf-8")...
12
321
saleor
saleor/webhook/transport/asynchronous/transport.py
.py
import datetime import json import logging from collections import defaultdict from collections.abc import Callable, Hashable, Sequence from dataclasses import asdict, dataclass from typing import TYPE_CHECKING, Any from urllib.parse import urlparse from celery import group from celery.exceptions import MaxRetriesExce...
1,032
38,908
saleor
saleor/webhook/transport/asynchronous/__init__.py
.py
from .transport import ( create_deliveries_for_subscriptions, send_webhook_request_async, trigger_webhooks_async, ) __all__ = [ "create_deliveries_for_subscriptions", "trigger_webhooks_async", "send_webhook_request_async", ]
12
250
saleor
saleor/webhook/transport/asynchronous/tests/test_send_webhooks_async_for_app.py
.py
from unittest.mock import ANY, patch from .....core.models import EventDelivery, EventDeliveryAttempt, EventDeliveryStatus from ..transport import ( WebhookResponse, send_webhooks_async_for_app, ) @patch( "saleor.webhook.transport.asynchronous.transport.send_webhook_using_scheme_method" ) @patch( "sa...
217
6,650
saleor
saleor/webhook/transport/asynchronous/tests/test_create_deliveries_for_subscriptions.py
.py
import json from unittest import mock import graphene from django.test import override_settings from .....graphql.webhook.subscription_payload import ( generate_payload_promise_from_subscription, ) from .....webhook.event_types import WebhookEventAsyncType from .....webhook.models import Webhook from ..transport ...
215
6,895
saleor
saleor/webhook/transport/asynchronous/tests/test_deferred_payload.py
.py
import datetime import json import uuid from dataclasses import asdict from decimal import Decimal from unittest import mock import graphene import pytest from celery.exceptions import Retry from django.test import override_settings from .....checkout.calculations import fetch_checkout_data from .....checkout.fetch i...
609
19,938
saleor
saleor/webhook/transport/asynchronous/tests/test_transport.py
.py
from unittest.mock import MagicMock, patch import botocore.exceptions import celery import google.api_core.exceptions import google.cloud.pubsub_v1.publisher import pytest from celery.exceptions import Retry as CeleryTaskRetryError from opentelemetry.trace import StatusCode from .....core.models import EventDelivery,...
312
10,781
saleor
saleor/webhook/transport/tests/test_list_stored_payment_methods.py
.py
import copy from unittest.mock import patch import pytest from ....payment.interface import ( PaymentGateway, PaymentGatewayInitializeTokenizationResult, PaymentMethodCreditCardInfo, PaymentMethodData, PaymentMethodTokenizationResult, StoredPaymentMethodRequestDeleteResult, ) from ...response_...
441
14,237
saleor
saleor/webhook/transport/tests/test_utils.py
.py
import datetime import json from unittest.mock import ANY, MagicMock, patch import pytest from celery import Task from celery.exceptions import Retry from celery.utils.threads import LocalStack from ....core import EventDeliveryStatus from ....core.models import EventDelivery, EventDeliveryAttempt from ...event_types...
429
12,797
saleor
saleor/webhook/transport/synchronous/transport.py
.py
import json import logging from json import JSONDecodeError from typing import TYPE_CHECKING, Any, TypeVar, Union from urllib.parse import urlparse from django.conf import settings from django.core.cache import cache from django.db import transaction from opentelemetry.trace import StatusCode from promise import Promi...
517
18,367
saleor
saleor/webhook/transport/synchronous/tests/test_transport.py
.py
from unittest.mock import MagicMock, patch import pytest from opentelemetry.trace import StatusCode from .....core.models import EventDeliveryStatus from .....core.telemetry import set_global_attributes from .....tests.utils import get_metric_data_point from ...metrics import ( METRIC_EXTERNAL_REQUEST_BODY_SIZE, ...
272
10,197
saleor
saleor/webhook/observability/utils.py
.py
import datetime import functools import logging from collections.abc import Callable, Generator from contextlib import contextmanager from dataclasses import dataclass from functools import partial from time import monotonic from typing import TYPE_CHECKING from asgiref.local import Local from django.conf import setti...
209
6,977
saleor
saleor/webhook/observability/exceptions.py
.py
from .payload_schema import ObservabilityEventTypes class ObservabilityError(Exception): pass class ConnectionNotConfigured(ObservabilityError): pass class TruncationError(ObservabilityError): _event_type: ObservabilityEventTypes | None = None def __init__(self, operation: str, bytes_limit: int, ...
38
1,027
saleor
saleor/webhook/observability/payload_schema.py
.py
import datetime from enum import Enum from json.encoder import ESCAPE_ASCII, ESCAPE_DCT from typing import TypedDict class JsonTruncText: def __init__(self, text="", truncated=False, added_bytes=0): self.text = text self.truncated = truncated self._added_bytes = max(0, added_bytes) de...
152
3,628
saleor
saleor/webhook/observability/__init__.py
.py
from .buffers import get_buffer from .exceptions import ObservabilityError from .payloads import concatenate_json_events, dump_payload from .tracing import otel_trace from .utils import ( WebhookData, get_buffer_name, get_webhooks, pop_events_with_remaining_size, report_api_call, report_event_de...
33
770
saleor
saleor/webhook/observability/buffers.py
.py
import math import zlib from asgiref.local import Local from django.conf import settings from redis import ConnectionPool, Redis from .exceptions import ConnectionNotConfigured KEY_TYPE = str DEFAULT_CONNECTION_TIMEOUT = 0.5 _local = Local() class BaseBuffer: _compressor_preset = 6 def __init__( s...
208
6,736
saleor
saleor/webhook/observability/tracing.py
.py
from contextlib import contextmanager from ...core.telemetry import saleor_attributes, tracer @contextmanager def otel_trace(span_name, component): with tracer.start_as_current_span(f"observability.{span_name}") as span: span.set_attribute(saleor_attributes.COMPONENT, component) yield
11
309
saleor
saleor/webhook/observability/sensitive_data.py
.py
"""Definitions of sensitive data for observability obfuscation methods. ALLOWED_HEADERS is a set of lowercase HTTP headers allowed for reporting. SENSITIVE_HEADERS is a set of lowercase HTTP headers to anonymize before reporting. SENSITIVE_GQL_FIELDS is a dict of sets representing fields of GraphGL types to anonymiz...
65
1,643
saleor
saleor/webhook/observability/payloads.py
.py
import datetime import json import uuid from collections.abc import Mapping from typing import TYPE_CHECKING, Any import graphene from django.core.serializers.json import DjangoJSONEncoder from django.http import HttpRequest, HttpResponse from django.utils import timezone from graphene.utils.str_converters import to_c...
276
9,761
saleor
saleor/webhook/observability/obfuscation.py
.py
from typing import TYPE_CHECKING, Any, cast from graphql import ( GraphQLError, GraphQLInterfaceType, GraphQLObjectType, GraphQLSchema, get_default_backend, get_named_type, ) from graphql.language.ast import ( Field, FragmentDefinition, FragmentSpread, InlineFragment, Operat...
207
7,258
saleor
saleor/webhook/observability/tests/test_payloads.py
.py
import datetime import json from unittest.mock import patch from uuid import UUID import graphene import pytest from django.http import JsonResponse from ....core import EventDeliveryStatus from ....webhook.event_types import WebhookEventAsyncType from ..exceptions import TruncationError from ..obfuscation import MAS...
492
17,678
saleor
saleor/webhook/observability/tests/test_buffer.py
.py
import datetime import pytest from django.utils import timezone from freezegun import freeze_time from ..buffers import RedisBuffer, get_buffer from ..exceptions import ConnectionNotConfigured from ..tests.conftest import BATCH_SIZE, BROKER_URL_HOST, KEY, MAX_SIZE def test_get_buffer(redis_server, settings): bu...
159
5,101
saleor
saleor/webhook/observability/tests/test_observability.py
.py
from unittest.mock import Mock, patch from celery.canvas import Signature from ....core import EventDeliveryStatus from ...event_types import WebhookEventAsyncType from ...transport.asynchronous.transport import ( observability_reporter_task, observability_send_events, send_observability_events, ) from .....
137
5,011
saleor
saleor/webhook/observability/tests/test_obfuscation.py
.py
import pytest from graphql import GraphQLError from ....graphql.api import schema from ..obfuscation import ( MASK, anonymize_event_payload, anonymize_gql_operation_response, filter_and_hide_headers, validate_sensitive_fields_map, ) @pytest.mark.parametrize( ("headers", "allowed", "sensitive"...
170
4,682
saleor
saleor/webhook/observability/tests/test_utils.py
.py
import datetime import json from unittest.mock import patch import pytest from celery.exceptions import Retry from django.http import HttpResponse from freezegun import freeze_time from ..exceptions import ApiCallTruncationError, EventDeliveryAttemptTruncationError from ..payload_schema import JsonTruncText from ..pa...
293
8,625
saleor
saleor/webhook/observability/tests/conftest.py
.py
import json from unittest.mock import patch import fakeredis import pytest from django.core.cache import cache from graphql import get_default_backend from redis import ConnectionPool from ....graphql.api import schema from ..buffers import RedisBuffer from ..utils import GraphQLOperationResponse, get_buffer_name ba...
80
2,002
saleor
saleor/webhook/tests/test_webhook_tasks.py
.py
import pytest from ...app.models import App from ..event_types import WebhookEventAsyncType from ..models import Webhook, WebhookEvent from ..utils import get_webhooks_for_event @pytest.fixture def webhooks_factory(): def factory(apps, event_type): webhooks = [Webhook(name=f"Webhook {i}", app=app) for i,...
36
1,189
saleor
saleor/webhook/tests/test_webhook_sample_payloads.py
.py
import copy import json from unittest import mock import graphene import pytest from ...order import OrderStatus from ..event_types import WebhookEventAsyncType from ..payloads import ( generate_checkout_payload, generate_fulfillment_payload, generate_order_payload, generate_product_payload, gener...
214
7,856
saleor
saleor/webhook/tests/test_tasks.py
.py
import json from decimal import Decimal from unittest import mock import pytest from django.utils import timezone from freezegun import freeze_time from graphene import Node from requests_hardened import HTTPSession from ...core import EventDeliveryStatus from ...core.models import EventDelivery, EventPayload from .....
1,155
35,997
saleor
saleor/webhook/tests/test_webhook_validators.py
.py
import pytest from django.core.exceptions import ValidationError from ..validators import ( HEADERS_LENGTH_LIMIT, HEADERS_NUMBER_LIMIT, custom_headers_validator, ) @pytest.mark.parametrize( ("headers", "err_msg"), [ ( { "Key1": "Value1", "Key2":...
72
2,103
saleor
saleor/webhook/tests/test_payment_webhook_utils.py
.py
import pytest from ...core import EventDeliveryStatus, private_storage from ...core.models import EventDelivery, EventPayload from ...payment import TransactionKind from ..const import APP_ID_PREFIX from ..transport.payment import ( parse_list_payment_gateways_response, parse_payment_action_response, ) from .....
296
9,867
saleor
saleor/webhook/tests/test_webhook_serializers.py
.py
from unittest.mock import ANY, sentinel import graphene import pytest from ...attribute import AttributeEntityType, AttributeInputType, AttributeType from ...attribute.models import Attribute, AttributeValue from ...attribute.utils import associate_attribute_values_to_instance from ...checkout.fetch import fetch_chec...
269
8,978
saleor
saleor/webhook/tests/test_models.py
.py
import pytest from django.db import IntegrityError from django.db.transaction import atomic from ...app.models import App from ..models import Webhook TARGET_URL = "http://www.example.com/test" def test_webhook_identifier_must_be_unique_per_app(app): # given identifier = "order-created-handler" Webhook....
50
1,826
saleor
saleor/webhook/tests/test_webhook_ip_filtering.py
.py
from ...core.http_client import HTTPClient from ...core.models import EventDeliveryAttempt from ..transport.asynchronous import trigger_webhooks_async def test_rejects_private_ips(webhook, monkeypatch): """Ensure private IP addresses are rejected by webhooks.""" # Enable IP filter monkeypatch.setattr(HTT...
29
987
saleor
saleor/webhook/tests/test_webhook_payloads.py
.py
import datetime import json from dataclasses import asdict from decimal import Decimal from itertools import chain from unittest import mock from unittest.mock import ANY, sentinel import graphene import pytest from django.contrib.sites.models import Site from django.core.serializers.json import DjangoJSONEncoder from...
1,813
67,599
saleor
saleor/webhook/tests/test_webhook_protocols.py
.py
import datetime from unittest import mock from unittest.mock import ANY, MagicMock, patch import boto3 import jwt import pytest from django.core.serializers import serialize from google.cloud.pubsub_v1 import PublisherClient from requests_hardened import HTTPSession from ...core import EventDeliveryStatus from ...cor...
550
17,723
saleor
saleor/webhook/tests/test_webhook_payload_serializers.py
.py
from ..payload_serializers import PythonSerializer def test_python_serializer_extra_model_fields(product_with_single_variant): serializer = PythonSerializer( extra_model_fields={"ProductVariant": ("quantity", "quantity_allocated")} ) annotated_variant = ( product_with_single_variant.varian...
35
1,307
saleor
saleor/webhook/tests/test_utils.py
.py
import pytest from django.utils import timezone from ...app.models import App from ..event_types import WebhookEventAsyncType, WebhookEventSyncType from ..models import Webhook from ..observability.exceptions import ( ApiCallTruncationError, EventDeliveryAttemptTruncationError, TruncationError, ) from ..ob...
461
13,741
saleor
saleor/webhook/tests/conftest.py
.py
from unittest.mock import Mock, patch import pytest @pytest.fixture def mocked_fetch_checkout(): def mocked_fetch_side_effect( checkout_info, manager, lines, address, force_update=False ): return checkout_info, lines with patch( "saleor.checkout.calculations.fetch_checkout_data",...
48
1,197
saleor
saleor/webhook/tests/circuit_breaker/utils.py
.py
from saleor.webhook.circuit_breaker.breaker_board import BreakerBoard def create_breaker_board( storage, failure_min_count=0, failure_threshold=1, failure_min_count_recovery=0, failure_threshold_recovery=1, success_count_recovery=10, cooldown_seconds=10, ttl_seconds=10, ): return B...
24
711
saleor
saleor/webhook/tests/circuit_breaker/fixtures.py
.py
import fakeredis import pytest from ....app.models import App from ....webhook.circuit_breaker.storage import RedisStorage from ....webhook.event_types import WebhookEventSyncType from ....webhook.models import Webhook, WebhookEvent @pytest.fixture def breaker_storage(): server = fakeredis.FakeServer() serve...
47
1,213
saleor
saleor/webhook/tests/circuit_breaker/test_breaker_board.py
.py
from unittest.mock import MagicMock import pytest from django.core.exceptions import ImproperlyConfigured from promise import Promise from ....graphql.app.enums import CircuitBreakerState from ....webhook.event_types import WebhookEventSyncType from .utils import create_breaker_board def test_breaker_board_failure_...
266
8,344
saleor
saleor/webhook/tests/circuit_breaker/test_redis_storage.py
.py
import datetime from freezegun import freeze_time from ....graphql.app.enums import CircuitBreakerState APP_ID = 1 NAME = "total" NOW = 1726215980 TTL_SECONDS = 60 def test_get_app_state(breaker_storage): # given status, changed_at = breaker_storage.get_app_state(APP_ID) assert status == CircuitBreaker...
80
2,418
saleor
saleor/webhook/tests/circuit_breaker/test_breaker_board_decorator.py
.py
import time from unittest.mock import Mock, patch from ....graphql.app.enums import CircuitBreakerState from ....webhook.event_types import WebhookEventSyncType from ....webhook.transport.synchronous import transport from .utils import create_breaker_board # The intention is to test whether BreakerBoard decorator is ...
205
7,258
saleor
saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
.py
import json from decimal import Decimal from unittest.mock import MagicMock, patch import graphene import pytest from django.core.files import File from freezegun import freeze_time from ....channel.models import Channel from ....giftcard.models import GiftCard from ....graphql.webhook.subscription_query import Subsc...
3,345
115,446
saleor
saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_process_tokenization.py
.py
import json import graphene from ....payment.interface import PaymentMethodProcessTokenizationRequestData from ...event_types import WebhookEventSyncType from ...transport.asynchronous import create_deliveries_for_subscriptions PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION = """ subscription{ event{ ...on Paymen...
96
2,658
saleor
saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_initialize_tokenization.py
.py
import json import graphene from ....payment import TokenizedPaymentFlow from ....payment.interface import PaymentMethodInitializeTokenizationRequestData from ...event_types import WebhookEventSyncType from ...transport.asynchronous import create_deliveries_for_subscriptions PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SE...
96
3,017
saleor
saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_gateway_initialize_session.py
.py
import json from decimal import Decimal import graphene from ...event_types import WebhookEventSyncType from ...models import Webhook from ...transport.asynchronous import create_deliveries_for_subscriptions PAYMENT_GATEWAY_INITIALIZE_SESSION = """ subscription { event{ ...on PaymentGatewayInitializeSession{ ...
162
4,637
saleor
saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_request_delete.py
.py
import json import graphene from ....payment.interface import StoredPaymentMethodRequestDeleteData from ...event_types import WebhookEventSyncType from ...transport.asynchronous import create_deliveries_for_subscriptions STORED_PAYMENT_METHOD_DELETE_REQUESTED = """ subscription { event { ... on StoredPaymentMe...
55
1,486
saleor
saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_refund_requested.py
.py
import json from decimal import Decimal import graphene from django.utils import timezone from freezegun import freeze_time from ....core.prices import quantize_price from ....graphql.tests.queries import fragments from ....payment import TransactionAction, TransactionEventType from ....payment.interface import Trans...
335
10,462
saleor
saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscriptions_payments.py
.py
import json import graphene from ...event_types import WebhookEventSyncType from ...transport.asynchronous import create_deliveries_for_subscriptions from .payloads import generate_payment_payload def test_payment_authorize(payment, subscription_payment_authorize_webhook): # given webhooks = [subscription_p...
128
4,340
saleor
saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_translation_subscription.py
.py
import json import graphene from ...event_types import WebhookEventAsyncType from ...transport.asynchronous.transport import create_deliveries_for_subscriptions def test_translation_created_product( product_translation_fr, subscription_product_translation_created_webhook ): webhooks = [subscription_product_...
818
28,538
saleor
saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_process_session.py
.py
import json from decimal import Decimal import graphene from ....channel import TransactionFlowStrategy from ....payment.interface import ( PaymentGatewayData, TransactionProcessActionData, TransactionSessionData, ) from ...event_types import WebhookEventSyncType from ...models import Webhook from ...tran...
398
11,520
saleor
saleor/webhook/tests/subscription_webhooks/payloads.py
.py
import json import graphene from django.utils import timezone from .... import __version__ from ....core.utils import build_absolute_uri from ....discount.models import Promotion from ....graphql.attribute.enums import AttributeInputTypeEnum, AttributeTypeEnum from ....graphql.discount.utils import get_categories_fro...
716
22,056
saleor
saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_initialize_session.py
.py
import json import uuid from decimal import Decimal import graphene from ....channel import TransactionFlowStrategy from ....payment.interface import ( PaymentGatewayData, TransactionProcessActionData, TransactionSessionData, ) from ...event_types import WebhookEventSyncType from ...models import Webhook ...
409
12,130
saleor
saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_list_payment_methods.py
.py
import json import graphene from ....payment.interface import ListStoredPaymentMethodsRequestData from ...event_types import WebhookEventSyncType from ...transport.asynchronous.transport import ( create_deliveries_for_subscriptions, ) LIST_STORED_PAYMENT_METHODS = """ subscription { event { ... on ListStor...
55
1,321
saleor
saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_gateway_initialize_tokenization_session.py
.py
import json import graphene from ....payment.interface import PaymentGatewayInitializeTokenizationRequestData from ...event_types import WebhookEventSyncType from ...transport.asynchronous import create_deliveries_for_subscriptions PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION = """ subscription { event { ... on Pay...
90
2,715
saleor
saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_charge_requested.py
.py
import json from decimal import Decimal import graphene from django.utils import timezone from freezegun import freeze_time from ....core.prices import quantize_price from ....graphql.tests.queries import fragments from ....payment import TransactionAction, TransactionEventType from ....payment.interface import Trans...
199
6,474
saleor
saleor/webhook/tests/subscription_webhooks/test_webhook.py
.py
import json from unittest import mock import graphene from ....core.models import EventDelivery from ...event_types import WebhookEventAsyncType, WebhookEventSyncType from ...models import Webhook from ...transport.asynchronous import trigger_webhooks_async from ...transport.asynchronous.transport import ( Webhoo...
160
5,363
saleor
saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_cancelation_requested.py
.py
import json from decimal import Decimal import graphene from django.utils import timezone from freezegun import freeze_time from ....core.prices import quantize_price from ....graphql.tests.queries import fragments from ....payment import TransactionAction, TransactionEventType from ....payment.interface import Trans...
197
6,382
saleor
saleor/webhook/tests/subscription_webhooks/subscription_queries.py
.py
from enum import Enum from graphene.utils.str_converters import to_snake_case from ....graphql.tests.queries import fragments from ....graphql.webhook.subscription_types import TRANSLATIONS_TYPES_MAP ACCOUNT_CONFIRMATION_REQUESTED = ( fragments.CUSTOMER_DETAILS + fragments.RECIPIENT_APP_DETAILS + """ ...
3,347
55,139
saleor
saleor/webhook/tests/fixtures/utils.py
.py
from ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType from ....webhook.models import WebhookEvent def prepare_async_and_sync_events(webhook): return [ WebhookEvent( webhook=webhook, event_type=WebhookEventSyncType.PAYMENT_AUTHORIZE ), WebhookEvent(webh...
27
711
saleor
saleor/webhook/tests/fixtures/webhook_response.py
.py
import pytest from ....core import EventDeliveryStatus from ....webhook.transport.utils import WebhookResponse @pytest.fixture def webhook_response(): return WebhookResponse( content="test_content", request_headers={"headers": "test_request"}, response_headers={"headers": "test_response"}...
29
762
saleor
saleor/webhook/tests/fixtures/subscription_webhooks.py
.py
import pytest from ...event_types import WebhookEventAsyncType, WebhookEventSyncType from ...models import Webhook from ..subscription_webhooks import subscription_queries as queries @pytest.fixture def subscription_webhook(webhook_app): def fun(query, event_type, name="Subscription", app=webhook_app): w...
1,392
39,531
saleor
saleor/webhook/tests/fixtures/webhook_data.py
.py
import pytest from ....webhook.observability import WebhookData @pytest.fixture def observability_webhook_data(observability_webhook): return WebhookData( id=observability_webhook.id, saleor_domain="example.com", target_url=observability_webhook.target_url, secret_key=observabilit...
14
348
saleor
saleor/webhook/tests/fixtures/webhook.py
.py
import pytest from ....app.models import App from ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType from ....webhook.models import Webhook, WebhookEvent @pytest.fixture def webhook(app): webhook = Webhook.objects.create( name="Simple webhook", app=app, target_url="http://www.exam...
434
11,998
saleor
saleor/webhook/tests/fixtures/webhook_event.py
.py
from itertools import cycle import pytest from ....webhook.models import WebhookEvent from .utils import ( prepare_async_and_sync_events, prepare_async_event, prepare_sync_event, ) @pytest.fixture def events_cycle(): return cycle( ( prepare_async_and_sync_events, prep...
34
703
saleor
saleor/webhook/tests/response_schemas/test_transaction.py
.py
import math from datetime import UTC, datetime from decimal import Decimal import pytest from django.utils import timezone from freezegun import freeze_time from pydantic import ValidationError from ....payment import TransactionAction, TransactionEventType from ...response_schemas.transaction import ( PaymentGat...
1,277
35,329
saleor
saleor/webhook/tests/response_schemas/test_validators.py
.py
import pytest from saleor.webhook.response_schemas.utils.validators import lower_values @pytest.mark.parametrize( ("input_value", "expected_output"), [ ("HELLO", "hello"), ("world", "world"), (["HELLO", "WORLD"], ["hello", "world"]), (["Python", "TEST"], ["python", "test"]), ...
20
525
saleor
saleor/webhook/tests/response_schemas/test_payment.py
.py
from unittest.mock import patch import pytest from pydantic import ValidationError from ....payment.interface import ( PaymentGatewayInitializeTokenizationResult, PaymentMethodTokenizationResult, StoredPaymentMethodRequestDeleteResult, ) from ...response_schemas.payment import ( CreditCardInfoSchema, ...
917
25,904
saleor
saleor/webhook/tests/response_schemas/test_taxes.py
.py
from decimal import Decimal import pytest from pydantic import ValidationError from ....core.prices import MAXIMUM_PRICE from ...response_schemas.taxes import CalculateTaxesSchema, LineCalculateTaxesSchema @pytest.mark.parametrize( "data", [ # Decimal values { "tax_rate": Decimal...
271
8,454
saleor
saleor/webhook/tests/response_schemas/test_helpers.py
.py
from pydantic import BaseModel, ValidationError from ...response_schemas.utils.helpers import parse_validation_error class ExampleSchema(BaseModel): field1: int field2: str def test_parse_validation_error_single_error(): # given invalid_data = {"field1": "not_an_int", "field2": "valid_string"} ...
56
1,623
saleor
saleor/webhook/tests/response_schemas/test_shipping.py
.py
import base64 from decimal import Decimal from unittest.mock import patch import graphene import pytest from pydantic import ValidationError from ...response_schemas.shipping import ( ExcludedShippingMethodSchema, FilterShippingMethodsSchema, ListShippingMethodsSchema, ShippingMethodSchema, logger...
488
14,814
saleor
saleor/webhook/response_schemas/taxes.py
.py
from decimal import Decimal from typing import Annotated from pydantic import BaseModel, Field, ValidationInfo, field_validator from ...core.prices import MAXIMUM_PRICE class LineCalculateTaxesSchema(BaseModel): tax_rate: Annotated[Decimal, Field(ge=0)] total_gross_amount: Annotated[Decimal, Field(ge=0, le=...
37
1,376
saleor
saleor/webhook/response_schemas/shipping.py
.py
import logging from decimal import Decimal from typing import Annotated, TypeVar from graphql.error import GraphQLError from prices import Money from pydantic import ( BaseModel, Field, RootModel, ValidationInfo, field_validator, ) from ...app.models import App from ...graphql.core.utils import fr...
137
4,287
saleor
saleor/webhook/response_schemas/__init__.py
.py
from .payment import ( ListStoredPaymentMethodsSchema, PaymentGatewayInitializeTokenizationSessionSchema, PaymentMethodTokenizationFailedSchema, PaymentMethodTokenizationPendingSchema, PaymentMethodTokenizationSuccessSchema, StoredPaymentMethodDeleteRequestedSchema, ) from .shipping import Filte...
127
3,900
saleor
saleor/webhook/response_schemas/payment.py
.py
from enum import Enum from typing import Annotated, Any, Literal from pydantic import ( AfterValidator, BaseModel, Field, ValidationInfo, field_validator, model_validator, ) from ...app.models import App from ...graphql.core.utils import str_to_enum from ...payment import TokenizedPaymentFlow ...
248
7,303
saleor
saleor/webhook/response_schemas/transaction.py
.py
import logging from datetime import datetime from decimal import Decimal from enum import Enum from typing import Annotated, Any, Literal from django.conf import settings from django.utils import timezone from pydantic import BaseModel, Field, HttpUrl, field_validator from ...graphql.core.utils import str_to_enum fro...
464
14,366
saleor
saleor/webhook/response_schemas/utils/annotations.py
.py
import logging from datetime import UTC, datetime from enum import Enum from typing import Annotated, Any, TypeVar import pydantic from pydantic import ( AfterValidator, BeforeValidator, Field, GetCoreSchemaHandler, TypeAdapter, ValidationError, ValidationInfo, ValidatorFunctionWrapHand...
174
4,989
saleor
saleor/webhook/response_schemas/utils/helpers.py
.py
from pydantic import ValidationError def parse_validation_error(error: ValidationError) -> str: """Parse pydantic ValidationError to a human-readable message.""" errors = error.errors() error_msg: list[str] = [] for error_data in errors: field = "" loc_data = error_data["loc"] ...
22
744
saleor
saleor/webhook/response_schemas/utils/validators.py
.py
def lower_values( values: str | list[str] | None, ) -> str | list[str] | None: """Lowercase all values in a string or a list.""" match values: case str(): return values.lower() case list(): return [value.lower() for value in values] case _: return ...
12
327
saleor
saleor/site/context_processors.py
.py
from typing import TYPE_CHECKING from django.contrib.sites.models import Site from django.contrib.sites.shortcuts import get_current_site from django.db.models import prefetch_related_objects if TYPE_CHECKING: from django.http.request import HttpRequest def site(request: "HttpRequest") -> dict: """Add site ...
17
530
saleor
saleor/site/error_codes.py
.py
from enum import Enum class SiteErrorCode(Enum): FORBIDDEN_CHARACTER = "forbidden_character" GRAPHQL_ERROR = "graphql_error" class GiftCardSettingsErrorCode(Enum): INVALID = "invalid" REQUIRED = "required" GRAPHQL_ERROR = "graphql_error" class RefundSettingsErrorCode(Enum): INVALID = "inva...
26
540
saleor
saleor/site/models.py
.py
import uuid from email.headerregistry import Address from email.utils import parseaddr from typing import Final from django.conf import settings from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from django.core.validators import MaxLengthValidator, MinValueValidator,...
215
7,664
saleor
saleor/site/apps.py
.py
from collections.abc import Callable from typing import TYPE_CHECKING from django.apps import AppConfig from django.conf import settings from django.utils.module_loading import import_string if TYPE_CHECKING is True: from ..graphql.shop.types import Announcement class SiteAppConfig(AppConfig): name = "saleo...
26
711
saleor
saleor/site/__init__.py
.py
class PasswordLoginMode: """Controls whether password-based authentication is allowed. ENABLED - any user can log in with a password. This is the default behavior. CUSTOMERS_ONLY - only customer users can log in with a password. If a staff user logs in with a password, they will be treated as a cus...
72
2,050
saleor
saleor/site/patch_sites.py
.py
"""A hack to allow safe clearing of the cache in django.contrib.sites. Since django.contrib.sites may not be thread-safe when there are multiple instances of the application server, we're patching it with a thread-safe structure and methods that use it underneath. """ import threading from django.contrib.sites.model...
84
3,175
saleor
saleor/site/tests/test_site_settings.py
.py
import pytest from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from ..models import SiteSettings def test_new_get_current(): result = Site.objects.get_current() assert result.name == "example.com" assert result.domain == "example.com" assert type(re...
22
703
saleor
saleor/site/tests/fixtures/site_settings.py
.py
import pytest from ....menu.models import Menu from ...models import Site, SiteSettings @pytest.fixture(autouse=True) def site_settings(db, settings) -> SiteSettings: """Create a site and matching site settings. This fixture is autouse because django.contrib.sites.models.Site and saleor.site.models.Site...
46
1,549
saleor
saleor/seo/models.py
.py
from django.core.validators import MaxLengthValidator from django.db import models from ..core.utils.translations import Translation class SeoModel(models.Model): seo_title = models.CharField( max_length=70, blank=True, null=True, validators=[MaxLengthValidator(70)] ) seo_description = models.Cha...
48
1,293
saleor
saleor/menu/error_codes.py
.py
from enum import Enum class MenuErrorCode(Enum): CANNOT_ASSIGN_NODE = "cannot_assign_node" GRAPHQL_ERROR = "graphql_error" INVALID = "invalid" INVALID_MENU_ITEM = "invalid_menu_item" NO_MENU_ITEM_PROVIDED = "no_item_provided" NOT_FOUND = "not_found" REQUIRED = "required" TOO_MANY_MENU_...
14
367
saleor
saleor/menu/models.py
.py
from django.db import models from mptt.managers import TreeManager from mptt.models import MPTTModel from ..core.models import ModelWithMetadata, SortableModel from ..core.utils.translations import Translation from ..page.models import Page from ..permission.enums import MenuPermissions from ..product.models import Ca...
87
2,718
saleor
saleor/menu/tests/fixtures/menu_item_translation.py
.py
import pytest from ...models import MenuItemTranslation @pytest.fixture def menu_item_translation_fr(menu_item): return MenuItemTranslation.objects.create( language_code="fr", menu_item=menu_item, name="French manu item name" )
11
247
saleor
saleor/menu/tests/fixtures/menu.py
.py
import pytest from ...models import Menu @pytest.fixture def menu(db): return Menu.objects.get_or_create(name="test-navbar", slug="test-navbar")[0] @pytest.fixture def menu_with_items(menu, category, published_collection): menu.items.create(name="Link 1", url="http://example.com/") menu_item = menu.ite...
22
603
saleor
saleor/menu/tests/fixtures/menu_item.py
.py
import pytest from ...models import MenuItem @pytest.fixture def menu_item(menu): return MenuItem.objects.create(menu=menu, name="Link 1", url="http://example.com/") @pytest.fixture def menu_item_list(menu): menu_item_1 = MenuItem.objects.create(menu=menu, name="Link 1") menu_item_2 = MenuItem.objects....
17
470
saleor
saleor/thumbnail/utils.py
.py
import mimetypes import os import secrets from io import BytesIO from typing import TYPE_CHECKING, Optional from urllib.parse import urlparse import graphene import magic from django.core.files import File from django.core.files.storage import default_storage from django.urls import reverse from PIL import Image from...
287
10,218