⇤ ← Revision 1 as of 2006-01-26 18:41:25
13126
Comment: Added test_path.py
|
13142
python format
|
Deletions are marked like this. | Additions are marked like this. |
Line 1: | Line 1: |
#format PYTHON |
1 """ test_path.py - Test the path module.
2
3 This only runs on Posix and NT right now. I would like to have more
4 tests. You can help! Just add appropriate pathnames for your
5 platform (os.name) in each place where the p() function is called.
6 Then send me the result. If you can't get the test to run at all on
7 your platform, there's probably a bug in path.py -- please let me
8 know!
9
10 TempDirTestCase.testTouch() takes a while to run. It sleeps a few
11 seconds to allow some time to pass between calls to check the modify
12 time on files.
13
14 URL: http://www.jorendorff.com/articles/python/path
15 Author: Jason Orendorff <jason@jorendorff.com>
16 Date: 7 Mar 2004
17 Modified by Björn Lindqvist <bjourne@gmail.com>, January 2005
18 """
19
20 import unittest
21 import codecs, os, random, shutil, tempfile, time
22 from path import path, __version__ as path_version
23
24 # This should match the version of path.py being tested.
25 __version__ = '2.0.4'
26
27 # Uncomment this to speed up testing. One test will fail.
28 #time.sleep = lambda *args: None
29
30 def p(**choices):
31 """ Choose a value from several possible values, based on os.name """
32 return choices[os.name]
33
34 class BasicTestCase(unittest.TestCase):
35 def testRelpath(self):
36 root = path(p(nt='C:\\', posix='/'))
37 foo = path(root, 'foo')
38 quux = path(foo, 'quux')
39 bar = path(foo, 'bar')
40 boz = path(bar, 'Baz', 'Boz')
41 up = path(os.pardir)
42
43 # basics
44 self.assertEqual(root.relpathto(boz),
45 path('foo', 'bar', 'Baz', 'Boz'))
46 self.assertEqual(bar.relpathto(boz), path('Baz', 'Boz'))
47 self.assertEqual(quux.relpathto(boz), path(up, 'bar', 'Baz', 'Boz'))
48 self.assertEqual(boz.relpathto(quux), path(up, up, up, 'quux'))
49 self.assertEqual(boz.relpathto(bar), path(up, up))
50
51 # x.relpathto(x) == curdir
52 self.assertEqual(root.relpathto(root), os.curdir)
53 self.assertEqual(boz.relpathto(boz), os.curdir)
54 # Make sure case is properly noted (or ignored)
55 self.assertEqual(boz.relpathto(boz.normcase()), os.curdir)
56
57 # relpath()
58 cwd = path(os.getcwd())
59 self.assertEqual(boz.relpath(), cwd.relpathto(boz))
60
61 if os.name == 'nt':
62 # Check relpath across drives.
63 d = path('D:\\')
64 self.assertEqual(d.relpathto(boz), boz)
65
66 def testStringCompatibility(self):
67 """ Test compatibility with ordinary strings. """
68 x = path('xyzzy')
69 self.assert_(x == 'xyzzy')
70 self.assert_(x == u'xyzzy')
71
72 # sorting
73 items = [path('fhj'),
74 path('fgh'),
75 'E',
76 path('d'),
77 'A',
78 path('B'),
79 'c']
80 items.sort()
81 self.assert_(items == ['A', 'B', 'E', 'c', 'd', 'fgh', 'fhj'])
82
83 def testProperties(self):
84 # Create sample path object.
85 f = p(nt='C:\\Program Files\\Python\\Lib\\xyzzy.py',
86 posix='/usr/local/python/lib/xyzzy.py')
87 f = path(f)
88
89 # .parent
90 self.assertEqual(f.parent, p(nt='C:\\Program Files\\Python\\Lib',
91 posix='/usr/local/python/lib'))
92
93 # .name
94 self.assertEqual(f.name, 'xyzzy.py')
95 self.assertEqual(f.parent.name, p(nt='Lib', posix='lib'))
96
97 # .ext
98 self.assertEqual(f.ext, '.py')
99 self.assertEqual(f.parent.ext, '')
100
101 # .drive
102 self.assertEqual(f.drive, p(nt='C:', posix=''))
103
104 def testMethods(self):
105 # .abspath()
106 self.assertEqual(path(os.curdir).abspath(), os.getcwd())
107
108 # .getcwd()
109 cwd = path.cwd()
110 self.assert_(isinstance(cwd, path))
111 self.assertEqual(cwd, os.getcwd())
112
113 def testUNC(self):
114 if hasattr(os.path, 'splitunc'):
115 p = path(r'\\python1\share1\dir1\file1.txt')
116 self.assert_(p.uncshare == r'\\python1\share1')
117 self.assert_(p.splitunc() == os.path.splitunc(str(p)))
118
119 def testDefaultCtor(self):
120 self.assert_(os.getcwd() == path().abspath())
121
122 # On most platforms, current working directory is "."
123 self.assert_(path() == ".")
124
125 # But that is different from os.getcwd()...
126 self.assert_(path() != path().cwd())
127
128 def testSplittingAndStripping(self):
129 p = path("~/python/config.h.in")
130 noext = p.stripext()
131 self.assert_(isinstance(p, path))
132 self.assertEquals(noext, "~/python/config.h")
133
134
135 class TempDirTestCase(unittest.TestCase):
136 def setUp(self):
137 # Create a temporary directory.
138 f = tempfile.mktemp()
139 system_tmp_dir = os.path.dirname(f)
140 my_dir = 'testpath_tempdir_' + str(random.random())[2:]
141 self.tempdir = os.path.join(system_tmp_dir, my_dir)
142 os.mkdir(self.tempdir)
143
144 def tearDown(self):
145 shutil.rmtree(self.tempdir)
146
147 def testTouch(self):
148 # NOTE: This test takes a long time to run (~10 seconds).
149 # It sleeps several seconds because on Windows, the resolution
150 # of a file's mtime and ctime is about 2 seconds.
151 #
152 # atime isn't tested because on Windows the resolution of atime
153 # is something like 24 hours.
154
155 d = path(self.tempdir)
156 f = path(d, 'test.txt')
157 t0 = time.time() - 3
158 f.touch()
159 t1 = time.time() + 3
160 try:
161 self.assert_(f.exists())
162 self.assert_(f.isfile())
163 self.assertEqual(f.size, 0)
164 self.assert_(t0 <= f.mtime <= t1)
165 ct = f.ctime
166 self.assert_(t0 <= ct <= t1)
167
168 time.sleep(5)
169 fobj = file(f, 'ab')
170 fobj.write('some bytes')
171 fobj.close()
172
173 time.sleep(5)
174 t2 = time.time() - 3
175 f.touch()
176 t3 = time.time() + 3
177
178 assert t0 <= t1 < t2 <= t3 # sanity check
179
180 self.assert_(f.exists())
181 self.assert_(f.isfile())
182 self.assertEqual(f.size, 10)
183 self.assert_(t2 <= f.mtime <= t3)
184 if hasattr(os.path, 'getctime'):
185 ct2 = f.ctime
186 if os.name == 'nt':
187 # On Windows, "ctime" is CREATION time
188 self.assertEqual(ct, ct2)
189 self.assert_(ct2 < t2)
190 else:
191 # On other systems, it might be the CHANGE time
192 # (especially on Unix, time of inode changes)
193 self.failUnless(ct == ct2 or ct2 == f.mtime)
194 finally:
195 f.remove()
196
197 def testListing(self):
198 d = path(self.tempdir)
199 self.assertEqual(d.listdir(), [])
200
201 f = 'testfile.txt'
202 af = path(d, f)
203 self.assertEqual(af, os.path.join(d, f))
204 af.touch()
205 try:
206 self.assert_(af.exists())
207
208 self.assertEqual(d.listdir(), [af])
209
210 # .glob()
211 self.assertEqual(d.glob('testfile.txt'), [af])
212 self.assertEqual(d.glob('test*.txt'), [af])
213 self.assertEqual(d.glob('*.txt'), [af])
214 self.assertEqual(d.glob('*txt'), [af])
215 self.assertEqual(d.glob('*'), [af])
216 self.assertEqual(d.glob('*.html'), [])
217 self.assertEqual(d.glob('testfile'), [])
218 finally:
219 af.remove()
220
221 # Try a test with 20 files
222 files = [path(d, '%d.txt' % i) for i in range(20)]
223 for f in files:
224 fobj = file(f, 'w')
225 fobj.write('some text\n')
226 fobj.close()
227 try:
228 files2 = d.listdir()
229 files.sort()
230 files2.sort()
231 self.assertEqual(files, files2)
232 finally:
233 for f in files:
234 try:
235 f.remove()
236 except:
237 pass
238
239 def testMakeDirs(self):
240 d = path(self.tempdir)
241
242 # Placeholder file so that when removedirs() is called,
243 # it doesn't remove the temporary directory itself.
244 tempf = path(d, 'temp.txt')
245 tempf.touch()
246 try:
247 foo = path(d, 'foo')
248 boz = path(foo, 'bar', 'baz', 'boz')
249 boz.makedirs()
250 try:
251 self.assert_(boz.isdir())
252 finally:
253 boz.removedirs()
254 self.failIf(foo.exists())
255 self.assert_(d.exists())
256
257 foo.mkdir(0750)
258 boz.makedirs(0700)
259 try:
260 self.assert_(boz.isdir())
261 finally:
262 boz.removedirs()
263 self.failIf(foo.exists())
264 self.assert_(d.exists())
265 finally:
266 os.remove(tempf)
267
268 def assertSetsEqual(self, a, b):
269 ad = {}
270 for i in a: ad[i] = None
271 bd = {}
272 for i in b: bd[i] = None
273 self.assertEqual(ad, bd)
274
275 def testShutil(self):
276 # Note: This only tests the methods exist and do roughly what
277 # they should, neglecting the details as they are shutil's
278 # responsibility.
279
280 d = path(self.tempdir)
281 testDir = path(d, 'testdir')
282 testFile = path(testDir, 'testfile.txt')
283 testA = path(testDir, 'A')
284 testCopy = path(testA, 'testcopy.txt')
285 testLink = path(testA, 'testlink.txt')
286 testB = path(testDir, 'B')
287 testC = path(testB, 'C')
288 testCopyOfLink = path(testC, testA.relpathto(testLink))
289
290 # Create test dirs and a file
291 testDir.mkdir()
292 testA.mkdir()
293 testB.mkdir()
294
295 f = open(testFile, 'w')
296 f.write('x' * 10000)
297 f.close()
298
299 # Test simple file copying.
300 testFile.copyfile(testCopy)
301 self.assert_(testCopy.isfile())
302
303 # Test copying into a directory.
304 testCopy2 = path(testA, testFile.name)
305 testFile.copy(testA)
306 self.assert_(testCopy2.isfile())
307
308 # Make a link for the next test to use.
309 if hasattr(os, 'symlink'):
310 testFile.symlink(testLink)
311 else:
312 testFile.copy(testLink) # fallback
313
314 # Test copying directory tree.
315 testA.copytree(testC)
316 self.assert_(testC.isdir())
317 self.assertSetsEqual(
318 testC.listdir(),
319 [path(testC, testCopy.name),
320 path(testC, testFile.name),
321 testCopyOfLink])
322 self.assert_(not testCopyOfLink.islink())
323
324 # Clean up for another try.
325 testC.rmtree()
326 self.assert_(not testC.exists())
327
328 # Copy again, preserving symlinks.
329 testA.copytree(testC, True)
330 self.assert_(testC.isdir())
331 self.assertSetsEqual(
332 testC.listdir(),
333 [path(testC, testCopy.name),
334 path(testC, testFile.name),
335 testCopyOfLink])
336 if hasattr(os, 'symlink'):
337 self.assert_(testCopyOfLink.islink())
338 self.assert_(testCopyOfLink.readlink() == testFile)
339
340 # Clean up.
341 testDir.rmtree()
342 self.assert_(not testDir.exists())
343 self.assertList(d.listdir(), [])
344
345 def assertList(self, listing, expected):
346 listing = list(listing)
347 listing.sort()
348 expected = list(expected)
349 expected.sort()
350 self.assertEqual(listing, expected)
351
352 def testPatterns(self):
353 d = path(self.tempdir)
354 names = [ 'x.tmp', 'x.xtmp', 'x2g', 'x22', 'x.txt' ]
355 dirs = [d, path(d, 'xdir'), path(d, 'xdir.tmp'),
356 path(d, 'xdir.tmp', 'xsubdir')]
357
358 for e in dirs:
359 if not e.isdir():
360 e.makedirs()
361 for name in names:
362 path(e, name).touch()
363 self.assertList(d.listdir('*.tmp'), [path(d, 'x.tmp'),
364 path(d, 'xdir.tmp')])
365 self.assertList(d.files('*.tmp'), [path(d, 'x.tmp')])
366 self.assertList(d.dirs('*.tmp'), [path(d, 'xdir.tmp')])
367 self.assertList(d.walk(),
368 [e for e in dirs if e != d] +
369 [path(e, n) for e in dirs for n in names])
370 self.assertList(d.walk('*.tmp'),
371 [path(e, 'x.tmp') for e in dirs] +
372 [path(d, 'xdir.tmp')])
373 self.assertList(d.walkfiles('*.tmp'),
374 [path(e, 'x.tmp') for e in dirs])
375 self.assertList(d.walkdirs('*.tmp'), [path(d, 'xdir.tmp')])
376
377 self.assert_(path("/foobar/file.png").match("*.png"))
378 self.assert_(not path("/foobar/FILE.PNG").matchcase("*.png"))
379
380
381
382 if __name__ == '__main__':
383 if __version__ != path_version:
384 print ("Version mismatch: test_path.py version %s, path version %s" %
385 (__version__, path_version))
386 unittest.main()