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/thumbnail/models.py
.py
from django.core.exceptions import ValidationError from django.db import models from ..account.models import User from ..app.models import App, AppInstallation from ..product.models import Category, Collection, ProductMedia from . import THUMBNAIL_SIZES, ThumbnailFormat def validate_thumbnail_size(size: int): if...
58
1,757
saleor
saleor/thumbnail/apps.py
.py
from django.apps import AppConfig from django.db.models.signals import post_delete class ThumbnailAppConfig(AppConfig): name = "saleor.thumbnail" def ready(self): from .models import Thumbnail from .signals import delete_thumbnail_image post_delete.connect( delete_thumbna...
17
421
saleor
saleor/thumbnail/__init__.py
.py
# defines the available thumbnail resolutions THUMBNAIL_SIZES = [32, 64, 128, 256, 512, 1024, 2048, 4096] DEFAULT_THUMBNAIL_SIZE = 4096 FILE_NAME_MAX_LENGTH = 55 class ThumbnailFormat: ORIGINAL = "original" AVIF = "avif" WEBP = "webp" CHOICES = [ (ORIGINAL, "Original"), (AVIF, "AVIF...
65
1,501
saleor
saleor/thumbnail/views.py
.py
import logging from typing import NamedTuple from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.http import ( HttpResponse, HttpResponseBadRequest, HttpResponseNotFound, HttpResponseRedirect, ) from graphql.error import GraphQLError from ..account.models...
184
6,883
saleor
saleor/thumbnail/signals.py
.py
from ..core.tasks import delete_from_storage_task def delete_thumbnail_image(sender, instance, **kwargs): if image := instance.image: delete_from_storage_task.delay(image.name)
7
191
saleor
saleor/thumbnail/validators.py
.py
from collections.abc import Collection from django.core.exceptions import ValidationError from PIL import Image, UnidentifiedImageError from . import ( ICON_MIME_TYPES, MIME_TYPE_TO_PIL_IDENTIFIER, MIN_ICON_SIZE, PIL_IDENTIFIER_TO_MIME_TYPE, ) def validate_image_format( img: Image.Image, err...
73
2,483
saleor
saleor/thumbnail/tests/test_views.py
.py
from unittest.mock import patch import graphene from PIL import Image from ...product import ProductMediaTypes from .. import IconThumbnailFormat, ThumbnailFormat from ..models import Thumbnail def test_handle_thumbnail_view_with_format(client, category_with_image, settings): # given size = 60 format = ...
603
17,563
saleor
saleor/thumbnail/tests/test_validators.py
.py
from io import BytesIO from unittest.mock import Mock import pytest from django.core.exceptions import ValidationError from PIL import Image, UnidentifiedImageError from .. import MIN_ICON_SIZE from ..validators import ( validate_icon_image, validate_image_exif, validate_image_format, validate_image_s...
80
2,370
saleor
saleor/thumbnail/tests/test_utils.py
.py
from unittest import mock from unittest.mock import MagicMock, patch import graphene import pytest from django.core.files import File from PIL.JpegImagePlugin import JpegImageFile from .. import FILE_NAME_MAX_LENGTH, ThumbnailFormat from ..models import Thumbnail from ..utils import ( ProcessedImage, get_file...
229
6,842
saleor
saleor/thumbnail/tests/fixtures/thumbnail.py
.py
import pytest from ...models import Thumbnail @pytest.fixture def thumbnail_product_media(product_media_image, image_list, media_root): return Thumbnail.objects.create( product_media=product_media_image, size=128, image=image_list[1], ) @pytest.fixture def thumbnail_category(categor...
41
946
saleor
saleor/warehouse/lock_objects.py
.py
from .models import Allocation, Stock def stock_select_for_update_for_existing_qs(qs): return qs.order_by("pk").select_for_update(of=(["self"])) def stock_qs_select_for_update(): return stock_select_for_update_for_existing_qs(Stock.objects.all()) def allocation_with_stock_qs_select_for_update(): retur...
23
530
saleor
saleor/warehouse/reservations.py
.py
import datetime from collections import defaultdict from collections.abc import Iterable from typing import TYPE_CHECKING, NamedTuple from django.conf import settings from django.db.models import F, Sum from django.db.models.functions import Coalesce from django.utils import timezone from ..core.exceptions import Ins...
438
14,876
saleor
saleor/warehouse/error_codes.py
.py
from enum import Enum class WarehouseErrorCode(str, Enum): ALREADY_EXISTS = "already_exists" GRAPHQL_ERROR = "graphql_error" INVALID = "invalid" NOT_FOUND = "not_found" REQUIRED = "required" UNIQUE = "unique" class StockErrorCode(str, Enum): ALREADY_EXISTS = "already_exists" GRAPHQL_...
27
603
saleor
saleor/warehouse/models.py
.py
import itertools import uuid from collections import defaultdict from collections.abc import Iterable from typing import TYPE_CHECKING, TypedDict, TypeVar, cast from django.contrib.postgres.indexes import BTreeIndex from django.db import models from django.db.models import Exists, F, OuterRef, Prefetch, Q, Sum from dj...
690
25,509
saleor
saleor/warehouse/__init__.py
.py
class WarehouseClickAndCollectOption: DISABLED = "disabled" LOCAL_STOCK = "local" ALL_WAREHOUSES = "all" CHOICES = [ (DISABLED, "Disabled"), (LOCAL_STOCK, "Local stock only"), (ALL_WAREHOUSES, "All warehouses"), ]
11
259
saleor
saleor/warehouse/management.py
.py
import math from collections import defaultdict from collections.abc import Iterable from functools import partial from typing import TYPE_CHECKING, Any, NamedTuple, cast from uuid import UUID from django.db import transaction from django.db.models import F, Sum from django.db.models.expressions import Exists, OuterRe...
1,078
39,533
saleor
saleor/warehouse/channel_stock_availability.py
.py
from collections import defaultdict from dataclasses import dataclass from typing import TYPE_CHECKING from uuid import UUID from django.db.models import Exists, OuterRef from . import WarehouseClickAndCollectOption from .interface import VariantChannelStockInfo from .models import ChannelWarehouse, Stock, Warehouse ...
380
14,346
saleor
saleor/warehouse/interface.py
.py
from dataclasses import dataclass @dataclass class VariantChannelStockInfo: variant_id: int channel_slug: str @property def pk(self) -> tuple[int, str]: """Required by deferred payload mechanism to group deliveries per object. Uses (variant_id, channel_slug) because the same variant ...
17
449
saleor
saleor/warehouse/tasks.py
.py
from celery.utils.log import get_task_logger from django.db.models import F, Sum from django.db.models.functions import Coalesce from django.utils import timezone from ..celeryconf import app from ..core.db.connection import allow_writer from .management import delete_allocations, stock_bulk_update from .models import...
69
2,257
saleor
saleor/warehouse/validation.py
.py
from ..shipping.models import ShippingZone from .models import Warehouse def validate_warehouse_count(shipping_zones, instance: Warehouse) -> bool: """Every ShippingZone can be assigned to only one warehouse. If not there would be issue with automatically selecting stock for operation. """ warehouse...
25
730
saleor
saleor/warehouse/availability.py
.py
from collections import defaultdict from collections.abc import Iterable from typing import ( TYPE_CHECKING, Any, NamedTuple, NoReturn, Optional, ) from django.conf import settings from django.core.exceptions import ValidationError from django.db.models import F, QuerySet, Sum from django.db.models...
624
21,992
saleor
saleor/warehouse/webhooks/stock_events.py
.py
from collections.abc import Iterable from functools import partial from typing import TYPE_CHECKING from ...account.models import User from ...app.models import App from ...webhook.event_types import WebhookEventAsyncType from ...webhook.transport.asynchronous.transport import ( WebhookPayloadData, trigger_web...
98
2,805
saleor
saleor/warehouse/webhooks/channel_stock_events.py
.py
import json from collections import defaultdict from functools import partial from typing import TYPE_CHECKING import graphene from ...account.models import User from ...app.models import App from ...webhook.event_types import WebhookEventAsyncType from ...webhook.transport.asynchronous.transport import ( Webhook...
135
4,076
saleor
saleor/warehouse/webhooks/payloads.py
.py
from collections.abc import Iterable from typing import TYPE_CHECKING, Optional import graphene from ...core.db.connection import allow_writer from ...webhook import traced_payload_generator from ...webhook.payload_helpers import generate_meta, generate_requestor from ...webhook.payload_serializers import PayloadSeri...
36
1,277
saleor
saleor/warehouse/tests/test_warehouse.py
.py
import pytest from django.db.models import Q, Sum from ...order.models import OrderLine from .. import WarehouseClickAndCollectOption from ..models import Stock, Warehouse def test_applicable_for_click_and_collect_finds_warehouse_with_all_and_local( stocks_for_cc, warehouses_for_cc, checkout_with_items_for_cc, c...
826
27,634
saleor
saleor/warehouse/tests/test_tasks.py
.py
import datetime import pytest from django.utils import timezone from ..models import Allocation, PreorderReservation, Reservation from ..tasks import ( delete_empty_allocations_task, delete_expired_reservations_task, update_stocks_quantity_allocated_task, ) def test_delete_empty_allocations_task(allocat...
107
3,227
saleor
saleor/warehouse/tests/utils.py
.py
from django.db.models import Sum from django.db.models.functions import Coalesce def get_quantity_allocated_for_stock(stock): """Count how many items are allocated for stock.""" return stock.allocations.aggregate( quantity_allocated=Coalesce(Sum("quantity_allocated"), 0) )["quantity_allocated"] ...
16
537
saleor
saleor/warehouse/tests/test_stock_availability.py
.py
import pytest from ...checkout.fetch import fetch_checkout_lines from ...core.exceptions import InsufficientStock from ..availability import ( _get_available_quantity, check_stock_and_preorder_quantity, check_stock_quantity, check_stock_quantity_bulk, get_available_quantity, is_product_in_stock...
599
17,142
saleor
saleor/warehouse/tests/test_preorder_complete.py
.py
from django.db.models.aggregates import Sum from ...product.models import ProductVariantChannelListing from ..management import deactivate_preorder_for_variant from ..models import Allocation, PreorderAllocation, Stock def test_deactivate_preorder_for_variant( preorder_variant_global_and_channel_threshold, p...
149
4,871
saleor
saleor/warehouse/tests/test_channel_stock_availability.py
.py
from .. import WarehouseClickAndCollectOption from ..channel_stock_availability import ( trigger_back_in_stock_in_channel_events_for_stocks, trigger_out_of_stock_in_channel_events_for_stocks, ) from ..interface import VariantChannelStockInfo from ..models import Allocation, Stock, Warehouse OUT_IN_CHANNEL = ( ...
1,051
37,462
saleor
saleor/warehouse/tests/test_stock_reservations_management.py
.py
import datetime import pytest from django.utils import timezone from ...channel import AllocationStrategy from ...checkout.models import Checkout from ...core.exceptions import InsufficientStock from ..models import ChannelWarehouse, Reservation, Stock, Warehouse from ..reservations import reserve_stocks COUNTRY_COD...
370
11,677
saleor
saleor/warehouse/tests/test_preorder_reservations_management.py
.py
import datetime from decimal import Decimal import pytest from django.utils import timezone from ...checkout.models import Checkout from ...core.exceptions import InsufficientStock from ...product.models import ProductVariantChannelListing from ..models import PreorderAllocation, PreorderReservation from ..reservatio...
286
9,186
saleor
saleor/warehouse/tests/test_preorder_availability.py
.py
import datetime from unittest.mock import patch import pytest from django.db.models import F, Sum from django.db.models.functions import Coalesce from django.utils import timezone from freezegun import freeze_time from ...checkout.fetch import CheckoutLineInfo from ...core.exceptions import InsufficientStock from ..a...
352
11,089
saleor
saleor/warehouse/tests/test_stock_management.py
.py
from unittest import mock import pytest from django.db.models import Sum from django.db.models.functions import Coalesce from ...channel import AllocationStrategy from ...core.exceptions import InsufficientStock from ...order.fetch import OrderLineInfo from ...order.models import OrderLine from ...warehouse.models im...
1,713
54,189
saleor
saleor/warehouse/tests/test_stock.py
.py
import pytest from ..models import Stock COUNTRY_CODE = "US" @pytest.fixture def variant_with_stocks_in_two_channels( variant, warehouses, shipping_zone, channel_USD, channel_PLN ): """Variant with stocks in warehouses across two channels. - warehouse_usd (warehouses[0]): linked to channel_USD and ship...
320
8,327
saleor
saleor/warehouse/tests/webhooks/test_channel_stock_events.py
.py
import json from unittest import mock import graphene import pytest from ....webhook.event_types import WebhookEventAsyncType from ...interface import VariantChannelStockInfo from ...webhooks.channel_stock_events import ( _trigger, trigger_product_variant_back_in_stock_for_click_and_collect, trigger_produ...
288
8,458
saleor
saleor/warehouse/tests/webhooks/test_payloads.py
.py
import json from unittest.mock import ANY import graphene from .... import __version__ from ...webhooks.payloads import ( generate_product_variant_with_stock_payload, ) def test_generate_base_product_variant_payload(product_with_two_variants): stocks_to_serialize = [ variant.stocks.first() for varia...
61
2,124
saleor
saleor/warehouse/tests/webhooks/test_stock_events.py
.py
from functools import partial from unittest import mock from saleor.warehouse.webhooks.stock_events import ( trigger_product_variant_back_in_stock, trigger_product_variant_out_of_stock, trigger_product_variant_stocks_updated, ) from saleor.webhook.event_types import WebhookEventAsyncType from saleor.webhoo...
130
4,539
saleor
saleor/warehouse/tests/webhooks/subscriptions/test_channel_stock_events.py
.py
import json import graphene import pytest from .....webhook.event_types import WebhookEventAsyncType from .....webhook.transport.asynchronous.transport import ( create_deliveries_for_subscriptions, ) from ....interface import VariantChannelStockInfo PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL = """ subscription{...
201
6,000
saleor
saleor/warehouse/tests/fixtures/warehouse.py
.py
import pytest from ... import WarehouseClickAndCollectOption from ...models import Stock, Warehouse @pytest.fixture def warehouse(address, shipping_zone, channel_USD): warehouse = Warehouse.objects.create( address=address, name="Example Warehouse", slug="example-warehouse", email=...
166
5,172
saleor
saleor/warehouse/tests/fixtures/stock.py
.py
import pytest from ...models import Stock @pytest.fixture def stock(variant, warehouse): return Stock.objects.create( product_variant=variant, warehouse=warehouse, quantity=15 ) @pytest.fixture def stocks_for_cc(warehouses_for_cc, product_variant_list, product_with_two_variants): return Stock.o...
64
1,889
saleor
saleor/warehouse/tests/fixtures/preorder_allocation.py
.py
import pytest from ...models import PreorderAllocation @pytest.fixture def preorder_allocation( order_line, preorder_variant_global_and_channel_threshold, channel_PLN ): variant = preorder_variant_global_and_channel_threshold product_variant_channel_listing = variant.channel_listings.get(channel=channel_...
17
519
saleor
saleor/warehouse/tests/fixtures/allocation.py
.py
from decimal import Decimal import pytest from ....core.postgres import FlatConcatSearchVector from ....core.prices import Money, TaxedMoney from ....order.models import Order, OrderLine from ....order.search import prepare_order_search_vector_value from ....tax.utils import get_tax_class_kwargs_for_order_line from ....
97
3,577
saleor
saleor/channel/utils.py
.py
import warnings from django.conf import settings from .exceptions import ChannelNotDefined, NoDefaultChannel from .models import Channel DEPRECATION_WARNING_MESSAGE = ( "Default channel used in a query. Please make sure that channel is explicitly " "provided. This behavior works only when a one channel exist...
48
1,785
saleor
saleor/channel/exceptions.py
.py
class ChannelNotDefined(Exception): def __init__(self, msg=None): if msg is None: msg = "More than one channel exists. Specify which channel to use." super().__init__(msg) class NoDefaultChannel(Exception): def __init__(self, msg=None): if msg is None: msg = "A ...
13
383
saleor
saleor/channel/error_codes.py
.py
from enum import Enum class ChannelErrorCode(Enum): ALREADY_EXISTS = "already_exists" GRAPHQL_ERROR = "graphql_error" INVALID = "invalid" NOT_FOUND = "not_found" REQUIRED = "required" UNIQUE = "unique" CHANNELS_CURRENCY_MUST_BE_THE_SAME = "channels_currency_must_be_the_same" CHANNEL_WI...
14
406
saleor
saleor/channel/models.py
.py
import datetime from django.conf import settings from django.db import models from django_countries.fields import CountryField from ..core.models import ModelWithMetadata from ..permission.enums import ChannelPermissions from . import AllocationStrategy, MarkAsPaidStrategy, TransactionFlowStrategy class Channel(Mod...
89
3,345
saleor
saleor/channel/__init__.py
.py
class AllocationStrategy: """Determine the allocation strategy for the channel. PRIORITIZE_SORTING_ORDER - allocate stocks according to the warehouses' order within the channel PRIORITIZE_HIGH_STOCK - allocate stock in a warehouse with the most stock """ PRIORITIZE_SORTING_ORDER = "prioritize...
50
1,409
saleor
saleor/channel/tasks/saleor3_22.py
.py
from ....celeryconf import app from ....core.db.connection import allow_writer from ...models import Channel @app.task @allow_writer() def set_automatic_completion_delay_task(): Channel.objects.filter( automatically_complete_fully_paid_checkouts=True, automatic_completion_delay__isnull=True, )...
13
358
saleor
saleor/channel/tests/test_utils.py
.py
import warnings import pytest from ..exceptions import ChannelNotDefined, NoDefaultChannel from ..utils import DEPRECATION_WARNING_MESSAGE, get_default_channel def test_get_default_channel_without_channels(): with pytest.raises(NoDefaultChannel): get_default_channel() def test_get_default_channel_with...
25
699
saleor
saleor/channel/tests/fixtures/channel.py
.py
import pytest from django.conf import settings from ....channel import AllocationStrategy from ....channel.models import Channel from ....graphql.channel.tests.benchmark import CHANNEL_COUNT_IN_BENCHMARKS from ....tax.tests.fixtures.utils import create_channel_tax_configuration from ....warehouse.models import Warehou...
96
2,652
saleor
saleor/page/utils.py
.py
from .tasks import mark_pages_search_vector_as_dirty # Results in update time ~0.2s, consumes ~30 MB MARK_SEARCH_VECTOR_DIRTY_BATCH_SIZE = 1000 def mark_pages_search_vector_as_dirty_in_batches(page_ids: list[int]): """Mark pages as needing search index updates.""" for i in range(0, len(page_ids), MARK_SEARCH...
12
480
saleor
saleor/page/lock_objects.py
.py
from django.db.models import QuerySet from .models import Page def page_qs_select_for_update() -> QuerySet[Page]: return Page.objects.order_by("pk").select_for_update(of=["self"])
8
187
saleor
saleor/page/error_codes.py
.py
from enum import Enum class PageErrorCode(Enum): GRAPHQL_ERROR = "graphql_error" INVALID = "invalid" NOT_FOUND = "not_found" REQUIRED = "required" UNIQUE = "unique" DUPLICATED_INPUT_ITEM = "duplicated_input_item" ATTRIBUTE_ALREADY_ASSIGNED = "attribute_already_assigned"
12
301
saleor
saleor/page/models.py
.py
from typing import TYPE_CHECKING, Union from django.contrib.postgres.indexes import BTreeIndex, GinIndex from django.contrib.postgres.search import SearchVectorField from django.db import models from ..core.db.fields import SanitizedJSONField from ..core.editorjs import clean_editorjs from ..core.models import ModelW...
108
3,682
saleor
saleor/page/search.py
.py
from collections import defaultdict from typing import NamedTuple from django.conf import settings from django.db import transaction from django.db.models import Value from ..attribute.models import Attribute, AttributeValue from ..attribute.search import get_search_vectors_for_attribute_values from ..core.context im...
212
7,235
saleor
saleor/page/tasks.py
.py
from django.conf import settings from django.db import transaction from ..celeryconf import app from ..core.db.connection import allow_writer from .lock_objects import page_qs_select_for_update from .models import Page from .search import update_pages_search_vector # Results in update time ~1s, consumes ~25 MB UPDATE...
39
1,122
saleor
saleor/page/tests/test_tasks.py
.py
from unittest.mock import patch from ..models import Page from ..tasks import mark_pages_search_vector_as_dirty, update_pages_search_vector_task @patch("saleor.page.tasks.update_pages_search_vector") def test_update_pages_search_vector(update_pages_search_vector_mock, page_list): """Test updating search vector w...
49
1,314
saleor
saleor/page/tests/test_search.py
.py
import pytest from ...attribute.models import AttributeValue from ...attribute.utils import associate_attribute_values_to_instance from ..models import Page from ..search import ( update_pages_search_vector, ) def test_update_pages_search_vector_multiple_pages(page_list): """Test updating search vector for m...
125
4,024
saleor
saleor/page/tests/test_utils.py
.py
from unittest.mock import patch from ..models import Page from ..utils import mark_pages_search_vector_as_dirty_in_batches @patch("saleor.page.utils.MARK_SEARCH_VECTOR_DIRTY_BATCH_SIZE", 1) def test_mark_pages_search_vector_as_dirty_in_batches(page_list): # given page_ids = [page.id for page in page_list] ...
22
591
saleor
saleor/page/tests/fixtures/page_type.py
.py
import pytest from ...models import Page, PageType @pytest.fixture def page_type(db, size_page_attribute, tag_page_attribute): page_type = PageType.objects.create(name="Test page type", slug="test-page-type") page_type.page_attributes.add(size_page_attribute) page_type.page_attributes.add(tag_page_attrib...
46
1,325
saleor
saleor/page/tests/fixtures/page.py
.py
import pytest from ....attribute.utils import associate_attribute_values_to_instance from ....tests.utils import dummy_editorjs from ...models import Page from ...search import update_pages_search_vector @pytest.fixture def page(db, page_type, size_page_attribute): data = { "slug": "test-url", "t...
105
2,894
saleor
saleor/page/tests/fixtures/page_translation.py
.py
import pytest from ....tests.utils import dummy_editorjs from ...models import PageTranslation @pytest.fixture def page_translation_fr(page): return PageTranslation.objects.create( language_code="fr", page=page, title="French page title", content=dummy_editorjs("French page conten...
15
332
saleor
saleor/plugins/error_codes.py
.py
from enum import Enum class PluginErrorCode(Enum): GRAPHQL_ERROR = "graphql_error" INVALID = "invalid" PLUGIN_MISCONFIGURED = "plugin-misconfigured" NOT_FOUND = "not_found" REQUIRED = "required" UNIQUE = "unique"
11
239
saleor
saleor/plugins/models.py
.py
from django.db import models from django.db.models import JSONField from ..channel.models import Channel from ..core.utils.json_serializer import CustomJsonEncoder from ..permission.enums import PluginsPermissions class PluginConfiguration(models.Model): identifier = models.CharField(max_length=128) name = m...
36
1,176
saleor
saleor/plugins/apps.py
.py
from typing import TYPE_CHECKING from django.apps import AppConfig from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.module_loading import import_string if TYPE_CHECKING: from .base_plugin import BasePlugin class PluginConfig(AppConfig): name = "saleo...
36
1,113
saleor
saleor/plugins/manager.py
.py
from collections import defaultdict from collections.abc import Callable, Iterable from decimal import Decimal from typing import TYPE_CHECKING, Any, Optional, Union from django.conf import settings from django.http import HttpResponse, HttpResponseNotFound from django.utils.module_loading import import_string from pr...
2,877
109,949
saleor
saleor/plugins/__init__.py
.py
import importlib PLUGIN_IDENTIFIER_PREFIX = "plugin:" def discover_plugins_modules(plugins: list[str]): plugins_modules = [] for dotted_path in plugins: try: module_path, class_name = dotted_path.rsplit(".", 1) except ValueError as err: raise ImportError(f"{dotted_path...
17
498
saleor
saleor/plugins/email_common.py
.py
import logging import operator import os import re from collections.abc import Callable from dataclasses import asdict, dataclass from decimal import Decimal, InvalidOperation from email.headerregistry import Address from typing import TYPE_CHECKING, Any import dateutil.parser import i18naddress import pybars from bab...
427
13,620
saleor
saleor/plugins/views.py
.py
from django.http import HttpResponse from ..core.db.connection import allow_writer from ..graphql.core import SaleorContext from .manager import get_plugins_manager @allow_writer() def handle_plugin_webhook(request: SaleorContext, plugin_id: str) -> HttpResponse: manager = get_plugins_manager(allow_replica=False...
28
896
saleor
saleor/plugins/base_plugin.py
.py
from collections import defaultdict from collections.abc import Callable from copy import copy from dataclasses import dataclass from decimal import Decimal from typing import TYPE_CHECKING, Any, Optional, Union from django.http import HttpResponse from django.utils.functional import SimpleLazyObject from prices impor...
1,917
77,129
saleor
saleor/plugins/avatax/__init__.py
.py
import datetime import json import logging from collections.abc import Iterator from dataclasses import dataclass from decimal import Decimal from typing import TYPE_CHECKING, Any, cast from urllib.parse import urljoin import requests from django.core.cache import cache from requests.auth import HTTPBasicAuth from .....
771
26,633
saleor
saleor/plugins/avatax/tasks.py
.py
from celery.utils.log import get_task_logger from django.conf import settings from ...celeryconf import app from ...core.db.connection import allow_writer from ...core.taxes import TaxError from ...core.telemetry import saleor_attributes, tracer from ...order.events import external_notification_event from ...order.mod...
59
2,097
saleor
saleor/plugins/avatax/plugin.py
.py
import logging from collections.abc import Callable, Iterable from dataclasses import asdict from decimal import Decimal from functools import partial from typing import TYPE_CHECKING, Any, Optional, Union from urllib.parse import urljoin from django.core.exceptions import ValidationError from django.utils.functional ...
1,001
37,819
saleor
saleor/plugins/avatax/tests/test_tasks.py
.py
import os from dataclasses import asdict from urllib.parse import urljoin import pytest from ....core.taxes import TaxError from ....order import OrderEvents from .. import AvataxConfiguration, get_api_url, get_order_request_data from ..tasks import api_post_request_task @pytest.mark.vcr def test_api_post_request_t...
154
5,240
saleor
saleor/plugins/avatax/tests/test_avatax_caching.py
.py
from copy import deepcopy from decimal import Decimal from unittest.mock import ANY, Mock, patch from django.test import override_settings from prices import Money, TaxedMoney from ....checkout.fetch import fetch_checkout_lines from ...manager import get_plugins_manager from .. import CACHE_KEY, generate_request_data...
716
25,832
saleor
saleor/plugins/avatax/tests/test_avatax.py
.py
import datetime from copy import deepcopy from decimal import Decimal from json import JSONDecodeError from unittest.mock import Mock, patch import graphene import pytest from django.core.exceptions import ValidationError from django.test import override_settings from prices import Money, TaxedMoney from requests impo...
6,864
224,633
saleor
saleor/plugins/avatax/tests/conftest.py
.py
import os import pytest from ....account.models import Address from ...models import PluginConfiguration from .. import AvataxConfiguration from ..plugin import DeprecatedAvataxPlugin @pytest.fixture(scope="module") def vcr_config(): return { "filter_headers": [("Authorization", "Basic Og==")], } ...
980
36,752
saleor
saleor/plugins/sendgrid/__init__.py
.py
from dataclasses import dataclass @dataclass class SendgridConfiguration: api_key: str | None sender_name: str | None sender_address: str | None account_confirmation_template_id: str | None account_set_customer_password_template_id: str | None account_delete_template_id: str | None account...
24
914
saleor
saleor/plugins/sendgrid/tasks.py
.py
import logging from python_http_client import exceptions from sendgrid import SendGridAPIClient, SendGridException from sendgrid.helpers.mail import Mail from ...account import events as account_events from ...celeryconf import app from ...core.db.connection import allow_writer from ...giftcard import events as gift_...
364
12,767
saleor
saleor/plugins/sendgrid/plugin.py
.py
import logging from collections.abc import Callable from dataclasses import asdict from django.core.exceptions import ValidationError from ...core.notify import NotifyEventType, UserNotifyEvent from ...plugins.sendgrid.tasks import send_email_with_dynamic_template_id from ..base_plugin import BasePlugin, Configuratio...
285
10,973
saleor
saleor/plugins/sendgrid/tests/test_tasks.py
.py
from dataclasses import asdict from unittest.mock import Mock, patch import pytest from ....account import CustomerEvents from ....account.models import CustomerEvent from ....account.notifications import get_default_user_payload from ....giftcard import GiftCardEvents from ....giftcard.models import GiftCardEvent fr...
951
29,270
saleor
saleor/plugins/sendgrid/tests/test_plugin.py
.py
import json from dataclasses import asdict from unittest.mock import MagicMock, patch import pytest from django.core.exceptions import ValidationError from ....account.notifications import get_user_custom_payload from ....core.notify import AdminNotifyEvent, UserNotifyEvent from ....webhook.payloads import generate_p...
186
6,149
saleor
saleor/plugins/sendgrid/tests/conftest.py
.py
import pytest from ....plugins.sendgrid.plugin import DeprecatedSendgridEmailPlugin from ...manager import get_plugins_manager @pytest.fixture def sendgrid_email_plugin(settings, channel_USD): def fun( active=True, sender_name=None, sender_address=None, account_confirmation_templa...
111
4,577
saleor
saleor/plugins/openid_connect/utils.py
.py
import datetime import json import logging from typing import TYPE_CHECKING import requests from authlib.jose import JWTClaims, jwt from authlib.jose.errors import DecodeError, JoseError from authlib.oidc.core import CodeIDToken from django.conf import settings from django.contrib.auth.hashers import make_password fro...
761
25,800
saleor
saleor/plugins/openid_connect/exceptions.py
.py
class AuthenticationError(Exception): """Raises when error occurred during authentication."""
3
98
saleor
saleor/plugins/openid_connect/dataclasses.py
.py
from dataclasses import dataclass @dataclass class OpenIDConnectConfig: client_id: str client_secret: str enable_refresh_token: bool json_web_key_set_url: str authorization_url: str logout_url: str token_url: str user_info_url: str audience: str use_scope_permissions: bool ...
18
372
saleor
saleor/plugins/openid_connect/client.py
.py
from authlib.integrations import requests_client from requests_hardened import HTTPSession from ...core.http_client import HTTPConfig class OAuth2Client(HTTPSession, requests_client.OAuth2Session): """Override the 3rd party OAuth client with our custom HTTP client.""" def __init__(self, **kwargs): k...
13
394
saleor
saleor/plugins/openid_connect/plugin.py
.py
import logging from typing import cast from urllib.parse import urlparse from authlib.common.errors import AuthlibBaseError from django.core import signing from django.core.exceptions import ValidationError from jwt import DecodeError, ExpiredSignatureError, InvalidTokenError from requests import HTTPError, PreparedRe...
578
22,704
saleor
saleor/plugins/openid_connect/tests/test_ip_filtering.py
.py
import pytest from django.core import signing from requests_hardened.ip_filter import InvalidIPAddress from ....core.http_client import HTTPClient def test_rejects_private_ips(openid_plugin, id_token, rf, monkeypatch): """Ensure private IP addresses are rejected by OIDC.""" monkeypatch.setattr(HTTPClient.con...
21
720
saleor
saleor/plugins/openid_connect/tests/test_plugin.py
.py
from unittest.mock import MagicMock, Mock, patch from urllib.parse import parse_qs, urlparse import pytest from authlib.integrations.base_client.errors import OAuthError from authlib.jose.errors import JoseError from django.core import signing from django.core.exceptions import ValidationError from freezegun import fr...
2,147
72,680
saleor
saleor/plugins/openid_connect/tests/test_utils.py
.py
import datetime import json import time import warnings from functools import partial from unittest import mock from unittest.mock import MagicMock, Mock, call, patch import pytest import requests from authlib.jose import JWTClaims from django.core.cache import cache from django.core.exceptions import ValidationError ...
1,372
44,705
saleor
saleor/plugins/openid_connect/tests/conftest.py
.py
import jwt import pytest from ...manager import get_plugins_manager from ..plugin import OpenIDConnectPlugin @pytest.fixture def plugin_configuration(): def fun( client_id=None, client_secret=None, enable_refresh_token=True, oauth_authorization_url=None, oauth_token_url=No...
181
6,768
saleor
saleor/plugins/tests/test_views.py
.py
import pytest from .sample_plugins import ( ChannelPluginSample, InactiveChannelPluginSample, PluginInactive, PluginSample, ) @pytest.mark.parametrize( ("plugin_id", "plugin_path", "status_code"), [ (PluginSample.PLUGIN_ID, "/webhook/paid", 200), (PluginInactive.PLUGIN_ID, "/w...
73
2,240
saleor
saleor/plugins/tests/sample_plugins.py
.py
from collections import defaultdict from decimal import Decimal from typing import TYPE_CHECKING, Any, Optional, Union from django.http import HttpResponse, HttpResponseNotFound, JsonResponse from prices import Money, TaxedMoney from ...account.models import User from ...core.taxes import TaxType from ...graphql.core...
474
14,839
saleor
saleor/plugins/tests/utils.py
.py
def get_config_value( field_name: str, configuration: list[dict[str, str | bool]] ) -> str | bool | None: for elem in configuration: if elem["name"] == field_name: return elem["value"] return None
8
229
saleor
saleor/plugins/tests/test_manager.py
.py
import json from decimal import Decimal from functools import partial from unittest import mock from unittest.mock import patch import pytest from django.http import HttpResponseNotFound, JsonResponse from django.test import override_settings from prices import Money, TaxedMoney from ...channel import TransactionFlow...
1,627
52,804
saleor
saleor/plugins/tests/test_plugin_config_checks.py
.py
import pytest from ..apps import PluginConfig def test_empty_plugin_path(): plugin_path = "" with pytest.raises(ImportError): PluginConfig.load_and_check_plugin(None, plugin_path) def test_invalid_plugin_path(): plugin_path = "saleor.core.plugins.wrong_path.Plugin" with pytest.raises(Import...
16
390
saleor
saleor/plugins/tests/test_email_common.py
.py
import json from unittest.mock import ANY, patch import pytest from django.core.exceptions import ValidationError from ...order.notifications import get_image_payload from ..email_common import ( DEFAULT_EMAIL_CONFIGURATION, EmailConfig, get_plain_text_message_for_email, get_product_image_thumbnail, ...
191
6,103
saleor
saleor/plugins/tests/test_plugins.py
.py
from ..base_plugin import ConfigurationTypeField from ..manager import get_plugins_manager from ..tests.sample_plugins import PluginSample from ..tests.utils import get_config_value def test_update_config_items_keeps_bool_value(plugin_configuration, settings): settings.PLUGINS = ["saleor.plugins.tests.sample_plug...
233
8,346