def json_as_html(self): """ Print out self.json in a nice way. """ # To avoid circular import from cspreports import utils formatted_json = utils.format_report(self.json) return mark_safe(u"<pre>\n%s</pre>" % escape(formatted_json))
def test_format_report_handles_invalid_json(self): """ Test that `format_report` doesn't trip up on invalid JSON. Note: this is about not getting a ValueError, rather than any kind of security thing. """ invalid_json = '{"key": undefined_variable, nonsense here}' try: formatted = utils.format_report(invalid_json) except ValueError as e: self.fail("format_report did not handle invalid JSON: %s" % e) # we expect our invalid JSON to remain in the output, as is self.assertTrue(invalid_json in formatted)
def test_log_report(self): """ Test that the `log_report` handler correctly logs at the right level. """ request = HttpRequest() report = '{"document-uri": "http://example.com/"}' formatted_report = utils.format_report(report) request._body = report with mock.patch("cspreports.utils.logger.warning") as warning_mock: utils.log_report(request) self.assertTrue(warning_mock.called) log_message = warning_mock.call_args[0][0] % warning_mock.call_args[0][1:] self.assertTrue(formatted_report in log_message)
def test_email_admins(self): """ Test that the `email_admins` handler correctly sends an email. """ request = HttpRequest() report = '{"document-uri": "http://example.com/"}' formatted_report = utils.format_report(report) request._body = report # Note that we are mocking the *Django* mail_admins function here. with patch("cspreports.utils.mail_admins") as mock_mail_admins: utils.email_admins(request) self.assertTrue(mock_mail_admins.called) message = mock_mail_admins.call_args[0][1] self.assertTrue(formatted_report in message)
def test_log_report(self): """ Test that the `log_report` handler correctly logs at the right level. """ request = HttpRequest() report = '{"document-uri": "http://example.com/"}' formatted_report = utils.format_report(report) request._body = report with patch("cspreports.utils.logger.warning") as warning_mock: utils.log_report(request) self.assertTrue(warning_mock.called) log_message = warning_mock.call_args[0][ 0] % warning_mock.call_args[0][1:] self.assertTrue(formatted_report in log_message)
def test_email_admins(self): """ Test that the `email_admins` handler correctly sends an email. """ request = HttpRequest() report = '{"document-uri": "http://example.com/"}' formatted_report = utils.format_report(report) request._body = report # Note that we are mocking the *Django* mail_admins function here. with mock.patch("cspreports.utils.mail_admins") as mock_mail_admins: utils.email_admins(request) self.assertTrue(mock_mail_admins.called) message = mock_mail_admins.call_args[0][1] self.assertTrue(formatted_report in message)
def json_as_html(self): """ Print out self.json in a nice way. """ formatted_json = utils.format_report(self.json) return mark_safe(u"<pre>\n%s</pre>" % escape(formatted_json))