Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_flask_intergration_includes_middleware_severity(self):
app = Flask("bugsnag")
@app.route("/test")
def test():
raise SentinelError("oops")
handle_exceptions(app)
app.test_client().get("/test")
self.assertEqual(1, len(self.server.received))
payload = self.server.received[0]['json_body']
event = payload['events'][0]
self.assertTrue(event['unhandled'])
self.assertEqual(event['severityReason'], {
"type": "unhandledExceptionMiddleware",
"attributes": {
"framework": "Flask"
}
def test_appends_framework_version(self):
app = Flask("bugsnag")
@app.route("/hello")
def hello():
raise SentinelError("oops")
handle_exceptions(app)
app.test_client().get('/hello')
self.assertEqual(len(self.server.received), 1)
payload = self.server.received[0]['json_body']
device_data = payload['events'][0]['device']
self.assertEquals(len(device_data['runtimeVersions']), 2)
self.assertTrue(re.match(r'\d+\.\d+\.\d+',
device_data['runtimeVersions']['python']))
self.assertTrue(re.match(r'\d+\.\d+\.\d+',
device_data['runtimeVersions']['flask']))
def test_bugsnag_notify_with_custom_context(self):
app = Flask("bugsnag")
@app.route("/hello")
def hello():
bugsnag.notify(SentinelError("oops"),
context="custom_context_notification_testing")
return "OK"
handle_exceptions(app)
app.test_client().get('/hello')
self.assertEqual(1, len(self.server.received))
payload = self.server.received[0]['json_body']
self.assertEqual(payload['events'][0]['context'],
'custom_context_notification_testing')
log.warning('Unable to run "git describe" to get git revision: %s', ex)
app.config['GIT_REVISION'] = 'unknown'
log.info('Git revision %r', app.config['GIT_REVISION'])
# Configure Bugsnag
if not app.config.get('TESTING') and app.config.get('BUGSNAG_API_KEY'):
import bugsnag
import bugsnag.flask
import bugsnag.handlers
bugsnag.configure(
api_key=app.config['BUGSNAG_API_KEY'],
project_root="/data/git/pillar/pillar",
revision=app.config['GIT_REVISION'],
)
bugsnag.flask.handle_exceptions(app)
bs_handler = bugsnag.handlers.BugsnagHandler()
bs_handler.setLevel(logging.ERROR)
log.addHandler(bs_handler)
else:
log.info('Bugsnag NOT configured.')
# Google Cloud project
try:
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = \
app.config['GCLOUD_APP_CREDENTIALS']
except KeyError:
raise SystemExit('GCLOUD_APP_CREDENTIALS configuration is missing')
# Storage backend (GCS)
try:
registry.register('https?://instagram.com/p/*',
Provider('http://api.instagram.com/oembed'))
if app.config.get('CACHE_REDIS_HOST') and app.config['CACHE_TYPE'] == 'redis':
redis_client = redis.StrictRedis(
host=app.config['CACHE_REDIS_HOST'],
port=app.config['CACHE_REDIS_PORT'])
else:
redis_client = None
if app.config.get('BUGSNAG_KEY'):
bugsnag.configure(
api_key = app.config['BUGSNAG_KEY'],
project_root = app.config['BUGSNAG_APP_PATH']
)
handle_exceptions(app)
# Config at https://console.developers.google.com/
if app.config.get('SOCIAL_GOOGLE'):
google = oauth.remote_app(
'google',
consumer_key=app.config.get('SOCIAL_GOOGLE')['consumer_key'],
consumer_secret=app.config.get('SOCIAL_GOOGLE')['consumer_secret'],
request_token_params={
'scope': 'https://www.googleapis.com/auth/userinfo.email'
},
base_url='https://www.googleapis.com/oauth2/v1/',
request_token_url=None,
access_token_method='POST',
access_token_url='https://accounts.google.com/o/oauth2/token',
authorize_url='https://accounts.google.com/o/oauth2/auth',
)
@server.template_filter('pluralize')
def pluralize(number, name, plural="s"):
if number == 1:
return f"{number} {name}"
else:
return f"{number} {name}{plural}"
# Setup Bugsnag if info is provided
if config.auth['bugsnag'].get('backend', ''):
bugsnag.configure(
api_key=config.auth['bugsnag'].get('backend', ''),
project_root=getcwd(),
auto_capture_sessions=True
)
handle_exceptions(server)
# If profiling is enabled setup the middlware
if server.debug and config.profile:
server.config['PROFILE'] = True
server.config['SQLALCHEMY_ECHO'] = True
server.wsgi_app = ProfilerMiddleware(server.wsgi_app, restrictions=[30], profile_dir='profiles')
# Get the first set of JWT keys
update.jwt_update.delay().wait()
# Do search indexing
search.initialize_indices.delay().wait()
# Defines which release stages bugsnag should report. e.g. ignore staging errors.
notify_release_stages = [ 'development', 'production'],
# Any param key that contains one of these strings will be filtered out of all error reports.
params_filters = ["credit_card_number", "password", "ssn"],
# We mark stacktrace lines as inProject if they come from files inside root:
# project_root = "/path/to/your/app",
# Useful if you are wrapping bugsnag.notify() in with your own library, to ensure errors group properly.
# traceback_exclude_module = [myapp.custom_logging],
)
# Attach Bugsnag to flask's exception handler
handle_exceptions(app)
# You can define a callback function which, when attached to to your Bugsnag client, will run right before each and every report is sent to the api. Here you can evaluate and modify the report data.
def callback(notification):
"""This callback will evaluate and modify every exception report, handled and unhandled, that occurs within the app, right before it is sent to Bugsnag.
"""
# adding user info and metadata to every report:
notification.user = {
# in your app, you can pull these details from session.
'name': 'Alan Turing',
'email': 'turing@code.net',
'id': '1234567890'
}
notification.add_tab(
'company', {
'name': 'Stark Industries'
mail_handler.setLevel(logging.ERROR)
app.logger.addHandler(mail_handler)
# Configure bugsnag
info = cfg.bugsnag
if info:
if not bugsnag:
raise _bugsnag_import_error
root_path = os.path.abspath(os.path.join(os.path.dirname(__file__),
'..'))
bugsnag.configure(api_key=info,
project_root=root_path,
release_stage=cfg.flavor,
notify_release_stages=[cfg.flavor],
app_version=VERSION
)
bugsnag.flask.handle_exceptions(app)
def boot(application, api_key, flavor, version):
# Configure bugsnag
if api_key:
try:
import bugsnag
import bugsnag.flask
root_path = os.path.abspath(
os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
bugsnag.configure(api_key=api_key,
project_root=root_path,
release_stage=flavor,
notify_release_stages=[flavor],
app_version=version
)
bugsnag.flask.handle_exceptions(application)
except Exception as e:
raise Exception('Failed to init bugsnag agent %s' % e)