test_modulefinder.py 9.05 KB
Newer Older
1
import os
2
import errno
3 4
import importlib.machinery
import py_compile
5
import shutil
6 7 8
import unittest
import tempfile

9
from test import support
10 11 12 13

import modulefinder

TEST_DIR = tempfile.mkdtemp()
14
TEST_PATH = [TEST_DIR, os.path.dirname(tempfile.__file__)]
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

# Each test description is a list of 5 items:
#
# 1. a module name that will be imported by modulefinder
# 2. a list of module names that modulefinder is required to find
# 3. a list of module names that modulefinder should complain
#    about because they are not found
# 4. a list of module names that modulefinder should complain
#    about because they MAY be not found
# 5. a string specifying packages to create; the format is obvious imo.
#
# Each package will be created in TEST_DIR, and TEST_DIR will be
# removed after the tests again.
# Modulefinder searches in a path that contains TEST_DIR, plus
# the standard Lib directory.

maybe_test = [
    "a.module",
    ["a", "a.module", "sys",
     "b"],
    ["c"], ["b.something"],
    """\
a/__init__.py
a/module.py
                                from b import something
                                from c import something
b/__init__.py
                                from sys import *
"""]

maybe_test_new = [
    "a.module",
    ["a", "a.module", "sys",
48
     "b", "__future__"],
49 50 51 52 53 54 55
    ["c"], ["b.something"],
    """\
a/__init__.py
a/module.py
                                from b import something
                                from c import something
b/__init__.py
56
                                from __future__ import absolute_import
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
                                from sys import *
"""]

package_test = [
    "a.module",
    ["a", "a.b", "a.c", "a.module", "mymodule", "sys"],
    ["blahblah", "c"], [],
    """\
mymodule.py
a/__init__.py
                                import blahblah
                                from a import b
                                import c
a/module.py
                                import sys
                                from a import b as x
                                from a.c import sillyname
a/b.py
a/c.py
                                from a.module import x
                                import mymodule as sillyname
                                from sys import version_info
"""]

absolute_import_test = [
    "a.module",
    ["a", "a.module",
     "b", "b.x", "b.y", "b.z",
85
     "__future__", "sys", "gc"],
86 87 88 89 90
    ["blahblah", "z"], [],
    """\
mymodule.py
a/__init__.py
a/module.py
91
                                from __future__ import absolute_import
92 93
                                import sys # sys
                                import blahblah # fails
94
                                import gc # gc
95 96 97
                                import b.x # b.x
                                from b import y # b.y
                                from b.z import * # b.z.*
98
a/gc.py
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
a/sys.py
                                import mymodule
a/b/__init__.py
a/b/x.py
a/b/y.py
a/b/z.py
b/__init__.py
                                import z
b/unused.py
b/x.py
b/y.py
b/z.py
"""]

relative_import_test = [
    "a.module",
115 116
    ["__future__",
     "a", "a.module",
117 118 119 120
     "a.b", "a.b.y", "a.b.z",
     "a.b.c", "a.b.c.moduleC",
     "a.b.c.d", "a.b.c.e",
     "a.b.x",
121
     "gc"],
122 123 124 125 126 127
    [], [],
    """\
mymodule.py
a/__init__.py
                                from .b import y, z # a.b.y, a.b.z
a/module.py
128
                                from __future__ import absolute_import # __future__
129 130
                                import gc # gc
a/gc.py
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
a/sys.py
a/b/__init__.py
                                from ..b import x # a.b.x
                                #from a.b.c import moduleC
                                from .c import moduleC # a.b.moduleC
a/b/x.py
a/b/y.py
a/b/z.py
a/b/g.py
a/b/c/__init__.py
                                from ..c import e # a.b.c.e
a/b/c/moduleC.py
                                from ..c import d # a.b.c.d
a/b/c/d.py
a/b/c/e.py
a/b/c/x.py
"""]

relative_import_test_2 = [
    "a.module",
    ["a", "a.module",
     "a.sys",
     "a.b", "a.b.y", "a.b.z",
     "a.b.c", "a.b.c.d",
     "a.b.c.e",
     "a.b.c.moduleC",
     "a.b.c.f",
     "a.b.x",
     "a.another"],
    [], [],
    """\
mymodule.py
a/__init__.py
                                from . import sys # a.sys
a/another.py
a/module.py
                                from .b import y, z # a.b.y, a.b.z
168
a/gc.py
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
a/sys.py
a/b/__init__.py
                                from .c import moduleC # a.b.c.moduleC
                                from .c import d # a.b.c.d
a/b/x.py
a/b/y.py
a/b/z.py
a/b/c/__init__.py
                                from . import e # a.b.c.e
a/b/c/moduleC.py
                                #
                                from . import f   # a.b.c.f
                                from .. import x  # a.b.x
                                from ... import another # a.another
a/b/c/d.py
a/b/c/e.py
a/b/c/f.py
"""]

188 189 190 191 192 193 194 195 196 197 198 199 200
relative_import_test_3 = [
    "a.module",
    ["a", "a.module"],
    ["a.bar"],
    [],
    """\
a/__init__.py
                                def foo(): pass
a/module.py
                                from . import foo
                                from . import bar
"""]

201 202 203 204 205 206 207 208 209 210 211 212
relative_import_test_4 = [
    "a.module",
    ["a", "a.module"],
    [],
    [],
    """\
a/__init__.py
                                def foo(): pass
a/module.py
                                from . import *
"""]

213 214 215 216 217 218 219 220
bytecode_test = [
    "a",
    ["a"],
    [],
    [],
    ""
]

221

222 223
def open_file(path):
    dirname = os.path.dirname(path)
224 225 226 227 228
    try:
        os.makedirs(dirname)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise
229 230
    return open(path, "w")

231

232 233
def create_package(source):
    ofi = None
234 235 236 237 238 239 240 241 242 243 244
    try:
        for line in source.splitlines():
            if line.startswith(" ") or line.startswith("\t"):
                ofi.write(line.strip() + "\n")
            else:
                if ofi:
                    ofi.close()
                ofi = open_file(os.path.join(TEST_DIR, line.strip()))
    finally:
        if ofi:
            ofi.close()
245

246

247
class ModuleFinderTest(unittest.TestCase):
248
    def _do_test(self, info, report=False, debug=0, replace_paths=[]):
249 250 251
        import_this, modules, missing, maybe_missing, source = info
        create_package(source)
        try:
252 253
            mf = modulefinder.ModuleFinder(path=TEST_PATH, debug=debug,
                                           replace_paths=replace_paths)
254 255 256 257 258 259 260 261 262 263 264 265
            mf.import_hook(import_this)
            if report:
                mf.report()
##                # This wouldn't work in general when executed several times:
##                opath = sys.path[:]
##                sys.path = TEST_PATH
##                try:
##                    __import__(import_this)
##                except:
##                    import traceback; traceback.print_exc()
##                sys.path = opath
##                return
266 267
            modules = sorted(set(modules))
            found = sorted(mf.modules)
268
            # check if we found what we expected, not more, not less
269
            self.assertEqual(found, modules)
270 271 272

            # check for missing and maybe missing modules
            bad, maybe = mf.any_missing_maybe()
273 274
            self.assertEqual(bad, missing)
            self.assertEqual(maybe, maybe_missing)
275
        finally:
276
            shutil.rmtree(TEST_DIR)
277 278 279 280 281 282 283

    def test_package(self):
        self._do_test(package_test)

    def test_maybe(self):
        self._do_test(maybe_test)

284 285
    def test_maybe_new(self):
        self._do_test(maybe_test_new)
286

287 288
    def test_absolute_imports(self):
        self._do_test(absolute_import_test)
289

290 291
    def test_relative_imports(self):
        self._do_test(relative_import_test)
292

293 294
    def test_relative_imports_2(self):
        self._do_test(relative_import_test_2)
295

296 297
    def test_relative_imports_3(self):
        self._do_test(relative_import_test_3)
298

299 300 301
    def test_relative_imports_4(self):
        self._do_test(relative_import_test_4)

302 303 304 305 306 307 308 309 310 311
    def test_bytecode(self):
        base_path = os.path.join(TEST_DIR, 'a')
        source_path = base_path + importlib.machinery.SOURCE_SUFFIXES[0]
        bytecode_path = base_path + importlib.machinery.BYTECODE_SUFFIXES[0]
        with open_file(source_path) as file:
            file.write('testing_modulefinder = True\n')
        py_compile.compile(source_path, cfile=bytecode_path)
        os.remove(source_path)
        self._do_test(bytecode_test)

312 313 314 315 316 317 318
    def test_replace_paths(self):
        old_path = os.path.join(TEST_DIR, 'a', 'module.py')
        new_path = os.path.join(TEST_DIR, 'a', 'spam.py')
        with support.captured_stdout() as output:
            self._do_test(maybe_test, debug=2,
                          replace_paths=[(old_path, new_path)])
        output = output.getvalue()
319
        expected = "co_filename %r changed to %r" % (old_path, new_path)
320
        self.assertIn(expected, output)
321

322 323 324 325 326 327 328 329 330 331 332 333 334
    def test_extended_opargs(self):
        extended_opargs_test = [
            "a",
            ["a", "b"],
            [], [],
            """\
a.py
                                %r
                                import b
b.py
""" % list(range(2**16))]  # 2**16 constants
        self._do_test(extended_opargs_test)

335 336 337

if __name__ == "__main__":
    unittest.main()