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