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