def test_attr_obj(): """ Test `prewikka.utils.misc.AttrObj()`. """ attr1 = misc.AttrObj() attr2 = misc.AttrObj(foo=12, bar=list()) assert attr1 assert attr2 assert json.dumps(attr1) == '{}' assert json.dumps(attr2) == '{"foo": 12, "bar": []}' assert not attr1 == attr2
def set_properties(self, user, values): rows = [(view or "", user.id, key, json.dumps(value)) for view, key, value in values] self.upsert("Prewikka_User_Configuration", ("view", "userid", "name", "value"), rows, pkey=("view", "userid", "name"))
def escapejs(value): value = json.dumps(value, cls=json.PrewikkaHTMLJSONEncoder) if "__prewikka_class__" in value: value = "_prewikka_revive(%s)" % value return Markup(value)
def upsert_filter(self, user, filter_): values = (user.id, filter_.id_, filter_.name, filter_.category, filter_.description, json.dumps(filter_.criteria)) self.upsert( "Prewikka_Filter", ("userid", "id", "name", "category", "description", "value"), [values], pkey=("id", ))
def _encode_response(self, res): if res is None: res = "" if not isinstance(res, compat.STRING_TYPES): self.headers["Content-Type"] = "application/json" res = json.dumps(res) return res.encode(env.config.general.get("encoding", "utf8"), "xmlcharrefreplace")
def test_dumps(): """ Test prewikka.utils.json.dump(). """ assert json.dumps(['foo', {'bar': ['baz', None, 1.0, 2]}]) == '["foo", {"bar": ["baz", null, 1.0, 2]}]' assert json.dumps('"foo\x08ar') == '"\\"foo\\bar"' # Prewikka objects criterion = Criterion('alert.messageid', '=', 'fakemessageid') criterion_dumps = json.dumps(criterion) assert '{"__prewikka_class__": ["Criterion"' in criterion_dumps assert '"operator": "="' in criterion_dumps assert '"right": "fakemessageid"' in criterion_dumps assert '"left": "alert.messageid"' in criterion_dumps # datetime object assert json.dumps(datetime(year=2012, month=10, day=12, hour=0, minute=0, second=0)) == \ '"2012-10-12 00:00:00"' # object not JSON serializable fake_obj = FakeClass() with pytest.raises(TypeError): json.dumps(fake_obj)
def content(self): if self.data is None: if not self.ext_content: return None self.data = {} if isinstance(self.data, compat.STRING_TYPES): return self.data self.headers["Content-Type"] = "application/json" if isinstance(self.data, dict): self.data["_extensions"] = self.ext_content return json.dumps(self.data)
def get_html_select(selected_paths=None, default_paths=None, all_paths=True, max_paths=0): if default_paths is None: default_paths = env.dataprovider.get_common_paths("alert", index=True) if selected_paths is None: selected_paths = [] _html_default_value = _gen_option_list(default_paths, selected_paths) if all_paths: _html_all_value = _gen_option_list( ((i, i) for i in env.dataprovider.get_paths("alert") if i not in zip(default_paths)[1]), selected_paths) all_paths = resource.HTMLSource('<optgroup label="%s">%s</optgroup>' ) % (_("All paths"), _html_all_value) html = resource.HTMLSource(""" <link rel="stylesheet" type="text/css" href="prewikka/css/chosen.min.css"> <link rel="stylesheet" type="text/css" href="prewikka/css/bootstrap-chosen.css"> <select class="data-paths chosen-sortable form-control" %s name="selected_path" data-placeholder="%s"> <optgroup label="%s"> %s </optgroup> %s </select> <script type="text/javascript"> $LAB.script("prewikka/js/chosen.jquery.min.js").wait() .script("prewikka/js/jquery-chosen-sortable.js").wait(function() { $(".data-paths").chosen({ max_selected_options: %d, width: "100%%", search_contains: true }).chosenSortable(); $(".data-paths").chosenSetOrder(%s); }); </script> """) % (resource.HTMLSource('multiple') if max_paths != 1 else "", _("Select paths..."), _("Default paths"), _html_default_value, all_paths or "", max_paths, Markup(json.dumps(selected_paths))) return html
def setMessage(self, message, ident): self["selection"] = json.dumps(Criterion("heartbeat.messageid", "=", ident)) self["summary"] = url_for("HeartbeatSummary", messageid=ident) if ident else None self["agent"] = self.createInlineFilteredField("heartbeat.analyzer(-1).name", message["heartbeat.analyzer(-1).name"]) self["model"] = self.createInlineFilteredField("heartbeat.analyzer(-1).model", message["heartbeat.analyzer(-1).model"]) self["node.name"] = self.createInlineFilteredField("heartbeat.analyzer(-1).node.name", message["heartbeat.analyzer(-1).node.name"]) self["node.address(*).address"] = [] for address in message["heartbeat.analyzer(-1).node.address"]: hfield = self.createHostField("heartbeat.analyzer(-1).node.address.address", address["address"], address["category"]) self["node.address(*).address"].append(hfield) self["time"] = self.createTimeField(message["heartbeat.create_time"])
def test_html_node(): """ Test `prewikka.resource.HTMLNode` class. """ node = HTMLNode('a') assert node.to_string() == str(node) assert json.dumps(node) node2 = HTMLNode('a', **{ '_icon': 'gears', 'class': 'foobar', 'test': 'true' }) assert str(node2) assert not node == node2 assert node < node2
def generate_html(self, kwargs, data, options, chart_type, mapping=None, multiple=False): """ Generate HTML used in all ChartJS charts Keyword arguments: kwargs -- kwargs options -- Specific options for the chart element_type -- Type of ChartJS element (Point, Segment, ...) mapping -- Array use for onclick event (default None) """ html = """<div id="chartjs-%(cssid)s"><canvas id="canvas-%(cssid)s"></canvas></div>""" % { "cssid": kwargs["cssid"] } script = """ $LAB.script("%(chartjs_js)s").wait(function() { var size = prewikka_getRenderSize("#%(cssid)s", %(kwargs)s); var ctx = $("#canvas-%(cssid)s") var dom = $("#chartjs-%(cssid)s"); Chart.defaults.global.maintainAspectRatio = false; dom.css("width", size[0]); dom.css("height", size[1]); $("#%(cssid)s").attr('resizeable', true); var myChart = new Chart(ctx, {type: '%(chart_type)s', data: %(data)s, options: %(options)s}); $("#%(cssid)s").on('resize', function() { myChart.resize(); }); var mapping = %(mapping)s; if ( ! mapping ) return; $("#canvas-%(cssid)s").click(function(evt) { var activePoint = myChart.getElementAtEvent(evt)[0]; var value = %(multiple)s ? mapping[activePoint._view.datasetLabel][activePoint._view.label] : mapping[activePoint._view.label]; if ( activePoint ) prewikka_ajax({url: value}); }); });""" % { "cssid": kwargs["cssid"], "chartjs_js": self._chartjs_filename, "chart_type": chart_type, "kwargs": json.dumps(kwargs), "data": json.dumps(data), "options": json.dumps(options), "mapping": json.dumps(mapping), "multiple": json.dumps(multiple) } return {"html": html, "script": script}
def sync_properties(self): if self._orig_configuration is not None and self._orig_configuration != self.configuration: self._orig_configuration = copy.deepcopy(self.configuration) env.db.upsert("Prewikka_User_Configuration", ["userid", "config"], [[self.id, json.dumps(self.configuration)]], pkey=("userid",)) if env.request.user == self: env.request.user = self
def to_db(self): return json.dumps({ k: v for k, v in self.items() if k not in self._ignored and v is not None })
def upsert_filter(self, user, filter): values = (user.id, filter.name, filter.description, json.dumps(filter.criteria)) self.upsert("Prewikka_Filter", ("userid", "name", "description", "value"), [values], pkey=("userid", "name"), returning=["id"])