def setup_generic_app(package):
    """Setup for both gui and console apps."""
    import os
    if os.getenv("WACLIENT_ENABLE_TYPEGUARD"):
        from typeguard.importhook import install_import_hook
        install_import_hook(package)

    if IS_ANDROID:
        patch_ctypes_module()  # Necessary for wacryptolib
예제 #2
0
def pytest_configure(config):
    value = config.getoption("typeguard_packages")
    if not value:
        return

    packages = [pkg.strip() for pkg in value.split(",")]

    already_imported_packages = sorted(package for package in packages
                                       if package in sys.modules)
    if already_imported_packages:
        message = ("typeguard cannot check these packages because they "
                   "are already imported: {}")
        raise RuntimeError(message.format(
            ", ".join(already_imported_packages)))

    install_import_hook(packages=packages)
예제 #3
0
def dummymodule():
    if cached_module_path.exists():
        cached_module_path.unlink()

    sys.path.insert(0, str(this_dir))
    try:
        with install_import_hook('dummymodule'):
            with warnings.catch_warnings():
                warnings.filterwarnings('error', module='typeguard')
                module = import_module('dummymodule')
                return module
    finally:
        sys.path.remove(str(this_dir))
예제 #4
0
def import_fixtures_module(module_name):
    if cached_module_path.exists():
        cached_module_path.unlink()

    sys.path.insert(0, str(this_dir))

    try:
        with install_import_hook(module_name):
            with warnings.catch_warnings():
                warnings.filterwarnings('error', module='typeguard')

                if module_name not in sys.modules:
                    module = importlib.import_module(module_name)
                else:
                    module = importlib.reload(sys.modules[module_name])

                return module
    finally:
        sys.path.remove(str(this_dir))
예제 #5
0
import sys
sys.path.append( "../psml" )

from typeguard.importhook import install_import_hook
install_import_hook('psml')

from psml import *

m = (
MediumVioletRed ** sphere( 10 ) +
right( 30 ) ** blue ** sphere( 10 ) +
right( 60 ) ** mediumspringgreen ** sphere( 10 )
)
m.write()
예제 #6
0
import sys

TESTS_RUNNING = 'test' in sys.argv or 'testserver' in sys.argv

################################################################
# typeguard MUST be initialized before any poject related imports
# and only for tests
################################################################
if TESTS_RUNNING:
    from typeguard.importhook import install_import_hook
    install_import_hook('the_tale')
################################################################

import smart_imports

smart_imports.all()

RUNSERVER_RUNNING = 'runserver' in sys.argv

PROJECT_DIR = os.path.abspath(os.path.dirname(__file__))
HOME_DIR = os.getenv("HOME")

PROJECT_MODULE = os.path.basename(PROJECT_DIR)

META_CONFIG_FILE = os.path.join(PROJECT_DIR, 'meta_config.json')
META_CONFIG = utils_meta_config.MetaConfig(config_path=META_CONFIG_FILE)

DEBUG = False

SENTRY_RAVEN_CONFIG = None
예제 #7
0
def pytest_sessionstart(session):
    install_import_hook(packages=["cumulusci"])
예제 #8
0
#!/usr/bin/env python
import runpy
import os

if bool(os.environ.get('NUMBA_USE_TYPEGUARD')):
    # The typeguard import hook must be installed prior to importing numba.
    # Therefore, this cannot be part of the numba package.
    from typeguard.importhook import install_import_hook
    install_import_hook(packages=['numba'])

# ensure full tracebacks are available and no help messages appear in test mode
os.environ['NUMBA_DEVELOPER_MODE'] = '1'


if __name__ == "__main__":
    runpy.run_module('numba.runtests', run_name='__main__')
예제 #9
0
import os
if os.getenv("WACLIENT_ENABLE_TYPEGUARD"):
    from typeguard.importhook import install_import_hook
    install_import_hook('waclient')

try:
    # MUST BE ROBUST DUE TO NEED FOR RESILIENT "CRASH HANDLER" ACCESS #

    import logging
    import sys
    custom_kivy_stream_handler = logging.StreamHandler()
    sys._kivy_logging_handler = custom_kivy_stream_handler
    from kivy.logger import Logger as logger  # Trigger init of Kivy logging
    del logger

    # Finish ugly monkey-patching by Kivy
    assert logging.getLogger("kivy") is logging.root
    logging.Logger.root = logging.root
    logging.Logger.manager.root = logging.root

    # For now allow EVERYTHING
    logging.root.setLevel(logging.DEBUG)
    logging.disable(0)

    # import logging_tree
    # logging_tree.printout()
except Exception as exc:
    print(">>>>>>>> FAILED INITIALIZATION OF WACLIENT LOGGING: %r" % exc)
예제 #10
0
from typeguard.importhook import install_import_hook
import unittest

with install_import_hook('utils.functional.dict'):
    from ..functional.dict import FunctionalDict, dmap, dzip, merge_dicts, rmerge_dicts


class FuncDictTest(unittest.TestCase):
    def test_subset_keys(self):
        fd = FunctionalDict({'foo': 'hello',
                             'bar': 'world',
                             'baz': 'spam',
                             'moo': 'polly',
                             'myon': 'ni'})
        self.assertEqual({'foo': 'hello',
                          'bar': 'world'},
                         fd.copy_subset(whitelist=('foo', 'bar', 'baz', 'fyon'),
                                        blacklist=('baz', 'moo', 'nargle')))
        self.assertEqual({'bar': 'world',
                          'moo': 'polly'},
                         fd.only_keys({'bar', 'moo', 'fyon'}))
        self.assertEqual({'foo': 'hello',
                          'baz': 'spam',
                          'myon': 'ni'},
                         fd.without_keys(['bar', 'moo', 'fyon']))

    def test_map(self):
        d1 = {'foo': 7,
              'bar': 'spam',
              'baz': [0, 1, 2]}
        self.assertEqual({'foofoo': 7,
예제 #11
0
import os

import pyximport
from typeguard.importhook import install_import_hook

pyximport.install()

if not os.environ.get("STACK_DATA_SLOW_TESTS"):
    install_import_hook(["stack_data"])
예제 #12
0
파일: utils.py 프로젝트: XedaHQ/xeda
from typeguard.importhook import install_import_hook


from varname import argname

from .dataclass import XedaBaseModel

try:
    import tomllib  # type: ignore # pyright: reportMissingImports=none
except ModuleNotFoundError:
    # python_version < "3.11":
    import tomli as tomllib  # type: ignore


install_import_hook("xeda")

__all__ = [
    "SDF",
    # utility functions
    "toml_load",
    "toml_loads",
    "cached_property",
    "unique",
    "WorkingDirectory",
]

log = logging.getLogger(__name__)


T = TypeVar("T")
예제 #13
0
# this file `conftest.py` gets called by pytest automatically, before anything else
import logging
import os
import sys
from typeguard import importhook
from tests import SrcTypeguardFinder

logging.getLogger().setLevel("DEBUG")

# prevent all imports in tests/ from requiring the prefix "src."
EXTRA_PATH = os.getcwd() + "/src"
sys.path.insert(1, EXTRA_PATH)

# apply runtime typechecking to "./src" and "./tests"
SrcTypeguardFinder.path_prefixes.extend([EXTRA_PATH, os.getcwd() + "/tests"])

importhook.install_import_hook([], cls=SrcTypeguardFinder)

# pull all fixtures into scope of the tests
from tests.jeroenbos.partest.fixtures.test_fixtures import *  # type: ignore  # noqa
예제 #14
0
__version__ = '0.4.1'

from encomp.settings import SETTINGS

if SETTINGS.type_checking:

    from typeguard.importhook import install_import_hook

    # installs the @typechecked decorator on all functions imported after this
    install_import_hook('encomp')
예제 #15
0
def pytest_sessionstart(session):
    packages = session.config.getoption('typeguard_packages')
    if packages:
        package_list = [pkg.strip() for pkg in packages.split(',')]
        install_import_hook(packages=package_list)
예제 #16
0
from io import StringIO
from time import sleep
from typeguard.importhook import install_import_hook
import unittest
from unittest.mock import patch

with install_import_hook('utils.timer'):
    from ..timer import ExecutionTimer

DELAY = 0.5


class Callback:
    def __call__(self, interval):
        self.interval = interval


class TimerTest(unittest.TestCase):
    @patch('sys.stdout', new_callable=StringIO)
    def test_none(self, mock_stdout):
        with ExecutionTimer(output=None) as e:
            sleep(DELAY)
        self.assertGreater(e.interval, DELAY)
        self.assertEqual(mock_stdout.getvalue(), '')

    @patch('sys.stdout', new_callable=StringIO)
    def test_string(self, mock_stdout):
        with ExecutionTimer() as e:
            sleep(DELAY)
        self.assertGreater(e.interval, DELAY)
        self.assertTrue(