|
18 | 18 | import os
|
19 | 19 | import re
|
20 | 20 | import sys
|
| 21 | +import tempfile |
21 | 22 | from functools import reduce
|
22 | 23 | from typing import Any, Dict, Iterable, List, Optional, Tuple
|
23 | 24 | import unittest
|
@@ -144,16 +145,16 @@ def import_object(import_name: str):
|
144 | 145 | # the script, if there is a script named module_name. Otherwise, raise
|
145 | 146 | # an ImportError as it did before.
|
146 | 147 | import glob
|
147 |
| - import sys |
148 | 148 | import os
|
149 |
| - import imp |
| 149 | + import sys |
| 150 | + import types |
150 | 151 |
|
151 | 152 | for p in sys.path:
|
152 | 153 | f = glob.glob(os.path.join(p, module_name))
|
153 | 154 | if len(f) > 0:
|
154 | 155 | with open(f[0]) as fobj:
|
155 | 156 | codestring = fobj.read()
|
156 |
| - foo = imp.new_module("foo") |
| 157 | + foo = types.ModuleType("foo") |
157 | 158 | exec(codestring, foo.__dict__)
|
158 | 159 |
|
159 | 160 | sys.modules["foo"] = foo
|
@@ -590,6 +591,14 @@ def test_import_object(self) -> None:
|
590 | 591 | )
|
591 | 592 | self.assertIsInstance(instance, UtilTestCase)
|
592 | 593 |
|
| 594 | + def test_import_object_filename(self) -> None: |
| 595 | + with tempfile.TemporaryDirectory() as tmpdirname: |
| 596 | + filename = os.path.join(tmpdirname, 'somefile') |
| 597 | + with open(filename, 'w') as fp: |
| 598 | + fp.write("bar = 42\n") |
| 599 | + value = import_object("{}:bar".format(filename)) |
| 600 | + self.assertTrue(value == 42) |
| 601 | + |
593 | 602 | if not hasattr(unittest.TestCase, "assertIsInstance"):
|
594 | 603 |
|
595 | 604 | def assertIsInstance(self, instance, cls) -> None: # type: ignore[override]
|
|
0 commit comments