Example #1
0
def limit_loader(request, monkeypatch):
    """Patch pkgutil.get_loader to give loader without get_filename or archive.

    This provides for tests where a system has custom loaders, e.g. Google App
    Engine's HardenedModulesHook, which have neither the `get_filename` method
    nor the `archive` attribute.

    This fixture will run the testcase twice, once with and once without the
    limitation/mock.
    """
    if not request.param:
        return

    class LimitedLoader(object):
        def __init__(self, loader):
            self.loader = loader

        def __getattr__(self, name):
            if name in ("archive", "get_filename"):
                msg = "Mocking a loader which does not have `%s.`" % name
                raise AttributeError(msg)
            return getattr(self.loader, name)

    old_get_loader = pkgutil.get_loader

    def get_loader(*args, **kwargs):
        return LimitedLoader(old_get_loader(*args, **kwargs))

    monkeypatch.setattr(pkgutil, "get_loader", get_loader)
Example #2
0
def test_mainWindow(monkeypatch, mocker):

    if len(sys.argv) > 1:  # when run directly with pytest
        current_location = os.path.abspath(os.path.dirname(sys.argv[1]))
    else:  # when run through the runTests.py wrapper
        current_location = os.path.abspath(os.path.dirname(
            sys.argv[0]))  # pytest

    script_location = [
        os.path.join(current_location, 'App', 'easyDiffraction'),
        os.path.join(current_location, 'App')
    ]
    # Make the main script think it's been run from the command line by overwriting its sys.argv[]
    monkeypatch.setattr(sys, 'argv', script_location)

    mocker.patch.object(QQmlApplicationEngine, 'load')

    widget = MainWindow()

    # test app
    assert widget.app.organizationName() == 'easyDiffraction'
    assert widget.app.organizationDomain() == 'easyDiffraction.org'
    assert widget.app.applicationName() == 'easyDiffraction'

    assert isinstance(widget.engine, QQmlApplicationEngine)
    assert any('Imports' in s for s in widget.engine.importPathList())

    # test engine
    QQmlApplicationEngine.load.assert_called_once()

    proxy = [1, 2]
    widget.setupEngine(proxy=proxy)
    assert widget.engine.rootContext().contextProperty("proxy") == [1, 2]
Example #3
0
    def test_all_lang_sections(self, monkeypatch):
        monkeypatch.setattr('builtins.input', lambda _: "dummy_input")

        res, dom = fetch_resdom("llevar", redundance=True)
        sections = list(pyetymology.eobjects.mwparserhelper.all_lang_sections(dom, flat=False)) #type: List[List[Wikicode]]
        assert len(sections) == 2
        catalan = sections[0][0]
        spanish = sections[1][0]

        catalantxt = asset_llevar.catalan_txt
        spanishtxt = asset_llevar.spanish_txt

        assert str(catalan) == catalantxt
        assert str(spanish) == spanishtxt

        sections = list(pyetymology.eobjects.mwparserhelper.all_lang_sections(dom, flat=True)) #type: List[List[Wikicode]]
        assert len(sections) == 2
        catalan = sections[0]
        spanish = sections[1]
        assert str(catalan) == catalantxt
        assert str(spanish) == spanishtxt

        res, dom = fetch_resdom("llevar", redundance=False)
        sections = list(pyetymology.eobjects.mwparserhelper.all_lang_sections(dom)) #type: List[List[Wikicode]] # This has been changed, b/c the removal of antiredundance
        assert len(sections) == 2
        catalan = sections[0]
        spanish = sections[1]
        assert str(catalan) == '==Catalan==\n\n'
        assert str(spanish) == '==Spanish==\n\n'
Example #4
0
def limit_loader(request, monkeypatch):
    """Patch pkgutil.get_loader to give loader without get_filename or archive.

    This provides for tests where a system has custom loaders, e.g. Google App
    Engine's HardenedModulesHook, which have neither the `get_filename` method
    nor the `archive` attribute.

    This fixture will run the testcase twice, once with and once without the
    limitation/mock.
    """
    if not request.param:
        return

    class LimitedLoader:
        def __init__(self, loader):
            self.loader = loader

        def __getattr__(self, name):
            if name in {"archive", "get_filename"}:
                raise AttributeError(
                    f"Mocking a loader which does not have {name!r}.")
            return getattr(self.loader, name)

    old_get_loader = pkgutil.get_loader

    def get_loader(*args, **kwargs):
        return LimitedLoader(old_get_loader(*args, **kwargs))

    monkeypatch.setattr(pkgutil, "get_loader", get_loader)
def test_s3_faulty_lifecycle(monkeypatch: monkeypatch.MonkeyPatch) -> None:
    monkeypatch.setattr("boto3.client", s3.s3_faulty_client)
    env = test_util.get_dummy_env()
    manager = tensorboard.build(env.det_cluster_id, env.det_experiment_id,
                                env.det_trial_id, default_conf)

    with pytest.raises(exceptions.S3UploadFailedError):
        manager.sync()
Example #6
0
    def test_auto_lang(self, monkeypatch):
        res, dom = fetch_resdom("adelante", redundance=True)
        monkeypatch.setattr('builtins.input', lambda _: "dummy_input")

        assert pyetymology.eobjects.mwparserhelper.reduce_to_one_lang(dom) == (
            list(
                pyetymology.eobjects.mwparserhelper.sections_by_lang(
                    dom, "Spanish")), "Spanish")
Example #7
0
    def _mockpatch(obj: Any,
                   member_name: str,
                   obj_name: Optional[str] = None) -> MagicMock:
        mock = MagicMock(name=f'{member_name}<M>' if obj_name is None else
                         f'{obj_name}.{member_name}<M>')

        monkeypatch.setattr(obj, member_name, mock)

        return mock
Example #8
0
def test_bdm_find_free_device_name_exhausted(
        monkeypatch: _pytest.monkeypatch.MonkeyPatch) -> None:
    mappings = tft.artemis.drivers.aws.BlockDeviceMappings()
    monkeypatch.setattr(tft.artemis.drivers.aws, 'EBS_DEVICE_NAMES', [])

    r = mappings.find_free_device_name()

    assert r.is_error
    assert r.unwrap_error().message == 'cannot find any free EBS device name'
Example #9
0
    def test_auto_lang_failure(self, monkeypatch):

        res, dom = fetch_resdom("llevar", redundance=True)
        monkeypatch.setattr('builtins.input', lambda _: "English")
        with pytest.raises(MissingException) as e_info:
            pyetymology.eobjects.mwparserhelper.reduce_to_one_lang(dom) == (list(
                pyetymology.eobjects.mwparserhelper.sections_by_lang(dom, "Spanish")), "Spanish")

        assert e_info.value.G is None
        assert e_info.value.missing_thing == "language_section"
Example #10
0
def patch(monkeypatch: _pytest.monkeypatch.MonkeyPatch,
          obj: Any,
          member_name: str,
          obj_name: Optional[str] = None) -> MagicMock:
    mock = MagicMock(name=f'{member_name}<mock>' if obj_name is None else
                     f'{obj_name}.{member_name}<mock>')

    monkeypatch.setattr(obj, member_name, mock)

    return mock
Example #11
0
def app(monkeypatch: _pytest.monkeypatch.MonkeyPatch) -> flask.Flask:
    def _get_google_secrets() -> typing.Dict[str, str]:
        return {
            'GOOGLE_OAUTH2_CLIENT_ID': 'client_id',
            'GOOGLE_OAUTH2_CLIENT_SECRET': 'client_secret',
            'SECRET_KEY': 'secret_key',
        }
    monkeypatch.setattr(app_generator, '_get_google_secrets', _get_google_secrets)
    monkeypatch.setattr(app_generator, 'oauth', mock.Mock())

    return app_generator.create_app()
Example #12
0
def test_s3_lifecycle(monkeypatch: monkeypatch.MonkeyPatch) -> None:
    monkeypatch.setattr("boto3.client", s3.s3_client)
    manager = tensorboard.build(test_util.get_dummy_env(), default_conf)
    assert isinstance(manager, tensorboard.S3TensorboardManager)

    manager.sync()
    expected = (
        "s3_bucket",
        "uuid-123/tensorboard/experiment/1/trial/1/events.out.tfevents.example",
    )
    assert expected in manager.client.objects
Example #13
0
    def test_all_lang_sections(self, monkeypatch):
        monkeypatch.setattr('builtins.input', lambda _: "Spanish")

        res, dom = fetch_resdom("llegar")
        sections = list(
            pyetymology.eobjects.mwparserhelper.all_lang_sections(dom)
        )  #type: List[List[Wikicode]] # This has been changed, b/c the removal of antiredundance
        assert sections == [
            '==Asturian==\n\n', '==Catalan==\n\n', '==Old Irish==\n\n',
            '==Spanish==\n\n'
        ]
Example #14
0
def do_test_policy_supports_snapshots(
    mock_inputs: MockInputs,
    require_snapshots: bool,
    provide_snapshots: bool,
    monkeypatch: _pytest.monkeypatch.MonkeyPatch
) -> None:
    mock_logger, mock_session, mock_pools, mock_guest_request = mock_inputs

    for mock_pool in mock_pools:
        monkeypatch.setattr(
            mock_pool,
            'capabilities',
            lambda: Ok(tft.artemis.drivers.PoolCapabilities(supports_snapshots=False))
        )

    if provide_snapshots:
        monkeypatch.setattr(
            mock_pools[0],
            'capabilities',
            lambda: Ok(tft.artemis.drivers.PoolCapabilities(supports_snapshots=True))
        )

    mock_guest_request.environment = tft.artemis.environment.Environment(
        hw=tft.artemis.environment.HWRequirements(arch='x86_64'),
        os=tft.artemis.environment.OsRequirements(compose='dummy-compose'),
        snapshots=require_snapshots
    )

    r_ruling = tft.artemis.routing_policies.policy_supports_snapshots(
        mock_logger,
        mock_session,
        mock_pools,
        mock_guest_request
    )

    assert r_ruling.is_ok

    ruling = r_ruling.unwrap()

    assert isinstance(ruling, tft.artemis.routing_policies.PolicyRuling)
    assert ruling.cancel is False

    if require_snapshots and provide_snapshots:
        assert ruling.allowed_pools == [mock_pools[0]]

    elif require_snapshots and not provide_snapshots:
        assert ruling.allowed_pools == []

    elif not require_snapshots:
        assert ruling.allowed_pools == mock_pools

    else:
        assert False, 'unreachable'
Example #15
0
    def test_graph(self, monkeypatch):
        monkeypatch.setattr('builtins.input',
                            lambda _: "1")  # Multiple Definitions
        _Q = fetch_query("adelante", "Spanish")
        # TODO: investigate the effect of flattening on this line
        G = wx.graph(_Q)
        G2 = nx.DiGraph()
        nx.add_path(
            G2, ["adelante#Spanish$0", "$0{m|Spanish|delante ['in front']}"])
        assert nx.is_isomorphic(G, G2)

        assert [repr(s) for s in G.nodes] == [s for s in G2.nodes]
Example #16
0
def test_generate_dataset_name_dataset_only_one(monkeypatch):
    def mockreturn(app_root, username):
        return ['dataset_1']

    def path_already_exists(app_root, username):
        return True

    monkeypatch.setattr(utils.profile, 'find_all_datasets', mockreturn)
    monkeypatch.setattr(utils.profile, 'path_already_exists',
                        path_already_exists)
    result = generate_dataset_name('a', 'b', 'dataset')
    assert result == 'dataset_2'
Example #17
0
def test_search_isbn(client: flask.testing.FlaskClient,
                     monkeypatch: _pytest.monkeypatch.MonkeyPatch) -> None:
    with client.session_transaction() as sess:
        sess['user.email'] = 'me'

    get_prices = mock.Mock()
    get_prices.return_value = {'Seller1': '100.00', 'Seller2': '99.00'}
    monkeypatch.setattr(app_generator.meta_scraper, 'get_resale_prices',
                        get_prices)

    res = client.get(flask.url_for('search', isbn='1234'))
    assert res.status_code == 200
    assert get_prices.call_count == 1
Example #18
0
def oauth_requests(monkeypatch: '_pytest.monkeypatch.monkeypatch'):
    def fake_get(url: str, params: dict=None):
        params = params or {}
        if url == "https://ouath.example/token_info":
            token = params['access_token']
            if token == "100":
                return FakeResponse(200, '{"scope": ["myscope"]}')
            if token == "200":
                return FakeResponse(200, '{"scope": ["wrongscope"]}')
            if token == "300":
                return FakeResponse(404, '')
        return url

    monkeypatch.setattr(requests, 'get', fake_get)
def test_templates_auto_reload_debug_run(monkeypatch):
    app = flask.Flask(__name__)

    def run_simple_mock(*args, **kwargs):
        pass

    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)

    app.run()
    assert app.templates_auto_reload == False
    assert app.jinja_env.auto_reload == False

    app.run(debug=True)
    assert app.templates_auto_reload == True
    assert app.jinja_env.auto_reload == True
Example #20
0
def oauth_requests(monkeypatch):
    def fake_get(url, params=None, timeout=None):
        """
        :type url: str
        :type params: dict| None
        """
        params = params or {}
        if url == "https://ouath.example/token_info":
            token = params['access_token']
            if token == "100":
                return FakeResponse(200, '{"uid": "test-user", "scope": ["myscope"]}')
            if token == "200":
                return FakeResponse(200, '{"uid": "test-user", "scope": ["wrongscope"]}')
            if token == "300":
                return FakeResponse(404, '')
        return url

    monkeypatch.setattr('connexion.decorators.security.session.get', fake_get)
Example #21
0
def oauth_requests(monkeypatch):
    def fake_get(url, params=None, timeout=None):
        """
        :type url: str
        :type params: dict| None
        """
        params = params or {}
        if url == "https://ouath.example/token_info":
            token = params['access_token']
            if token == "100":
                return FakeResponse(200, '{"uid": "test-user", "scope": ["myscope"]}')
            if token == "200":
                return FakeResponse(200, '{"uid": "test-user", "scope": ["wrongscope"]}')
            if token == "300":
                return FakeResponse(404, '')
        return url

    monkeypatch.setattr('connexion.decorators.security.session.get', fake_get)
Example #22
0
def workdir(request, tmpdir, monkeypatch):
    """Provide a working dir (scope: function).

    Creates a temporary directory with subdirs 'src/', 'cache/', and
    'tmp/'. In 'src/sample.txt' a simple text file is created.

    The system working directory is changed to the temporary dir during
    test.

    Global root temporary dir is set to the newly created 'tmp/' dir
    during test.
    """
    tmpdir.mkdir('src')
    tmpdir.mkdir('cache')
    tmpdir.mkdir('tmp')
    tmpdir.join('src').join('sample.txt').write('Hi there!')
    monkeypatch.chdir(tmpdir)
    monkeypatch.setattr(tempfile, 'tempdir', str(tmpdir.join('tmp')))
    return tmpdir
Example #23
0
def workdir(request, tmpdir, monkeypatch):
    """Provide a working dir (scope: function).

    Creates a temporary directory with subdirs 'src/', 'cache/', and
    'tmp/'. In 'src/sample.txt' a simple text file is created.

    The system working directory is changed to the temporary dir during
    test.

    Global root temporary dir is set to the newly created 'tmp/' dir
    during test.
    """
    tmpdir.mkdir('src')
    tmpdir.mkdir('cache')
    tmpdir.mkdir('tmp')
    tmpdir.join('src').join('sample.txt').write('Hi there!')
    monkeypatch.chdir(tmpdir)
    monkeypatch.setattr(tempfile, 'tempdir', str(tmpdir.join('tmp')))
    return tmpdir
def test_s3_lifecycle(monkeypatch: monkeypatch.MonkeyPatch,
                      prefix: Optional[str]) -> None:
    monkeypatch.setattr("boto3.client", s3.s3_client)
    env = test_util.get_dummy_env()
    conf = copy.deepcopy(default_conf)
    conf["prefix"] = prefix
    manager = tensorboard.build(env.det_cluster_id, env.det_experiment_id,
                                env.det_trial_id, conf)
    assert isinstance(manager, tensorboard.S3TensorboardManager)

    tfevents_path = "uuid-123/tensorboard/experiment/1/trial/1/events.out.tfevents.example"

    manager.sync()
    if prefix is not None:
        tfevents_path = os.path.join(
            os.path.normpath(prefix).lstrip("/"), tfevents_path)

    expected = (
        "s3_bucket",
        tfevents_path,
    )
    assert expected in manager.client.objects
Example #25
0
def fixture_redis(
        monkeypatch: _pytest.monkeypatch.MonkeyPatch, tmpdir: py.path.local,
        logger: gluetool.log.ContextAdapter) -> Generator[None, None, None]:
    redislite.client.logger.setLevel(logging.DEBUG)

    redis_db_file = tmpdir.join('redis.db')

    def get_cache(logger: gluetool.log.ContextAdapter) -> redislite.Redis:
        return redislite.Redis(dbfilename=str(redis_db_file))

    mock_contextvar = contextvars.ContextVar('CACHE',
                                             default=get_cache(logger))

    monkeypatch.setattr(tft.artemis, 'get_cache', get_cache)
    monkeypatch.setattr(tft.artemis.context, 'get_cache', get_cache)

    monkeypatch.setattr(tft.artemis.context, 'CACHE', mock_contextvar)

    monkeypatch.setitem(tft.artemis.context.CONTEXT_PROVIDERS,
                        ('cache', redis.Redis), mock_contextvar)

    yield
Example #26
0
def fake_version_and_paths():
    if is_running_as_site_user():
        return

    import _pytest.monkeypatch  # type: ignore # pylint: disable=import-outside-toplevel

    monkeypatch = _pytest.monkeypatch.MonkeyPatch()
    tmp_dir = tempfile.mkdtemp(prefix="pytest_cmk_")

    import cmk.utils.paths  # pylint: disable=import-outside-toplevel
    import cmk.utils.version as cmk_version  # pylint: disable=import-outside-toplevel

    if is_managed_repo():
        edition_short = "cme"
    elif is_enterprise_repo():
        edition_short = "cee"
    else:
        edition_short = "cre"

    monkeypatch.setattr(
        cmk_version, "omd_version", lambda: "%s.%s" %
        (cmk_version.__version__, edition_short))

    monkeypatch.setattr("cmk.utils.paths.agents_dir", "%s/agents" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.checks_dir", "%s/checks" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.notifications_dir",
                        Path(cmk_path()) / "notifications")
    monkeypatch.setattr("cmk.utils.paths.inventory_dir",
                        "%s/inventory" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.inventory_output_dir",
                        os.path.join(tmp_dir, "var/check_mk/inventory"))
    monkeypatch.setattr(
        "cmk.utils.paths.inventory_archive_dir",
        os.path.join(tmp_dir, "var/check_mk/inventory_archive"),
    )
    monkeypatch.setattr("cmk.utils.paths.check_manpages_dir",
                        "%s/checkman" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.web_dir", "%s/web" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.omd_root", tmp_dir)
    monkeypatch.setattr("cmk.utils.paths.tmp_dir",
                        os.path.join(tmp_dir, "tmp/check_mk"))
    monkeypatch.setattr("cmk.utils.paths.counters_dir",
                        os.path.join(tmp_dir, "tmp/check_mk/counters"))
    monkeypatch.setattr("cmk.utils.paths.tcp_cache_dir",
                        os.path.join(tmp_dir, "tmp/check_mk/cache"))
    monkeypatch.setattr("cmk.utils.paths.trusted_ca_file",
                        os.path.join(tmp_dir, "var/ssl/ca-certificates.crt"))
    monkeypatch.setattr(
        "cmk.utils.paths.data_source_cache_dir",
        os.path.join(tmp_dir, "tmp/check_mk/data_source_cache"),
    )
    monkeypatch.setattr("cmk.utils.paths.var_dir",
                        os.path.join(tmp_dir, "var/check_mk"))
    monkeypatch.setattr("cmk.utils.paths.log_dir",
                        os.path.join(tmp_dir, "var/log"))
    monkeypatch.setattr("cmk.utils.paths.core_helper_config_dir",
                        Path(tmp_dir, "var/check_mk/core/helper_config"))
    monkeypatch.setattr("cmk.utils.paths.autochecks_dir",
                        os.path.join(tmp_dir, "var/check_mk/autochecks"))
    monkeypatch.setattr(
        "cmk.utils.paths.precompiled_checks_dir",
        os.path.join(tmp_dir, "var/check_mk/precompiled_checks"),
    )
    monkeypatch.setattr("cmk.utils.paths.crash_dir",
                        Path(cmk.utils.paths.var_dir) / "crashes")
    monkeypatch.setattr("cmk.utils.paths.include_cache_dir",
                        os.path.join(tmp_dir, "tmp/check_mk/check_includes"))
    monkeypatch.setattr("cmk.utils.paths.check_mk_config_dir",
                        os.path.join(tmp_dir, "etc/check_mk/conf.d"))
    monkeypatch.setattr("cmk.utils.paths.main_config_file",
                        os.path.join(tmp_dir, "etc/check_mk/main.mk"))
    monkeypatch.setattr("cmk.utils.paths.default_config_dir",
                        os.path.join(tmp_dir, "etc/check_mk"))
    monkeypatch.setattr("cmk.utils.paths.piggyback_dir",
                        Path(tmp_dir) / "var/check_mk/piggyback")
    monkeypatch.setattr("cmk.utils.paths.piggyback_source_dir",
                        Path(tmp_dir) / "var/check_mk/piggyback_sources")
    monkeypatch.setattr("cmk.utils.paths.htpasswd_file",
                        os.path.join(tmp_dir, "etc/htpasswd"))

    monkeypatch.setattr("cmk.utils.paths.local_share_dir",
                        Path(tmp_dir, "local/share/check_mk"))
    monkeypatch.setattr("cmk.utils.paths.local_checks_dir",
                        Path(tmp_dir, "local/share/check_mk/checks"))
    monkeypatch.setattr(
        "cmk.utils.paths.local_notifications_dir",
        Path(tmp_dir, "local/share/check_mk/notifications"),
    )
    monkeypatch.setattr("cmk.utils.paths.local_inventory_dir",
                        Path(tmp_dir, "local/share/check_mk/inventory"))
    monkeypatch.setattr("cmk.utils.paths.local_check_manpages_dir",
                        Path(tmp_dir, "local/share/check_mk/checkman"))
    monkeypatch.setattr("cmk.utils.paths.local_agents_dir",
                        Path(tmp_dir, "local/share/check_mk/agents"))
    monkeypatch.setattr("cmk.utils.paths.local_web_dir",
                        Path(tmp_dir, "local/share/check_mk/web"))
    monkeypatch.setattr(
        "cmk.utils.paths.local_pnp_templates_dir",
        Path(tmp_dir, "local/share/check_mk/pnp-templates"),
    )
    monkeypatch.setattr("cmk.utils.paths.local_doc_dir",
                        Path(tmp_dir, "local/share/doc/check_mk"))
    monkeypatch.setattr("cmk.utils.paths.local_locale_dir",
                        Path(tmp_dir, "local/share/check_mk/locale"))
    monkeypatch.setattr("cmk.utils.paths.local_bin_dir",
                        Path(tmp_dir, "local/bin"))
    monkeypatch.setattr("cmk.utils.paths.local_lib_dir",
                        Path(tmp_dir, "local/lib"))
    monkeypatch.setattr("cmk.utils.paths.local_mib_dir",
                        Path(tmp_dir, "local/share/snmp/mibs"))
    monkeypatch.setattr("cmk.utils.paths.diagnostics_dir",
                        Path(tmp_dir).joinpath("var/check_mk/diagnostics"))
    monkeypatch.setattr("cmk.utils.paths.site_config_dir",
                        Path(cmk.utils.paths.var_dir, "site_configs"))
    monkeypatch.setattr("cmk.utils.paths.disabled_packages_dir",
                        Path(cmk.utils.paths.var_dir, "disabled_packages"))
    monkeypatch.setattr(
        "cmk.utils.paths.nagios_objects_file",
        os.path.join(tmp_dir, "etc/nagios/conf.d/check_mk_objects.cfg"),
    )
    monkeypatch.setattr(
        "cmk.utils.paths.precompiled_hostchecks_dir",
        os.path.join(tmp_dir, "var/check_mk/precompiled"),
    )
    monkeypatch.setattr(
        "cmk.utils.paths.discovered_host_labels_dir",
        Path(tmp_dir, "var/check_mk/discovered_host_labels"),
    )
    monkeypatch.setattr("cmk.utils.paths.profile_dir",
                        Path(cmk.utils.paths.var_dir, "web"))
def test_task_17_get_factorial(monkeypatch):
    monkeypatch.setattr('builtins.input', lambda x: 4)
    assert tasks_practice.task_17_get_factorial(4) == math.factorial(4)
Example #28
0
def fake_version_and_paths():
    if is_running_as_site_user():
        return

    import _pytest.monkeypatch  # type: ignore # pylint: disable=import-outside-toplevel
    monkeypatch = _pytest.monkeypatch.MonkeyPatch()
    tmp_dir = tempfile.mkdtemp(prefix="pytest_cmk_")

    import cmk.utils.version as cmk_version  # pylint: disable=import-outside-toplevel
    import cmk.utils.paths  # pylint: disable=import-outside-toplevel

    # TODO: handle CME case
    #if is_managed_repo():
    #    monkeypatch.setattr(cmk_version, "omd_version", lambda: "%s.cee" % cmk_version.__version__)
    #elif is_enterprise_repo():
    if is_enterprise_repo():
        monkeypatch.setattr(cmk_version, "omd_version", lambda: "%s.cee" % cmk_version.__version__)
    else:
        monkeypatch.setattr(cmk_version, "omd_version", lambda: "%s.cre" % cmk_version.__version__)

    monkeypatch.setattr("cmk.utils.paths.agents_dir", "%s/agents" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.checks_dir", "%s/checks" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.notifications_dir", Path(cmk_path()) / "notifications")
    monkeypatch.setattr("cmk.utils.paths.inventory_dir", "%s/inventory" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.inventory_output_dir",
                        os.path.join(tmp_dir, "var/check_mk/inventory"))
    monkeypatch.setattr("cmk.utils.paths.inventory_archive_dir",
                        os.path.join(tmp_dir, "var/check_mk/inventory_archive"))
    monkeypatch.setattr("cmk.utils.paths.check_manpages_dir", "%s/checkman" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.web_dir", "%s/web" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.omd_root", tmp_dir)
    monkeypatch.setattr("cmk.utils.paths.tmp_dir", os.path.join(tmp_dir, "tmp/check_mk"))
    monkeypatch.setattr("cmk.utils.paths.counters_dir",
                        os.path.join(tmp_dir, "tmp/check_mk/counters"))
    monkeypatch.setattr("cmk.utils.paths.tcp_cache_dir", os.path.join(tmp_dir,
                                                                      "tmp/check_mk/cache"))
    monkeypatch.setattr("cmk.utils.paths.data_source_cache_dir",
                        os.path.join(tmp_dir, "tmp/check_mk/data_source_cache"))
    monkeypatch.setattr("cmk.utils.paths.var_dir", os.path.join(tmp_dir, "var/check_mk"))
    monkeypatch.setattr("cmk.utils.paths.autochecks_dir",
                        os.path.join(tmp_dir, "var/check_mk/autochecks"))
    monkeypatch.setattr("cmk.utils.paths.precompiled_checks_dir",
                        os.path.join(tmp_dir, "var/check_mk/precompiled_checks"))
    monkeypatch.setattr("cmk.utils.paths.crash_dir", Path(cmk.utils.paths.var_dir) / "crashes")
    monkeypatch.setattr("cmk.utils.paths.include_cache_dir",
                        os.path.join(tmp_dir, "tmp/check_mk/check_includes"))
    monkeypatch.setattr("cmk.utils.paths.check_mk_config_dir",
                        os.path.join(tmp_dir, "etc/check_mk/conf.d"))
    monkeypatch.setattr("cmk.utils.paths.main_config_file",
                        os.path.join(tmp_dir, "etc/check_mk/main.mk"))
    monkeypatch.setattr("cmk.utils.paths.default_config_dir", os.path.join(tmp_dir, "etc/check_mk"))
    monkeypatch.setattr("cmk.utils.paths.piggyback_dir", Path(tmp_dir) / "var/check_mk/piggyback")
    monkeypatch.setattr("cmk.utils.paths.piggyback_source_dir",
                        Path(tmp_dir) / "var/check_mk/piggyback_sources")
    monkeypatch.setattr("cmk.utils.paths.htpasswd_file", os.path.join(tmp_dir, "etc/htpasswd"))

    monkeypatch.setattr("cmk.utils.paths.local_share_dir", Path(tmp_dir, "local/share/check_mk"))
    monkeypatch.setattr("cmk.utils.paths.local_checks_dir",
                        Path(tmp_dir, "local/share/check_mk/checks"))
    monkeypatch.setattr("cmk.utils.paths.local_notifications_dir",
                        Path(tmp_dir, "local/share/check_mk/notifications"))
    monkeypatch.setattr("cmk.utils.paths.local_inventory_dir",
                        Path(tmp_dir, "local/share/check_mk/inventory"))
    monkeypatch.setattr("cmk.utils.paths.local_check_manpages_dir",
                        Path(tmp_dir, "local/share/check_mk/checkman"))
    monkeypatch.setattr("cmk.utils.paths.local_agents_dir",
                        Path(tmp_dir, "local/share/check_mk/agents"))
    monkeypatch.setattr("cmk.utils.paths.local_web_dir", Path(tmp_dir, "local/share/check_mk/web"))
    monkeypatch.setattr("cmk.utils.paths.local_pnp_templates_dir",
                        Path(tmp_dir, "local/share/check_mk/pnp-templates"))
    monkeypatch.setattr("cmk.utils.paths.local_doc_dir", Path(tmp_dir, "local/share/doc/check_mk"))
    monkeypatch.setattr("cmk.utils.paths.local_locale_dir",
                        Path(tmp_dir, "local/share/check_mk/locale"))
    monkeypatch.setattr("cmk.utils.paths.local_bin_dir", Path(tmp_dir, "local/bin"))
    monkeypatch.setattr("cmk.utils.paths.local_lib_dir", Path(tmp_dir, "local/lib"))
    monkeypatch.setattr("cmk.utils.paths.local_mib_dir", Path(tmp_dir, "local/share/snmp/mibs"))
Example #29
0
def fake_version_and_paths():
    if is_running_as_site_user():
        return

    monkeypatch = _pytest.monkeypatch.MonkeyPatch()
    tmp_dir = tempfile.mkdtemp(prefix="pytest_cmk_")

    import cmk
    monkeypatch.setattr(cmk, "omd_version", lambda: "%s.cee" % cmk.__version__)

    monkeypatch.setattr("cmk.utils.paths.checks_dir", "%s/checks" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.notifications_dir",
                        "%s/notifications" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.inventory_dir",
                        "%s/inventory" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.check_manpages_dir",
                        "%s/checkman" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.web_dir", "%s/web" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.omd_root", tmp_dir)
    monkeypatch.setattr("cmk.utils.paths.tmp_dir",
                        os.path.join(tmp_dir, "tmp/check_mk"))
    monkeypatch.setattr("cmk.utils.paths.var_dir",
                        os.path.join(tmp_dir, "var/check_mk"))
    monkeypatch.setattr(
        "cmk.utils.paths.precompiled_checks_dir",
        os.path.join(tmp_dir, "var/check_mk/precompiled_checks"))
    monkeypatch.setattr("cmk.utils.paths.include_cache_dir",
                        os.path.join(tmp_dir, "tmp/check_mk/check_includes"))
    monkeypatch.setattr("cmk.utils.paths.check_mk_config_dir",
                        os.path.join(tmp_dir, "etc/check_mk/conf.d"))
    monkeypatch.setattr("cmk.utils.paths.default_config_dir",
                        os.path.join(tmp_dir, "etc/check_mk"))
    monkeypatch.setattr("cmk.utils.paths.piggyback_dir",
                        Path(tmp_dir) / "var/check_mk/piggyback")
    monkeypatch.setattr("cmk.utils.paths.piggyback_source_dir",
                        Path(tmp_dir) / "var/check_mk/piggyback_sources")
Example #30
0
def fake_version_and_paths():
    if is_running_as_site_user():
        return

    import _pytest.monkeypatch  # type: ignore
    monkeypatch = _pytest.monkeypatch.MonkeyPatch()
    tmp_dir = tempfile.mkdtemp(prefix="pytest_cmk_")

    import cmk

    # TODO: handle CME case
    #if is_managed_repo():
    #    monkeypatch.setattr(cmk, "omd_version", lambda: "%s.cee" % cmk.__version__)
    #elif is_enterprise_repo():
    if is_enterprise_repo():
        monkeypatch.setattr(cmk, "omd_version",
                            lambda: "%s.cee" % cmk.__version__)
    else:
        monkeypatch.setattr(cmk, "omd_version",
                            lambda: "%s.cre" % cmk.__version__)

    monkeypatch.setattr("cmk.utils.paths.agents_dir", "%s/agents" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.checks_dir", "%s/checks" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.notifications_dir",
                        Path(cmk_path()) / "notifications")
    monkeypatch.setattr("cmk.utils.paths.inventory_dir",
                        "%s/inventory" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.inventory_output_dir",
                        os.path.join(tmp_dir, "var/check_mk/inventory"))
    monkeypatch.setattr(
        "cmk.utils.paths.inventory_archive_dir",
        os.path.join(tmp_dir, "var/check_mk/inventory_archive"))
    monkeypatch.setattr("cmk.utils.paths.check_manpages_dir",
                        "%s/checkman" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.web_dir", "%s/web" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.omd_root", tmp_dir)
    monkeypatch.setattr("cmk.utils.paths.tmp_dir",
                        os.path.join(tmp_dir, "tmp/check_mk"))
    monkeypatch.setattr("cmk.utils.paths.counters_dir",
                        os.path.join(tmp_dir, "tmp/check_mk/counters"))
    monkeypatch.setattr("cmk.utils.paths.tcp_cache_dir",
                        os.path.join(tmp_dir, "tmp/check_mk/cache"))
    monkeypatch.setattr(
        "cmk.utils.paths.data_source_cache_dir",
        os.path.join(tmp_dir, "tmp/check_mk/data_source_cache"))
    monkeypatch.setattr("cmk.utils.paths.var_dir",
                        os.path.join(tmp_dir, "var/check_mk"))
    monkeypatch.setattr("cmk.utils.paths.autochecks_dir",
                        os.path.join(tmp_dir, "var/check_mk/autochecks"))
    monkeypatch.setattr(
        "cmk.utils.paths.precompiled_checks_dir",
        os.path.join(tmp_dir, "var/check_mk/precompiled_checks"))
    monkeypatch.setattr("cmk.utils.paths.crash_dir",
                        Path(cmk.utils.paths.var_dir) / "crashes")
    monkeypatch.setattr("cmk.utils.paths.include_cache_dir",
                        os.path.join(tmp_dir, "tmp/check_mk/check_includes"))
    monkeypatch.setattr("cmk.utils.paths.check_mk_config_dir",
                        os.path.join(tmp_dir, "etc/check_mk/conf.d"))
    monkeypatch.setattr("cmk.utils.paths.main_config_file",
                        os.path.join(tmp_dir, "etc/check_mk/main.mk"))
    monkeypatch.setattr("cmk.utils.paths.default_config_dir",
                        os.path.join(tmp_dir, "etc/check_mk"))
    monkeypatch.setattr("cmk.utils.paths.piggyback_dir",
                        Path(tmp_dir) / "var/check_mk/piggyback")
    monkeypatch.setattr("cmk.utils.paths.piggyback_source_dir",
                        Path(tmp_dir) / "var/check_mk/piggyback_sources")
    monkeypatch.setattr("cmk.utils.paths.htpasswd_file",
                        os.path.join(tmp_dir, "etc/htpasswd"))
Example #31
0
def modules_tmpdir_prefix(modules_tmpdir, monkeypatch):
    monkeypatch.setattr(sys, "prefix", str(modules_tmpdir))
    return modules_tmpdir
def test_task_16_get_sum_of_numbers(monkeypatch):
    monkeypatch.setattr('builtins.input', lambda x: 4)
    assert tasks_practice.task_16_get_sum_of_numbers(4) == 10
Example #33
0
 def value_store_fixture(monkeypatch):
     value_store: MutableMapping[str, Any] = {}
     monkeypatch.setattr(module, 'get_value_store', lambda: value_store)
     yield value_store
Example #34
0
def fake_version_and_paths():
    if is_running_as_site_user():
        return

    import _pytest.monkeypatch  # type: ignore # pylint: disable=import-outside-toplevel

    monkeypatch = _pytest.monkeypatch.MonkeyPatch()
    tmp_dir = tempfile.mkdtemp(prefix="pytest_cmk_")

    import cmk.utils.paths  # pylint: disable=import-outside-toplevel
    import cmk.utils.version as cmk_version  # pylint: disable=import-outside-toplevel

    if is_managed_repo():
        edition_short = "cme"
    elif is_plus_repo():
        edition_short = "cpe"
    elif is_enterprise_repo():
        edition_short = "cee"
    else:
        edition_short = "cre"

    monkeypatch.setattr(
        cmk_version, "omd_version", lambda: "%s.%s" %
        (cmk_version.__version__, edition_short))

    # Unit test context: load all available modules
    monkeypatch.setattr(
        cmk_version,
        "is_raw_edition",
        lambda: not (is_enterprise_repo() and is_managed_repo() and
                     is_plus_repo()),
    )
    monkeypatch.setattr(cmk_version, "is_enterprise_edition",
                        is_enterprise_repo)
    monkeypatch.setattr(cmk_version, "is_managed_edition", is_managed_repo)
    monkeypatch.setattr(cmk_version, "is_plus_edition", is_plus_repo)

    monkeypatch.setattr("cmk.utils.paths.agents_dir", "%s/agents" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.checks_dir", "%s/checks" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.notifications_dir",
                        Path(cmk_path()) / "notifications")
    monkeypatch.setattr("cmk.utils.paths.inventory_dir",
                        "%s/inventory" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.inventory_output_dir",
                        os.path.join(tmp_dir, "var/check_mk/inventory"))
    monkeypatch.setattr(
        "cmk.utils.paths.inventory_archive_dir",
        os.path.join(tmp_dir, "var/check_mk/inventory_archive"),
    )
    monkeypatch.setattr(
        "cmk.utils.paths.inventory_delta_cache_dir",
        os.path.join(tmp_dir, "var/check_mk/inventory_delta_cache"),
    )
    monkeypatch.setattr("cmk.utils.paths.check_manpages_dir",
                        "%s/checkman" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.web_dir", "%s/web" % cmk_path())
    monkeypatch.setattr("cmk.utils.paths.omd_root", Path(tmp_dir))
    monkeypatch.setattr("cmk.utils.paths.tmp_dir",
                        os.path.join(tmp_dir, "tmp/check_mk"))
    monkeypatch.setattr("cmk.utils.paths.counters_dir",
                        os.path.join(tmp_dir, "tmp/check_mk/counters"))
    monkeypatch.setattr("cmk.utils.paths.tcp_cache_dir",
                        os.path.join(tmp_dir, "tmp/check_mk/cache"))
    monkeypatch.setattr("cmk.utils.paths.trusted_ca_file",
                        Path(tmp_dir, "var/ssl/ca-certificates.crt"))
    monkeypatch.setattr(
        "cmk.utils.paths.data_source_cache_dir",
        os.path.join(tmp_dir, "tmp/check_mk/data_source_cache"),
    )
    monkeypatch.setattr("cmk.utils.paths.var_dir",
                        os.path.join(tmp_dir, "var/check_mk"))
    monkeypatch.setattr("cmk.utils.paths.log_dir",
                        os.path.join(tmp_dir, "var/log"))
    monkeypatch.setattr("cmk.utils.paths.core_helper_config_dir",
                        Path(tmp_dir, "var/check_mk/core/helper_config"))
    monkeypatch.setattr("cmk.utils.paths.autochecks_dir",
                        os.path.join(tmp_dir, "var/check_mk/autochecks"))
    monkeypatch.setattr(
        "cmk.utils.paths.precompiled_checks_dir",
        os.path.join(tmp_dir, "var/check_mk/precompiled_checks"),
    )
    monkeypatch.setattr("cmk.utils.paths.crash_dir",
                        Path(cmk.utils.paths.var_dir) / "crashes")
    monkeypatch.setattr("cmk.utils.paths.include_cache_dir",
                        os.path.join(tmp_dir, "tmp/check_mk/check_includes"))
    monkeypatch.setattr("cmk.utils.paths.check_mk_config_dir",
                        os.path.join(tmp_dir, "etc/check_mk/conf.d"))
    monkeypatch.setattr("cmk.utils.paths.main_config_file",
                        os.path.join(tmp_dir, "etc/check_mk/main.mk"))
    monkeypatch.setattr("cmk.utils.paths.default_config_dir",
                        os.path.join(tmp_dir, "etc/check_mk"))
    monkeypatch.setattr("cmk.utils.paths.piggyback_dir",
                        Path(tmp_dir) / "var/check_mk/piggyback")
    monkeypatch.setattr("cmk.utils.paths.piggyback_source_dir",
                        Path(tmp_dir) / "var/check_mk/piggyback_sources")
    monkeypatch.setattr("cmk.utils.paths.htpasswd_file",
                        os.path.join(tmp_dir, "etc/htpasswd"))

    monkeypatch.setattr("cmk.utils.paths.local_share_dir",
                        Path(tmp_dir, "local/share/check_mk"))
    monkeypatch.setattr("cmk.utils.paths.local_checks_dir",
                        Path(tmp_dir, "local/share/check_mk/checks"))
    monkeypatch.setattr(
        "cmk.utils.paths.local_notifications_dir",
        Path(tmp_dir, "local/share/check_mk/notifications"),
    )
    monkeypatch.setattr("cmk.utils.paths.local_inventory_dir",
                        Path(tmp_dir, "local/share/check_mk/inventory"))
    monkeypatch.setattr("cmk.utils.paths.local_check_manpages_dir",
                        Path(tmp_dir, "local/share/check_mk/checkman"))
    monkeypatch.setattr("cmk.utils.paths.local_agents_dir",
                        Path(tmp_dir, "local/share/check_mk/agents"))
    monkeypatch.setattr("cmk.utils.paths.local_web_dir",
                        Path(tmp_dir, "local/share/check_mk/web"))
    monkeypatch.setattr(
        "cmk.utils.paths.local_pnp_templates_dir",
        Path(tmp_dir, "local/share/check_mk/pnp-templates"),
    )
    monkeypatch.setattr("cmk.utils.paths.local_doc_dir",
                        Path(tmp_dir, "local/share/doc/check_mk"))
    monkeypatch.setattr("cmk.utils.paths.local_locale_dir",
                        Path(tmp_dir, "local/share/check_mk/locale"))
    monkeypatch.setattr("cmk.utils.paths.local_bin_dir",
                        Path(tmp_dir, "local/bin"))
    monkeypatch.setattr("cmk.utils.paths.local_lib_dir",
                        Path(tmp_dir, "local/lib"))
    monkeypatch.setattr("cmk.utils.paths.local_gui_plugins_dir",
                        Path(tmp_dir, "local/lib/check_mk/gui/plugins"))
    monkeypatch.setattr("cmk.utils.paths.local_mib_dir",
                        Path(tmp_dir, "local/share/snmp/mibs"))
    monkeypatch.setattr("cmk.utils.paths.diagnostics_dir",
                        Path(tmp_dir).joinpath("var/check_mk/diagnostics"))
    monkeypatch.setattr("cmk.utils.paths.site_config_dir",
                        Path(cmk.utils.paths.var_dir, "site_configs"))
    monkeypatch.setattr("cmk.utils.paths.disabled_packages_dir",
                        Path(cmk.utils.paths.var_dir, "disabled_packages"))
    monkeypatch.setattr(
        "cmk.utils.paths.nagios_objects_file",
        os.path.join(tmp_dir, "etc/nagios/conf.d/check_mk_objects.cfg"),
    )
    monkeypatch.setattr(
        "cmk.utils.paths.precompiled_hostchecks_dir",
        os.path.join(tmp_dir, "var/check_mk/precompiled"),
    )
    monkeypatch.setattr(
        "cmk.utils.paths.discovered_host_labels_dir",
        Path(tmp_dir, "var/check_mk/discovered_host_labels"),
    )
    monkeypatch.setattr("cmk.utils.paths.profile_dir",
                        Path(cmk.utils.paths.var_dir, "web"))

    # Agent registration paths
    monkeypatch.setattr(
        "cmk.utils.paths.received_outputs_dir",
        Path(cmk.utils.paths.var_dir, "agent-receiver/received-outputs"),
    )
    monkeypatch.setattr(
        "cmk.utils.paths.data_source_push_agent_dir",
        Path(cmk.utils.paths.data_source_cache_dir, "push-agent"),
    )
    monkeypatch.setattr(
        "cmk.utils.paths._r4r_base_dir",
        Path(cmk.utils.paths.var_dir, "wato/requests-for-registration"),
    )
    monkeypatch.setattr(
        "cmk.utils.paths.r4r_new_dir",
        Path(cmk.utils.paths._r4r_base_dir, "NEW"),
    )
    monkeypatch.setattr(
        "cmk.utils.paths.r4r_pending_dir",
        Path(cmk.utils.paths._r4r_base_dir, "PENDING"),
    )
    monkeypatch.setattr(
        "cmk.utils.paths.r4r_declined_dir",
        Path(cmk.utils.paths._r4r_base_dir, "DECLINED"),
    )
    monkeypatch.setattr(
        "cmk.utils.paths.r4r_declined_bundles_dir",
        Path(cmk.utils.paths._r4r_base_dir, "DECLINED-BUNDLES"),
    )
    monkeypatch.setattr(
        "cmk.utils.paths.r4r_ready_dir",
        Path(cmk.utils.paths._r4r_base_dir, "READY"),
    )
    monkeypatch.setattr(
        "cmk.utils.paths.r4r_discoverable_dir",
        Path(cmk.utils.paths._r4r_base_dir, "DISCOVERABLE"),
    )
Example #35
0
def modules_tmpdir_prefix(modules_tmpdir, monkeypatch):
    monkeypatch.setattr(sys, "prefix", str(modules_tmpdir))
    return modules_tmpdir