language stringclasses 4
values | source_code stringlengths 21 986k | test_code stringlengths 125 698k | repo_name stringclasses 95
values |
|---|---|---|---|
python | """Automatically generated file.
To update, run python3 -m script.hassfest
"""
FLOWS = {
"helper": [
"derivative",
"filter",
"generic_hygrostat",
"generic_thermostat",
"group",
"history_stats",
"integration",
"min_max",
"mold_indicator",
... | """Test the Bond config flow."""
from __future__ import annotations
from http import HTTPStatus
from ipaddress import ip_address
from typing import Any
from unittest.mock import MagicMock, Mock, patch
from aiohttp import ClientConnectionError, ClientResponseError
from homeassistant import config_entries
from homeas... | core |
python | """Support for Unifi Led lights."""
from __future__ import annotations
import logging
from typing import Any
from unifiled import unifiled
import voluptuous as vol
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
PLATFORM_SCHEMA as LIGHT_PLATFORM_SCHEMA,
ColorMode,
LightEntity,
)
from h... | """Velbus light platform tests."""
from unittest.mock import AsyncMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_FLASH,
ATTR_TRANSITION,
DOMAIN as LIGHT_DOMAIN,
FLASH_LONG,
FLASH_SHORT,
)
from homeass... | core |
python | """Platform for cover integration."""
from typing import Any
from boschshcpy import SHCShutterControl
from homeassistant.components.cover import (
ATTR_POSITION,
CoverDeviceClass,
CoverEntity,
CoverEntityFeature,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platfor... | """The tests for the Template cover platform."""
from typing import Any
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components import cover, template
from homeassistant.components.cover import (
ATTR_POSITION,
ATTR_TILT_POSITION,
DOMAIN as COVER_DOMAIN,
CoverEntity... | core |
python | from collections.abc import Mapping
from typing import Any, Literal, TypedDict
from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_serializer
from rest_framework import serializers, status
from rest_framework.exceptions import ValidationError
from rest_framework.request import Request
from ... | from functools import cached_property
from unittest.mock import MagicMock, patch
from django.test import override_settings
from rest_framework import status
from sentry.auth import access
from sentry.core.endpoints.organization_member_team_details import ERR_INSUFFICIENT_ROLE
from sentry.models.groupassignee import G... | sentry |
python | """
accessor.py contains base classes for implementing accessor properties
that can be mixed into or pinned onto other pandas classes.
"""
from __future__ import annotations
import functools
from typing import (
TYPE_CHECKING,
final,
)
import warnings
from pandas.util._decorators import (
set_module,
)... | import string
import numpy as np
import pytest
import pandas as pd
from pandas import SparseDtype
import pandas._testing as tm
from pandas.core.arrays.sparse import SparseArray
class TestSeriesAccessor:
def test_to_dense(self):
ser = pd.Series([0, 1, 0, 10], dtype="Sparse[int64]")
result = ser.s... | pandas |
python | from abc import ABC, abstractmethod
import io
import os
import gzip
import socket
import ssl
import time
import warnings
from datetime import datetime, timedelta, timezone
from collections import defaultdict
from urllib.request import getproxies
try:
import brotli # type: ignore
except ImportError:
brotli = N... | import logging
import pickle
import os
import socket
import sys
from collections import defaultdict
from datetime import datetime, timedelta, timezone
from unittest import mock
import pytest
from tests.conftest import CapturingServer
try:
import httpcore
except (ImportError, ModuleNotFoundError):
httpcore = N... | sentry-python |
python | import os
import time
from threading import Thread, Lock
import sentry_sdk
from sentry_sdk.utils import logger
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import Optional
MAX_DOWNSAMPLE_FACTOR = 10
class Monitor:
"""
Performs health checks in a separate thread once every interval s... | from collections import Counter
from unittest import mock
import sentry_sdk
from sentry_sdk.transport import Transport
class HealthyTestTransport(Transport):
def capture_envelope(self, _):
pass
def is_healthy(self):
return True
class UnhealthyTestTransport(HealthyTestTransport):
def is... | sentry-python |
python | """Provides device automations for control of Samsung TV."""
from __future__ import annotations
import voluptuous as vol
from homeassistant.components.device_automation import (
DEVICE_TRIGGER_BASE_SCHEMA,
InvalidDeviceAutomationConfig,
)
from homeassistant.const import CONF_DEVICE_ID, CONF_PLATFORM, CONF_TY... | """The tests for Kodi device triggers."""
import pytest
from homeassistant.components import automation
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.kodi.const import DOMAIN
from homeassistant.components.media_player import DOMAIN as MP_DOMAIN
from homeassi... | core |
python | """Support for Palazzetti sensors."""
from dataclasses import dataclass
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import UnitOfLength, UnitOfMass, UnitOfTemperature
from homeassistant.core import... | """Test the OralB sensors."""
from datetime import timedelta
import time
import pytest
from homeassistant.components.bluetooth import (
FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS,
async_address_present,
)
from homeassistant.components.oralb.const import DOMAIN
from homeassistant.const import ATTR_ASSUMED_S... | core |
python | from datetime import datetime
from django.core.cache import cache
from sentry.data_secrecy.types import CACHE_KEY_PATTERN, EffectiveGrantStatus
class EffectiveGrantStatusCache:
@staticmethod
def get(organization_id: int) -> EffectiveGrantStatus:
"""
Retrieve cached grant status for an organi... | from unittest import TestCase
from sentry.lang.javascript.cache import SourceCache
class BasicCacheTest(TestCase):
def test_basic_features(self) -> None:
cache = SourceCache()
url = "http://example.com/foo.js"
assert url not in cache
assert cache.get(url) is None
cache.a... | sentry |
python | import logging
from collections.abc import Mapping
import sentry_sdk
from django.conf import settings
from django.utils import timezone
from urllib3.exceptions import MaxRetryError, TimeoutError
from sentry import options
from sentry.conf.server import (
SEER_MAX_GROUPING_DISTANCE,
SEER_SIMILAR_ISSUES_URL,
... | from datetime import timedelta
from typing import Any
from unittest import mock
from unittest.mock import ANY, MagicMock
from django.utils import timezone
from urllib3.exceptions import MaxRetryError, TimeoutError
from urllib3.response import HTTPResponse
from sentry import options
from sentry.conf.server import SEER... | sentry |
python | """Zeroconf usage utility to warn about multiple instances."""
from typing import Any
import zeroconf
from homeassistant.helpers.frame import ReportBehavior, report_usage
from .models import HaZeroconf
def install_multiple_zeroconf_catcher(hass_zc: HaZeroconf) -> None:
"""Wrap the Zeroconf class to return the... | """Tests for the Bluetooth integration."""
import bleak
from habluetooth.usage import (
install_multiple_bleak_catcher,
uninstall_multiple_bleak_catcher,
)
from habluetooth.wrappers import HaBleakClientWrapper, HaBleakScannerWrapper
import pytest
from homeassistant.core import HomeAssistant
from . import gen... | core |
python | """
Check that doc/source/reference/testing.rst documents
all exceptions and warnings in pandas/errors/__init__.py.
This is meant to be run as a pre-commit hook - to run it manually, you can do:
pre-commit run pandas-errors-documented --all-files
"""
from __future__ import annotations
import argparse
import ast... | import datetime
from io import BytesIO
import re
import numpy as np
import pytest
from pandas import (
CategoricalIndex,
DataFrame,
HDFStore,
Index,
MultiIndex,
date_range,
read_hdf,
)
from pandas.io.pytables import (
Term,
_maybe_adjust_name,
)
pytestmark = [pytest.mark.single_c... | pandas |
python | from __future__ import annotations
from typing import Any
import jsonschema
import orjson
import sentry_sdk
from django.conf import settings
from rest_framework.request import Request
from rest_framework.response import Response
from sentry import analytics, features
from sentry.api.api_owners import ApiOwner
from s... | from hashlib import sha1
from unittest.mock import MagicMock, patch
import orjson
from django.core.files.base import ContentFile
from django.urls import reverse
from sentry.constants import ObjectStatus
from sentry.models.apitoken import ApiToken
from sentry.models.files.fileblob import FileBlob
from sentry.models.fi... | sentry |
python | """Automatically generated file.
To update, run python3 -m script.hassfest
"""
FLOWS = {
"helper": [
"derivative",
"filter",
"generic_hygrostat",
"generic_thermostat",
"group",
"history_stats",
"integration",
"min_max",
"mold_indicator",
... | """Tests for the TOLO Sauna config flow."""
from unittest.mock import Mock, patch
import pytest
from tololib import ToloCommunicationError
from homeassistant.components.tolo.const import DOMAIN
from homeassistant.config_entries import SOURCE_DHCP, SOURCE_USER
from homeassistant.const import CONF_HOST
from homeassist... | core |
python | #
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 Raphael Michel and contributors
# Copyright (C) 2020-today pretix GmbH and contributors
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as published by... | #
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 Raphael Michel and contributors
# Copyright (C) 2020-today pretix GmbH and contributors
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as published by... | pretix |
python | from langchain_core.load.serializable import (
BaseSerialized,
Serializable,
SerializedConstructor,
SerializedNotImplemented,
SerializedSecret,
to_json_not_implemented,
try_neq_default,
)
__all__ = [
"BaseSerialized",
"Serializable",
"SerializedConstructor",
"SerializedNotIm... | import json
import pytest
from pydantic import BaseModel, ConfigDict, Field, SecretStr
from langchain_core.load import Serializable, dumpd, dumps, load
from langchain_core.load.serializable import _is_field_useful
from langchain_core.messages import AIMessage
from langchain_core.outputs import ChatGeneration, Generat... | langchain |
python | from sentry.dynamic_sampling.rules.biases.base import Bias
from sentry.dynamic_sampling.rules.utils import RESERVED_IDS, PolymorphicRule, RuleType
from sentry.models.project import Project
class BoostReplayIdBias(Bias):
"""
Boosts at 100% sample rate all the traces that have a replay_id.
"""
def gene... | from sentry.dynamic_sampling.rules.biases.boost_replay_id_bias import BoostReplayIdBias
from sentry.testutils.pytest.fixtures import django_db_all
@django_db_all
def test_generate_bias_rules_v2(default_project) -> None:
rules = BoostReplayIdBias().generate_rules(project=default_project, base_sample_rate=0.1)
... | sentry |
python | r"""
Renderer that will decrypt GPG ciphers
Any value in the SLS file can be a GPG cipher, and this renderer will decrypt it
before passing it off to Salt. This allows you to safely store secrets in
source control, in such a way that only your Salt master can decrypt them and
distribute them only to the minions that n... | import os
from subprocess import PIPE
from textwrap import dedent
import pytest
import salt.renderers.gpg as gpg
from salt.exceptions import SaltRenderError
from tests.support.mock import MagicMock, Mock, call, patch
@pytest.fixture
def configure_loader_modules(minion_opts):
"""
GPG renderer configuration
... | salt |
python | """Automatically generated file.
To update, run python3 -m script.hassfest
"""
FLOWS = {
"helper": [
"derivative",
"filter",
"generic_hygrostat",
"generic_thermostat",
"group",
"history_stats",
"integration",
"min_max",
"mold_indicator",
... | """Test the Matter config flow."""
from __future__ import annotations
from collections.abc import Generator
from ipaddress import ip_address
from unittest.mock import AsyncMock, MagicMock, call, patch
from uuid import uuid4
from aiohasupervisor import SupervisorError
from aiohasupervisor.models import Discovery
from... | core |
python | from datetime import timezone
import numpy as np
from pandas._libs.tslibs.tzconversion import tz_localize_to_utc
from .tslib import (
_sizes,
_tzs,
tzlocal_obj,
)
try:
old_sig = False
from pandas._libs.tslibs import tz_convert_from_utc
except ImportError:
try:
old_sig = False
... | from datetime import datetime
import dateutil.tz
from dateutil.tz import gettz
import numpy as np
import pytest
from pandas._libs.tslibs import timezones
from pandas import (
DatetimeIndex,
Index,
NaT,
Timestamp,
date_range,
offsets,
)
import pandas._testing as tm
class TestTZConvert:
d... | pandas |
python | """Automatically generated file.
To update, run python3 -m script.hassfest
"""
FLOWS = {
"helper": [
"derivative",
"filter",
"generic_hygrostat",
"generic_thermostat",
"group",
"history_stats",
"integration",
"min_max",
"mold_indicator",
... | """Tests for the Mealie config flow."""
from unittest.mock import AsyncMock
from aiomealie import About, MealieAuthenticationError, MealieConnectionError
import pytest
from homeassistant.components.mealie.const import DOMAIN
from homeassistant.config_entries import SOURCE_HASSIO, SOURCE_IGNORE, SOURCE_USER
from home... | core |
python | """Provides diagnostics for Palazzetti."""
from __future__ import annotations
from typing import Any
from homeassistant.core import HomeAssistant
from .coordinator import PalazzettiConfigEntry
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, entry: PalazzettiConfigEntry
) -> dict[str, Any]:
... | """Tests for the diagnostics data provided by the Plugwise integration."""
from unittest.mock import MagicMock
from syrupy.assertion import SnapshotAssertion
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
from tests.components.diagnostics import get_diagnostics_for_config_entr... | core |
python | """Support for Unifi Led lights."""
from __future__ import annotations
import logging
from typing import Any
from unifiled import unifiled
import voluptuous as vol
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
PLATFORM_SCHEMA as LIGHT_PLATFORM_SCHEMA,
ColorMode,
LightEntity,
)
from h... | """Tests for the Nanoleaf light platform."""
from unittest.mock import AsyncMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.light import ATTR_EFFECT_LIST, DOMAIN as LIGHT_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERV... | core |
python | """Automatically generated file.
To update, run python3 -m script.hassfest
"""
FLOWS = {
"helper": [
"derivative",
"filter",
"generic_hygrostat",
"generic_thermostat",
"group",
"history_stats",
"integration",
"min_max",
"mold_indicator",
... | """Test the iNELS config flow."""
from homeassistant.components.inels.const import DOMAIN, TITLE
from homeassistant.components.mqtt import MQTT_CONNECTION_STATE
from homeassistant.config_entries import SOURCE_MQTT, SOURCE_USER
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowR... | core |
python | # types.py
# Copyright (C) 2005-2025 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
"""Compatibility namespace for sqlalchemy.sql.types."""
from __future__ import annotatio... | import array
import datetime
import decimal
import os
import random
from sqlalchemy import bindparam
from sqlalchemy import cast
from sqlalchemy import CHAR
from sqlalchemy import DATE
from sqlalchemy import Date
from sqlalchemy import DateTime
from sqlalchemy import Double
from sqlalchemy import DOUBLE_PRECISION
from... | sqlalchemy |
python | 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... | 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... | saleor |
python | import re
from collections import defaultdict
from typing import Optional
from ..exceptions import (
InvalidParameterValueErrorTagNull,
TagLimitExceeded,
)
from ..utils import (
EC2_PREFIX_TO_RESOURCE,
get_prefix,
simple_aws_filter_to_re,
)
class TagBackend:
VALID_TAG_FILTERS = ["key", "resou... | from uuid import uuid4
import boto3
import pytest
from botocore.exceptions import ClientError
from moto import mock_aws
from tests import EXAMPLE_AMI_ID
from .helpers import assert_dryrun_error
from .test_instances import retrieve_all_instances
@mock_aws
def test_instance_create_tags():
ec2 = boto3.resource("e... | moto |
python | import threading
from moto.iam.models import (
AccessKey,
AWSManagedPolicy,
IAMBackend,
InlinePolicy,
Policy,
User,
)
from moto.iam.models import Role as MotoRole
from moto.iam.policy_validation import VALID_STATEMENT_ELEMENTS
from localstack import config
from localstack.constants import TAG_... | import json
import os
import pytest
from localstack.services.iam.provider import SERVICE_LINKED_ROLE_PATH_PREFIX
from localstack.testing.pytest import markers
from localstack.utils.common import short_uid
@markers.aws.validated
def test_delete_role_detaches_role_policy(deploy_cfn_template, aws_client):
role_nam... | localstack |
python | import re
import warnings
from typing import TYPE_CHECKING, TypeVar
from .typedefs import Handler, Middleware
from .web_exceptions import HTTPMove, HTTPPermanentRedirect
from .web_request import Request
from .web_response import StreamResponse
from .web_urldispatcher import SystemRoute
__all__ = (
"middleware",
... | import asyncio
from collections.abc import Awaitable, Callable, Iterable
from typing import NoReturn
import pytest
from yarl import URL
from aiohttp import web, web_app
from aiohttp.pytest_plugin import AiohttpClient
from aiohttp.test_utils import TestClient
from aiohttp.typedefs import Handler, Middleware
CLI = Cal... | aiohttp |
python | import graphene
from ....permission.enums import ShippingPermissions
from ....shipping import models
from ...core import ResolveInfo
from ...core.context import ChannelContext
from ...core.doc_category import DOC_CATEGORY_SHIPPING
from ...core.fields import JSONString
from ...core.mutations import DeprecatedModelMutat... | import json
from unittest import mock
import graphene
import pytest
from django.utils.functional import SimpleLazyObject
from freezegun import freeze_time
from .....core.utils.json_serializer import CustomJsonEncoder
from .....shipping.error_codes import ShippingErrorCode
from .....shipping.models import ShippingMeth... | saleor |
python | """Support for Palazzetti buttons."""
from __future__ import annotations
from pypalazzetti.exceptions import CommunicationError
from homeassistant.components.button import ButtonEntity
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.enti... | """Tests for the WLED button platform."""
from unittest.mock import MagicMock
import pytest
from syrupy.assertion import SnapshotAssertion
from wled import WLEDConnectionError, WLEDError
from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRESS
from homeassistant.components.wled.const import... | core |
python | """Init file for Home Assistant."""
| """Test init for Snoo."""
from unittest.mock import AsyncMock
from python_snoo.exceptions import SnooAuthException
from homeassistant.components.snoo import SnooDeviceError
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from . import async_init_integration
a... | core |
python | """Init file for Home Assistant."""
| """Tests for the Smappee component init module."""
from unittest.mock import patch
from homeassistant.components.smappee.const import DOMAIN
from homeassistant.config_entries import SOURCE_ZEROCONF
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def test_unload_config_en... | core |
python | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | ansible |
python | from __future__ import annotations
from collections.abc import Mapping, Sequence
from typing import Any
from django.http import HttpResponse
from django.http.request import HttpRequest
from django.http.response import HttpResponseBase
from sentry.integrations.base import (
FeatureDescription,
IntegrationData... | from dataclasses import asdict
from datetime import datetime, timezone
from unittest.mock import MagicMock, Mock, patch
from urllib.parse import parse_qs, quote, urlencode, urlparse
import orjson
import responses
from django.core.cache import cache
from django.test import override_settings
from fixtures.gitlab import... | sentry |
python | from snuba_sdk import Column, Condition, Direction, Op, OrderBy, Query, Request, Storage
from sentry import options
from sentry.search.events.fields import resolve_datetime64
from sentry.search.events.types import SnubaParams
from sentry.snuba.dataset import Dataset, StorageKey
from sentry.snuba.referrer import Referr... | import os
from datetime import timedelta
from io import BytesIO
from unittest.mock import MagicMock, Mock, patch
from uuid import uuid4
import pytest
from django.core.files.base import ContentFile
from django.db import DatabaseError
from django.utils import timezone
from sentry.models.files.file import File
from sent... | sentry |
python | import json
import logging
from ssl import SSLContext
from typing import Dict, Union, List, Optional
import aiohttp
from aiohttp import BasicAuth, ClientSession
from slack.errors import SlackApiError
from .internal_utils import _debug_log_response, _build_request_headers, _build_body
from .webhook_response import Web... | import time
import unittest
from slack_sdk.scim import User, Group
from slack_sdk.scim.v1.async_client import AsyncSCIMClient
from slack_sdk.scim.v1.group import GroupMember
from slack_sdk.scim.v1.user import UserName, UserEmail
from tests.helpers import async_test
from tests.slack_sdk.scim.mock_web_api_handler import... | python-slack-sdk |
python | """Switch platform for Growatt."""
from __future__ import annotations
from dataclasses import dataclass
import logging
from typing import Any
from growattServer import GrowattV1ApiError
from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
from homeassistant.const import EntityCategory
f... | """The tests for the Modbus switch component."""
from datetime import timedelta
from unittest import mock
from pymodbus.exceptions import ModbusException
import pytest
from homeassistant.components.homeassistant import SERVICE_UPDATE_ENTITY
from homeassistant.components.modbus.const import (
CALL_TYPE_COIL,
... | core |
python | """Automatically generated file.
To update, run python3 -m script.hassfest
"""
FLOWS = {
"helper": [
"derivative",
"filter",
"generic_hygrostat",
"generic_thermostat",
"group",
"history_stats",
"integration",
"min_max",
"mold_indicator",
... | """Test the Portainer config flow."""
from unittest.mock import AsyncMock, MagicMock
from pyportainer.exceptions import (
PortainerAuthenticationError,
PortainerConnectionError,
PortainerTimeoutError,
)
import pytest
from homeassistant.components.portainer.const import DOMAIN
from homeassistant.config_en... | core |
python | import os
import tempfile
from collections import defaultdict
from functools import partial
from langgraph.checkpoint.base import (
ChannelVersions,
Checkpoint,
CheckpointMetadata,
SerializerProtocol,
)
from langgraph.checkpoint.memory import InMemorySaver, PersistentDict
from langgraph.pregel._checkpo... | import pytest
from langchain_classic.base_memory import BaseMemory
from langchain_classic.chains.conversation.memory import (
ConversationBufferMemory,
ConversationBufferWindowMemory,
ConversationSummaryMemory,
)
from langchain_classic.memory import ReadOnlySharedMemory, SimpleMemory
from tests.unit_tests.... | langchain |
python | """Support for Palazzetti buttons."""
from __future__ import annotations
from pypalazzetti.exceptions import CommunicationError
from homeassistant.components.button import ButtonEntity
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.enti... | """Tests for Miele button module."""
from unittest.mock import MagicMock, Mock
from aiohttp import ClientResponseError
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRESS
from homeassistant.const import ATTR_ENTITY_ID
from ho... | core |
python | """Provides device automations for Cover."""
from __future__ import annotations
import voluptuous as vol
from homeassistant.const import (
CONF_ABOVE,
CONF_BELOW,
CONF_CONDITION,
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ENTITY_ID,
CONF_TYPE,
)
from homeassistant.core import HomeAssistant, callba... | """The tests for Cover device conditions."""
import pytest
from pytest_unordered import unordered
from homeassistant.components import automation
from homeassistant.components.cover import DOMAIN, CoverEntityFeature, CoverState
from homeassistant.components.device_automation import DeviceAutomationType
from homeassis... | core |
python | from multiprocessing.connection import Connection
from os import environ, getpid
from typing import Any, Callable, Optional
from sanic.log import Colors, logger
from sanic.worker.process import ProcessState
from sanic.worker.state import WorkerState
class WorkerMultiplexer:
"""Multiplexer for Sanic workers.
... | import sys
from multiprocessing import Event
from os import environ, getpid
from typing import Any, Union
from unittest.mock import Mock
import pytest
from sanic import Sanic
from sanic.compat import use_context
from sanic.worker.multiplexer import WorkerMultiplexer
from sanic.worker.state import WorkerState
def n... | sanic |
python | """Support for Palazzetti sensors."""
from dataclasses import dataclass
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import UnitOfLength, UnitOfMass, UnitOfTemperature
from homeassistant.core import... | """Tests for the sensors provided by the easyEnergy integration."""
from unittest.mock import MagicMock
from easyenergy import EasyEnergyNoDataError
import pytest
from homeassistant.components.easyenergy.const import DOMAIN
from homeassistant.components.homeassistant import SERVICE_UPDATE_ENTITY
from homeassistant.c... | core |
python | """Init file for Home Assistant."""
| """Tests for Fritz!Tools."""
from unittest.mock import patch
import pytest
from homeassistant.components.device_tracker import (
CONF_CONSIDER_HOME,
DEFAULT_CONSIDER_HOME,
)
from homeassistant.components.fritz.const import (
DOMAIN,
FRITZ_AUTH_EXCEPTIONS,
FRITZ_EXCEPTIONS,
)
from homeassistant.co... | core |
python | """Automatically generated file.
To update, run python3 -m script.hassfest
"""
FLOWS = {
"helper": [
"derivative",
"filter",
"generic_hygrostat",
"generic_thermostat",
"group",
"history_stats",
"integration",
"min_max",
"mold_indicator",
... | """Define tests for the OpenWeatherMap config flow."""
from unittest.mock import AsyncMock
from pyopenweathermap import RequestError
import pytest
from homeassistant.components.openweathermap.const import (
DEFAULT_LANGUAGE,
DEFAULT_NAME,
DEFAULT_OWM_MODE,
DOMAIN,
OWM_MODE_V30,
)
from homeassista... | core |
python | """
Python renderer that includes a Pythonic Object based interface
:maintainer: Evan Borgstrom <evan@borgstrom.ca>
Let's take a look at how you use pyobjects in a state file. Here's a quick
example that ensures the ``/tmp`` directory is in the correct state.
.. code-block:: python
:linenos:
#!pyobjects
... | import logging
import pytest
import salt.renderers.pyobjects as pyobjects
from salt.utils.odict import OrderedDict
from tests.support.mock import MagicMock
log = logging.getLogger(__name__)
@pytest.fixture()
def configure_loader_modules(minion_opts):
minion_opts["file_client"] = "local"
minion_opts["id"] =... | salt |
python | from __future__ import annotations
import logging
from django import forms
from django.contrib import messages
from django.core.exceptions import PermissionDenied
from django.http import HttpRequest, HttpResponseRedirect
from django.http.response import HttpResponse, HttpResponseBadRequest, HttpResponseBase
from djan... | from unittest.mock import MagicMock, patch
import pytest
from django.core import mail
from django.db import models
from django.urls import reverse
from sentry import audit_log
from sentry.auth.authenticators.totp import TotpInterface
from sentry.auth.exceptions import IdentityNotValid
from sentry.auth.providers.dummy... | sentry |
python | import re
from django.core import validators
from django.utils.deconstruct import deconstructible
from django.utils.translation import gettext_lazy as _
@deconstructible
class ASCIIUsernameValidator(validators.RegexValidator):
regex = r"^[\w.@+-]+\Z"
message = _(
"Enter a valid username. This value m... | import os
from unittest import mock
from django.contrib.auth import validators
from django.contrib.auth.models import User
from django.contrib.auth.password_validation import (
CommonPasswordValidator,
MinimumLengthValidator,
NumericPasswordValidator,
UserAttributeSimilarityValidator,
get_default_p... | django |
python | from mitmproxy import ctx
from mitmproxy.addons import asgiapp
from mitmproxy.addons.onboardingapp import app
APP_HOST = "mitm.it"
class Onboarding(asgiapp.WSGIApp):
name = "onboarding"
def __init__(self):
super().__init__(app, APP_HOST, None)
def load(self, loader):
loader.add_option(
... | import pytest
from mitmproxy.addons import onboarding
from mitmproxy.test import taddons
@pytest.fixture
def client():
with onboarding.app.test_client() as client:
yield client
class TestApp:
def addons(self):
return [onboarding.Onboarding()]
def test_basic(self, client):
ob = ... | mitmproxy |
python | """Init file for Home Assistant."""
| """The tests for the Button component."""
from collections.abc import Generator
from datetime import timedelta
from unittest.mock import MagicMock
from freezegun.api import FrozenDateTimeFactory
import pytest
from homeassistant.components.button import (
DOMAIN,
SERVICE_PRESS,
ButtonDeviceClass,
Butt... | core |
python | from __future__ import annotations
import logging
from typing import Any, cast
from rest_framework import serializers
from sentry.auth.access import SystemAccess
from sentry.incidents.logic import (
ChannelLookupTimeoutError,
InvalidTriggerActionError,
get_slack_channel_ids,
)
from sentry.incidents.model... | import unittest
from collections.abc import Generator
from unittest import mock
from unittest.mock import Mock
import pytest
from django.core.cache import cache
from sentry.incidents.logic import delete_alert_rule, update_alert_rule
from sentry.incidents.models.alert_rule import (
AlertRule,
AlertRuleActivity... | sentry |
python | from __future__ import annotations
from datetime import (
datetime,
timedelta,
)
from typing import (
TYPE_CHECKING,
Literal,
overload,
)
import warnings
from dateutil.relativedelta import (
FR,
MO,
SA,
SU,
TH,
TU,
WE,
)
import numpy as np
from pandas._libs.tslibs.offs... | from datetime import (
datetime,
timezone,
)
from dateutil.relativedelta import MO
import pytest
from pandas import (
DateOffset,
DatetimeIndex,
Series,
Timestamp,
)
import pandas._testing as tm
from pandas.tseries.holiday import (
SA,
AbstractHolidayCalendar,
EasterMonday,
Go... | pandas |
python | """
Manage Windows Package Repository
"""
import itertools
# Python Libs
import os
import stat
import salt.config
# Salt Modules
import salt.runner
import salt.syspaths
import salt.utils.path
def __virtual__():
return "winrepo"
def genrepo(name, force=False, allow_empty=False):
"""
Refresh the winre... | import os
import pytest
from salt.runners import winrepo
from tests.support.mock import patch
pytestmark = [
pytest.mark.windows_whitelisted,
]
@pytest.fixture
def configure_loader_modules(minion_opts, tmp_path):
winrepo_dir = tmp_path / "winrepo"
winrepo_dir.mkdir()
winrepo_dir_ng = tmp_path / "wi... | salt |
python | """Init file for Home Assistant."""
| """Test the init file of Mailgun."""
import hashlib
import hmac
from aiohttp.test_utils import TestClient
import pytest
from homeassistant import config_entries
from homeassistant.components import mailgun, webhook
from homeassistant.const import CONF_API_KEY, CONF_DOMAIN
from homeassistant.core import Event, HomeAs... | core |
python | """
Process individual messages from a TCP connection.
This script replaces full occurrences of "foo" with "bar" and prints various details for each message.
Please note that TCP is stream-based and *not* message-based. mitmproxy splits stream contents into "messages"
as they are received by socket.recv(). This is pre... | import pytest
from ..tutils import Placeholder
from ..tutils import Playbook
from ..tutils import reply
from mitmproxy.proxy.commands import CloseConnection
from mitmproxy.proxy.commands import CloseTcpConnection
from mitmproxy.proxy.commands import OpenConnection
from mitmproxy.proxy.commands import SendData
from mit... | mitmproxy |
python | """HMAC-based One-time Password auth module.
Sending HOTP through notify service
"""
from __future__ import annotations
import asyncio
import logging
from typing import Any, cast
import attr
import voluptuous as vol
from homeassistant.const import CONF_EXCLUDE, CONF_INCLUDE
from homeassistant.core import HomeAssis... | """Notify platform tests for mobile_app."""
from datetime import datetime, timedelta
from unittest.mock import patch
import pytest
from homeassistant.components.mobile_app.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.setup... | core |
python | from typing import Annotated
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
q: str, item_id: Annotated[int, Path(title="The ID of the item to get")]
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
| import importlib
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from ...utils import needs_py39, needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial002",
pytest.param("tutorial002_py310", marks=needs_py310),
"tutorial002_an",
... | fastapi |
python | """
Minion data cache plugin for MySQL database.
.. versionadded:: 2018.3.0
It is up to the system administrator to set up and configure the MySQL
infrastructure. All is needed for this plugin is a working MySQL server.
.. warning::
The mysql.database and mysql.table_name will be directly added into certain
... | """
:codeauthor: Mike Place (mp@saltstack.com)
tests.unit.modules.mysql
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
import logging
import pytest
import salt.modules.mysql as mysql
from tests.support.mock import MagicMock, call, mock_open, patch
try:
import pymysql
HAS_PYMYSQL = True
except ImportErro... | salt |
python | """Support for Palazzetti buttons."""
from __future__ import annotations
from pypalazzetti.exceptions import CommunicationError
from homeassistant.components.button import ButtonEntity
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.enti... | """Tests for the AirGradient button platform."""
from datetime import timedelta
from unittest.mock import AsyncMock, patch
from airgradient import AirGradientConnectionError, AirGradientError, Config
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from hom... | core |
python | import re
from typing import Dict, Optional
import logging
from rich.logging import RichHandler
from ciphey.iface import Checker, Config, ParamSpec, T, registry
@registry.register
class Regex(Checker[str]):
def getExpectedRuntime(self, text: T) -> float:
return 1e-5 # TODO: actually calculate this
... | import pytest
from ciphey import decrypt
from ciphey.iface import Config
def test_regex_ip():
res = decrypt(
Config().library_default().complete_config(),
"MTkyLjE2MC4wLjE=",
)
assert res == "192.160.0.1"
def test_regex_domain():
res = decrypt(
Config().library_default().com... | Ciphey |
python | """Support for Palazzetti buttons."""
from __future__ import annotations
from pypalazzetti.exceptions import CommunicationError
from homeassistant.components.button import ButtonEntity
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.enti... | """Tests for the Cookidoo button platform."""
from unittest.mock import AsyncMock, patch
from cookidoo_api import CookidooRequestException
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRESS
from homeassistant.config_entries ... | core |
python | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any lat... | # (c) 2016, Saran Ahluwalia <ahlusar.ahluwalia@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any... | ansible |
python | from __future__ import annotations
import logging
from django.core.exceptions import ObjectDoesNotExist
from django.http.request import HttpRequest
from django.views.decorators.csrf import csrf_exempt
from rest_framework.request import Request
from rest_framework.response import Response
from sentry.api.api_owners i... | from unittest.mock import MagicMock, patch
import orjson
from fixtures.gitlab import (
EXTERNAL_ID,
MERGE_REQUEST_OPENED_EVENT,
PUSH_EVENT,
PUSH_EVENT_IGNORED_COMMIT,
WEBHOOK_TOKEN,
GitLabTestCase,
)
from sentry.integrations.models.integration import Integration
from sentry.models.commit impor... | sentry |
python | import graphene
from ....permission.enums import ShippingPermissions
from ....shipping import models
from ...core import ResolveInfo
from ...core.context import ChannelContext
from ...core.mutations import ModelDeleteMutation
from ...core.types import ShippingError
from ...plugins.dataloaders import get_plugin_manager... | import json
from unittest import mock
import graphene
import pytest
from django.utils.functional import SimpleLazyObject
from freezegun import freeze_time
from .....core.utils.json_serializer import CustomJsonEncoder
from .....webhook.event_types import WebhookEventAsyncType
from .....webhook.payloads import generate... | saleor |
python | """The iCloud component."""
from __future__ import annotations
import voluptuous as vol
from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.util import slugify
from .account import IcloudAccount, IcloudConfigEntry
from .con... | """Tests for Sonos services."""
import asyncio
from contextlib import asynccontextmanager
import logging
import re
from unittest.mock import Mock, patch
import pytest
from homeassistant.components.media_player import (
DOMAIN as MP_DOMAIN,
SERVICE_JOIN,
SERVICE_UNJOIN,
)
from homeassistant.core import Ho... | core |
python | """
███████╗████████╗ ██████╗ ██████╗
██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗
███████╗ ██║ ██║ ██║██████╔╝
╚════██║ ██║ ██║ ██║██╔═══╝
███████║ ██║ ╚██████╔╝██║
╚══════╝ ╚═╝ ╚═════╝ ╚═╝
Do not use any of these functions. They are private and subject to change.
This module contains a translation layer ... | from collections.abc import Iterable, Sequence
from datetime import datetime
import pytest
from google.protobuf.timestamp_pb2 import Timestamp
from sentry_protos.snuba.v1.attribute_conditional_aggregation_pb2 import (
AttributeConditionalAggregation,
)
from sentry_protos.snuba.v1.downsampled_storage_pb2 import Dow... | sentry |
python | """Support for Palazzetti buttons."""
from __future__ import annotations
from pypalazzetti.exceptions import CommunicationError
from homeassistant.components.button import ButtonEntity
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.enti... | """Test Roborock Button platform."""
from unittest.mock import Mock
import pytest
from roborock import RoborockException
from roborock.exceptions import RoborockTimeout
from homeassistant.components.button import SERVICE_PRESS
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from... | core |
python | """Support for Palazzetti buttons."""
from __future__ import annotations
from pypalazzetti.exceptions import CommunicationError
from homeassistant.components.button import ButtonEntity
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.enti... | """Test BMW buttons."""
from unittest.mock import AsyncMock, patch
from bimmer_connected.models import MyBMWRemoteServiceError
from bimmer_connected.vehicle.remote_services import RemoteServices
import pytest
import respx
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from ho... | core |
python | """
Detect disks
"""
import glob
import logging
import re
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.utils.files
import salt.utils.path
import salt.utils.platform
__salt__ = ... | """
:codeauthor: :email:`Shane Lee <slee@saltstack.com>`
"""
import pytest
import salt.grains.disks as disks
from tests.support.mock import MagicMock, mock_open, patch
@pytest.fixture
def configure_loader_modules():
return {
disks: {"__salt__": {}},
}
def test__windows_disks_dict():
"""
... | salt |
python | """Init file for Home Assistant."""
| """Tests for the Hisense AEH-W4A1 init file."""
from unittest.mock import patch
from pyaehw4a1 import exceptions
from homeassistant import config_entries
from homeassistant.components import hisense_aehw4a1
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from hom... | core |
python | # Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com>
#
# This file is part of Paramiko.
#
# Paramiko is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (a... | # Copyright (C) 2003-2009 Robey Pointer <robeypointer@gmail.com>
#
# This file is part of paramiko.
#
# Paramiko is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (a... | paramiko |
python | from django.db import models
from django.utils import timezone
from sentry.backup.scopes import RelocationScope
from sentry.db.models import (
BoundedBigIntegerField,
BoundedPositiveIntegerField,
FlexibleForeignKey,
Model,
region_silo_model,
)
from sentry.locks import locks
from sentry.models.envir... | import orjson
from django.utils import timezone
from sentry.models.activity import Activity
from sentry.models.deploy import Deploy
from sentry.notifications.notifications.activity.release import ReleaseActivityNotification
from sentry.testutils.cases import SlackActivityNotificationTest
from sentry.types.activity imp... | sentry |
python | from __future__ import annotations
import contextlib
import enum
import typing as t
from ansible.utils.display import Display
from ansible.constants import config
display = Display()
# FUTURE: add sanity test to detect use of skip_on_ignore without Skippable (and vice versa)
class ErrorAction(enum.Enum):
"""A... | from __future__ import annotations
import os
import pytest
import pytest_mock
from ansible.constants import config
from ansible.errors import AnsibleUndefinedConfigEntry
from ansible._internal._errors._handler import ErrorHandler, ErrorAction, Skippable, _SkipException
from ansible.utils.display import Display
def... | ansible |
python | """Init file for Home Assistant."""
| """Test the epson init."""
from unittest.mock import patch
from homeassistant.components.epson.const import CONF_CONNECTION_TYPE, DOMAIN
from homeassistant.const import CONF_HOST
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def test_migrate_entry(hass: HomeAssistant) ... | core |
python | """Resource management utilities for Home Assistant."""
from __future__ import annotations
import logging
import os
import resource
from typing import Final
_LOGGER = logging.getLogger(__name__)
# Default soft file descriptor limit to set
DEFAULT_SOFT_FILE_LIMIT: Final = 2048
def set_open_file_descriptor_limit() ... | """Test the resource utility module."""
import os
import resource
from unittest.mock import call, patch
import pytest
from homeassistant.util.resource import (
DEFAULT_SOFT_FILE_LIMIT,
set_open_file_descriptor_limit,
)
@pytest.mark.parametrize(
("original_soft", "expected_calls", "should_log_already_su... | core |
python | from drf_spectacular.utils import OpenApiExample
EXPLORE_SAVED_QUERY_OBJ = {
"id": "1",
"name": "Pageloads",
"projects": [],
"dateAdded": "2024-07-25T19:35:38.422859Z",
"dateUpdated": "2024-07-25T19:35:38.422874Z",
"environment": [],
"query": "span.op:pageload",
"fields": [
"spa... | from unittest.mock import patch
import pytest
from django.db import connections
from django.db.utils import OperationalError
from sentry.db.models.query import in_iexact
from sentry.models.commit import Commit
from sentry.models.organization import Organization
from sentry.models.userreport import UserReport
from sen... | sentry |
python | import graphene
from ....core import ResolveInfo
from ....core.doc_category import DOC_CATEGORY_AUTH
from ....core.fields import JSONString
from ....core.mutations import BaseMutation
from ....core.types import AccountError
from ....plugins.dataloaders import get_plugin_manager_promise
from ...types import User
clas... | import json
from unittest.mock import Mock
from .....tests.utils import get_graphql_content
MUTATION_EXTERNAL_VERIFY = """
mutation externalVerify($pluginId: String!, $input: JSONString!){
externalVerify(pluginId:$pluginId, input: $input){
verifyData
user{
email
... | saleor |
python | # Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# https://aws.amazon.com/apache2.0/
#
# or in the "license" file accomp... | # Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# https://aws.amazon.com/apache2.0/
#
# or in the "license" file accomp... | boto3 |
python | from __future__ import annotations
from collections.abc import Mapping
from typing import Any
from sentry.integrations.types import ExternalProviders
from sentry.types.actor import Actor
from .base import GroupActivityNotification
class EscalatingActivityNotification(GroupActivityNotification):
message_builder... | from unittest import mock
import orjson
from sentry.models.activity import Activity
from sentry.notifications.notifications.activity.escalating import EscalatingActivityNotification
from sentry.testutils.cases import PerformanceIssueTestCase, SlackActivityNotificationTest
from sentry.testutils.helpers.notifications i... | sentry |
python | """Automatically generated file.
To update, run python3 -m script.hassfest
"""
FLOWS = {
"helper": [
"derivative",
"filter",
"generic_hygrostat",
"generic_thermostat",
"group",
"history_stats",
"integration",
"min_max",
"mold_indicator",
... | """Test the APsystems Local API config flow."""
from unittest.mock import AsyncMock
from homeassistant.components.apsystems.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_IP_ADDRESS, CONF_PORT
from homeassistant.core import HomeAssistant
from homeassistan... | core |
python | # Copyright (c) Microsoft. All rights reserved.
import asyncio
import logging
import uuid
from collections.abc import Callable
from inspect import isawaitable
from queue import Queue
from typing import Any
from pydantic import Field, model_validator
from semantic_kernel import Kernel
from semantic_kernel.exceptions ... | # Copyright (c) Microsoft. All rights reserved.
from queue import Queue
from typing import cast
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from semantic_kernel import Kernel
from semantic_kernel.exceptions.kernel_exceptions import KernelException
from semantic_kernel.exceptions.process_except... | semantic-kernel |
python | #!/usr/bin/env python
# Copyright: (c) 2014, Nandor Sivok <dominis@haxor.hu>
# Copyright: (c) 2016, Redhat Inc
# Copyright: (c) 2018, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# PYTHON_ARGCOMPLETE_OK
from __future__ import annotations
# ansible.cli ne... | # (c) 2016, Thilo Uttendorfer <tlo@sengaya.de>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later vers... | ansible |
python | import string
import numpy as np
from pandas import (
DataFrame,
Index,
MultiIndex,
Series,
array,
concat,
date_range,
merge,
merge_asof,
)
try:
from pandas import merge_ordered
except ImportError:
from pandas import ordered_merge as merge_ordered
class Concat:
param... | import numpy as np
import pytest
from pandas import (
DataFrame,
Index,
Interval,
MultiIndex,
Series,
StringDtype,
)
import pandas._testing as tm
@pytest.mark.parametrize("other", [["three", "one", "two"], ["one"], ["one", "three"]])
def test_join_level(idx, other, join_type):
other = Ind... | pandas |
python | """Automatically generated file.
To update, run python3 -m script.hassfest
"""
FLOWS = {
"helper": [
"derivative",
"filter",
"generic_hygrostat",
"generic_thermostat",
"group",
"history_stats",
"integration",
"min_max",
"mold_indicator",
... | """Define tests for the Ambient PWS config flow."""
from unittest.mock import AsyncMock, patch
from aioambient.errors import AmbientError
import pytest
from homeassistant.components.ambient_station.const import CONF_APP_KEY, DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import ... | core |
python | """Automatically generated file.
To update, run python3 -m script.hassfest
"""
FLOWS = {
"helper": [
"derivative",
"filter",
"generic_hygrostat",
"generic_thermostat",
"group",
"history_stats",
"integration",
"min_max",
"mold_indicator",
... | """Test config flow for Twitch."""
from unittest.mock import AsyncMock
import pytest
from twitchAPI.object.api import TwitchUser
from homeassistant.components.twitch.const import (
CONF_CHANNELS,
DOMAIN,
OAUTH2_AUTHORIZE,
)
from homeassistant.config_entries import SOURCE_USER
from homeassistant.core impo... | core |
python | #
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 Raphael Michel and contributors
# Copyright (C) 2020-today pretix GmbH and contributors
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as published by... | #
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 Raphael Michel and contributors
# Copyright (C) 2020-today pretix GmbH and contributors
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as published by... | pretix |
python | """Automatically generated file.
To update, run python3 -m script.hassfest
"""
FLOWS = {
"helper": [
"derivative",
"filter",
"generic_hygrostat",
"generic_thermostat",
"group",
"history_stats",
"integration",
"min_max",
"mold_indicator",
... | """Test config flow."""
from collections.abc import Generator
from ipaddress import IPv4Address, ip_address
from unittest.mock import ANY, AsyncMock, MagicMock, Mock, patch
from pyatv import exceptions
from pyatv.const import PairingRequirement, Protocol
import pytest
from homeassistant import config_entries
from ho... | core |
python | from collections.abc import Iterable
import graphene
from django.core.exceptions import ValidationError
from django.db import transaction
from ....core.tracing import traced_atomic_transaction
from ....core.utils.promo_code import generate_promo_code
from ....core.utils.validators import is_date_in_future
from ....gi... | import datetime
from unittest import mock
import pytest
from .....giftcard import GiftCardEvents
from .....giftcard.error_codes import GiftCardErrorCode
from ....tests.utils import assert_no_permission, get_graphql_content
GIFT_CARD_BULK_CREATE_MUTATION = """
mutation GiftCardBulkCreate($input: GiftCardBulkCreat... | saleor |
python | from collections import namedtuple
import sqlparse
from django.db import DatabaseError
from django.db.backends.base.introspection import BaseDatabaseIntrospection
from django.db.backends.base.introspection import FieldInfo as BaseFieldInfo
from django.db.backends.base.introspection import TableInfo
from django.db.mod... | import unittest
import sqlparse
from django.db import connection
from django.test import TestCase
@unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests")
class IntrospectionTests(TestCase):
def test_get_primary_key_column(self):
"""
Get the primary key column regardless of whether or... | django |
python | """Intents for the cover integration."""
from homeassistant.const import SERVICE_CLOSE_COVER, SERVICE_OPEN_COVER
from homeassistant.core import HomeAssistant
from homeassistant.helpers import intent
from . import DOMAIN, INTENT_CLOSE_COVER, INTENT_OPEN_COVER, CoverDeviceClass
async def async_setup_intents(hass: Hom... | """The tests for the media_player platform."""
import math
from unittest.mock import patch
import pytest
from homeassistant.components.media_player import (
DOMAIN,
SERVICE_MEDIA_NEXT_TRACK,
SERVICE_MEDIA_PAUSE,
SERVICE_MEDIA_PLAY,
SERVICE_MEDIA_PREVIOUS_TRACK,
SERVICE_PLAY_MEDIA,
SERVICE... | core |
python | """Support led_brightness for Mi Air Humidifier."""
from __future__ import annotations
from dataclasses import dataclass, field
import logging
from typing import Any, NamedTuple
from miio import Device as MiioDevice
from miio.fan_common import LedBrightness as FanLedBrightness
from miio.integrations.airpurifier.dmak... | """Tests for the AirGradient select platform."""
from datetime import timedelta
from unittest.mock import AsyncMock, patch
from airgradient import AirGradientConnectionError, AirGradientError, Config
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from hom... | core |
python | from __future__ import annotations
import logging
from collections.abc import Callable
from typing import Any
from django.conf import settings
from django.http.response import HttpResponseBase
from rest_framework.request import Request
from sentry.hybridcloud.apigateway.proxy import (
proxy_error_embed_request,
... | from urllib.parse import urlencode
import pytest
import responses
from django.conf import settings
from django.test import override_settings
from django.urls import get_resolver, reverse
from rest_framework.response import Response
from sentry.silo.base import SiloLimit, SiloMode
from sentry.testutils.helpers.apigate... | sentry |
python | """Switch platform for Growatt."""
from __future__ import annotations
from dataclasses import dataclass
import logging
from typing import Any
from growattServer import GrowattV1ApiError
from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
from homeassistant.const import EntityCategory
f... | """Tests for the Geniushub switch platform."""
from unittest.mock import patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
f... | core |
python | """Init file for Home Assistant."""
| """Tests for Google Assistant SDK."""
from datetime import timedelta
import http
import time
from unittest.mock import call, patch
import aiohttp
from freezegun.api import FrozenDateTimeFactory
from grpc import RpcError
import pytest
from homeassistant.components import conversation
from homeassistant.components.goo... | core |
python | """Init file for Home Assistant."""
| """The tests for the litejet component."""
from homeassistant.components import litejet
from homeassistant.components.litejet.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from . import async_init_integration
async def test_setup_with_no_confi... | core |
python | """Switch platform for Growatt."""
from __future__ import annotations
from dataclasses import dataclass
import logging
from typing import Any
from growattServer import GrowattV1ApiError
from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
from homeassistant.const import EntityCategory
f... | """Tests for the devolo Home Network switch."""
from datetime import timedelta
from unittest.mock import AsyncMock
from devolo_plc_api.device_api import WifiGuestAccessGet
from devolo_plc_api.exceptions.device import DevicePasswordProtected, DeviceUnavailable
from freezegun.api import FrozenDateTimeFactory
import pyt... | core |
python | import graphene
from .....core.tracing import traced_atomic_transaction
from .....discount import models
from .....permission.enums import DiscountPermissions
from .....webhook.event_types import WebhookEventAsyncType
from ....core.descriptions import ADDED_IN_318
from ....core.doc_category import DOC_CATEGORY_DISCOUN... | import graphene
import pytest
from ....tests.utils import get_graphql_content
VOUCHER_CODE_BULK_DELETE_MUTATION = """
mutation voucherCodeBulkDelete($ids: [ID!]!) {
voucherCodeBulkDelete(ids: $ids) {
count
}
}
"""
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
d... | saleor |
python | #
# Author: Bo Maryniuk <bo@suse.de>
#
# Copyright 2017 SUSE LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | import json
import pathlib
import pytest
import salt.states.ansiblegate as ansiblegate
from tests.support.mock import MagicMock, patch
from tests.support.runtests import RUNTIME_VARS
@pytest.fixture
def configure_loader_modules():
return {ansiblegate: {}}
@pytest.fixture
def playbooks_examples_dir():
retu... | salt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.