Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
so that later subsegment can be attached. After each test run
it cleans up context storage again.
"""
pre_run_modules = set(module for module in sys.modules.keys())
xray_recorder.configure(service='test', sampling=False, context=Context())
xray_recorder.clear_trace_entities()
xray_recorder.begin_segment('name')
yield
xray_recorder.end_segment()
xray_recorder.clear_trace_entities()
global_sdk_config.set_sdk_enabled(True)
# Reload wrapt.importer references to modules to start off clean
reload(wrapt)
reload(wrapt.importer)
# Reload patcher references to already patched modules
reload(patcher)
# Cleanup the already imported module references in the system
for module_name, module in sorted(sys.modules.items(), key=lambda m: len(m[0]), reverse=True):
if module_name not in pre_run_modules and inspect.ismodule(module):
reload(module)
for module_name in sorted(sys.modules.keys(), key=lambda m: len(m), reverse=True):
if module_name not in pre_run_modules:
del sys.modules[module_name]
for loader, submodule_name, is_module in pkgutil.iter_modules([module.replace('.', '/')]):
submodule = '.'.join([module, submodule_name])
if is_module:
_external_module_patch(submodule, ignore_module_patterns)
else:
if submodule in _PATCHED_MODULES:
log.debug('%s already patched', submodule)
continue
elif any(pattern.match(submodule) for pattern in ignore_module_patterns):
log.debug('%s ignored due to rules: %s', submodule, ignore_module_patterns)
continue
if submodule in sys.modules:
_on_import(sys.modules[submodule])
else:
wrapt.importer.when_imported(submodule)(_on_import)
_PATCHED_MODULES.add(submodule)
log.info('successfully patched module %s', submodule)
if module not in _PATCHED_MODULES:
_PATCHED_MODULES.add(module)
log.info('successfully patched module %s', module)
def _external_module_patch(module, ignore_module_patterns):
if module.startswith('.'):
raise Exception('relative packages not supported for patching: {}'.format(module))
if module in _PATCHED_MODULES:
log.debug('%s already patched', module)
elif any(pattern.match(module) for pattern in ignore_module_patterns):
log.debug('%s ignored due to rules: %s', module, ignore_module_patterns)
else:
if module in sys.modules:
_on_import(sys.modules[module])
else:
wrapt.importer.when_imported(module)(_on_import)
for loader, submodule_name, is_module in pkgutil.iter_modules([module.replace('.', '/')]):
submodule = '.'.join([module, submodule_name])
if is_module:
_external_module_patch(submodule, ignore_module_patterns)
else:
if submodule in _PATCHED_MODULES:
log.debug('%s already patched', submodule)
continue
elif any(pattern.match(submodule) for pattern in ignore_module_patterns):
log.debug('%s ignored due to rules: %s', submodule, ignore_module_patterns)
continue
if submodule in sys.modules:
_on_import(sys.modules[submodule])
else: