ยปCore Development>Code coverage>Lib/test/test_genericpath.py

Python code coverage for Lib/test/test_genericpath.py

#countcontent
1n/a"""
2n/aTests common to genericpath, macpath, ntpath and posixpath
3n/a"""
4n/a
5n/aimport genericpath
6n/aimport os
7n/aimport sys
8n/aimport unittest
9n/aimport warnings
10n/afrom test import support
11n/aandroid_not_root = support.android_not_root
12n/a
13n/a
14n/adef create_file(filename, data=b'foo'):
15n/a with open(filename, 'xb', 0) as fp:
16n/a fp.write(data)
17n/a
18n/a
19n/aclass GenericTest:
20n/a common_attributes = ['commonprefix', 'getsize', 'getatime', 'getctime',
21n/a 'getmtime', 'exists', 'isdir', 'isfile']
22n/a attributes = []
23n/a
24n/a def test_no_argument(self):
25n/a for attr in self.common_attributes + self.attributes:
26n/a with self.assertRaises(TypeError):
27n/a getattr(self.pathmodule, attr)()
28n/a raise self.fail("{}.{}() did not raise a TypeError"
29n/a .format(self.pathmodule.__name__, attr))
30n/a
31n/a def test_commonprefix(self):
32n/a commonprefix = self.pathmodule.commonprefix
33n/a self.assertEqual(
34n/a commonprefix([]),
35n/a ""
36n/a )
37n/a self.assertEqual(
38n/a commonprefix(["/home/swenson/spam", "/home/swen/spam"]),
39n/a "/home/swen"
40n/a )
41n/a self.assertEqual(
42n/a commonprefix(["/home/swen/spam", "/home/swen/eggs"]),
43n/a "/home/swen/"
44n/a )
45n/a self.assertEqual(
46n/a commonprefix(["/home/swen/spam", "/home/swen/spam"]),
47n/a "/home/swen/spam"
48n/a )
49n/a self.assertEqual(
50n/a commonprefix(["home:swenson:spam", "home:swen:spam"]),
51n/a "home:swen"
52n/a )
53n/a self.assertEqual(
54n/a commonprefix([":home:swen:spam", ":home:swen:eggs"]),
55n/a ":home:swen:"
56n/a )
57n/a self.assertEqual(
58n/a commonprefix([":home:swen:spam", ":home:swen:spam"]),
59n/a ":home:swen:spam"
60n/a )
61n/a
62n/a self.assertEqual(
63n/a commonprefix([b"/home/swenson/spam", b"/home/swen/spam"]),
64n/a b"/home/swen"
65n/a )
66n/a self.assertEqual(
67n/a commonprefix([b"/home/swen/spam", b"/home/swen/eggs"]),
68n/a b"/home/swen/"
69n/a )
70n/a self.assertEqual(
71n/a commonprefix([b"/home/swen/spam", b"/home/swen/spam"]),
72n/a b"/home/swen/spam"
73n/a )
74n/a self.assertEqual(
75n/a commonprefix([b"home:swenson:spam", b"home:swen:spam"]),
76n/a b"home:swen"
77n/a )
78n/a self.assertEqual(
79n/a commonprefix([b":home:swen:spam", b":home:swen:eggs"]),
80n/a b":home:swen:"
81n/a )
82n/a self.assertEqual(
83n/a commonprefix([b":home:swen:spam", b":home:swen:spam"]),
84n/a b":home:swen:spam"
85n/a )
86n/a
87n/a testlist = ['', 'abc', 'Xbcd', 'Xb', 'XY', 'abcd',
88n/a 'aXc', 'abd', 'ab', 'aX', 'abcX']
89n/a for s1 in testlist:
90n/a for s2 in testlist:
91n/a p = commonprefix([s1, s2])
92n/a self.assertTrue(s1.startswith(p))
93n/a self.assertTrue(s2.startswith(p))
94n/a if s1 != s2:
95n/a n = len(p)
96n/a self.assertNotEqual(s1[n:n+1], s2[n:n+1])
97n/a
98n/a def test_getsize(self):
99n/a filename = support.TESTFN
100n/a self.addCleanup(support.unlink, filename)
101n/a
102n/a create_file(filename, b'Hello')
103n/a self.assertEqual(self.pathmodule.getsize(filename), 5)
104n/a os.remove(filename)
105n/a
106n/a create_file(filename, b'Hello World!')
107n/a self.assertEqual(self.pathmodule.getsize(filename), 12)
108n/a
109n/a def test_filetime(self):
110n/a filename = support.TESTFN
111n/a self.addCleanup(support.unlink, filename)
112n/a
113n/a create_file(filename, b'foo')
114n/a
115n/a with open(filename, "ab", 0) as f:
116n/a f.write(b"bar")
117n/a
118n/a with open(filename, "rb", 0) as f:
119n/a data = f.read()
120n/a self.assertEqual(data, b"foobar")
121n/a
122n/a self.assertLessEqual(
123n/a self.pathmodule.getctime(filename),
124n/a self.pathmodule.getmtime(filename)
125n/a )
126n/a
127n/a def test_exists(self):
128n/a filename = support.TESTFN
129n/a self.addCleanup(support.unlink, filename)
130n/a
131n/a self.assertIs(self.pathmodule.exists(filename), False)
132n/a
133n/a with open(filename, "xb") as f:
134n/a f.write(b"foo")
135n/a
136n/a self.assertIs(self.pathmodule.exists(filename), True)
137n/a
138n/a if not self.pathmodule == genericpath:
139n/a self.assertIs(self.pathmodule.lexists(filename), True)
140n/a
141n/a @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
142n/a def test_exists_fd(self):
143n/a r, w = os.pipe()
144n/a try:
145n/a self.assertTrue(self.pathmodule.exists(r))
146n/a finally:
147n/a os.close(r)
148n/a os.close(w)
149n/a self.assertFalse(self.pathmodule.exists(r))
150n/a
151n/a def test_isdir_file(self):
152n/a filename = support.TESTFN
153n/a self.addCleanup(support.unlink, filename)
154n/a self.assertIs(self.pathmodule.isdir(filename), False)
155n/a
156n/a create_file(filename)
157n/a self.assertIs(self.pathmodule.isdir(filename), False)
158n/a
159n/a def test_isdir_dir(self):
160n/a filename = support.TESTFN
161n/a self.addCleanup(support.rmdir, filename)
162n/a self.assertIs(self.pathmodule.isdir(filename), False)
163n/a
164n/a os.mkdir(filename)
165n/a self.assertIs(self.pathmodule.isdir(filename), True)
166n/a
167n/a def test_isfile_file(self):
168n/a filename = support.TESTFN
169n/a self.addCleanup(support.unlink, filename)
170n/a self.assertIs(self.pathmodule.isfile(filename), False)
171n/a
172n/a create_file(filename)
173n/a self.assertIs(self.pathmodule.isfile(filename), True)
174n/a
175n/a def test_isfile_dir(self):
176n/a filename = support.TESTFN
177n/a self.addCleanup(support.rmdir, filename)
178n/a self.assertIs(self.pathmodule.isfile(filename), False)
179n/a
180n/a os.mkdir(filename)
181n/a self.assertIs(self.pathmodule.isfile(filename), False)
182n/a
183n/a def test_samefile(self):
184n/a file1 = support.TESTFN
185n/a file2 = support.TESTFN + "2"
186n/a self.addCleanup(support.unlink, file1)
187n/a self.addCleanup(support.unlink, file2)
188n/a
189n/a create_file(file1)
190n/a self.assertTrue(self.pathmodule.samefile(file1, file1))
191n/a
192n/a create_file(file2)
193n/a self.assertFalse(self.pathmodule.samefile(file1, file2))
194n/a
195n/a self.assertRaises(TypeError, self.pathmodule.samefile)
196n/a
197n/a def _test_samefile_on_link_func(self, func):
198n/a test_fn1 = support.TESTFN
199n/a test_fn2 = support.TESTFN + "2"
200n/a self.addCleanup(support.unlink, test_fn1)
201n/a self.addCleanup(support.unlink, test_fn2)
202n/a
203n/a create_file(test_fn1)
204n/a
205n/a func(test_fn1, test_fn2)
206n/a self.assertTrue(self.pathmodule.samefile(test_fn1, test_fn2))
207n/a os.remove(test_fn2)
208n/a
209n/a create_file(test_fn2)
210n/a self.assertFalse(self.pathmodule.samefile(test_fn1, test_fn2))
211n/a
212n/a @support.skip_unless_symlink
213n/a def test_samefile_on_symlink(self):
214n/a self._test_samefile_on_link_func(os.symlink)
215n/a
216n/a @unittest.skipIf(android_not_root, "hard links not allowed, non root user")
217n/a def test_samefile_on_link(self):
218n/a self._test_samefile_on_link_func(os.link)
219n/a
220n/a def test_samestat(self):
221n/a test_fn1 = support.TESTFN
222n/a test_fn2 = support.TESTFN + "2"
223n/a self.addCleanup(support.unlink, test_fn1)
224n/a self.addCleanup(support.unlink, test_fn2)
225n/a
226n/a create_file(test_fn1)
227n/a stat1 = os.stat(test_fn1)
228n/a self.assertTrue(self.pathmodule.samestat(stat1, os.stat(test_fn1)))
229n/a
230n/a create_file(test_fn2)
231n/a stat2 = os.stat(test_fn2)
232n/a self.assertFalse(self.pathmodule.samestat(stat1, stat2))
233n/a
234n/a self.assertRaises(TypeError, self.pathmodule.samestat)
235n/a
236n/a def _test_samestat_on_link_func(self, func):
237n/a test_fn1 = support.TESTFN + "1"
238n/a test_fn2 = support.TESTFN + "2"
239n/a self.addCleanup(support.unlink, test_fn1)
240n/a self.addCleanup(support.unlink, test_fn2)
241n/a
242n/a create_file(test_fn1)
243n/a func(test_fn1, test_fn2)
244n/a self.assertTrue(self.pathmodule.samestat(os.stat(test_fn1),
245n/a os.stat(test_fn2)))
246n/a os.remove(test_fn2)
247n/a
248n/a create_file(test_fn2)
249n/a self.assertFalse(self.pathmodule.samestat(os.stat(test_fn1),
250n/a os.stat(test_fn2)))
251n/a
252n/a @support.skip_unless_symlink
253n/a def test_samestat_on_symlink(self):
254n/a self._test_samestat_on_link_func(os.symlink)
255n/a
256n/a @unittest.skipIf(android_not_root, "hard links not allowed, non root user")
257n/a def test_samestat_on_link(self):
258n/a self._test_samestat_on_link_func(os.link)
259n/a
260n/a def test_sameopenfile(self):
261n/a filename = support.TESTFN
262n/a self.addCleanup(support.unlink, filename)
263n/a create_file(filename)
264n/a
265n/a with open(filename, "rb", 0) as fp1:
266n/a fd1 = fp1.fileno()
267n/a with open(filename, "rb", 0) as fp2:
268n/a fd2 = fp2.fileno()
269n/a self.assertTrue(self.pathmodule.sameopenfile(fd1, fd2))
270n/a
271n/a
272n/aclass TestGenericTest(GenericTest, unittest.TestCase):
273n/a # Issue 16852: GenericTest can't inherit from unittest.TestCase
274n/a # for test discovery purposes; CommonTest inherits from GenericTest
275n/a # and is only meant to be inherited by others.
276n/a pathmodule = genericpath
277n/a
278n/a def test_null_bytes(self):
279n/a for attr in GenericTest.common_attributes:
280n/a # os.path.commonprefix doesn't raise ValueError
281n/a if attr == 'commonprefix':
282n/a continue
283n/a with self.subTest(attr=attr):
284n/a with self.assertRaises(ValueError) as cm:
285n/a getattr(self.pathmodule, attr)('/tmp\x00abcds')
286n/a self.assertIn('embedded null', str(cm.exception))
287n/a
288n/a# Following TestCase is not supposed to be run from test_genericpath.
289n/a# It is inherited by other test modules (macpath, ntpath, posixpath).
290n/a
291n/aclass CommonTest(GenericTest):
292n/a common_attributes = GenericTest.common_attributes + [
293n/a # Properties
294n/a 'curdir', 'pardir', 'extsep', 'sep',
295n/a 'pathsep', 'defpath', 'altsep', 'devnull',
296n/a # Methods
297n/a 'normcase', 'splitdrive', 'expandvars', 'normpath', 'abspath',
298n/a 'join', 'split', 'splitext', 'isabs', 'basename', 'dirname',
299n/a 'lexists', 'islink', 'ismount', 'expanduser', 'normpath', 'realpath',
300n/a ]
301n/a
302n/a def test_normcase(self):
303n/a normcase = self.pathmodule.normcase
304n/a # check that normcase() is idempotent
305n/a for p in ["FoO/./BaR", b"FoO/./BaR"]:
306n/a p = normcase(p)
307n/a self.assertEqual(p, normcase(p))
308n/a
309n/a self.assertEqual(normcase(''), '')
310n/a self.assertEqual(normcase(b''), b'')
311n/a
312n/a # check that normcase raises a TypeError for invalid types
313n/a for path in (None, True, 0, 2.5, [], bytearray(b''), {'o','o'}):
314n/a self.assertRaises(TypeError, normcase, path)
315n/a
316n/a def test_splitdrive(self):
317n/a # splitdrive for non-NT paths
318n/a splitdrive = self.pathmodule.splitdrive
319n/a self.assertEqual(splitdrive("/foo/bar"), ("", "/foo/bar"))
320n/a self.assertEqual(splitdrive("foo:bar"), ("", "foo:bar"))
321n/a self.assertEqual(splitdrive(":foo:bar"), ("", ":foo:bar"))
322n/a
323n/a self.assertEqual(splitdrive(b"/foo/bar"), (b"", b"/foo/bar"))
324n/a self.assertEqual(splitdrive(b"foo:bar"), (b"", b"foo:bar"))
325n/a self.assertEqual(splitdrive(b":foo:bar"), (b"", b":foo:bar"))
326n/a
327n/a def test_expandvars(self):
328n/a if self.pathmodule.__name__ == 'macpath':
329n/a self.skipTest('macpath.expandvars is a stub')
330n/a expandvars = self.pathmodule.expandvars
331n/a with support.EnvironmentVarGuard() as env:
332n/a env.clear()
333n/a env["foo"] = "bar"
334n/a env["{foo"] = "baz1"
335n/a env["{foo}"] = "baz2"
336n/a self.assertEqual(expandvars("foo"), "foo")
337n/a self.assertEqual(expandvars("$foo bar"), "bar bar")
338n/a self.assertEqual(expandvars("${foo}bar"), "barbar")
339n/a self.assertEqual(expandvars("$[foo]bar"), "$[foo]bar")
340n/a self.assertEqual(expandvars("$bar bar"), "$bar bar")
341n/a self.assertEqual(expandvars("$?bar"), "$?bar")
342n/a self.assertEqual(expandvars("$foo}bar"), "bar}bar")
343n/a self.assertEqual(expandvars("${foo"), "${foo")
344n/a self.assertEqual(expandvars("${{foo}}"), "baz1}")
345n/a self.assertEqual(expandvars("$foo$foo"), "barbar")
346n/a self.assertEqual(expandvars("$bar$bar"), "$bar$bar")
347n/a
348n/a self.assertEqual(expandvars(b"foo"), b"foo")
349n/a self.assertEqual(expandvars(b"$foo bar"), b"bar bar")
350n/a self.assertEqual(expandvars(b"${foo}bar"), b"barbar")
351n/a self.assertEqual(expandvars(b"$[foo]bar"), b"$[foo]bar")
352n/a self.assertEqual(expandvars(b"$bar bar"), b"$bar bar")
353n/a self.assertEqual(expandvars(b"$?bar"), b"$?bar")
354n/a self.assertEqual(expandvars(b"$foo}bar"), b"bar}bar")
355n/a self.assertEqual(expandvars(b"${foo"), b"${foo")
356n/a self.assertEqual(expandvars(b"${{foo}}"), b"baz1}")
357n/a self.assertEqual(expandvars(b"$foo$foo"), b"barbar")
358n/a self.assertEqual(expandvars(b"$bar$bar"), b"$bar$bar")
359n/a
360n/a @unittest.skipUnless(support.FS_NONASCII, 'need support.FS_NONASCII')
361n/a def test_expandvars_nonascii(self):
362n/a if self.pathmodule.__name__ == 'macpath':
363n/a self.skipTest('macpath.expandvars is a stub')
364n/a expandvars = self.pathmodule.expandvars
365n/a def check(value, expected):
366n/a self.assertEqual(expandvars(value), expected)
367n/a with support.EnvironmentVarGuard() as env:
368n/a env.clear()
369n/a nonascii = support.FS_NONASCII
370n/a env['spam'] = nonascii
371n/a env[nonascii] = 'ham' + nonascii
372n/a check(nonascii, nonascii)
373n/a check('$spam bar', '%s bar' % nonascii)
374n/a check('${spam}bar', '%sbar' % nonascii)
375n/a check('${%s}bar' % nonascii, 'ham%sbar' % nonascii)
376n/a check('$bar%s bar' % nonascii, '$bar%s bar' % nonascii)
377n/a check('$spam}bar', '%s}bar' % nonascii)
378n/a
379n/a check(os.fsencode(nonascii), os.fsencode(nonascii))
380n/a check(b'$spam bar', os.fsencode('%s bar' % nonascii))
381n/a check(b'${spam}bar', os.fsencode('%sbar' % nonascii))
382n/a check(os.fsencode('${%s}bar' % nonascii),
383n/a os.fsencode('ham%sbar' % nonascii))
384n/a check(os.fsencode('$bar%s bar' % nonascii),
385n/a os.fsencode('$bar%s bar' % nonascii))
386n/a check(b'$spam}bar', os.fsencode('%s}bar' % nonascii))
387n/a
388n/a def test_abspath(self):
389n/a self.assertIn("foo", self.pathmodule.abspath("foo"))
390n/a with warnings.catch_warnings():
391n/a warnings.simplefilter("ignore", DeprecationWarning)
392n/a self.assertIn(b"foo", self.pathmodule.abspath(b"foo"))
393n/a
394n/a # avoid UnicodeDecodeError on Windows
395n/a undecodable_path = b'' if sys.platform == 'win32' else b'f\xf2\xf2'
396n/a
397n/a # Abspath returns bytes when the arg is bytes
398n/a with warnings.catch_warnings():
399n/a warnings.simplefilter("ignore", DeprecationWarning)
400n/a for path in (b'', b'foo', undecodable_path, b'/foo', b'C:\\'):
401n/a self.assertIsInstance(self.pathmodule.abspath(path), bytes)
402n/a
403n/a def test_realpath(self):
404n/a self.assertIn("foo", self.pathmodule.realpath("foo"))
405n/a with warnings.catch_warnings():
406n/a warnings.simplefilter("ignore", DeprecationWarning)
407n/a self.assertIn(b"foo", self.pathmodule.realpath(b"foo"))
408n/a
409n/a def test_normpath_issue5827(self):
410n/a # Make sure normpath preserves unicode
411n/a for path in ('', '.', '/', '\\', '///foo/.//bar//'):
412n/a self.assertIsInstance(self.pathmodule.normpath(path), str)
413n/a
414n/a def test_abspath_issue3426(self):
415n/a # Check that abspath returns unicode when the arg is unicode
416n/a # with both ASCII and non-ASCII cwds.
417n/a abspath = self.pathmodule.abspath
418n/a for path in ('', 'fuu', 'f\xf9\xf9', '/fuu', 'U:\\'):
419n/a self.assertIsInstance(abspath(path), str)
420n/a
421n/a unicwd = '\xe7w\xf0'
422n/a try:
423n/a os.fsencode(unicwd)
424n/a except (AttributeError, UnicodeEncodeError):
425n/a # FS encoding is probably ASCII
426n/a pass
427n/a else:
428n/a with support.temp_cwd(unicwd):
429n/a for path in ('', 'fuu', 'f\xf9\xf9', '/fuu', 'U:\\'):
430n/a self.assertIsInstance(abspath(path), str)
431n/a
432n/a def test_nonascii_abspath(self):
433n/a if (support.TESTFN_UNDECODABLE
434n/a # Mac OS X denies the creation of a directory with an invalid
435n/a # UTF-8 name. Windows allows creating a directory with an
436n/a # arbitrary bytes name, but fails to enter this directory
437n/a # (when the bytes name is used).
438n/a and sys.platform not in ('win32', 'darwin')):
439n/a name = support.TESTFN_UNDECODABLE
440n/a elif support.TESTFN_NONASCII:
441n/a name = support.TESTFN_NONASCII
442n/a else:
443n/a self.skipTest("need support.TESTFN_NONASCII")
444n/a
445n/a with warnings.catch_warnings():
446n/a warnings.simplefilter("ignore", DeprecationWarning)
447n/a with support.temp_cwd(name):
448n/a self.test_abspath()
449n/a
450n/a def test_join_errors(self):
451n/a # Check join() raises friendly TypeErrors.
452n/a with support.check_warnings(('', BytesWarning), quiet=True):
453n/a errmsg = "Can't mix strings and bytes in path components"
454n/a with self.assertRaisesRegex(TypeError, errmsg):
455n/a self.pathmodule.join(b'bytes', 'str')
456n/a with self.assertRaisesRegex(TypeError, errmsg):
457n/a self.pathmodule.join('str', b'bytes')
458n/a # regression, see #15377
459n/a with self.assertRaisesRegex(TypeError, 'int'):
460n/a self.pathmodule.join(42, 'str')
461n/a with self.assertRaisesRegex(TypeError, 'int'):
462n/a self.pathmodule.join('str', 42)
463n/a with self.assertRaisesRegex(TypeError, 'int'):
464n/a self.pathmodule.join(42)
465n/a with self.assertRaisesRegex(TypeError, 'list'):
466n/a self.pathmodule.join([])
467n/a with self.assertRaisesRegex(TypeError, 'bytearray'):
468n/a self.pathmodule.join(bytearray(b'foo'), bytearray(b'bar'))
469n/a
470n/a def test_relpath_errors(self):
471n/a # Check relpath() raises friendly TypeErrors.
472n/a with support.check_warnings(('', (BytesWarning, DeprecationWarning)),
473n/a quiet=True):
474n/a errmsg = "Can't mix strings and bytes in path components"
475n/a with self.assertRaisesRegex(TypeError, errmsg):
476n/a self.pathmodule.relpath(b'bytes', 'str')
477n/a with self.assertRaisesRegex(TypeError, errmsg):
478n/a self.pathmodule.relpath('str', b'bytes')
479n/a with self.assertRaisesRegex(TypeError, 'int'):
480n/a self.pathmodule.relpath(42, 'str')
481n/a with self.assertRaisesRegex(TypeError, 'int'):
482n/a self.pathmodule.relpath('str', 42)
483n/a with self.assertRaisesRegex(TypeError, 'bytearray'):
484n/a self.pathmodule.relpath(bytearray(b'foo'), bytearray(b'bar'))
485n/a
486n/a
487n/aclass PathLikeTests(unittest.TestCase):
488n/a
489n/a class PathLike:
490n/a def __init__(self, path=''):
491n/a self.path = path
492n/a def __fspath__(self):
493n/a if isinstance(self.path, BaseException):
494n/a raise self.path
495n/a else:
496n/a return self.path
497n/a
498n/a def setUp(self):
499n/a self.file_name = support.TESTFN.lower()
500n/a self.file_path = self.PathLike(support.TESTFN)
501n/a self.addCleanup(support.unlink, self.file_name)
502n/a create_file(self.file_name, b"test_genericpath.PathLikeTests")
503n/a
504n/a def assertPathEqual(self, func):
505n/a self.assertEqual(func(self.file_path), func(self.file_name))
506n/a
507n/a def test_path_exists(self):
508n/a self.assertPathEqual(os.path.exists)
509n/a
510n/a def test_path_isfile(self):
511n/a self.assertPathEqual(os.path.isfile)
512n/a
513n/a def test_path_isdir(self):
514n/a self.assertPathEqual(os.path.isdir)
515n/a
516n/a def test_path_commonprefix(self):
517n/a self.assertEqual(os.path.commonprefix([self.file_path, self.file_name]),
518n/a self.file_name)
519n/a
520n/a def test_path_getsize(self):
521n/a self.assertPathEqual(os.path.getsize)
522n/a
523n/a def test_path_getmtime(self):
524n/a self.assertPathEqual(os.path.getatime)
525n/a
526n/a def test_path_getctime(self):
527n/a self.assertPathEqual(os.path.getctime)
528n/a
529n/a def test_path_samefile(self):
530n/a self.assertTrue(os.path.samefile(self.file_path, self.file_name))
531n/a
532n/a
533n/aif __name__=="__main__":
534n/a unittest.main()