##// END OF EJS Templates
Moving helper functions to utils.module_paths, adding tests.
Jörgen Stenarson -
Show More
@@ -0,0 +1,125 b''
1 """Utility functions for finding modules
2
3 Utility functions for finding modules on sys.path.
4
5 `find_mod` finds named module on sys.path.
6
7 `get_init` helper function that finds __init__ file in a directory.
8
9 `find_module` variant of imp.find_module in std_lib that only returns
10 path to module and not an open file object as well.
11
12
13
14 """
15 #-----------------------------------------------------------------------------
16 # Copyright (c) 2011, the IPython Development Team.
17 #
18 # Distributed under the terms of the Modified BSD License.
19 #
20 # The full license is in the file COPYING.txt, distributed with this software.
21 #-----------------------------------------------------------------------------
22
23 #-----------------------------------------------------------------------------
24 # Imports
25 #-----------------------------------------------------------------------------
26 from __future__ import print_function
27
28 # Stdlib imports
29 import imp
30 import os
31
32 # Third-party imports
33
34 # Our own imports
35
36
37 #-----------------------------------------------------------------------------
38 # Globals and constants
39 #-----------------------------------------------------------------------------
40
41 #-----------------------------------------------------------------------------
42 # Local utilities
43 #-----------------------------------------------------------------------------
44
45 #-----------------------------------------------------------------------------
46 # Classes and functions
47 #-----------------------------------------------------------------------------
48 def find_module(name, path=None):
49 """imp.find_module variant that only return path of module.
50
51 The `imp.find_module` returns a filehandle that we are not interested in.
52 Also we ignore any bytecode files that `imp.find_module` finds.
53
54 Parameters
55 ----------
56 name : str
57 name of module to locate
58 path : list of str
59 list of paths to search for `name`. If path=None then search sys.path
60
61 Returns
62 -------
63 filename : str
64 Return full path of module or None if module is missing or does not have
65 .py or .pyw extension
66 """
67 if name is None:
68 return None
69 try:
70 file, filename, _ = imp.find_module(name, path)
71 except ImportError:
72 return None
73 if file is None:
74 return filename
75 else:
76 file.close()
77 if os.path.splitext(filename)[1] in [".py", "pyc"]:
78 return filename
79 else:
80 return None
81
82 def get_init(dirname):
83 """Get __init__ file path for module directory
84
85 Parameters
86 ----------
87 dirname : str
88 Find the __init__ file in directory `dirname`
89
90 Returns
91 -------
92 init_path : str
93 Path to __init__ file
94 """
95 fbase = os.path.join(dirname, "__init__")
96 for ext in [".py", ".pyw"]:
97 fname = fbase + ext
98 if os.path.isfile(fname):
99 return fname
100
101
102 def find_mod(module_name):
103 """Find module `module_name` on sys.path
104
105 Return the path to module `module_name`. If `module_name` refers to
106 a module directory then return path to __init__ file. Return full
107 path of module or None if module is missing or does not have .py or .pyw
108 extension. We are not interested in running bytecode.
109
110 Parameters
111 ----------
112 module_name : str
113
114 Returns
115 -------
116 modulepath : str
117 Path to module `module_name`.
118 """
119 parts = module_name.split(".")
120 basepath = find_module(parts[0])
121 for submodname in parts[1:]:
122 basepath = find_module(submodname, [basepath])
123 if basepath and os.path.isdir(basepath):
124 basepath = get_init(basepath)
125 return basepath
@@ -0,0 +1,133 b''
1 # encoding: utf-8
2 """Tests for IPython.utils.path.py"""
3
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2008 The IPython Development Team
6 #
7 # Distributed under the terms of the BSD License. The full license is in
8 # the file COPYING, distributed as part of this software.
9 #-----------------------------------------------------------------------------
10
11 #-----------------------------------------------------------------------------
12 # Imports
13 #-----------------------------------------------------------------------------
14
15 from __future__ import with_statement
16
17 import os
18 import shutil
19 import sys
20 import tempfile
21 import StringIO
22
23 from os.path import join, abspath, split
24
25 import nose.tools as nt
26
27 from nose import with_setup
28
29 import IPython
30 from IPython.testing import decorators as dec
31 from IPython.testing.decorators import skip_if_not_win32, skip_win32
32 from IPython.testing.tools import make_tempfile
33 from IPython.utils import path, io
34 from IPython.utils import py3compat
35
36 import IPython.utils.module_paths as mp
37
38 env = os.environ
39 TEST_FILE_PATH = split(abspath(__file__))[0]
40 TMP_TEST_DIR = tempfile.mkdtemp()
41 #
42 # Setup/teardown functions/decorators
43 #
44
45 old_syspath = sys.path
46 sys.path = [TMP_TEST_DIR]
47
48 def make_empty_file(fname):
49 f = open(fname, 'w')
50 f.close()
51
52
53 def setup():
54 """Setup testenvironment for the module:
55
56 """
57 # Do not mask exceptions here. In particular, catching WindowsError is a
58 # problem because that exception is only defined on Windows...
59 os.makedirs(join(TMP_TEST_DIR, "xmod"))
60 os.makedirs(join(TMP_TEST_DIR, "nomod"))
61 make_empty_file(join(TMP_TEST_DIR, "xmod/__init__.py"))
62 make_empty_file(join(TMP_TEST_DIR, "xmod/sub.py"))
63 make_empty_file(join(TMP_TEST_DIR, "pack.py"))
64 make_empty_file(join(TMP_TEST_DIR, "packpyc.pyc"))
65
66 def teardown():
67 """Teardown testenvironment for the module:
68
69 - Remove tempdir
70 """
71 # Note: we remove the parent test dir, which is the root of all test
72 # subdirs we may have created. Use shutil instead of os.removedirs, so
73 # that non-empty directories are all recursively removed.
74 shutil.rmtree(TMP_TEST_DIR)
75
76
77 def test_get_init_1():
78 """See if get_init can find __init__.py in this testdir"""
79 with make_tempfile(join(TMP_TEST_DIR, "__init__.py")):
80 assert mp.get_init(TMP_TEST_DIR)
81
82 def test_get_init_2():
83 """See if get_init can find __init__.pyw in this testdir"""
84 with make_tempfile(join(TMP_TEST_DIR, "__init__.pyw")):
85 assert mp.get_init(TMP_TEST_DIR)
86
87 def test_get_init_3():
88 """get_init can't find __init__.pyc in this testdir"""
89 with make_tempfile(join(TMP_TEST_DIR, "__init__.pyc")):
90 assert mp.get_init(TMP_TEST_DIR) is None
91
92 def test_get_init_3():
93 """get_init can't find __init__ in empty testdir"""
94 assert mp.get_init(TMP_TEST_DIR) is None
95
96
97 def test_find_mod_1():
98 modpath = join(TMP_TEST_DIR, "xmod", "__init__.py")
99 assert mp.find_mod("xmod") == modpath
100
101 def test_find_mod_2():
102 modpath = join(TMP_TEST_DIR, "xmod", "__init__.py")
103 assert mp.find_mod("xmod") == modpath
104
105 def test_find_mod_3():
106 modpath = join(TMP_TEST_DIR, "xmod", "sub.py")
107 assert mp.find_mod("xmod.sub") == modpath
108
109 def test_find_mod_4():
110 modpath = join(TMP_TEST_DIR, "pack.py")
111 assert mp.find_mod("pack") == modpath
112
113 def test_find_mod_5():
114 assert mp.find_mod("packpyc") is None
115
116 def test_find_module_1():
117 modpath = join(TMP_TEST_DIR, "xmod")
118 assert mp.find_module("xmod") == modpath
119
120 def test_find_module_2():
121 """Testing sys.path that is empty"""
122 assert mp.find_module("xmod", []) is None
123
124 def test_find_module_3():
125 """Testing sys.path that is empty"""
126 assert mp.find_module(None, None) is None
127
128 def test_find_module_4():
129 """Testing sys.path that is empty"""
130 assert mp.find_module(None) is None
131
132 def test_find_module_5():
133 assert mp.find_module("xmod.nopack") is None
@@ -55,6 +55,7 b' from IPython.lib.pylabtools import mpl_runner'
55 from IPython.testing.skipdoctest import skip_doctest
55 from IPython.testing.skipdoctest import skip_doctest
56 from IPython.utils import py3compat
56 from IPython.utils import py3compat
57 from IPython.utils.io import file_read, nlprint
57 from IPython.utils.io import file_read, nlprint
58 from IPython.utils.module_paths import find_mod
58 from IPython.utils.path import get_py_filename, unquote_filename
59 from IPython.utils.path import get_py_filename, unquote_filename
59 from IPython.utils.process import arg_split, abbrev_cwd
60 from IPython.utils.process import arg_split, abbrev_cwd
60 from IPython.utils.terminal import set_term_title
61 from IPython.utils.terminal import set_term_title
@@ -92,85 +93,6 b' def needs_local_scope(func):'
92 func.needs_local_scope = True
93 func.needs_local_scope = True
93 return func
94 return func
94
95
95 def find_module(name, path=None):
96 """imp.find_module variant that only return path of module.
97
98 The `imp.find_module` returns a filehandle that we are not interested in.
99 Also we ignore any bytecode files that `imp.find_module` finds.
100
101 Parameters
102 ----------
103 name : str
104 name of module to locate
105 path : list of str
106 list of paths to search for `name`. If path=None then search sys.path
107
108 Returns
109 -------
110 filename : str
111 Return full path of module or None if module is missing or does not have
112 .py or .pyw extension
113 """
114 if name is None:
115 return None
116 try:
117 file, filename, _ = imp.find_module(name, path)
118 except ImportError:
119 return None
120 if file is None:
121 return filename
122 else:
123 file.close()
124 if os.path.splitext(filename)[1] in [".py", "pyc"]:
125 return filename
126 else:
127 return None
128
129 def get_init(dirname):
130 """Get __init__ file path for module directory
131
132 Parameters
133 ----------
134 dirname : str
135 Find the __init__ file in directory `dirname`
136
137 Returns
138 -------
139 init_path : str
140 Path to __init__ file
141 """
142 fbase = os.path.join(dirname, "__init__")
143 for ext in [".py", ".pyw"]:
144 fname = fbase + ext
145 if os.path.isfile(fname):
146 return fname
147
148
149 def find_mod(module_name):
150 """Find module `module_name` on sys.path
151
152 Return the path to module `module_name`. If `module_name` refers to
153 a module directory then return path to __init__ file. Return full
154 path of module or None if module is missing or does not have .py or .pyw
155 extension. We are not interested in running bytecode.
156
157 Parameters
158 ----------
159 module_name : str
160
161 Returns
162 -------
163 modulepath : str
164 Path to module `module_name`.
165 """
166 parts = module_name.split(".")
167 basepath = find_module(parts[0])
168 for submodname in parts[1:]:
169 basepath = find_module(submodname, [basepath])
170 if basepath and os.path.isdir(basepath):
171 basepath = get_init(basepath)
172 return basepath
173
174
96
175 # Used for exception handling in magic_edit
97 # Used for exception handling in magic_edit
176 class MacroToEdit(ValueError): pass
98 class MacroToEdit(ValueError): pass
General Comments 0
You need to be logged in to leave comments. Login now