blob: a02d2f4f6ffc6957ba8cbdb198328dd0785fc234 [file] [log] [blame]
Brett Cannonfd074152012-04-14 14:10:13 -04001import importlib
Nick Coghlan55175962013-07-28 22:11:50 +10002import shutil
Eli Bendersky6c519992011-07-23 08:48:53 +03003import sys
4import os
5import unittest
6import socket
7import tempfile
8import errno
9from test import support
10
11TESTFN = support.TESTFN
12TESTDIRN = os.path.basename(tempfile.mkdtemp(dir='.'))
13
14
15class TestSupport(unittest.TestCase):
16 def setUp(self):
17 support.unlink(TESTFN)
18 support.rmtree(TESTDIRN)
19 tearDown = setUp
20
21 def test_import_module(self):
22 support.import_module("ftplib")
23 self.assertRaises(unittest.SkipTest, support.import_module, "foo")
24
25 def test_import_fresh_module(self):
26 support.import_fresh_module("ftplib")
27
28 def test_get_attribute(self):
29 self.assertEqual(support.get_attribute(self, "test_get_attribute"),
30 self.test_get_attribute)
31 self.assertRaises(unittest.SkipTest, support.get_attribute, self, "foo")
32
Eli Bendersky7cd94a12011-07-23 15:00:31 +030033 @unittest.skip("failing buildbots")
Eli Bendersky6c519992011-07-23 08:48:53 +030034 def test_get_original_stdout(self):
35 self.assertEqual(support.get_original_stdout(), sys.stdout)
36
37 def test_unload(self):
38 import sched
39 self.assertIn("sched", sys.modules)
40 support.unload("sched")
41 self.assertNotIn("sched", sys.modules)
42
43 def test_unlink(self):
44 with open(TESTFN, "w") as f:
45 pass
46 support.unlink(TESTFN)
47 self.assertFalse(os.path.exists(TESTFN))
48 support.unlink(TESTFN)
49
50 def test_rmtree(self):
51 os.mkdir(TESTDIRN)
52 os.mkdir(os.path.join(TESTDIRN, TESTDIRN))
53 support.rmtree(TESTDIRN)
54 self.assertFalse(os.path.exists(TESTDIRN))
55 support.rmtree(TESTDIRN)
56
57 def test_forget(self):
Eli Bendersky8db645f2011-08-02 06:24:31 +030058 mod_filename = TESTFN + '.py'
59 with open(mod_filename, 'w') as f:
60 print('foo = 1', file=f)
Eli Bendersky2b6ee282011-08-03 05:18:33 +030061 sys.path.insert(0, os.curdir)
Brett Cannonfd074152012-04-14 14:10:13 -040062 importlib.invalidate_caches()
Eli Bendersky8db645f2011-08-02 06:24:31 +030063 try:
64 mod = __import__(TESTFN)
65 self.assertIn(TESTFN, sys.modules)
66
67 support.forget(TESTFN)
68 self.assertNotIn(TESTFN, sys.modules)
69 finally:
Eli Bendersky2b6ee282011-08-03 05:18:33 +030070 del sys.path[0]
Eli Bendersky8db645f2011-08-02 06:24:31 +030071 support.unlink(mod_filename)
Victor Stinner047b7ae2014-10-05 17:37:41 +020072 support.rmtree('__pycache__')
Eli Bendersky6c519992011-07-23 08:48:53 +030073
74 def test_HOST(self):
75 s = socket.socket()
76 s.bind((support.HOST, 0))
77 s.close()
78
79 def test_find_unused_port(self):
80 port = support.find_unused_port()
81 s = socket.socket()
82 s.bind((support.HOST, port))
83 s.close()
84
85 def test_bind_port(self):
86 s = socket.socket()
87 support.bind_port(s)
Charles-François Natali6e204602014-07-23 19:28:13 +010088 s.listen()
Eli Bendersky6c519992011-07-23 08:48:53 +030089 s.close()
90
Nick Coghlan55175962013-07-28 22:11:50 +100091 # Tests for temp_dir()
92
93 def test_temp_dir(self):
94 """Test that temp_dir() creates and destroys its directory."""
95 parent_dir = tempfile.mkdtemp()
96 parent_dir = os.path.realpath(parent_dir)
97
98 try:
99 path = os.path.join(parent_dir, 'temp')
100 self.assertFalse(os.path.isdir(path))
101 with support.temp_dir(path) as temp_path:
102 self.assertEqual(temp_path, path)
103 self.assertTrue(os.path.isdir(path))
104 self.assertFalse(os.path.isdir(path))
105 finally:
Benjamin Petersonbb185ab2014-03-12 15:07:01 -0500106 support.rmtree(parent_dir)
Nick Coghlan55175962013-07-28 22:11:50 +1000107
108 def test_temp_dir__path_none(self):
109 """Test passing no path."""
110 with support.temp_dir() as temp_path:
111 self.assertTrue(os.path.isdir(temp_path))
112 self.assertFalse(os.path.isdir(temp_path))
113
114 def test_temp_dir__existing_dir__quiet_default(self):
115 """Test passing a directory that already exists."""
116 def call_temp_dir(path):
117 with support.temp_dir(path) as temp_path:
118 raise Exception("should not get here")
119
120 path = tempfile.mkdtemp()
121 path = os.path.realpath(path)
122 try:
123 self.assertTrue(os.path.isdir(path))
124 self.assertRaises(FileExistsError, call_temp_dir, path)
125 # Make sure temp_dir did not delete the original directory.
126 self.assertTrue(os.path.isdir(path))
127 finally:
128 shutil.rmtree(path)
129
130 def test_temp_dir__existing_dir__quiet_true(self):
131 """Test passing a directory that already exists with quiet=True."""
132 path = tempfile.mkdtemp()
133 path = os.path.realpath(path)
134
135 try:
136 with support.check_warnings() as recorder:
137 with support.temp_dir(path, quiet=True) as temp_path:
138 self.assertEqual(path, temp_path)
139 warnings = [str(w.message) for w in recorder.warnings]
140 # Make sure temp_dir did not delete the original directory.
141 self.assertTrue(os.path.isdir(path))
142 finally:
143 shutil.rmtree(path)
144
145 expected = ['tests may fail, unable to create temp dir: ' + path]
146 self.assertEqual(warnings, expected)
147
148 # Tests for change_cwd()
149
150 def test_change_cwd(self):
151 original_cwd = os.getcwd()
152
153 with support.temp_dir() as temp_path:
154 with support.change_cwd(temp_path) as new_cwd:
155 self.assertEqual(new_cwd, temp_path)
156 self.assertEqual(os.getcwd(), new_cwd)
157
158 self.assertEqual(os.getcwd(), original_cwd)
159
160 def test_change_cwd__non_existent_dir(self):
161 """Test passing a non-existent directory."""
162 original_cwd = os.getcwd()
163
164 def call_change_cwd(path):
165 with support.change_cwd(path) as new_cwd:
166 raise Exception("should not get here")
167
168 with support.temp_dir() as parent_dir:
169 non_existent_dir = os.path.join(parent_dir, 'does_not_exist')
170 self.assertRaises(FileNotFoundError, call_change_cwd,
171 non_existent_dir)
172
173 self.assertEqual(os.getcwd(), original_cwd)
174
175 def test_change_cwd__non_existent_dir__quiet_true(self):
176 """Test passing a non-existent directory with quiet=True."""
177 original_cwd = os.getcwd()
178
179 with support.temp_dir() as parent_dir:
180 bad_dir = os.path.join(parent_dir, 'does_not_exist')
181 with support.check_warnings() as recorder:
182 with support.change_cwd(bad_dir, quiet=True) as new_cwd:
183 self.assertEqual(new_cwd, original_cwd)
184 self.assertEqual(os.getcwd(), new_cwd)
185 warnings = [str(w.message) for w in recorder.warnings]
186
187 expected = ['tests may fail, unable to change CWD to: ' + bad_dir]
188 self.assertEqual(warnings, expected)
189
190 # Tests for change_cwd()
191
192 def test_change_cwd__chdir_warning(self):
193 """Check the warning message when os.chdir() fails."""
194 path = TESTFN + '_does_not_exist'
195 with support.check_warnings() as recorder:
196 with support.change_cwd(path=path, quiet=True):
197 pass
198 messages = [str(w.message) for w in recorder.warnings]
199 self.assertEqual(messages, ['tests may fail, unable to change CWD to: ' + path])
200
201 # Tests for temp_cwd()
202
Eli Bendersky6c519992011-07-23 08:48:53 +0300203 def test_temp_cwd(self):
204 here = os.getcwd()
205 with support.temp_cwd(name=TESTFN):
206 self.assertEqual(os.path.basename(os.getcwd()), TESTFN)
207 self.assertFalse(os.path.exists(TESTFN))
208 self.assertTrue(os.path.basename(os.getcwd()), here)
209
Nick Coghlan55175962013-07-28 22:11:50 +1000210
211 def test_temp_cwd__name_none(self):
212 """Test passing None to temp_cwd()."""
213 original_cwd = os.getcwd()
214 with support.temp_cwd(name=None) as new_cwd:
215 self.assertNotEqual(new_cwd, original_cwd)
216 self.assertTrue(os.path.isdir(new_cwd))
217 self.assertEqual(os.getcwd(), new_cwd)
218 self.assertEqual(os.getcwd(), original_cwd)
Ezio Melotti050a61f2012-09-21 16:53:07 +0300219
Eli Bendersky6c519992011-07-23 08:48:53 +0300220 def test_sortdict(self):
221 self.assertEqual(support.sortdict({3:3, 2:2, 1:1}), "{1: 1, 2: 2, 3: 3}")
222
223 def test_make_bad_fd(self):
224 fd = support.make_bad_fd()
225 with self.assertRaises(OSError) as cm:
226 os.write(fd, b"foo")
227 self.assertEqual(cm.exception.errno, errno.EBADF)
228
229 def test_check_syntax_error(self):
230 support.check_syntax_error(self, "def class")
231 self.assertRaises(AssertionError, support.check_syntax_error, self, "1")
232
233 def test_CleanImport(self):
234 import importlib
235 with support.CleanImport("asyncore"):
236 importlib.import_module("asyncore")
237
238 def test_DirsOnSysPath(self):
239 with support.DirsOnSysPath('foo', 'bar'):
240 self.assertIn("foo", sys.path)
241 self.assertIn("bar", sys.path)
242 self.assertNotIn("foo", sys.path)
243 self.assertNotIn("bar", sys.path)
244
245 def test_captured_stdout(self):
R David Murray5a33f812013-07-11 12:28:40 -0400246 with support.captured_stdout() as stdout:
Eli Benderskyd11c3e32011-07-23 08:51:14 +0300247 print("hello")
R David Murray5a33f812013-07-11 12:28:40 -0400248 self.assertEqual(stdout.getvalue(), "hello\n")
Eli Bendersky6c519992011-07-23 08:48:53 +0300249
250 def test_captured_stderr(self):
R David Murray5a33f812013-07-11 12:28:40 -0400251 with support.captured_stderr() as stderr:
Eli Benderskyd11c3e32011-07-23 08:51:14 +0300252 print("hello", file=sys.stderr)
R David Murray5a33f812013-07-11 12:28:40 -0400253 self.assertEqual(stderr.getvalue(), "hello\n")
Eli Bendersky6c519992011-07-23 08:48:53 +0300254
255 def test_captured_stdin(self):
R David Murray5a33f812013-07-11 12:28:40 -0400256 with support.captured_stdin() as stdin:
257 stdin.write('hello\n')
258 stdin.seek(0)
259 # call test code that consumes from sys.stdin
260 captured = input()
261 self.assertEqual(captured, "hello")
Eli Bendersky6c519992011-07-23 08:48:53 +0300262
263 def test_gc_collect(self):
264 support.gc_collect()
265
266 def test_python_is_optimized(self):
267 self.assertIsInstance(support.python_is_optimized(), bool)
268
269 def test_swap_attr(self):
270 class Obj:
271 x = 1
272 obj = Obj()
273 with support.swap_attr(obj, "x", 5):
274 self.assertEqual(obj.x, 5)
275 self.assertEqual(obj.x, 1)
276
277 def test_swap_item(self):
278 D = {"item":1}
279 with support.swap_item(D, "item", 5):
280 self.assertEqual(D["item"], 5)
281 self.assertEqual(D["item"], 1)
282
283 # XXX -follows a list of untested API
284 # make_legacy_pyc
285 # is_resource_enabled
286 # requires
287 # fcmp
288 # umaks
289 # findfile
290 # check_warnings
291 # EnvironmentVarGuard
292 # TransientResource
293 # transient_internet
294 # run_with_locale
295 # set_memlimit
296 # bigmemtest
297 # precisionbigmemtest
298 # bigaddrspacetest
299 # requires_resource
300 # run_doctest
301 # threading_cleanup
302 # reap_threads
303 # reap_children
304 # strip_python_stderr
305 # args_from_interpreter_flags
306 # can_symlink
307 # skip_unless_symlink
Antoine Pitrou77e904e2013-10-08 23:04:32 +0200308 # SuppressCrashReport
Eli Bendersky6c519992011-07-23 08:48:53 +0300309
310
311def test_main():
312 tests = [TestSupport]
313 support.run_unittest(*tests)
314
315if __name__ == '__main__':
316 test_main()