def test_validate_unknown_config_option(self): c = Configuration() with pytest.warns(RuntimeWarning) as record: c.configure(emperor=True) assert len(record) == 1 assert (str(record[0].message) == 'received unknown configuration option "emperor"')
def test_hostname(self): c = Configuration() self.assertEqual(c.hostname, socket.gethostname()) os.environ["DYNO"] = "YES" c = Configuration() self.assertEqual(c.hostname, None)
def test_ignore_classes(self): # Test ignoring a class works c = Configuration() c.ignore_classes.append("SystemError") self.assertTrue(c.should_ignore(SystemError("Example"))) c = Configuration() c.ignore_classes.append("SystemError") self.assertFalse(c.should_ignore(Exception("Example")))
def test_ignore_classes(): # Test ignoring a class works c = Configuration() c.ignore_classes.append("SystemError") assert(c.should_ignore(SystemError("Example")) == True) c = Configuration() c.ignore_classes.append("SystemError") assert(c.should_ignore(Exception("Example")) == False)
def test_code_turned_off(): config = Configuration() config.send_code = False notification = Notification(Exception("oops"), config, {}, traceback=fixtures.end_of_file[2]) payload = notification._payload() code = payload['events'][0]['exceptions'][0]['stacktrace'][0]['code'] assert(None == code)
def test_code_turned_off(self): config = Configuration() config.send_code = False notification = Notification(Exception("oops"), config, {}, traceback=fixtures.end_of_file[2]) payload = json.loads(notification._payload()) code = payload['events'][0]['exceptions'][0]['stacktrace'][0]['code'] self.assertEqual(code, None)
def test_code_turned_off(): config = Configuration() config.send_code = False notification = Notification(Exception("oops"), config, {}, traceback=fixtures.end_of_file[2]) payload = notification._payload() code = payload['events'][0]['exceptions'][0]['stacktrace'][0]['code'] assert (None == code)
def test_configured_app_type(self): """ It should include app type if specified """ config = Configuration() config.configure(app_type='rq') notification = Notification(Exception("oops"), config, {}) payload = json.loads(notification._payload()) app = payload['events'][0]['app'] assert app['type'] == 'rq'
def test_no_traceback_exclude_modules(self): from tests.fixtures import helpers config = Configuration() config.configure(project_root=os.path.join(os.getcwd(), 'tests')) notification = helpers.invoke_exception_on_other_file(config) payload = json.loads(notification._payload()) exception = payload['events'][0]['exceptions'][0] first_traceback = exception['stacktrace'][0] self.assertEqual(first_traceback['file'], 'fixtures/helpers.py')
def test_device_data(self): """ It should include device data """ config = Configuration() config.hostname = 'test_host_name' config.runtime_versions = {'python': '9.9.9'} notification = Notification(Exception("oops"), config, {}) payload = json.loads(notification._payload()) device = payload['events'][0]['device'] self.assertEqual('test_host_name', device['hostname']) self.assertEqual('9.9.9', device['runtimeVersions']['python'])
def __init__(self, configuration=None, install_sys_hook=True, **kwargs): self.configuration = configuration or Configuration() self.session_tracker = SessionTracker(self.configuration) self.configuration.configure(**kwargs) if install_sys_hook: self.install_sys_hook()
def test_get_endpoint(): # Test default endpoint with ssl c = Configuration() c.use_ssl = True assert(c.get_endpoint() == "https://notify.bugsnag.com") # Test default endpoint without ssl c = Configuration() c.use_ssl = False assert(c.get_endpoint() == "http://notify.bugsnag.com") # Test custom endpoint c = Configuration() c.use_ssl = False c.endpoint = "localhost:1234" assert(c.get_endpoint() == "http://localhost:1234")
def test_code(self): """ It should include code """ config = Configuration() line = inspect.currentframe().f_lineno + 1 notification = Notification(Exception("oops"), config, {}) payload = json.loads(notification._payload()) code = payload['events'][0]['exceptions'][0]['stacktrace'][0]['code'] lvl = " " self.assertEqual(code[str(line - 3)], lvl + "\"\"\"") self.assertEqual(code[str(line - 2)], lvl + "config = Configuration()") self.assertEqual(code[str(line - 1)], lvl + "line = inspect.currentframe().f_lineno + 1") self.assertEqual( code[str(line)], lvl + "notification = Notification(Exception(\"oops\"), config, {})" ) self.assertEqual(code[str(line + 1)], "") self.assertEqual(code[str(line + 2)], lvl + "payload = json.loads(notification._payload())") self.assertEqual(code[str(line + 3)], "")
def __init__(self, configuration: Optional[Configuration] = None, install_sys_hook=True, **kwargs): self.configuration = configuration or Configuration() # type: Configuration # noqa: E501 self.session_tracker = SessionTracker(self.configuration) self.configuration.configure(**kwargs) if install_sys_hook: self.install_sys_hook()
def test_default_app_type(self): """ app_type is None by default """ config = Configuration() notification = Notification(Exception("oops"), config, {}) payload = json.loads(notification._payload()) app = payload['events'][0]['app'] assert app['type'] is None
def test_no_traceback_exclude_modules(self): from tests.fixtures import helpers config = Configuration() notification = helpers.invoke_exception_on_other_file(config) payload = json.loads(notification._payload()) first_traceback = payload['events'][0]['exceptions'][0]['stacktrace'][ 0] self.assertEqual(first_traceback['file'], 'fixtures/helpers.py')
def test_validate_delivery(self): c = Configuration() assert c.delivery is not None class BadDelivery(object): def deliv(self, *args, **kwargs): pass class GoodDelivery(object): def deliver(self, *args, **kwargs): pass with pytest.warns(RuntimeWarning) as record: c.configure(delivery=BadDelivery()) assert len(record) == 1 assert (str(record[0].message) == ( 'delivery should implement Delivery interface, ' + 'got BadDelivery. This will be an error in a future ' + 'release.')) good = GoodDelivery() c.configure(delivery=good) assert len(record) == 1 assert c.delivery == good
def test_validate_api_key(self): c = Configuration() with pytest.raises(TypeError) as e: c.configure(api_key=[]) assert str(e) == 'api_key should be str, got list.' c.configure(api_key='ffff') assert c.api_key == 'ffff'
def test_traceback_exclude_modules(self): # Make sure samples.py is compiling to pyc import py_compile py_compile.compile('./fixtures/helpers.py') from tests.fixtures import helpers reload(helpers) # .py variation might be loaded from previous test. if sys.version_info < (3, 0): # Python 2.6 & 2.7 returns the cached file on __file__, # and hence we verify it returns .pyc for these versions # and the code at _generate_stacktrace() handles that. self.assertTrue(helpers.__file__.endswith('.pyc')) config = Configuration() config.traceback_exclude_modules = [helpers] notification = helpers.invoke_exception_on_other_file(config) payload = json.loads(notification._payload()) exception = payload['events'][0]['exceptions'][0] first_traceback = exception['stacktrace'][0] self.assertEqual(first_traceback['file'], 'test_notification.py')
def test_sanitize(self): """ It should sanitize request data """ config = Configuration() notification = Notification(Exception("oops"), config, {}, request={"params": {"password": "******"}}) notification.add_tab("request", {"arguments": {"password": "******"}}) payload = json.loads(notification._payload()) request = payload['events'][0]['metaData']['request'] self.assertEqual(request['arguments']['password'], '[FILTERED]') self.assertEqual(request['params']['password'], '[FILTERED]')
class TestSessionMiddleware(unittest.TestCase): def setUp(self): self.config = Configuration() self.config.configure(api_key='fff', auto_capture_sessions=False) self.sessiontracker = SessionTracker(self.config) self.sessiontracker.auto_sessions = True # Stub session delivery queue def tearDown(self): pass def test_increment_counts(self): """ Every event should keep a list of prior events which occurred in the session """ def next_callable(event): pass middleware = SessionMiddleware(next_callable) self.sessiontracker.start_session() event = Notification(Exception('shucks'), self.config, None) middleware(event) assert event.session['events']['unhandled'] == 0 assert event.session['events']['handled'] == 1 event2 = Notification(Exception('oh no'), self.config, None) middleware(event2) assert event2.session['events']['unhandled'] == 0 assert event2.session['events']['handled'] == 2 # Session counts should not change for events already handled assert event.session['events']['unhandled'] == 0 assert event.session['events']['handled'] == 1
def test_validate_session_endpoint(self): c = Configuration() with pytest.raises(TypeError) as e: c.configure(session_endpoint=False) assert str(e) == 'session_endpoint should be str, got bool.' assert c.session_endpoint == 'https://sessions.bugsnag.com' c.configure(session_endpoint='https://sessions.example.com') assert c.session_endpoint == 'https://sessions.example.com'
def test_validate_endpoint(self): c = Configuration() with pytest.raises(TypeError) as e: c.configure(endpoint=56) assert str(e) == 'endpoint should be str, got int. ' assert c.endpoint == 'https://notify.bugsnag.com' c.configure(endpoint='https://notify.example.com') assert c.endpoint == 'https://notify.example.com'
def test_path_supports_ascii_characters(self): import bugsnag.wsgi.middleware environ = self.environ.copy() environ['PATH_INFO'] = '/hello/world' bugsnag.configure_request(wsgi_environ=environ) config = Configuration() event = Event(Exception("oops"), config, RequestConfiguration.get_instance()) bugsnag.wsgi.middleware.add_wsgi_request_data_to_notification(event) self.assertEqual('http://localhost/hello/world', event.metadata['request']['url'])
def test_path_supports_non_ascii_characters(self): import bugsnag.wsgi.middleware environ = self.environ.copy() environ['PATH_INFO'] = '/ôßłガ' config = Configuration() event = Event(Exception("oops"), config, RequestConfiguration.get_instance()) bugsnag.configure_request(wsgi_environ=environ) bugsnag.wsgi.middleware.add_wsgi_request_data_to_notification(event) # You can validate this by using "encodeURIComponent" in a browser. self.assertEqual('http://localhost/%C3%B4%C3%9F%C5%82%E3%82%AC', event.metadata['request']['url'])
def test_code_at_start_of_file(self): config = Configuration() notification = Notification(fixtures.start_of_file[1], config, {}, traceback=fixtures.start_of_file[2]) payload = json.loads(notification._payload()) code = payload['events'][0]['exceptions'][0]['stacktrace'][0]['code'] self.assertEqual( {'1': '# flake8: noqa', '2': 'try:', '3': ' import sys; raise Exception("start")', '4': 'except Exception: start_of_file = sys.exc_info()', '5': '# 4', '6': '# 5', '7': '# 6'}, code)
def test_code_at_end_of_file(self): config = Configuration() notification = Notification(fixtures.end_of_file[1], config, {}, traceback=fixtures.end_of_file[2]) payload = json.loads(notification._payload()) code = payload['events'][0]['exceptions'][0]['stacktrace'][0]['code'] self.assertEqual( {'6': '# 5', '7': '# 6', '8': '# 7', '9': '# 8', '10': 'try:', '11': ' import sys; raise Exception("end")', '12': 'except Exception: end_of_file = sys.exc_info()'}, code)
def test_path_supports_emoji(self): import bugsnag.wsgi.middleware environ = self.environ.copy() environ['PATH_INFO'] = '/😇' config = Configuration() notification = Notification(Exception("oops"), config, RequestConfiguration.get_instance()) bugsnag.configure_request(wsgi_environ=environ) bugsnag.wsgi.middleware.add_wsgi_request_data_to_notification( notification) # You can validate this by using "encodeURIComponent" in a browser. self.assertEqual('http://localhost/%F0%9F%98%87', notification.meta_data['request']['url'])
def test_validate_lib_root(self): c = Configuration() with pytest.warns(RuntimeWarning) as record: c.configure(lib_root=False) assert len(record) == 1 assert (str( record[0].message) == 'lib_root should be str, got bool') c.configure(lib_root='/path/to/python/lib') assert len(record) == 1 assert c.lib_root == '/path/to/python/lib'
def test_validate_auto_capture_sessions(self): c = Configuration() assert c.auto_capture_sessions is True with pytest.warns(RuntimeWarning) as record: c.configure(auto_capture_sessions='true') assert len(record) == 1 assert (str(record[0].message) == 'auto_capture_sessions should be bool, got str') c.configure(auto_capture_sessions=False) assert len(record) == 1 assert c.auto_capture_sessions is False
def test_validate_api_key(self): c = Configuration() with pytest.warns(RuntimeWarning) as record: c.configure(api_key=[]) assert len(record) == 1 assert (str( record[0].message) == 'api_key should be str, got list. ' + 'This will be an error in a future release.') c.configure(api_key='ffff') assert len(record) == 1 assert c.api_key == 'ffff'
def test_sanitize(): """ It should sanitize request data """ config = Configuration() notification = Notification(Exception("oops"), config, {}, request={"params": { "password": "******" }}) notification.add_tab("request", {"arguments": {"password": "******"}}) payload = notification._payload() assert (payload['events'][0]['metaData']['request']['arguments'] ['password'] == '[FILTERED]') assert (payload['events'][0]['metaData']['request']['params']['password'] == '[FILTERED]')
def test_wrongly_encoded_url_should_not_raise(self): import bugsnag.wsgi.middleware environ = self.environ.copy() environ['PATH_INFO'] = '/%83' bugsnag.configure_request(wsgi_environ=environ) config = Configuration() event = Event(Exception("oops"), config, RequestConfiguration.get_instance()) bugsnag.wsgi.middleware.add_wsgi_request_data_to_notification(event) # We have to use "urllib.parse.quote" here because the exact output # differs on different Python versions because of how they handle # invalid encoding sequences self.assertEqual('http://localhost/%s' % quote('%83'), event.metadata['request']['url'])
def test_custom_get_endpoint_default_ssl(self): c = Configuration() c.endpoint = "localhost:1234" self.assertEqual(c.get_endpoint(), "https://localhost:1234")
def test_should_notify(): # Test custom release_stage c = Configuration() c.release_stage = "anything" assert(c.should_notify() == True) # Test release_stage in notify_release_stages c = Configuration() c.notify_release_stages = ["production"] c.release_stage = "development" assert(c.should_notify() == False) # Test release_stage in notify_release_stages c = Configuration() c.notify_release_stages = ["custom"] c.release_stage = "custom" assert(c.should_notify() == True)
def test_full_custom_get_endpoint_no_use_ssl(self): c = Configuration() c.use_ssl = False c.endpoint = "https://localhost:1234" self.assertEqual(c.get_endpoint(), "http://localhost:1234")
def test_should_notify(self): # Test custom release_stage c = Configuration() c.release_stage = "anything" self.assertTrue(c.should_notify()) # Test release_stage in notify_release_stages c = Configuration() c.notify_release_stages = ["production"] c.release_stage = "development" self.assertFalse(c.should_notify()) # Test release_stage in notify_release_stages c = Configuration() c.notify_release_stages = ["custom"] c.release_stage = "custom" self.assertTrue(c.should_notify())
def test_get_endpoint_use_ssl(self): c = Configuration() c.use_ssl = True self.assertEqual(c.get_endpoint(), "https://notify.bugsnag.com")