def call_with_import(module_name, extra_argv=[], assert_result=True): """Import module_name and run module.main() with given argv, capturing output.""" pytest.register_assert_rewrite(py_str(module_name)) print("import", module_name, "with extra_argv=" + repr(extra_argv)) old_stdout, sys.stdout = sys.stdout, LoggingStringIO(sys.stdout) old_stderr, sys.stderr = sys.stderr, LoggingStringIO(sys.stderr) old_argv = sys.argv try: with using_coconut(): if sys.version_info >= (2, 7): module = importlib.import_module(module_name) else: module = imp.load_module(module_name, *imp.find_module(module_name)) sys.argv = [module.__file__] + extra_argv result = module.main() if assert_result: assert result except SystemExit as err: retcode = err.code or 0 except BaseException: logger.print_exc() retcode = 1 else: retcode = 0 finally: sys.argv = old_argv stdout = sys.stdout.getvalue() stderr = sys.stderr.getvalue() sys.stdout = old_stdout sys.stderr = old_stderr return stdout, stderr, retcode
def test(main: Callable[[str], Tuple[Any, Any]], *test_cases: TestCase) -> None: pytest.register_assert_rewrite() for test_case in test_cases: part1, part2 = main(test_case.input) if test_case.expected_part_1: assert part1 == test_case.expected_part_1, f"part1 failed (got {part1}, expected {test_case.expected_part_1})" if test_case.expected_part_2: assert part2 == test_case.expected_part_2, f"part2 failed (got {part2}, expected {test_case.expected_part_2})"
def fill_all_tested_migrations(): for migration in ALL_MIGRATIONS: if migration in ALL_MIGRATION_TESTS: ALL_TESTED_MIGRATIONS.append(migration) ALL_MIGRATION_TESTS.remove(migration) # Make sure pytest rewrites the assertions in these test files mod_name = 'migrations.migration_{}'.format(migration) pytest.register_assert_rewrite(mod_name)
def _github_connection_patcher(token, mode): pytest.register_assert_rewrite('pyci.tests.framework') from pyci.tests import github_patcher record = mode == 'RECORD' return github_patcher.GithubConnectionPatcher(record=record, token=token)
def test_all_bots_for_session_config( session_config_name, num_participants, export_path): """ this means all configs and test cases are in 1 big test case. so if 1 fails, the others will not get run. to separate them, we would need to move some of this code to pytest_generate_tests in conftest.py """ if session_config_name: session_config_names = [session_config_name] else: session_config_names = SESSION_CONFIGS_DICT.keys() for config_name in session_config_names: try: config = SESSION_CONFIGS_DICT[config_name] except KeyError: # important to alert the user, since people might be trying to enter app names. raise Exception(f"No session config with name '{config_name}'.") from None bot_modules = [f'{app_name}.tests' for app_name in config['app_sequence']] pytest.register_assert_rewrite(*bot_modules) num_bot_cases = config.get_num_bot_cases() for case_number in range(num_bot_cases): logger.info("Creating '{}' session (test case {})".format( config_name, case_number)) session = otree.session.create_session( session_config_name=config_name, num_participants=(num_participants or config['num_demo_participants']), ) run_bots(session, case_number=case_number) logger.info('Bots completed session') if export_path: now = datetime.datetime.now() if export_path == AUTO_NAME_BOTS_EXPORT_FOLDER: # oTree convention to prefix __temp all temp folders. export_path = now.strftime('__temp_bots_%b%d_%Hh%Mm%S.%f')[:-5] + 's' os.makedirs(export_path, exist_ok=True) for app in settings.INSTALLED_OTREE_APPS: model_module = otree.common_internal.get_models_module(app) if model_module.Player.objects.exists(): fpath = Path(export_path, "{}.csv".format(app)) with fpath.open("w", encoding="utf8") as fp: otree.export.export_app(app, fp, file_extension='csv') fpath = Path(export_path, "all_apps_wide.csv") with fpath.open("w", encoding="utf8") as fp: otree.export.export_wide(fp, 'csv') logger.info('Exported CSV to folder "{}"'.format(export_path))
def pytest_configure(config): pytest.register_assert_rewrite("sqlalchemy.testing.assertions") if hasattr(config, "slaveinput"): plugin_base.restore_important_follower_config(config.slaveinput) plugin_base.configure_follower(config.slaveinput["follower_ident"]) else: if config.option.write_idents and os.path.exists(config.option.write_idents): os.remove(config.option.write_idents) plugin_base.pre_begin(config.option) plugin_base.set_coverage_flag(bool(getattr(config.option, "cov_source", False))) plugin_base.set_fixture_functions(PytestFixtureFunctions)
import pytest pytest.register_assert_rewrite('cortexpy.test.expectation') # noqa from .graph import KmerGraphExpectation # noqa from .fasta import Fasta # noqa from .json import JsonGraph, JsonGraphs # noqa
"""This module sets up pytest hooks Please check pytest documentation and/or util module docstrings. """ import pytest import util def pytest_addoption(parser): parser.addoption( '--log-level', '-L', type='choice', action='store', dest='tests_log_level', choices=['disabled', 'debug', 'info', 'warning', 'error', 'critical'], default='disabled', help='Set verbosity of the testing framework.', ) def pytest_configure(config): util.setup_thread_debugger() util.configure_logger(config) pytest.register_assert_rewrite('generic_test_code.common') pytest.register_assert_rewrite('generic_test_code.open')
import pytest pytest.register_assert_rewrite('hexlet')
"""PyTest configuration for SQLAlchemy-Dataflex.""" # coding=utf-8 # noinspection PyPackageRequirements import pytest from sqlalchemy.dialects import registry registry.register("dataflex.pyodbc", "sqlalchemy_dataflex.pyodbc", "DataflexDialect_pyodbc") pytest.register_assert_rewrite("sqlalchemy.testing.assertions") from sqlalchemy.testing.plugin.pytestplugin import *
# You should have received a copy of the GNU General Public License # along with qutebrowser. If not, see <https://www.gnu.org/licenses/>. # pylint: disable=unused-import,wildcard-import,unused-wildcard-import """The qutebrowser test suite conftest file.""" import os import sys import warnings import pathlib import pytest import hypothesis from PyQt5.QtCore import PYQT_VERSION pytest.register_assert_rewrite('helpers') from helpers import logfail from helpers.logfail import fail_on_logging from helpers.messagemock import message_mock from helpers.fixtures import * # noqa: F403 from helpers import utils as testutils from qutebrowser.utils import qtutils, standarddir, usertypes, utils, version from qutebrowser.misc import objects, earlyinit from qutebrowser.qt import sip import qutebrowser.app # To register commands _qute_scheme_handler = None # Set hypothesis settings
import collections import json import cwt import pytest pytest.register_assert_rewrite('cwt_cert.process_base') MARKERS = [ 'stress: mark a test as a stress test.', 'performance: mark a test as a performance test.', 'api_compliance: mark a test as an api compliance test.', 'metrics: mark a test as a metrics test.', 'security: mark a test as a security test.', 'operator: mark a test as an operator test.', 'server: mark a test as a server test.', 'aggregate: mark a test as an aggregate test.', 'subset: mark a test as a subset test.', ] class Context(object): def __init__(self, host, token): self.host = host self.token = token self.data_inputs = {} def get_client(self): client = cwt.WPSClient(self.host, verify=False) return client
import inflection import pytest pytest.register_assert_rewrite("open_city_profile.tests.asserts") def to_graphql_name(s): return inflection.camelize(s, False) def to_graphql_object(dic): return dict([(to_graphql_name(k), v) for k, v in dic.items()])
'fixtures.ssh_client', 'fixtures.templateloader', 'fixtures.terminalreporter', 'fixtures.ui_coverage', 'fixtures.version_file', 'fixtures.version_info', 'fixtures.video', 'fixtures.virtual_machine', 'fixtures.widgets', 'fixtures.xunit_tools', 'markers', 'cfme.fixtures.base', 'cfme.fixtures.cli', 'cfme.fixtures.pytest_selenium', 'cfme.fixtures.configure_auth_mode', 'cfme.fixtures.rdb', 'cfme.fixtures.service_fixtures', 'cfme.fixtures.smtp', 'cfme.fixtures.tag', 'cfme.fixtures.vm_name', 'cfme.fixtures.vporizer', 'cfme.metaplugins', ) # work around pytest bug # https://github.com/pytest-dev/pytest/issues/2353 pytest.register_assert_rewrite(*pytest_plugins)
def test_register_assert_rewrite_checks_types(self): with pytest.raises(TypeError): pytest.register_assert_rewrite(['pytest_tests_internal_non_existing']) pytest.register_assert_rewrite('pytest_tests_internal_non_existing', 'pytest_tests_internal_non_existing2')
# -*- coding: utf-8 -*- # This program 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 version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Kallithea test package Refer to docs/contributing.rst for details on running the test suite. """ import pytest if getattr(pytest, 'register_assert_rewrite', None): # make sure that all asserts under kallithea/tests benefit from advanced # assert reporting with pytest-3.0.0+. pytest.register_assert_rewrite('kallithea.tests.')
import pytest pytest.register_assert_rewrite('core.common_fixtures')
import pytest # Use pytest verbose asserts # https://stackoverflow.com/questions/41522767/pytest-assert-introspection-in-helper-function pytest.register_assert_rewrite('utils.urls')
dhcp_versions = ['v6'] if dhcp_versions: metafunc.parametrize('dhcp_version', dhcp_versions) def pytest_configure(config): import terrain terrain.test_start() def pytest_unconfigure(config): import terrain terrain.say_goodbye() def pytest_addoption(parser): parser.addoption("--iters-factor", action="store", default=1, help="iterations factor, initial iterations in tests are multiplied by this value, default 1") @pytest.fixture def iters_factor(request): return int(request.config.getoption("--iters-factor")) # enable pytest assert introspection in the helper modules pytest.register_assert_rewrite('protosupport.v4.srv_msg') pytest.register_assert_rewrite('cb_model') pytest.register_assert_rewrite('dhcp4_scen')
def test_register_assert_rewrite_checks_types(self): with pytest.raises(TypeError): pytest.register_assert_rewrite( ['pytest_tests_internal_non_existing']) pytest.register_assert_rewrite('pytest_tests_internal_non_existing', 'pytest_tests_internal_non_existing2')
# You should have received a copy of the GNU General Public License # along with qutebrowser. If not, see <http://www.gnu.org/licenses/>. # pylint: disable=unused-import,wildcard-import,unused-wildcard-import """The qutebrowser test suite conftest file.""" import os import sys import warnings import pytest import hypothesis from PyQt5.QtCore import PYQT_VERSION pytest.register_assert_rewrite('helpers') from helpers import logfail from helpers.logfail import fail_on_logging from helpers.messagemock import message_mock from helpers.fixtures import * from qutebrowser.utils import qtutils, standarddir, usertypes from qutebrowser.misc import objects import qutebrowser.app # To register commands # Set hypothesis settings hypothesis.settings.register_profile( 'default', hypothesis.settings(strict=True, deadline=400)) hypothesis.settings.load_profile('default')
# # Copyright (c) 2018-2019 Red Hat, Inc. # # This file is part of nmstate # # This program 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 # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # import pytest pytest.register_assert_rewrite(__name__ + ".assertlib")
""" Note: The expected error strings may change in a future version of mypy. Please update as needed. """ import pytest pytest.importorskip('mypy') # we only install mypy in python>=3.6 tests pytest.register_assert_rewrite('pynamodb.tests.mypy_helpers') from .mypy_helpers import assert_mypy_output # noqa def test_model(): assert_mypy_output(""" from pynamodb.models import Model from pynamodb.expressions.operand import Path class MyModel(Model): pass reveal_type(MyModel.count('hash', Path('a').between(1, 3))) # E: Revealed type is 'builtins.int' """) def test_model_query(): assert_mypy_output(""" from pynamodb.attributes import NumberAttribute from pynamodb.models import Model class MyModel(Model): my_attr = NumberAttribute()
import pytest pytest.register_assert_rewrite("pytest_foo.helper")
# Author: Christian Brodbeck <*****@*****.**> import pytest pytest.register_assert_rewrite('eelbrain.testing._testing') from ._testing import ( gui_test, requires_mne_sample_data, requires_pyarrow, requires_r_ez, skip_on_windows, TempDir, working_directory, assert_dataset_equal, assert_dataobj_equal, assert_source_space_equal, file_path, import_attr, path, )
import pytest pytest.register_assert_rewrite("python_proto.tests.helpers") from python_proto.tests.helpers import check_encode_decode_invariant from python_proto.tests.strategies import envelopes, metadatas, raw_logs def test_metadata_encode_decode() -> None: check_encode_decode_invariant(metadatas()) def test_envelope_encode_decode() -> None: check_encode_decode_invariant(envelopes()) def test_raw_log_encode_decode() -> None: check_encode_decode_invariant(raw_logs())
# # You should have received a copy of the GNU General Public License # along with qutebrowser. If not, see <http://www.gnu.org/licenses/>. # pylint: disable=unused-import """The qutebrowser test suite conftest file.""" import os import sys import warnings import pytest import hypothesis pytest.register_assert_rewrite("helpers") from helpers import logfail from helpers.logfail import fail_on_logging from helpers.messagemock import message_mock from helpers.fixtures import * # pylint: disable=wildcard-import # Set hypothesis settings hypothesis.settings.register_profile("default", hypothesis.settings(strict=True)) hypothesis.settings.load_profile("default") def _apply_platform_markers(item): """Apply a skip marker to a given item.""" markers = [
def test_register_assert_rewrite_checks_types(self): with pytest.raises(TypeError): pytest.register_assert_rewrite(["pytest_tests_internal_non_existing"]) pytest.register_assert_rewrite( "pytest_tests_internal_non_existing", "pytest_tests_internal_non_existing2" )
# (C) British Crown Copyright 2013 - 2018, Met Office # # This file is part of cartopy. # # cartopy 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 3 of the License, or # (at your option) any later version. # # cartopy is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with cartopy. If not, see <https://www.gnu.org/licenses/>. """ Tests for specific Cartopy CRS subclasses. """ from __future__ import (absolute_import, division, print_function) import pytest pytest.register_assert_rewrite('cartopy.tests.crs.helpers')
import asyncio import httpx import pytest from sqlalchemy import create_engine from sqlalchemy_utils import create_database, database_exists, drop_database from wallet import models from wallet.db import DB, init_db from wallet.deps import db from wallet.main import app from wallet.settings import settings from . import factories pytest.register_assert_rewrite("tests.asserts") @pytest.fixture(scope="session") def event_loop() -> Generator[asyncio.AbstractEventLoop, None, None]: loop = asyncio.get_event_loop() yield loop loop.close() @pytest.fixture(scope="session") def test_db() -> Generator[DB, None, None]: url = settings.TEST_DATABASE_URI # Databases uses PyMySQL by default, while SQLAlchemy uses MySQLdb. We have to pass the driver explicitly sqlalchemy_url = url.replace("mysql://", "mysql+pymysql://") engine = create_engine(sqlalchemy_url)
import os import pytest # needed to get pretty assertion failures in unit tests: if hasattr(pytest, 'register_assert_rewrite'): pytest.register_assert_rewrite('borg.testsuite') from borg.logger import setup_logging # Ensure that the loggers exist for all tests setup_logging() from borg.testsuite import has_lchflags, has_llfuse from borg.testsuite import are_symlinks_supported, are_hardlinks_supported, is_utime_fully_supported from borg.testsuite.platform import fakeroot_detected, are_acls_working from borg import xattr, constants def pytest_configure(config): # no fixture-based monkey-patching since star-imports are used for the constants module constants.PBKDF2_ITERATIONS = 1 @pytest.fixture(autouse=True) def clean_env(tmpdir_factory, monkeypatch): # avoid that we access / modify the user's normal .config / .cache directory: monkeypatch.setenv('XDG_CONFIG_HOME', tmpdir_factory.mktemp('xdg-config-home')) monkeypatch.setenv('XDG_CACHE_HOME', tmpdir_factory.mktemp('xdg-cache-home')) # also avoid to use anything from the outside environment: keys = [key for key in os.environ if key.startswith('BORG_')]
import pytest # This register_assert_rewrite must appear before the module is imported. pytest.register_assert_rewrite("opencodelists.tests.fixtures") from opencodelists.tests.fixtures import * # noqa pytest.register_assert_rewrite("codelists.tests.views.assertions") pytest.register_assert_rewrite("opencodelists.tests.assertions") @pytest.fixture(autouse=True) def enable_db_access_for_all_tests(db): pass
import pytest # Custom assertions defined in the following package need to be registered to be properly # displayed in a pytest report when they are failing. pytest.register_assert_rewrite('certbot_integration_tests.certbot_tests.assertions')
"""HomeKit controller session fixtures.""" import datetime from unittest import mock import unittest.mock from aiohomekit.testing import FakeController import pytest import homeassistant.util.dt as dt_util from tests.components.light.conftest import mock_light_profiles # noqa: F401 pytest.register_assert_rewrite("tests.components.homekit_controller.common") @pytest.fixture def utcnow(request): """Freeze time at a known point.""" now = dt_util.utcnow() start_dt = datetime.datetime(now.year + 1, 1, 1, 0, 0, 0, tzinfo=now.tzinfo) with mock.patch("homeassistant.util.dt.utcnow") as dt_utcnow: dt_utcnow.return_value = start_dt yield dt_utcnow @pytest.fixture def controller(hass): """Replace aiohomekit.Controller with an instance of aiohomekit.testing.FakeController.""" instance = FakeController() with unittest.mock.patch( "homeassistant.components.homekit_controller.utils.Controller",
# Copyright (C) 2018 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> import pytest pytest.register_assert_rewrite("lib")
# Copyright (C) Mesosphere, Inc. See LICENSE file for details. """This module sets up pytest hooks Please check pytest documentation and/or util module docstrings. """ import pytest import util def pytest_addoption(parser): parser.addoption('--log-level', '-L', type='choice', action='store', dest='tests_log_level', choices=['disabled', 'debug', 'info', 'warning', 'error', 'critical'], default='disabled', help='Set verbosity of the testing framework.',) def pytest_configure(config): util.setup_thread_debugger() util.configure_logger(config) pytest.register_assert_rewrite('generic_test_code.common') pytest.register_assert_rewrite('generic_test_code.open')
import shutil import subprocess import time from pathlib import Path import pytest import redis import requests from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, clear_mappers from tenacity import retry, stop_after_delay from allocation.adapters.orm import metadata, start_mappers from allocation import config pytest.register_assert_rewrite('tests.e2e.api_client') @pytest.fixture def in_memory_sqlite_db(): engine = create_engine('sqlite:///:memory:') metadata.create_all(engine) return engine @pytest.fixture def sqlite_session_factory(in_memory_sqlite_db): yield sessionmaker(bind=in_memory_sqlite_db) @pytest.fixture def mappers(): start_mappers() yield
import pytest pytest.register_assert_rewrite('gen.tests.utils')
"""Sqlfluff is a SQL linter for humans.""" import sys import pytest # Expose the public API. from sqlfluff.api import lint, fix, parse, list_rules, list_dialects # noqa: F401 # Check major python version if sys.version_info[0] < 3: raise Exception( "Sqlfluff does not support Python 2. Please upgrade to Python 3.") # Check minor python version elif sys.version_info[1] < 6: raise Exception( "Sqlfluff 0.4.0 only supports Python 3.6 and beyond. " "Use an earlier version of sqlfluff or a later version of Python") # Set the version attribute of the library import pkg_resources import configparser # Get the current version config = configparser.ConfigParser() config.read([pkg_resources.resource_filename("sqlfluff", "config.ini")]) __version__ = config.get("sqlfluff", "version") # Register helper functions to support variable introspection on failure. pytest.register_assert_rewrite("sqlfluff.testing")
import pytest pytest.register_assert_rewrite('core')
# pylint: disable=unused-import """Things needed for end2end testing.""" import re import os import sys import shutil import pstats import os.path import operator import pytest from PyQt5.QtCore import PYQT_VERSION pytest.register_assert_rewrite('end2end.fixtures') from end2end.fixtures.webserver import httpbin, httpbin_after_test, ssl_server from end2end.fixtures.quteprocess import (quteproc_process, quteproc, quteproc_new) from end2end.fixtures.testprocess import pytest_runtest_makereport from qutebrowser.utils import qtutils def pytest_configure(config): """Remove old profile files.""" if config.getoption('--qute-profile-subprocs'): try: shutil.rmtree('prof') except FileNotFoundError: pass
import pytest pytest.register_assert_rewrite('chainerx.testing.array') pytest.register_assert_rewrite('chainerx.testing.helper') from chainerx._testing import _DeviceBuffer # NOQA from chainerx._testing import _fromnumpy # NOQA from chainerx.testing import array # NOQA from chainerx.testing import helper # NOQA from chainerx.testing.array import assert_allclose # NOQA from chainerx.testing.array import assert_allclose_ex # NOQA from chainerx.testing.array import assert_array_equal # NOQA from chainerx.testing.array import assert_array_equal_ex # NOQA from chainerx.testing.dtypes import all_dtypes # NOQA from chainerx.testing.dtypes import float_dtypes # NOQA from chainerx.testing.dtypes import nonfloat_dtypes # NOQA from chainerx.testing.dtypes import numeric_dtypes # NOQA from chainerx.testing.dtypes import parametrize_dtype_specifier # NOQA from chainerx.testing.dtypes import signed_dtypes # NOQA from chainerx.testing.dtypes import unsigned_dtypes # NOQA from chainerx.testing.helper import ignore # NOQA from chainerx.testing.helper import numpy_chainerx_allclose # NOQA from chainerx.testing.helper import numpy_chainerx_array_equal # NOQA
import pytest # Enable pytest assert introspection for assertion helper pytest.register_assert_rewrite('tests.support.asserts')
import signal import subprocess import sys import tempfile import time from pathlib import Path import gevent import pytest import structlog from _pytest.pathlib import LOCK_TIMEOUT, ensure_reset_dir, make_numbered_dir_with_cleanup from _pytest.tmpdir import get_user # Execute these before the raiden imports because rewrites can't work after the # module has been imported. pytest.register_assert_rewrite("raiden.tests.utils.eth_node") pytest.register_assert_rewrite("raiden.tests.utils.factories") pytest.register_assert_rewrite("raiden.tests.utils.messages") pytest.register_assert_rewrite("raiden.tests.utils.network") pytest.register_assert_rewrite("raiden.tests.utils.protocol") pytest.register_assert_rewrite("raiden.tests.utils.smartcontracts") pytest.register_assert_rewrite("raiden.tests.utils.smoketest") pytest.register_assert_rewrite("raiden.tests.utils.transfer") from raiden.constants import ( # isort:skip HIGHEST_SUPPORTED_GETH_VERSION, HIGHEST_SUPPORTED_PARITY_VERSION, LOWEST_SUPPORTED_GETH_VERSION, LOWEST_SUPPORTED_PARITY_VERSION, EthClient, ) from raiden.log_config import configure_logging # isort:skip from raiden.tests.fixtures.blockchain import * # noqa: F401,F403 # isort:skip from raiden.tests.fixtures.variables import * # noqa: F401,F403 # isort:skip
from homeassistant.auth.providers import homeassistant, legacy_api_password from homeassistant.components import mqtt, recorder from homeassistant.components.websocket_api.auth import ( TYPE_AUTH, TYPE_AUTH_OK, TYPE_AUTH_REQUIRED, ) from homeassistant.components.websocket_api.http import URL from homeassistant.const import HASSIO_USER_NAME from homeassistant.helpers import config_entry_oauth2_flow from homeassistant.setup import async_setup_component from homeassistant.util import dt as dt_util, location from tests.ignore_uncaught_exceptions import IGNORE_UNCAUGHT_EXCEPTIONS pytest.register_assert_rewrite("tests.common") from tests.common import ( # noqa: E402, isort:skip CLIENT_ID, INSTANCES, MockConfigEntry, MockUser, async_fire_mqtt_message, async_init_recorder_component, async_test_home_assistant, get_test_home_assistant, init_recorder_component, mock_storage as mock_storage, ) from tests.test_util.aiohttp import mock_aiohttp_client # noqa: E402, isort:skip logging.basicConfig(level=logging.DEBUG) logging.getLogger("sqlalchemy.engine").setLevel(logging.INFO) asyncio.set_event_loop_policy(runner.HassEventLoopPolicy(False)) # Disable fixtures overriding our beautiful policy asyncio.set_event_loop_policy = lambda policy: None
import qcodes as qc from qcodes import (experiments, load_by_counter, load_by_id, new_data_set, new_experiment) from qcodes.dataset.data_set import CompletedError, DataSet from qcodes.dataset.descriptions.dependencies import InterDependencies_ from qcodes.dataset.descriptions.param_spec import ParamSpecBase from qcodes.dataset.descriptions.rundescriber import RunDescriber from qcodes.dataset.guids import parse_guid from qcodes.dataset.sqlite.connection import path_to_dbfile from qcodes.dataset.sqlite.database import get_DB_location from qcodes.dataset.sqlite.queries import _unicode_categories from qcodes.tests.common import error_caused_by from qcodes.tests.dataset.test_links import generate_some_links from qcodes.utils.deprecate import QCoDeSDeprecationWarning pytest.register_assert_rewrite('qcodes.tests.dataset.helper_functions') from qcodes.tests.dataset.helper_functions import verify_data_dict n_experiments = 0 def make_shadow_dataset(dataset: DataSet): """ Creates a new DataSet object that points to the same run_id in the same database file as the given dataset object. Note that for a pristine run, the shadow dataset may be out of sync with its input dataset. Note that in order to achieve it `path_to_db` because this will create a new sqlite3 connection object behind the scenes. This is very useful for situations where one needs to assert the underlying modifications to the database file.
# pylint: disable=unused-import """Things needed for end2end testing.""" import re import os import os.path import sys import shutil import pstats import operator import pytest from PyQt5.QtCore import PYQT_VERSION pytest.register_assert_rewrite('end2end.fixtures') from end2end.fixtures.webserver import server, server_per_test, ssl_server from end2end.fixtures.quteprocess import (quteproc_process, quteproc, quteproc_new) from end2end.fixtures.testprocess import pytest_runtest_makereport from qutebrowser.utils import qtutils, utils from qutebrowser.browser.webengine import spell def pytest_configure(config): """Remove old profile files.""" if config.getoption('--qute-profile-subprocs'): try: shutil.rmtree('prof') except FileNotFoundError:
import shutil import subprocess import time from pathlib import Path import pytest import redis import requests from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, clear_mappers from tenacity import retry, stop_after_delay from src.barkylib.adapters.orm import metadata, start_mappers from src.barkylib import config pytest.register_assert_rewrite("tests.e2e.api_client") @pytest.fixture def in_memory_sqlite_db(): engine = create_engine("sqlite:///:memory:") metadata.create_all(engine) return engine @pytest.fixture def sqlite_session_factory(in_memory_sqlite_db): yield sessionmaker(bind=in_memory_sqlite_db) @pytest.fixture
import pytest pytest.register_assert_rewrite('tests.pytest_helpers')