##// END OF EJS Templates
Moved skip decorator to testing and created similar ones for OSX and linux, create delete testdirs in module setup/teardown
Jorgen Stenarson -
Show More
@@ -1,160 +1,165 b''
1 1 """Decorators for labeling test objects.
2 2
3 3 Decorators that merely return a modified version of the original
4 4 function object are straightforward. Decorators that return a new
5 5 function object need to use
6 6 nose.tools.make_decorator(original_function)(decorator) in returning
7 7 the decorator, in order to preserve metadata such as function name,
8 8 setup and teardown functions and so on - see nose.tools for more
9 9 information.
10 10
11 11 This module provides a set of useful decorators meant to be ready to use in
12 12 your own tests. See the bottom of the file for the ready-made ones, and if you
13 13 find yourself writing a new one that may be of generic use, add it here.
14 14
15 15 NOTE: This file contains IPython-specific decorators and imports the
16 16 numpy.testing.decorators file, which we've copied verbatim. Any of our own
17 17 code will be added at the bottom if we end up extending this.
18 18 """
19 19
20 20 # Stdlib imports
21 21 import inspect
22 22 import sys
23 23
24 24 # Third-party imports
25 25
26 26 # This is Michele Simionato's decorator module, also kept verbatim.
27 27 from decorator_msim import decorator, update_wrapper
28 28
29 29 # Grab the numpy-specific decorators which we keep in a file that we
30 30 # occasionally update from upstream: decorators_numpy.py is an IDENTICAL copy
31 31 # of numpy.testing.decorators.
32 32 from decorators_numpy import *
33 33
34 34 ##############################################################################
35 35 # Local code begins
36 36
37 37 # Utility functions
38 38
39 39 def apply_wrapper(wrapper,func):
40 40 """Apply a wrapper to a function for decoration.
41 41
42 42 This mixes Michele Simionato's decorator tool with nose's make_decorator,
43 43 to apply a wrapper in a decorator so that all nose attributes, as well as
44 44 function signature and other properties, survive the decoration cleanly.
45 45 This will ensure that wrapped functions can still be well introspected via
46 46 IPython, for example.
47 47 """
48 48 import nose.tools
49 49
50 50 return decorator(wrapper,nose.tools.make_decorator(func)(wrapper))
51 51
52 52
53 53 def make_label_dec(label,ds=None):
54 54 """Factory function to create a decorator that applies one or more labels.
55 55
56 56 :Parameters:
57 57 label : string or sequence
58 58 One or more labels that will be applied by the decorator to the functions
59 59 it decorates. Labels are attributes of the decorated function with their
60 60 value set to True.
61 61
62 62 :Keywords:
63 63 ds : string
64 64 An optional docstring for the resulting decorator. If not given, a
65 65 default docstring is auto-generated.
66 66
67 67 :Returns:
68 68 A decorator.
69 69
70 70 :Examples:
71 71
72 72 A simple labeling decorator:
73 73 >>> slow = make_label_dec('slow')
74 74 >>> print slow.__doc__
75 75 Labels a test as 'slow'.
76 76
77 77 And one that uses multiple labels and a custom docstring:
78 78 >>> rare = make_label_dec(['slow','hard'],
79 79 ... "Mix labels 'slow' and 'hard' for rare tests.")
80 80 >>> print rare.__doc__
81 81 Mix labels 'slow' and 'hard' for rare tests.
82 82
83 83 Now, let's test using this one:
84 84 >>> @rare
85 85 ... def f(): pass
86 86 ...
87 87 >>>
88 88 >>> f.slow
89 89 True
90 90 >>> f.hard
91 91 True
92 92 """
93 93
94 94 if isinstance(label,basestring):
95 95 labels = [label]
96 96 else:
97 97 labels = label
98 98
99 99 # Validate that the given label(s) are OK for use in setattr() by doing a
100 100 # dry run on a dummy function.
101 101 tmp = lambda : None
102 102 for label in labels:
103 103 setattr(tmp,label,True)
104 104
105 105 # This is the actual decorator we'll return
106 106 def decor(f):
107 107 for label in labels:
108 108 setattr(f,label,True)
109 109 return f
110 110
111 111 # Apply the user's docstring, or autogenerate a basic one
112 112 if ds is None:
113 113 ds = "Labels a test as %r." % label
114 114 decor.__doc__ = ds
115 115
116 116 return decor
117 117
118 118 #-----------------------------------------------------------------------------
119 119 # Decorators for public use
120 120
121 121 skip_doctest = make_label_dec('skip_doctest',
122 122 """Decorator - mark a function or method for skipping its doctest.
123 123
124 124 This decorator allows you to mark a function whose docstring you wish to
125 125 omit from testing, while preserving the docstring for introspection, help,
126 126 etc.""")
127 127
128 128 def skip(msg=''):
129 129 """Decorator - mark a test function for skipping from test suite.
130 130
131 131 This function *is* already a decorator, it is not a factory like
132 132 make_label_dec or some of those in decorators_numpy.
133 133
134 134 :Parameters:
135 135
136 136 func : function
137 137 Test function to be skipped
138 138
139 139 msg : string
140 140 Optional message to be added.
141 141 """
142 142
143 143 import nose
144 144
145 145 def inner(func):
146 146
147 147 def wrapper(*a,**k):
148 148 if msg: out = '\n'+msg
149 149 else: out = ''
150 150 raise nose.SkipTest("Skipping test for function: %s%s" %
151 151 (func.__name__,out))
152 152
153 153 return apply_wrapper(wrapper,func)
154 154
155 155 return inner
156 156
157 157 # Decorators to skip certain tests on specific platforms.
158 skip_win32 = skipif(sys.platform=='win32',"This test does not run under Windows")
159 skip_linux = skipif(sys.platform=='linux2',"This test does not run under Linux")
160 skip_osx = skipif(sys.platform=='darwin',"This test does not run under OSX")
158 skip_win32 = skipif(sys.platform == 'win32',"This test does not run under Windows")
159 skip_linux = skipif(sys.platform == 'linux2',"This test does not run under Linux")
160 skip_osx = skipif(sys.platform == 'darwin',"This test does not run under OSX")
161
162 # Decorators to skip tests if not on specific platforms.
163 skip_if_not_win32 = skipif(sys.platform != 'win32', "This test only runs under Windows")
164 skip_if_not_linux = skipif(sys.platform != 'linux2', "This test only runs under Linux")
165 skip_if_not_osx = skipif(sys.platform != 'darwin', "This test only runs under OSX")
@@ -1,227 +1,240 b''
1 1 # encoding: utf-8
2 2
3 3 """Tests for genutils.py"""
4 4
5 5 __docformat__ = "restructuredtext en"
6 6
7 7 #-----------------------------------------------------------------------------
8 8 # Copyright (C) 2008 The IPython Development Team
9 9 #
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #-----------------------------------------------------------------------------
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Imports
16 16 #-----------------------------------------------------------------------------
17 17
18 18 from IPython import genutils
19 19 from IPython.testing.decorators import skipif
20 20 from nose import with_setup
21 21 from nose.tools import raises
22 22
23 23 from os.path import join, abspath, split
24 24 import os, sys, IPython
25 25 import nose.tools as nt
26 26
27 27 env = os.environ
28 28
29 29 try:
30 30 import _winreg as wreg
31 31 except ImportError:
32 32 #Fake _winreg module on none windows platforms
33 33 import new
34 34 sys.modules["_winreg"] = new.module("_winreg")
35 35 import _winreg as wreg
36 36 #Add entries that needs to be stubbed by the testing code
37 37 (wreg.OpenKey, wreg.QueryValueEx,) = (None, None)
38 38
39 39 test_file_path = split(abspath(__file__))[0]
40 40
41 #skip_if_not_win32 = skipif(sys.platform!='win32',"This test only runs under Windows")
41 #
42
43 def setup():
44 try:
45 os.makedirs("home_test_dir/_ipython")
46 except WindowsError:
47 pass #Or should we complain that the test directory already exists??
48
49 def teardown():
50 try:
51 os.removedirs("home_test_dir/_ipython")
52 except WindowsError:
53 pass #Or should we complain that the test directory already exists??
54
42 55
43 56 def setup_environment():
44 57 global oldstuff, platformstuff
45 58 oldstuff = (env.copy(), os.name, genutils.get_home_dir, IPython.__file__,)
46 59
47 60 if os.name == 'nt':
48 61 platformstuff = (wreg.OpenKey, wreg.QueryValueEx,)
49 62
50 63 if 'IPYTHONDIR' in env:
51 64 del env['IPYTHONDIR']
52 65
53 66 def teardown_environment():
54 67 (oldenv, os.name, genutils.get_home_dir, IPython.__file__,) = oldstuff
55 68 for key in env.keys():
56 69 if key not in oldenv:
57 70 del env[key]
58 71 env.update(oldenv)
59 72 if hasattr(sys, 'frozen'):
60 73 del sys.frozen
61 74 if os.name == 'nt':
62 75 (wreg.OpenKey, wreg.QueryValueEx,) = platformstuff
63 76
64 77 with_enivronment = with_setup(setup_environment, teardown_environment)
65 78
66 79 @with_enivronment
67 80 def test_get_home_dir_1():
68 81 """Testcase for py2exe logic, un-compressed lib
69 82 """
70 83 sys.frozen = True
71 84
72 85 #fake filename for IPython.__init__
73 86 IPython.__file__ = abspath(join(test_file_path, "home_test_dir/Lib/IPython/__init__.py"))
74 87
75 88 home_dir = genutils.get_home_dir()
76 89 nt.assert_equal(home_dir, abspath(join(test_file_path, "home_test_dir")))
77 90
78 91 @with_enivronment
79 92 def test_get_home_dir_2():
80 93 """Testcase for py2exe logic, compressed lib
81 94 """
82 95 sys.frozen = True
83 96 #fake filename for IPython.__init__
84 97 IPython.__file__ = abspath(join(test_file_path, "home_test_dir/Library.zip/IPython/__init__.py"))
85 98
86 99 home_dir = genutils.get_home_dir()
87 100 nt.assert_equal(home_dir, abspath(join(test_file_path, "home_test_dir")).lower())
88 101
89 102 @with_enivronment
90 103 def test_get_home_dir_3():
91 104 """Testcase $HOME is set, then use its value as home directory."""
92 105 env["HOME"] = join(test_file_path, "home_test_dir")
93 106 home_dir = genutils.get_home_dir()
94 107 nt.assert_equal(home_dir, env["HOME"])
95 108
96 109 @with_enivronment
97 110 def test_get_home_dir_4():
98 111 """Testcase $HOME is not set, os=='posix'.
99 112 This should fail with HomeDirError"""
100 113
101 114 os.name = 'posix'
102 115 del os.environ["HOME"]
103 116 nt.assert_raises(genutils.HomeDirError, genutils.get_home_dir)
104 117
105 118 @with_enivronment
106 119 def test_get_home_dir_5():
107 120 """Testcase $HOME is not set, os=='nt'
108 121 env['HOMEDRIVE'],env['HOMEPATH'] points to path."""
109 122
110 123 os.name = 'nt'
111 124 del os.environ["HOME"]
112 125 env['HOMEDRIVE'], env['HOMEPATH'] = os.path.abspath(test_file_path), "home_test_dir"
113 126
114 127 home_dir = genutils.get_home_dir()
115 128 nt.assert_equal(home_dir, abspath(join(test_file_path, "home_test_dir")))
116 129
117 130 @with_enivronment
118 131 def test_get_home_dir_6():
119 132 """Testcase $HOME is not set, os=='nt'
120 133 env['HOMEDRIVE'],env['HOMEPATH'] do not point to path.
121 134 env['USERPROFILE'] points to path
122 135 """
123 136
124 137 os.name = 'nt'
125 138 del os.environ["HOME"]
126 139 env['HOMEDRIVE'], env['HOMEPATH'] = os.path.abspath(test_file_path), "DOES NOT EXIST"
127 140 env["USERPROFILE"] = abspath(join(test_file_path, "home_test_dir"))
128 141
129 142 home_dir = genutils.get_home_dir()
130 143 nt.assert_equal(home_dir, abspath(join(test_file_path, "home_test_dir")))
131 144
132 145 # Should we stub wreg fully so we can run the test on all platforms?
133 146 #@skip_if_not_win32
134 147 @with_enivronment
135 148 def test_get_home_dir_7():
136 149 """Testcase $HOME is not set, os=='nt'
137 150 env['HOMEDRIVE'],env['HOMEPATH'], env['USERPROFILE'] missing
138 151 """
139 152 os.name = 'nt'
140 153 del env["HOME"], env['HOMEDRIVE']
141 154
142 155 #Stub windows registry functions
143 156 def OpenKey(x, y):
144 157 class key:
145 158 def Close(self):
146 159 pass
147 160 return key()
148 161 def QueryValueEx(x, y):
149 162 return [abspath(join(test_file_path, "home_test_dir"))]
150 163
151 164 wreg.OpenKey = OpenKey
152 165 wreg.QueryValueEx = QueryValueEx
153 166
154 167 home_dir = genutils.get_home_dir()
155 168 nt.assert_equal(home_dir, abspath(join(test_file_path, "home_test_dir")))
156 169
157 170
158 171 #
159 172 # Tests for get_ipython_dir
160 173 #
161 174
162 175 @with_enivronment
163 176 def test_get_ipython_dir_1():
164 177 """2 Testcase to see if we can call get_ipython_dir without Exceptions."""
165 178 env['IPYTHONDIR'] = "someplace/.ipython"
166 179 ipdir = genutils.get_ipython_dir()
167 180 nt.assert_equal(ipdir, os.path.abspath("someplace/.ipython"))
168 181
169 182
170 183 @with_enivronment
171 184 def test_get_ipython_dir_2():
172 185 """3 Testcase to see if we can call get_ipython_dir without Exceptions."""
173 186 genutils.get_home_dir = lambda : "someplace"
174 187 os.name = "posix"
175 188 ipdir = genutils.get_ipython_dir()
176 189 nt.assert_equal(ipdir, os.path.abspath(os.path.join("someplace", ".ipython")))
177 190
178 191 @with_enivronment
179 192 def test_get_ipython_dir_3():
180 193 """4 Testcase to see if we can call get_ipython_dir without Exceptions."""
181 194 genutils.get_home_dir = lambda : "someplace"
182 195 os.name = "nt"
183 196 ipdir = genutils.get_ipython_dir()
184 197 nt.assert_equal(ipdir, os.path.abspath(os.path.join("someplace", "_ipython")))
185 198
186 199
187 200 #
188 201 # Tests for get_security_dir
189 202 #
190 203
191 204 @with_enivronment
192 205 def test_get_security_dir():
193 206 """Testcase to see if we can call get_security_dir without Exceptions."""
194 207 sdir = genutils.get_security_dir()
195 208
196 209
197 210 #
198 211 # Tests for popkey
199 212 #
200 213
201 214 def test_popkey_1():
202 215 dct = dict(a=1, b=2, c=3)
203 216 nt.assert_equal(genutils.popkey(dct, "a"), 1)
204 217 nt.assert_equal(dct, dict(b=2, c=3))
205 218 nt.assert_equal(genutils.popkey(dct, "b"), 2)
206 219 nt.assert_equal(dct, dict(c=3))
207 220 nt.assert_equal(genutils.popkey(dct, "c"), 3)
208 221 nt.assert_equal(dct, dict())
209 222
210 223 def test_popkey_2():
211 224 dct = dict(a=1, b=2, c=3)
212 225 nt.assert_raises(KeyError, genutils.popkey, dct, "d")
213 226
214 227 def test_popkey_3():
215 228 dct = dict(a=1, b=2, c=3)
216 229 nt.assert_equal(genutils.popkey(dct, "A", 13), 13)
217 230 nt.assert_equal(dct, dict(a=1, b=2, c=3))
218 231 nt.assert_equal(genutils.popkey(dct, "B", 14), 14)
219 232 nt.assert_equal(dct, dict(a=1, b=2, c=3))
220 233 nt.assert_equal(genutils.popkey(dct, "C", 15), 15)
221 234 nt.assert_equal(dct, dict(a=1, b=2, c=3))
222 235 nt.assert_equal(genutils.popkey(dct, "a"), 1)
223 236 nt.assert_equal(dct, dict(b=2, c=3))
224 237 nt.assert_equal(genutils.popkey(dct, "b"), 2)
225 238 nt.assert_equal(dct, dict(c=3))
226 239 nt.assert_equal(genutils.popkey(dct, "c"), 3)
227 240 nt.assert_equal(dct, dict())
General Comments 0
You need to be logged in to leave comments. Login now