Skip to content

Commit eba8a55

Browse files
Improve performance of jinja2_convenience_function by not importing NAPALM when called (#466)
* Improve performance of jinja2_convenience_function by not importing NAPALM unnecessarily * Fix optional test as well
1 parent e835dc3 commit eba8a55

3 files changed

Lines changed: 10 additions & 13 deletions

File tree

netutils/lib_helpers.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,6 @@
55

66
from netutils.lib_mapper import NAPALM_LIB_MAPPER
77

8-
try:
9-
from napalm import get_network_driver
10-
from napalm.base.exceptions import ModuleImportError
11-
except ImportError:
12-
HAS_NAPALM = False
13-
else:
14-
HAS_NAPALM = True
15-
168

179
def get_napalm_getters() -> t.Dict[str, t.Dict[str, bool]]:
1810
"""Utility to return a dictionary of napalm getters based on install napalm version.
@@ -31,8 +23,13 @@ def get_napalm_getters() -> t.Dict[str, t.Dict[str, bool]]:
3123
>>> napalm_getters["eos"]["get_ipv6_neighbors_table"] # doctest: +SKIP
3224
>>> False # doctest: +SKIP
3325
"""
34-
if not HAS_NAPALM:
35-
raise ImportError("Napalm must be install for this function to operate.")
26+
try:
27+
# Import NAPALM here at call time, rather than at import time, as importing NAPALM is rather time consuming
28+
# pylint: disable=import-outside-toplevel
29+
from napalm import get_network_driver
30+
from napalm.base.exceptions import ModuleImportError
31+
except ImportError as err:
32+
raise ImportError("Napalm must be installed for this function to operate.") from err
3633

3734
napalm_dict: t.Dict[str, t.Dict[str, bool]] = {}
3835
oses = NAPALM_LIB_MAPPER.keys()

tests/unit/test_lib_helpers.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
from netutils.lib_helpers import get_napalm_getters
66

77

8-
@mock.patch("netutils.lib_helpers.HAS_NAPALM", False)
8+
@mock.patch.dict("sys.modules", {"napalm": None})
99
def test_get_napalm_getters_napalm_not_installed():
1010
with pytest.raises(ImportError) as exc:
1111
get_napalm_getters()
12-
assert "Napalm must be install for this function to operate." == str(exc.value)
12+
assert "Napalm must be installed for this function to operate." == str(exc.value)

tests/unit/test_lib_helpers_optionals.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
def test_get_napalm_getters_napalm_installed_default():
99
pytest.importorskip("napalm")
10-
with mock.patch("netutils.lib_helpers.get_network_driver"):
10+
with mock.patch("napalm.get_network_driver"):
1111
napalm_getters = get_napalm_getters()
1212
assert all(item in napalm_getters.keys() for item in ["asa", "eos", "fortios"])
1313

0 commit comments

Comments
 (0)