blob: 015c580b61ff1a7128f923e8e51037199860a2b6 [file] [log] [blame]
Fred Drake91751142001-03-21 18:29:25 +00001"""Test cases for the fnmatch module."""
2
Barry Warsaw04f357c2002-07-23 19:04:11 +00003from test import test_support
Fred Drake91751142001-03-21 18:29:25 +00004import unittest
5
R. David Murraybda5f2b2010-07-09 13:29:33 +00006from fnmatch import fnmatch, fnmatchcase, _MAXCACHE, _cache
Fred Drake91751142001-03-21 18:29:25 +00007
8
9class FnmatchTestCase(unittest.TestCase):
Ezio Melotti4bd45852010-02-20 22:56:58 +000010 def check_match(self, filename, pattern, should_match=1, fn=fnmatch):
Fred Drake91751142001-03-21 18:29:25 +000011 if should_match:
Ezio Melotti4bd45852010-02-20 22:56:58 +000012 self.assertTrue(fn(filename, pattern),
13 "expected %r to match pattern %r"
14 % (filename, pattern))
Fred Drake91751142001-03-21 18:29:25 +000015 else:
Ezio Melotti4bd45852010-02-20 22:56:58 +000016 self.assertTrue(not fn(filename, pattern),
17 "expected %r not to match pattern %r"
18 % (filename, pattern))
Fred Drake91751142001-03-21 18:29:25 +000019
20 def test_fnmatch(self):
21 check = self.check_match
22 check('abc', 'abc')
23 check('abc', '?*?')
24 check('abc', '???*')
25 check('abc', '*???')
26 check('abc', '???')
27 check('abc', '*')
28 check('abc', 'ab[cd]')
29 check('abc', 'ab[!de]')
30 check('abc', 'ab[de]', 0)
31 check('a', '??', 0)
32 check('a', 'b', 0)
33
34 # these test that '\' is handled correctly in character sets;
Gregory P. Smith56629242009-11-01 20:33:31 +000035 # see SF bug #409651
Fred Drake91751142001-03-21 18:29:25 +000036 check('\\', r'[\]')
37 check('a', r'[!\]')
38 check('\\', r'[!\]', 0)
39
Gregory P. Smith56629242009-11-01 20:33:31 +000040 # test that filenames with newlines in them are handled correctly.
41 # http://bugs.python.org/issue6665
42 check('foo\nbar', 'foo*')
43 check('foo\nbar\n', 'foo*')
44 check('\nfoo', 'foo*', False)
45 check('\n', '*')
46
Georg Brandl9bbf8362010-02-07 13:02:10 +000047 def test_fnmatchcase(self):
48 check = self.check_match
Ezio Melotti4bd45852010-02-20 22:56:58 +000049 check('AbC', 'abc', 0, fnmatchcase)
50 check('abc', 'AbC', 0, fnmatchcase)
Georg Brandl9bbf8362010-02-07 13:02:10 +000051
R. David Murraybda5f2b2010-07-09 13:29:33 +000052 def test_cache_clearing(self):
53 # check that caches do not grow too large
54 # http://bugs.python.org/issue7846
55
56 # string pattern cache
57 for i in range(_MAXCACHE + 1):
58 fnmatch('foo', '?' * i)
59
60 self.assertTrue(len(_cache) <= _MAXCACHE)
Fred Drake91751142001-03-21 18:29:25 +000061
Fred Drake2e2be372001-09-20 21:33:42 +000062def test_main():
63 test_support.run_unittest(FnmatchTestCase)
64
65
66if __name__ == "__main__":
67 test_main()