Skip to content

Commit 8294302

Browse files
committed
Use importlib.resources instead of deprecated pkg_resources
1 parent ced67d2 commit 8294302

File tree

4 files changed

+36
-23
lines changed

4 files changed

+36
-23
lines changed

mqttwarn/core.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
# -*- coding: utf-8 -*-
22
# (c) 2014-2023 The mqttwarn developers
3+
try:
4+
from importlib.resources import files as resource_files # type: ignore[attr-defined]
5+
except ImportError:
6+
from importlib_resources import files as resource_files # type: ignore[no-redef]
7+
38
import logging
49
import os
510
import socket
@@ -14,7 +19,6 @@
1419
import paho.mqtt.client as paho
1520
from paho.mqtt.client import Client as MqttClient
1621
from paho.mqtt.client import MQTTMessage
17-
from pkg_resources import resource_filename
1822

1923
import mqttwarn.configuration
2024
from mqttwarn.context import FunctionInvoker, RuntimeContext
@@ -594,7 +598,9 @@ def load_services(services):
594598
if module == "http":
595599
module = "http_urllib"
596600
logger.debug('Trying to load built-in service "{}" from "{}"'.format(service, module))
597-
modulefile_candidates = [resource_filename("mqttwarn.services", module + ".py")]
601+
service_filename = module + ".py"
602+
service_filepath = resource_files("mqttwarn.services") / service_filename
603+
modulefile_candidates = [service_filepath]
598604

599605
success = False
600606
for modulefile in modulefile_candidates:
@@ -610,9 +616,9 @@ def load_services(services):
610616
logger.exception(f'Loading service "{service}" from file "{modulefile}" failed')
611617

612618
if not success:
613-
logger.critical('Unable to load service "{}"'.format(service))
614-
# TODO: Review this.
615-
sys.exit(1)
619+
msg = "Failed loading service: {}".format(service)
620+
logger.critical(msg)
621+
raise ImportError(msg)
616622

617623

618624
def connect():

mqttwarn/util.py

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
# (c) 2014-2023 The mqttwarn developers
22
import functools
33
import importlib.machinery
4+
5+
try:
6+
from importlib.resources import files as resource_files # type: ignore[attr-defined]
7+
except ImportError:
8+
from importlib_resources import files as resource_files # type: ignore[no-redef]
9+
410
import importlib.util
511
import json
612
import logging
@@ -12,7 +18,6 @@
1218
from pathlib import Path
1319

1420
import funcy
15-
import pkg_resources
1621
from six import string_types
1722

1823
if t.TYPE_CHECKING:
@@ -128,19 +133,20 @@ def sanitize_function_name(name: str) -> str:
128133
raise ValueError(f"Invalid function name: {name}")
129134

130135

131-
def load_module_from_file(path: str) -> types.ModuleType:
136+
def load_module_from_file(path: t.Union[str, Path]) -> types.ModuleType:
132137
"""
133138
http://code.davidjanes.com/blog/2008/11/27/how-to-dynamically-load-python-code/
134139
135140
:param path:
136141
:return:
137142
"""
138-
name = Path(path).stem
143+
path = Path(path)
144+
name = path.stem
139145
loader: "FileLoader"
140-
if path.endswith(".py"):
141-
loader = importlib.machinery.SourceFileLoader(fullname=name, path=path)
142-
elif path.endswith(".pyc"):
143-
loader = importlib.machinery.SourcelessFileLoader(fullname=name, path=path)
146+
if path.suffix == ".py":
147+
loader = importlib.machinery.SourceFileLoader(fullname=name, path=str(path))
148+
elif path.suffix == ".pyc":
149+
loader = importlib.machinery.SourcelessFileLoader(fullname=name, path=str(path))
144150
else:
145151
raise ImportError(f"Loading file failed (only .py and .pyc): {path}")
146152
spec = importlib.util.spec_from_loader(loader.name, loader)
@@ -235,8 +241,8 @@ def load_function(name: str, py_mod: t.Optional[types.ModuleType]) -> t.Callable
235241

236242

237243
def get_resource_content(package: str, filename: str) -> str:
238-
with pkg_resources.resource_stream(package, filename) as stream:
239-
return stream.read().decode("utf-8")
244+
path = resource_files(package) / filename
245+
return path.read_text()
240246

241247

242248
def truncate(s: t.Union[str, bytes], limit: int = 200, ellipsis="...") -> str:

setup.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
"funcy<3",
1717
"future>=0.18.0,<1",
1818
"importlib-metadata; python_version<'3.8'",
19+
"importlib-resources; python_version<'3.8'",
1920
"jinja2<4",
2021
"paho-mqtt<2",
2122
"requests<3",

tests/test_core_infra.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -709,11 +709,11 @@ def test_load_services_spec_not_found(caplog):
709709
config = Config()
710710
config.add_section("config:foo.bar")
711711
bootstrap(config=config)
712-
with pytest.raises(SystemExit) as ex:
712+
with pytest.raises(ImportError) as ex:
713713
load_services(["foo.bar"])
714714
assert 'Loading service "foo.bar" from module "foo.bar" failed' in caplog.messages
715-
assert 'Unable to load service "foo.bar"' in caplog.messages
716-
assert ex.match("1")
715+
assert "Failed loading service: foo.bar" in caplog.messages
716+
assert ex.match("Failed loading service: foo.bar")
717717

718718

719719
def test_load_services_file_not_found(tmp_path, caplog):
@@ -728,12 +728,12 @@ def test_load_services_file_not_found(tmp_path, caplog):
728728
config.add_section("config:foo.bar")
729729
config.set("config:foo.bar", "module", "foo_bar.py")
730730
bootstrap(config=config)
731-
with pytest.raises(SystemExit) as ex:
731+
with pytest.raises(ImportError) as ex:
732732
load_services(["foo.bar"])
733733
assert 'Module "foo_bar.py" is not a file' in caplog.messages
734734
assert f'Module "{modulefile}" is not a file' in caplog.messages
735-
assert 'Unable to load service "foo.bar"' in caplog.messages
736-
assert ex.match("1")
735+
assert "Failed loading service: foo.bar" in caplog.messages
736+
assert ex.match("Failed loading service: foo.bar")
737737

738738

739739
def test_load_services_file_failure(tmp_path, caplog):
@@ -751,12 +751,12 @@ def test_load_services_file_failure(tmp_path, caplog):
751751
config.set("config:foo.bar", "module", "foo_bar.py")
752752
bootstrap(config=config)
753753

754-
with pytest.raises(SystemExit) as ex:
754+
with pytest.raises(ImportError) as ex:
755755
load_services(["foo.bar"])
756756
assert f'Loading service "foo.bar" from file "{modulefile}" failed' in caplog.text
757757
assert "AssertionError" in caplog.text
758-
assert 'Unable to load service "foo.bar"' in caplog.messages
759-
assert ex.match("1")
758+
assert "Failed loading service: foo.bar" in caplog.messages
759+
assert ex.match("Failed loading service: foo.bar")
760760

761761

762762
def test_run_plugin_success(caplog):

0 commit comments

Comments
 (0)