예제 #1
0
def test_flash(user_id):
    # Execute the first request flash some message
    with application_and_request_context(), login.UserSessionContext(user_id):
        session_id = on_succeeded_login(user_id)  # Create and activate session
        assert session is not None

        flash("abc")
        assert session.session_info.flashes == ["abc"]

    # Now create the second request to get the previously flashed message
    with application_and_request_context(), login.UserSessionContext(user_id):
        on_access(user_id, session_id)
        assert session is not None
        assert session.session_info.flashes == ["abc"]

        # Get the flashed messages removes the messages from the session
        # and subsequent calls to get_flashed_messages return the messages
        # over and over.
        assert get_flashed_messages() == [HTML("abc")]
        assert get_flashed_messages() == [HTML("abc")]
        assert session.session_info.flashes == []

    # Now create the third request that should not have access to the flashed messages since the
    # second one consumed them.
    with application_and_request_context(), login.UserSessionContext(user_id):
        on_access(user_id, session_id)
        assert session is not None
        assert session.session_info.flashes == []
        assert get_flashed_messages() == []
예제 #2
0
def test_add_message_commit_separation():
    with application_and_request_context():
        assert git._git_messages() == []
        git.add_message("dingdong")
        assert git._git_messages() == ["dingdong"]

    with application_and_request_context():
        assert git._git_messages() == []
        git.add_message("xyz")
        assert git._git_messages() == ["xyz"]
예제 #3
0
    def run(self):
        self._logger.log(VERBOSE, "Initializing application...")
        with application_and_request_context():
            self._initialize_gui_environment()
            self._initialize_base_environment()

            self._logger.log(VERBOSE, "Updating Checkmk configuration...")
            self._logger.log(
                VERBOSE,
                f"{tty.red}ATTENTION: Some steps may take a long time depending "
                f"on your installation, e.g. during major upgrades.{tty.normal}"
            )
            total = len(self._steps())
            count = itertools.count(1)
            for step_func, title in self._steps():
                self._logger.log(VERBOSE,
                                 " %i/%i %s..." % (next(count), total, title))
                try:
                    step_func()
                except Exception:
                    self._logger.error(" + \"%s\" failed" % title,
                                       exc_info=True)
                    if self._arguments.debug:
                        raise

        self._logger.log(VERBOSE, "Done")
예제 #4
0
def test_host_downtime_with_services(mock_livestatus, with_request_context,
                                     dates):
    start_time, end_time = dates

    with mock_livestatus(
            expect_status_query=True) as live, application_and_request_context(
            ), SuperUserContext():
        load_config()
        live.expect_query(
            "GET hosts\nColumns: name\nFilter: name = example.com")
        live.expect_query(
            "COMMAND [...] SCHEDULE_HOST_DOWNTIME;example.com;0;86400;12;0;120;;Going down",
            match_type="ellipsis",
        )
        live.expect_query(
            "GET services\nColumns: host_name description\nFilter: host_name = example.com",
        )
        live.expect_query(
            "COMMAND [...] SCHEDULE_SVC_DOWNTIME;example.com;Memory;0;86400;12;0;120;;Going down",
            match_type="ellipsis",
        )
        live.expect_query(
            "COMMAND [...] SCHEDULE_SVC_DOWNTIME;example.com;CPU load;0;86400;12;0;120;;Going down",
            match_type="ellipsis",
        )
        downtimes.schedule_host_downtime(
            sites.live(),
            "example.com",
            start_time,
            end_time,
            include_all_services=True,
            recur="weekday_start",
            duration=120,
            comment="Going down",
        )
예제 #5
0
    def run(self) -> bool:
        self._has_errors = False
        self._logger.log(VERBOSE, "Initializing application...")
        with application_and_request_context(), SuperUserContext():
            self._initialize_gui_environment()
            self._initialize_base_environment()

            self._logger.log(VERBOSE, "Updating Checkmk configuration...")
            self._logger.log(
                VERBOSE,
                f"{tty.red}ATTENTION: Some steps may take a long time depending "
                f"on your installation, e.g. during major upgrades.{tty.normal}",
            )
            total = len(self._steps())
            for count, (step_func, title) in enumerate(self._steps(), start=1):
                self._logger.log(VERBOSE,
                                 " %i/%i %s..." % (count, total, title))
                try:
                    step_func()
                except Exception:
                    self._has_errors = True
                    self._logger.error(' + "%s" failed' % title, exc_info=True)
                    if self._arguments.debug:
                        raise

        self._logger.log(VERBOSE, "Done")
        return self._has_errors
예제 #6
0
파일: main.py 프로젝트: gradecke/checkmk
def run(arguments: argparse.Namespace, old_site_id: SiteId,
        new_site_id: SiteId) -> bool:
    has_errors = False
    logger.debug("Initializing application...")
    with application_and_request_context(), SuperUserContext():
        initialize_gui_environment()

        logger.debug("Starting actions...")
        actions = sorted(rename_action_registry.values(),
                         key=lambda a: a.sort_index)
        total = len(actions)
        for count, rename_action in enumerate(actions, start=1):
            logger.log(VERBOSE, " %i/%i %s...", count, total,
                       rename_action.title)
            try:
                rename_action.run(old_site_id, new_site_id)
            except Exception:
                has_errors = True
                logger.error(' + "%s" failed',
                             rename_action.title,
                             exc_info=True)
                if arguments.debug:
                    raise

    logger.log(VERBOSE, "Done")
    return has_errors
예제 #7
0
def test_del_vars_from_env():
    environ = dict(create_environ(),
                   REQUEST_URI='',
                   QUERY_STRING='foo=foo&_username=foo&_password=bar&bar=bar')
    with application_and_request_context(environ):
        # First we hit the cached property so we can see that the underlying Request object
        # actually got replaced later.
        _ = global_request.args
        _ = html.request.args

        html.request.set_var("foo", "123")

        html.request.del_var_from_env("_username")
        html.request.del_var_from_env("_password")

        # Make test independent of dict sorting
        assert html.request.query_string in [b'foo=foo&bar=bar', b'bar=bar&foo=foo']

        assert '_password' not in html.request.args
        assert '_username' not in html.request.args

        # Check the request local proxied version too.
        # Make test independent of dict sorting
        assert global_request.query_string in [b'foo=foo&bar=bar', b'bar=bar&foo=foo']
        assert '_password' not in global_request.args
        assert '_username' not in global_request.args

        assert html.request.var("foo") == "123"
예제 #8
0
def test_hostgroup_host_downtime(mock_livestatus, with_request_context, dates):
    start_time, end_time = dates

    with mock_livestatus(
            expect_status_query=True) as live, application_and_request_context(
            ), SuperUserContext():
        load_config()
        live.expect_query([
            "GET hostgroups",
            "Columns: members",
            "Filter: name = example",
        ])
        live.expect_query(
            "GET hosts\nColumns: name\nFilter: name = example.com\nFilter: name = heute\nOr: 2"
        )
        live.expect_query(
            "COMMAND [...] SCHEDULE_HOST_DOWNTIME;heute;0;86400;16;0;120;;Boom",
            match_type="ellipsis",
        )
        live.expect_query(
            "COMMAND [...] SCHEDULE_HOST_DOWNTIME;example.com;0;86400;16;0;120;;Boom",
            match_type="ellipsis",
        )

        downtimes.schedule_hostgroup_host_downtime(
            sites.live(),
            "example",
            start_time,
            end_time,
            recur="day_of_month",
            duration=120,
            comment="Boom",
        )
예제 #9
0
def test_del_vars_from_env():
    environ = create_environ(
        query_string="foo=foo&_username=foo&_password=bar&bar=bar", )
    with application_and_request_context(environ):
        # First we hit the cached property, so we can see that the underlying Request object
        # actually got replaced later.
        _ = global_request.args
        _ = html.request.args

        assert html.request.query_string

        html.request.set_var("foo", "123")

        html.request.del_var_from_env("_username")
        html.request.del_var_from_env("_password")

        # Make test independent of dict sorting
        assert html.request.query_string in [
            b"foo=foo&bar=bar", b"bar=bar&foo=foo"
        ]

        assert "_password" not in html.request.args
        assert "_username" not in html.request.args

        # Check the request local proxied version too.
        # Make test independent of dict sorting
        assert global_request.query_string in [
            b"foo=foo&bar=bar", b"bar=bar&foo=foo"
        ]
        assert "_password" not in global_request.args
        assert "_username" not in global_request.args

        assert html.request.var("foo") == "123"
예제 #10
0
def fixture_pre_20_cookie():
    environ = dict(
        create_environ(),
        HTTP_COOKIE=
        u"xyz=123; auth_stable=lärs:1534272374.61:1f59cac3fcd5bcc389e4f8397bed315b; abc=123"
        .encode("utf-8"))

    with application_and_request_context(environ):
        yield "auth_stable"
예제 #11
0
def test_web_server_auth_session(user_id):
    environ = dict(create_environ(), REMOTE_USER=str(user_id))

    with application_and_request_context(environ):
        assert user.id is None
        with login.authenticate(request) as authenticated:
            assert authenticated is True
            assert user.id == user_id
            assert session.user_id == user.id
        assert user.id is None
예제 #12
0
def fixture_current_cookie(with_user, session_id):
    user_id = with_user[0]
    cookie_name = login.auth_cookie_name()
    cookie_value = login._auth_cookie_value(user_id, session_id)

    environ = dict(create_environ(),
                   HTTP_COOKIE=f"{cookie_name}={cookie_value}".encode("utf-8"))

    with application_and_request_context(environ):
        yield cookie_name
예제 #13
0
def test_bi_legacy_config_conversion(monkeypatch):
    monkeypatch.setattr(
        "cmk.utils.bi.bi_legacy_config_converter.BIManagement._get_config_string",
        lambda x: sample_config.LEGACY_BI_PACKS_CONFIG_STRING,
    )

    with application_and_request_context():
        schema_from_legacy_packs = cmk.utils.bi.bi_legacy_config_converter.BILegacyConfigConverter(
            logging.Logger("unit test")).get_schema_for_packs()
    assert sample_config.bi_packs_config["packs"] == schema_from_legacy_packs
예제 #14
0
def test_del_vars_from_post():
    environ = create_environ(
        input_stream=io.BytesIO(b"_username=foo&_secret=bar"),
        content_type="application/x-www-form-urlencoded",
    )
    with application_and_request_context(environ):
        assert global_request.form

        global_request.del_var_from_env("_username")
        global_request.del_var_from_env("_secret")

        assert not global_request.form
예제 #15
0
파일: openapi.py 프로젝트: m3rlinux/checkmk
def generate(args=None):
    if args is None:
        args = [None]

    with application_and_request_context():
        data = generate_data(target="debug")

    if args[-1] == "--json":
        output = json.dumps(data, indent=2).rstrip()
    else:
        output = dict_to_yaml(data).rstrip()

    return output
예제 #16
0
def test_del_vars():
    environ = dict(create_environ(), REQUEST_URI="", QUERY_STRING="opt_x=x&foo=foo")
    with application_and_request_context(environ):
        assert html.request.var("opt_x") == "x"
        assert html.request.var("foo") == "foo"

        html.request.del_vars(prefix="opt_")

        assert html.request.var("opt_x") is None
        assert html.request.var("foo") == "foo"

        # Check the request local proxied version too
        assert global_request.var("opt_x") is None
        assert global_request.var("foo") == "foo"
예제 #17
0
def test_del_vars():
    environ = create_environ(query_string="opt_x=x&foo=foo", )
    with application_and_request_context(environ):
        assert html.request.var("opt_x") == "x"
        assert html.request.var("foo") == "foo"

        html.request.del_vars(prefix="opt_")

        assert html.request.var("opt_x") is None
        assert html.request.var("foo") == "foo"

        # Check the request local proxied version too
        assert global_request.var("opt_x") is None
        assert global_request.var("foo") == "foo"
예제 #18
0
    def run(self):
        self._logger.log(VERBOSE, "Initializing application...")
        with application_and_request_context():
            self._initialize_gui_environment()
            self._initialize_base_environment()

            self._logger.log(VERBOSE, "Updating Checkmk configuration...")
            for step_func, title in self._steps():
                self._logger.log(VERBOSE, " + %s..." % title)
                try:
                    step_func()
                except Exception:
                    self._logger.error(" + \"%s\" failed" % title,
                                       exc_info=True)
                    if self._arguments.debug:
                        raise

        self._logger.log(VERBOSE, "Done")
예제 #19
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2021 tribe29 GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.
"""Initialize the Checkmk default configuration in case it is necessary.
"""
# pylint: disable=cmk-module-layer-violation
from cmk.gui import watolib
from cmk.gui.utils.script_helpers import application_and_request_context, initialize_gui_environment

if __name__ == "__main__":
    with application_and_request_context():
        initialize_gui_environment()
        watolib.init_wato_datastructures()
예제 #20
0
def test_load_group_information(tmp_path, run_as_superuser):
    with open(cmk.utils.paths.check_mk_config_dir + "/wato/groups.mk",
              "w") as f:
        f.write("""# encoding: utf-8

define_contactgroups.update({'all': u'Everything'})
define_hostgroups.update({'all_hosts': u'All hosts :-)'})
define_servicegroups.update({'all_services': u'All särvices'})
""")

    with open(
            cmk.utils.paths.default_config_dir + "/multisite.d/wato/groups.mk",
            "w") as f:
        f.write("""# encoding: utf-8

multisite_hostgroups = {
    "all_hosts": {
        "ding": "dong",
    },
}

multisite_servicegroups = {
    "all_services": {
        "d1ng": "dong",
    },
}

multisite_contactgroups = {
    "all": {
        "d!ng": "dong",
    },
}
""")

    with application_and_request_context(), run_as_superuser():
        assert groups.load_group_information() == {
            "contact": {
                "all": {
                    "alias": "Everything",
                    "d!ng": "dong",
                }
            },
            "host": {
                "all_hosts": {
                    "alias": "All hosts :-)",
                    "ding": "dong",
                }
            },
            "service": {
                "all_services": {
                    "alias": "All s\xe4rvices",
                    "d1ng": "dong",
                }
            },
        }

        assert groups.load_contact_group_information() == {
            "all": {
                "alias": "Everything",
                "d!ng": "dong",
            }
        }

        assert gui_groups.load_host_group_information() == {
            "all_hosts": {
                "alias": "All hosts :-)",
                "ding": "dong",
            }
        }

        assert gui_groups.load_service_group_information() == {
            "all_services": {
                "alias": "All s\xe4rvices",
                "d1ng": "dong",
            }
        }
예제 #21
0
def test_load_group_information_empty(tmp_path, run_as_superuser):
    with application_and_request_context(), run_as_superuser():
        assert groups.load_contact_group_information() == {}
        assert gui_groups.load_host_group_information() == {}
        assert gui_groups.load_service_group_information() == {}
예제 #22
0
def request_context():
    with application_and_request_context():
        yield
예제 #23
0
파일: conftest.py 프로젝트: bbaumer/checkmk
def module_wide_request_context():
    # This one is kind of an hack because some other test-fixtures touch the user object AFTER the
    # request context has already ended. If we increase our scope this won't matter, but it is of
    # course wrong. These other fixtures have to be fixed.
    with application_and_request_context():
        yield
예제 #24
0
def test_load_group_information(tmp_path):
    with open(cmk.utils.paths.check_mk_config_dir + "/wato/groups.mk", "w") as f:
        f.write("""# encoding: utf-8

if type(define_contactgroups) != dict:
    define_contactgroups = {}
define_contactgroups.update({'all': u'Everything'})

if type(define_hostgroups) != dict:
    define_hostgroups = {}
define_hostgroups.update({'all_hosts': u'All hosts :-)'})

if type(define_servicegroups) != dict:
    define_servicegroups = {}
define_servicegroups.update({'all_services': u'All särvices'})
""")

    with open(cmk.utils.paths.default_config_dir + "/multisite.d/wato/groups.mk", "w") as f:
        f.write("""# encoding: utf-8

multisite_hostgroups = {
    "all_hosts": {
        "ding": "dong",
    },
}

multisite_servicegroups = {
    "all_services": {
        "d1ng": "dong",
    },
}

multisite_contactgroups = {
    "all": {
        "d!ng": "dong",
    },
}
""")

    with application_and_request_context():
        assert groups.load_group_information() == {
            'contact': {
                'all': {
                    'alias': u'Everything',
                    "d!ng": "dong",
                }
            },
            'host': {
                'all_hosts': {
                    'alias': u'All hosts :-)',
                    "ding": "dong",
                }
            },
            'service': {
                'all_services': {
                    'alias': u'All s\xe4rvices',
                    "d1ng": "dong",
                }
            },
        }

        assert groups.load_contact_group_information() == {
            'all': {
                'alias': u'Everything',
                "d!ng": "dong",
            }
        }

        assert gui_groups.load_host_group_information() == {
            'all_hosts': {
                'alias': u'All hosts :-)',
                "ding": "dong",
            }
        }

        assert gui_groups.load_service_group_information() == {
            'all_services': {
                'alias': u'All s\xe4rvices',
                "d1ng": "dong",
            }
        }
예제 #25
0
def request_context() -> Iterator[None]:
    """This fixture registers a global htmllib.html() instance just like the regular GUI"""
    with application_and_request_context():
        yield
예제 #26
0
def request_context() -> Iterator[None]:
    with application_and_request_context():
        yield