def _show_view_as_dashlet(self, view_spec: ViewSpec): html.add_body_css_class("view") html.open_div(id_="dashlet_content_wrapper") is_reload = request.has_var("_reload") view_display_options = "SIXLW" if not is_reload: view_display_options += "HR" request.set_var("display_options", view_display_options) request.set_var("_display_options", view_display_options) html.add_body_css_class("dashlet") # Need to be loaded before processing the painter_options below. # TODO: Make this dependency explicit display_options.load_from_html(request, html) painter_options = PainterOptions.get_instance() painter_options.load(self._dashlet_spec["name"]) # Here the linked view default context has the highest priority # linkedview default>dashlet>url active filter, dashboard context = visuals.get_merged_context(self.context, view_spec["context"]) view = views.View(self._dashlet_spec["name"], view_spec, context) view.row_limit = views.get_limit() view.only_sites = visuals.get_only_sites_from_context(context) view.user_sorters = views.get_user_sorters() views.process_view(views.GUIViewRenderer(view, show_buttons=False)) html.close_div()
def test_get_url_input(request_context): global_request.set_var("url", "view.py?bla=blub") global_request.set_var("no_url", "2") global_request.set_var("invalid_url", "http://bla/") global_request.set_var("invalid_char", "viäw.py") global_request.set_var("invalid_char2", "vi+w.py") with pytest.raises(MKUserError) as e: global_request.get_url_input("not_existing") assert "is missing" in "%s" % e assert global_request.get_url_input("get_default", "my_url.py") == "my_url.py" assert global_request.get_url_input("get_default", "http://bla/") == "http://bla/" assert global_request.get_url_input("url") == "view.py?bla=blub" assert global_request.get_url_input("no_url") == "2" with pytest.raises(MKUserError) as e: global_request.get_url_input("invalid_url") assert "not a valid" in "%s" % e with pytest.raises(MKUserError) as e: global_request.get_url_input("invalid_char") assert "not a valid" in "%s" % e with pytest.raises(MKUserError) as e: global_request.get_url_input("invalid_char2") assert "not a valid" in "%s" % e assert global_request.get_url_input("no_url") == "2"
def _get_time_range_of(self, what: str) -> Union[None, int, float]: varprefix = self.ident + "_" + what rangename = request.var(varprefix + "_range") if rangename == "abs": try: return time.mktime( time.strptime(request.get_str_input_mandatory(varprefix), "%Y-%m-%d")) except Exception: user_errors.add( MKUserError( varprefix, _("Please enter the date in the format YYYY-MM-DD."))) return None if rangename == "unix": return request.get_integer_input_mandatory(varprefix) if rangename is None: return None try: count = request.get_integer_input_mandatory(varprefix) secs = count * int(rangename) return int(time.time()) - secs except Exception: request.set_var(varprefix, "") return None
def _show_view_as_dashlet(self, view_spec: ViewSpec): html.add_body_css_class("view") html.open_div(id_="dashlet_content_wrapper") is_reload = request.has_var("_reload") view_display_options = "SIXLW" if not is_reload: view_display_options += "HR" request.set_var('display_options', view_display_options) request.set_var('_display_options', view_display_options) html.add_body_css_class('dashlet') # Need to be loaded before processing the painter_options below. # TODO: Make this dependency explicit display_options.load_from_html(request, html) painter_options = PainterOptions.get_instance() painter_options.load(self._dashlet_spec["name"]) view = views.View(self._dashlet_spec["name"], view_spec, self.context) view.row_limit = views.get_limit() view.only_sites = visuals.get_only_sites_from_context(self.context) view.user_sorters = views.get_user_sorters() views.process_view(views.GUIViewRenderer(view, show_buttons=False)) html.close_div()
def test_request_processing(request_context: RequestContextFixture) -> None: global_request.set_var("varname", "1a") global_request.set_var("varname2", "1") global_request.get_str_input("varname", deflt="lol") global_request.get_integer_input_mandatory("varname2") global_request.get_request(exclude_vars=["varname2"])
def test_filters_filter_table(register_builtin_html, test, monkeypatch): # Needed for DeploymentTristateFilter test def deployment_states(host_name): return { "abc": { "target_aghash": "abc", }, "zzz": {}, }[host_name] if not cmk_version.is_raw_edition(): import cmk.gui.cee.agent_bakery as agent_bakery # pylint: disable=redefined-outer-name,import-outside-toplevel,no-name-in-module monkeypatch.setattr(agent_bakery, "get_cached_deployment_status", deployment_states) # Needed for FilterInvFloat test monkeypatch.setattr(cmk.gui.inventory, "get_inventory_data", get_inventory_data_patch) # Needed for FilterAggrServiceUsed test def is_part_of_aggregation_patch(host, service): return { ("h", "srv1"): True }.get((host, service), False) monkeypatch.setattr(cmk.gui.bi, "is_part_of_aggregation", is_part_of_aggregation_patch) with request.stashed_vars(), on_time('2018-04-15 16:50', 'CET'): request.del_vars() for key, val in test.request_vars: request.set_var(key, val) # TODO: Fix this for real... if not cmk_version.is_raw_edition or test.ident != "deployment_has_agent": filt = cmk.gui.plugins.visuals.utils.filter_registry[test.ident] assert filt.filter_table({}, test.rows) == test.expected_rows
def test_request_processing(request_context): global_request.set_var("varname", "1a") global_request.set_var("varname2", "1") global_request.get_unicode_input("varname", deflt="lol") global_request.get_integer_input_mandatory("varname2") global_request.get_request(exclude_vars=["varname2"])
def breadcrumb(self) -> Breadcrumb: # The ModeEditRuleset.breadcrumb_item does not know anything about the fact that this mode # is a child of the logwatch_rules ruleset. It can not construct the correct link to the # logwatch_rules ruleset in the breadcrumb. We hand over the ruleset variable name that we # are interested in to the mode. It's a bit hacky to do it this way, but it's currently the # only way to get these information to the modes breadcrumb method. with request.stashed_vars(): request.set_var("varname", "logwatch_rules") request.del_var("host") request.del_var("service") return super().breadcrumb()
def _show_view_as_dashlet(self, view_spec: ViewSpec): html.add_body_css_class("view") html.open_div(id_="dashlet_content_wrapper") is_reload = request.has_var("_reload") view_display_options = "SIXLW" if not is_reload: view_display_options += "HR" request.set_var("display_options", view_display_options) request.set_var("_display_options", view_display_options) html.add_body_css_class("dashlet") # Need to be loaded before processing the painter_options below. # TODO: Make this dependency explicit display_options.load_from_html(request, html) painter_options = PainterOptions.get_instance() painter_options.load(self._dashlet_spec["name"]) # Here the linked view default context has the highest priority # linkedview default>dashlet>url active filter> dashboard. However views # have the "show_filters" default to prefill the filtermenu with empty # valued filters(UX). Those need to be cleared out. Otherwise those # empty filters are the highest priority filters and the user can never # filter the view. view_context = { filtername: filtervalues for filtername, filtervalues in view_spec["context"].items() if { var: value for var, value in filtervalues.items() # These are the filters request variables. Keep set values # For the TriStateFilters unset == ignore == "-1" # all other cases unset is an empty string if (var.startswith("is_") and value != "-1" ) # TriState filters except ignore or (not var.startswith("is_") and value ) # Rest of filters with some value } } context = visuals.get_merged_context(self.context, view_context) view = views.View(self._dashlet_spec["name"], view_spec, context) view.row_limit = views.get_limit() view.only_sites = visuals.get_only_sites_from_context(context) view.user_sorters = views.get_user_sorters() views.process_view(views.GUIViewRenderer(view, show_buttons=False)) html.close_div()
def test_filters_filter(register_builtin_html, test, monkeypatch): # Needed for ABCFilterCustomAttribute monkeypatch.setattr(cmk.gui.config, "wato_host_attrs", [{"name": "bla", "title": "Bla"}]) # Need for ABCTagFilter monkeypatch.setattr(cmk.gui.config, "tags", cmk.utils.tags.BuiltinTagConfig()) with request.stashed_vars(), on_time('2018-04-15 16:50', 'CET'): request.del_vars() for key, val in test.request_vars: request.set_var(key, val) filt = cmk.gui.plugins.visuals.utils.filter_registry[test.ident] assert filt.filter(infoname="bla") == test.expected_filters
def selection_id() -> str: """Generates a selection id or uses the given one""" if not request.has_var('selection'): sel_id = utils.gen_id() request.set_var('selection', sel_id) return sel_id sel_id = request.get_str_input_mandatory('selection') # Avoid illegal file access by introducing .. or / if not re.match("^[-0-9a-zA-Z]+$", sel_id): new_id = utils.gen_id() request.set_var('selection', new_id) return new_id return sel_id
def _evaluate_user_opts(self) -> Tuple[TableRows, bool, Optional[str]]: assert self.id is not None table_id = ensure_str(self.id) rows = self.rows search_term = None actions_enabled = (self.options["searchable"] or self.options["sortable"]) if not actions_enabled: return rows, False, None table_opts = user.tableoptions.setdefault(table_id, {}) # Handle the initial visibility of the actions actions_visible = table_opts.get('actions_visible', False) if request.get_ascii_input('_%s_actions' % table_id): actions_visible = request.get_ascii_input('_%s_actions' % table_id) == '1' table_opts['actions_visible'] = actions_visible if self.options["searchable"]: search_term = request.get_unicode_input_mandatory('search', '') # Search is always lower case -> case insensitive search_term = search_term.lower() if search_term: request.set_var('search', search_term) rows = _filter_rows(rows, search_term) if request.get_ascii_input('_%s_reset_sorting' % table_id): request.del_var('_%s_sort' % table_id) if 'sort' in table_opts: del table_opts['sort'] # persist if self.options["sortable"]: # Now apply eventual sorting settings sort = self._get_sort_column(table_opts) if sort is not None: request.set_var('_%s_sort' % table_id, sort) table_opts['sort'] = sort # persist sort_col, sort_reverse = map(int, sort.split(',', 1)) rows = _sort_rows(rows, sort_col, sort_reverse) if actions_enabled: user.save_tableoptions() return rows, actions_visible, search_term
def _upload_csv_file(self) -> None: store.makedirs(self._upload_tmp_path) self._cleanup_old_files() upload_info = self._vs_upload().from_html_vars("_upload") self._vs_upload().validate_value(upload_info, "_upload") file_id = "%s-%d" % (config.user.id, int(time.time())) store.save_text_to_file(self._file_path(), upload_info["file"]) # make selections available to next page request.set_var("file_id", file_id) if upload_info["do_service_detection"]: request.set_var("do_service_detection", "1")
def _upload_csv_file(self) -> None: store.makedirs(self._upload_tmp_path) self._cleanup_old_files() upload_info = self._vs_upload().from_html_vars("_upload") self._vs_upload().validate_value(upload_info, "_upload") file_id = uuid.uuid4().hex store.save_text_to_file(self._file_path(file_id=file_id), upload_info["file"]) # make selections available to next page request.set_var("file_id", file_id) if upload_info["do_service_detection"]: request.set_var("do_service_detection", "1")
def setup_request_fixture(self, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(automation, "_get_login_secret", lambda **_kwargs: "secret") request.set_var("secret", "secret") request.set_var("command", "checkmk-automation") request.set_var("automation", "test") request.set_var("arguments", mk_repr(None).decode()) request.set_var("indata", mk_repr(None).decode()) request.set_var("stdin_data", mk_repr(None).decode()) request.set_var("timeout", mk_repr(None).decode())
def _set_query_vars(query_vars: QueryVars) -> None: for name, vals in query_vars.items(): request.set_var(name, vals[0])
def breadcrumb(self) -> Breadcrumb: # To be able to calculate the breadcrumb with ModeCheckPluginTopic as parent, we need to # ensure that the topic is available. with request.stashed_vars(): request.set_var("topic", self._manpage["header"]["catalog"]) return super().breadcrumb()