|
| 1 | +from pytest import raises |
| 2 | + |
| 3 | + |
| 4 | +def test_import_hook_finder(): |
| 5 | + """ |
| 6 | + This asserts the behavior of ImportHookFinder.find_module. It behaves |
| 7 | + differently depending on whether or not the module it is looking for |
| 8 | + exists, has been registered with an import hook, and across different |
| 9 | + python versions. |
| 10 | + """ |
| 11 | + from newrelic.api.import_hook import ImportHookFinder, register_import_hook |
| 12 | + import sys |
| 13 | + |
| 14 | + PY2 = sys.version_info[0] == 2 |
| 15 | + |
| 16 | + finder = ImportHookFinder() |
| 17 | + |
| 18 | + # a dummy hook just to be able to register hooks for modules |
| 19 | + def hook(*args, **kwargs): |
| 20 | + pass |
| 21 | + |
| 22 | + # Finding a module that does not exist and is not registered returns None. |
| 23 | + module = finder.find_module('some_module_that_does_not_exist') |
| 24 | + assert module is None |
| 25 | + |
| 26 | + # Finding a module that does not exist and is registered behaves |
| 27 | + # differently on python 2 vs python 3. |
| 28 | + register_import_hook('some_module_that_does_not_exist', hook) |
| 29 | + if PY2: |
| 30 | + with raises(ImportError): |
| 31 | + module = finder.find_module('some_module_that_does_not_exist') |
| 32 | + else: |
| 33 | + module = finder.find_module('some_module_that_does_not_exist') |
| 34 | + assert module is None |
| 35 | + |
| 36 | + # Finding a module that exists, but is not registered returns None. |
| 37 | + module = finder.find_module('newrelic') |
| 38 | + assert module is None |
| 39 | + |
| 40 | + # Finding a module that exists, and is registered, finds that module. |
| 41 | + register_import_hook('newrelic', hook) |
| 42 | + module = finder.find_module('newrelic') |
| 43 | + assert module is not None |
0 commit comments