Skip to content

Commit 9bfac97

Browse files
jlevequeCarl Keene
authored andcommitted
Use 'importlib' module in lieu of deprecated 'imp' module (sonic-net#6832)
Migrate from using the `imp` module to using the `importlib` module. As of Python 3, the `imp` module has been deprecated in favor of the `importlib` module.
1 parent d967980 commit 9bfac97

4 files changed

Lines changed: 53 additions & 39 deletions

File tree

src/sonic-host-services/scripts/procdockerstatsd

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ class ProcDockerStats(daemon_base.DaemonBase):
7272
UNITS_MiB = 'MiB'
7373
UNITS_GiB = 'GiB'
7474

75-
res = re.match('(\d+\.?\d*)([a-zA-Z]+)', value)
75+
res = re.match(r'(\d+\.?\d*)([a-zA-Z]+)', value)
7676
value = float(res.groups()[0])
7777
units = res.groups()[1]
7878
if units.lower() == UNITS_KB.lower():
Lines changed: 30 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import imp
1+
import importlib
22
import sys
33
import os
44
import pytest
@@ -28,6 +28,15 @@
2828
scripts_path = os.path.join(modules_path, "scripts")
2929
sys.path.insert(0, modules_path)
3030

31+
# Load the file under test
32+
determine_reboot_cause_path = os.path.join(scripts_path, 'determine-reboot-cause')
33+
loader = importlib.machinery.SourceFileLoader('determine_reboot_cause', determine_reboot_cause_path)
34+
spec = importlib.util.spec_from_loader(loader.name, loader)
35+
determine_reboot_cause = importlib.util.module_from_spec(spec)
36+
loader.exec_module(determine_reboot_cause)
37+
sys.modules['determine_reboot_cause'] = determine_reboot_cause
38+
39+
3140
PROC_CMDLINE_CONTENTS = """\
3241
BOOT_IMAGE=/image-20191130.52/boot/vmlinuz-4.9.0-11-2-amd64 root=/dev/sda4 rw console=tty0 console=ttyS1,9600n8 quiet net.ifnames=0 biosdevname=0 loop=image-20191130.52/fs.squashfs loopfstype=squashfs apparmor=1 security=apparmor varlog_size=4096 usbcore.autosuspend=-1 module_blacklist=gpio_ich SONIC_BOOT_TYPE=warm"""
3342

@@ -37,9 +46,9 @@
3746
BOOT_IMAGE=/image-20191130.52/boot/vmlinuz-4.9.0-11-2-amd64 root=/dev/sda4 rw console=tty0 console=ttyS1,9600n8 quiet net.ifnames=0 biosdevname=0 loop=image-20191130.52/fs.squashfs loopfstype=squashfs apparmor=1 security=apparmor varlog_size=4096 usbcore.autosuspend=-1 module_blacklist=gpio_ich SONIC_BOOT_TYPE=warm"""
3847

3948
REBOOT_CAUSE_CONTENTS = """\
40-
User issued 'warm-reboot' command [User: admin, Time: Mon Nov 2 22:37:45 UTC 2020]"""
49+
User issued 'warm-reboot' command [User: admin, Time: Mon Nov 2 22:37:45 UTC 2020]"""
4150

42-
GET_SONIC_VERSION_INFO = {'commit_id': 'e59ec8291', 'build_date': 'Mon Nov 2 06:00:14 UTC 2020', 'build_number': 75, 'kernel_version': '4.9.0-11-2-amd64', 'debian_version': '9.13', 'built_by': 'sonicbld@jenkins-slave-phx-2', 'asic_type': 'mellanox', 'build_version': '20191130.52'}
51+
GET_SONIC_VERSION_INFO = {'commit_id': 'e59ec8291', 'build_date': 'Mon Nov 2 06:00:14 UTC 2020', 'build_number': 75, 'kernel_version': '4.9.0-11-2-amd64', 'debian_version': '9.13', 'built_by': 'sonicbld@jenkins-slave-phx-2', 'asic_type': 'mellanox', 'build_version': '20191130.52'}
4352

4453
REBOOT_CAUSE_WATCHDOG = "Watchdog"
4554
GEN_TIME_WATCHDOG = "2020_10_22_03_15_08"
@@ -55,63 +64,52 @@
5564
EXPECTED_WATCHDOG_REBOOT_CAUSE_DICT = {'comment': '', 'gen_time': '2020_10_22_03_15_08', 'cause': 'Watchdog', 'user': 'N/A', 'time': 'N/A'}
5665
EXPECTED_USER_REBOOT_CAUSE_DICT = {'comment': '', 'gen_time': '2020_10_22_03_14_07', 'cause': 'reboot', 'user': 'admin', 'time': 'Thu Oct 22 03:11:08 UTC 2020'}
5766

58-
imp.load_source('determine_reboot_cause', scripts_path + '/determine-reboot-cause')
59-
from determine_reboot_cause import *
6067

6168
class TestDetermineRebootCause(object):
62-
@classmethod
63-
def setup_class(cls):
64-
print("SETUP")
65-
6669
def test_parse_warmfast_reboot_from_proc_cmdline(self):
6770
with mock.patch("os.path.isfile") as mock_isfile:
6871
mock_isfile.return_value = True
69-
open_mocked = mock.mock_open(read_data=PROC_CMDLINE_CONTENTS)
70-
with mock.patch("{}.open".format(BUILTINS), open_mocked):
71-
result = parse_warmfast_reboot_from_proc_cmdline()
72+
open_mocked = mock.mock_open(read_data=PROC_CMDLINE_CONTENTS)
73+
with mock.patch("{}.open".format(BUILTINS), open_mocked):
74+
result = determine_reboot_cause.parse_warmfast_reboot_from_proc_cmdline()
7275
assert result == EXPECTED_PARSE_WARMFAST_REBOOT_FROM_PROC_CMDLINE
73-
open_mocked.assert_called_once_with("/proc/cmdline")
76+
open_mocked.assert_called_once_with("/proc/cmdline")
7477

7578
def test_find_software_reboot_cause_user(self):
76-
with mock.patch("os.path.isfile") as mock_isfile:
77-
mock_isfile.return_value = True
78-
open_mocked = mock.mock_open(read_data=REBOOT_CAUSE_CONTENTS)
79-
with mock.patch("{}.open".format(BUILTINS), open_mocked):
80-
result = find_software_reboot_cause_from_reboot_cause_file()
79+
with mock.patch("os.path.isfile") as mock_isfile:
80+
mock_isfile.return_value = True
81+
open_mocked = mock.mock_open(read_data=REBOOT_CAUSE_CONTENTS)
82+
with mock.patch("{}.open".format(BUILTINS), open_mocked):
83+
result = determine_reboot_cause.find_software_reboot_cause_from_reboot_cause_file()
8184
assert result == EXPECTED_FIND_SOFTWARE_REBOOT_CAUSE_USER
82-
open_mocked.assert_called_once_with("/host/reboot-cause/reboot-cause.txt")
85+
open_mocked.assert_called_once_with("/host/reboot-cause/reboot-cause.txt")
8386

8487
def test_find_software_reboot_cause_first_boot(self):
8588
with mock.patch("sonic_py_common.device_info.get_sonic_version_info", return_value=GET_SONIC_VERSION_INFO):
86-
result = find_first_boot_version()
89+
result = determine_reboot_cause.find_first_boot_version()
8790
assert result == EXPECTED_FIND_FIRSTBOOT_VERSION
8891

8992
def test_find_software_reboot_cause(self):
9093
with mock.patch("determine_reboot_cause.find_software_reboot_cause_from_reboot_cause_file", return_value="Unknown"):
91-
with mock.patch("os.path.isfile") as mock_isfile:
92-
mock_isfile.return_value = False
93-
result = find_software_reboot_cause()
94+
with mock.patch("os.path.isfile") as mock_isfile:
95+
mock_isfile.return_value = False
96+
result = determine_reboot_cause.find_software_reboot_cause()
9497
assert result == "Unknown"
9598

9699
def test_find_proc_cmdline_reboot_cause(self):
97100
with mock.patch("determine_reboot_cause.parse_warmfast_reboot_from_proc_cmdline", return_value="fast-reboot"):
98-
result = find_proc_cmdline_reboot_cause()
101+
result = determine_reboot_cause.find_proc_cmdline_reboot_cause()
99102
assert result == "fast-reboot"
100103

101104
def test_find_hardware_reboot_cause(self):
102105
with mock.patch("determine_reboot_cause.get_reboot_cause_from_platform", return_value=("Powerloss", None)):
103-
result = find_hardware_reboot_cause()
106+
result = determine_reboot_cause.find_hardware_reboot_cause()
104107
assert result == "Powerloss (None)"
105108

106109
def test_get_reboot_cause_dict_watchdog(self):
107-
reboot_cause_dict = get_reboot_cause_dict(REBOOT_CAUSE_WATCHDOG, "", GEN_TIME_WATCHDOG)
110+
reboot_cause_dict = determine_reboot_cause.get_reboot_cause_dict(REBOOT_CAUSE_WATCHDOG, "", GEN_TIME_WATCHDOG)
108111
assert reboot_cause_dict == EXPECTED_WATCHDOG_REBOOT_CAUSE_DICT
109112

110113
def test_get_reboot_cause_dict_user(self):
111-
reboot_cause_dict = get_reboot_cause_dict(REBOOT_CAUSE_USER, "", GEN_TIME_USER)
114+
reboot_cause_dict = determine_reboot_cause.get_reboot_cause_dict(REBOOT_CAUSE_USER, "", GEN_TIME_USER)
112115
assert reboot_cause_dict == EXPECTED_USER_REBOOT_CAUSE_DICT
113-
114-
@classmethod
115-
def teardown_class(cls):
116-
print("TEARDOWN")
117-

src/sonic-host-services/tests/procdockerstatsd_test.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import imp
1+
import importlib
22
import sys
33
import os
44
import pytest
@@ -14,8 +14,13 @@
1414
scripts_path = os.path.join(modules_path, "scripts")
1515
sys.path.insert(0, modules_path)
1616

17-
imp.load_source('procdockerstatsd', scripts_path + '/procdockerstatsd')
18-
from procdockerstatsd import *
17+
# Load the file under test
18+
procdockerstatsd_path = os.path.join(scripts_path, 'procdockerstatsd')
19+
loader = importlib.machinery.SourceFileLoader('procdockerstatsd', procdockerstatsd_path)
20+
spec = importlib.util.spec_from_loader(loader.name, loader)
21+
procdockerstatsd = importlib.util.module_from_spec(spec)
22+
loader.exec_module(procdockerstatsd)
23+
sys.modules['procdockerstatsd'] = procdockerstatsd
1924

2025
class TestProcDockerStatsDaemon(object):
2126
def test_convert_to_bytes(self):
@@ -35,7 +40,7 @@ def test_convert_to_bytes(self):
3540
('7.751GiB', 8322572878)
3641
]
3742

38-
pdstatsd = ProcDockerStats(SYSLOG_IDENTIFIER)
43+
pdstatsd = procdockerstatsd.ProcDockerStats(procdockerstatsd.SYSLOG_IDENTIFIER)
3944

4045
for test_input, expected_output in test_data:
4146
res = pdstatsd.convert_to_bytes(test_input)

src/sonic-py-common/sonic_py_common/daemon_base.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import imp
1+
import importlib
22
import signal
33
import sys
44

@@ -25,10 +25,21 @@ def db_connect(db_name, namespace=EMPTY_NAMESPACE):
2525
from swsscommon import swsscommon
2626
return swsscommon.DBConnector(db_name, REDIS_TIMEOUT_MSECS, True, namespace)
2727

28+
29+
def _load_module_from_file(module_name, file_path):
30+
loader = importlib.machinery.SourceFileLoader(module_name, file_path)
31+
spec = importlib.util.spec_from_loader(loader.name, loader)
32+
module = importlib.util.module_from_spec(spec)
33+
loader.exec_module(module)
34+
sys.modules[module_name] = module
35+
return module
36+
37+
2838
#
2939
# DaemonBase ===================================================================
3040
#
3141

42+
3243
class DaemonBase(Logger):
3344
def __init__(self, log_identifier):
3445
super(DaemonBase, self).__init__(
@@ -68,7 +79,7 @@ def load_platform_util(self, module_name, class_name):
6879

6980
try:
7081
module_file = "/".join([platform_path, "plugins", module_name + ".py"])
71-
module = imp.load_source(module_name, module_file)
82+
module = _load_module_from_file(module_name, module_file)
7283
except IOError as e:
7384
raise IOError("Failed to load platform module '%s': %s" % (module_name, str(e)))
7485

0 commit comments

Comments
 (0)