blob: 37ec50d71a52cddf8556e9fdfeb4e36870f83420 [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 Murrayabd45532010-07-09 13:16:00 +00006from fnmatch import fnmatch, fnmatchcase, _MAXCACHE, _cache
R. David Murray2ab02f02010-07-10 14:06:51 +00007from fnmatch import fnmatch, fnmatchcase, _MAXCACHE, _cache, _purge
Fred Drake91751142001-03-21 18:29:25 +00008
9
10class FnmatchTestCase(unittest.TestCase):
R. David Murray2ab02f02010-07-10 14:06:51 +000011
12 def tearDown(self):
13 _purge()
14
Georg Brandl6eedef62010-02-08 00:04:54 +000015 def check_match(self, filename, pattern, should_match=1, fn=fnmatch):
Fred Drake91751142001-03-21 18:29:25 +000016 if should_match:
Georg Brandl6eedef62010-02-08 00:04:54 +000017 self.assertTrue(fn(filename, pattern),
Fred Drake91751142001-03-21 18:29:25 +000018 "expected %r to match pattern %r"
19 % (filename, pattern))
20 else:
Georg Brandl6eedef62010-02-08 00:04:54 +000021 self.assertTrue(not fn(filename, pattern),
Fred Drake91751142001-03-21 18:29:25 +000022 "expected %r not to match pattern %r"
23 % (filename, pattern))
24
25 def test_fnmatch(self):
26 check = self.check_match
27 check('abc', 'abc')
28 check('abc', '?*?')
29 check('abc', '???*')
30 check('abc', '*???')
31 check('abc', '???')
32 check('abc', '*')
33 check('abc', 'ab[cd]')
34 check('abc', 'ab[!de]')
35 check('abc', 'ab[de]', 0)
36 check('a', '??', 0)
37 check('a', 'b', 0)
38
39 # these test that '\' is handled correctly in character sets;
Gregory P. Smithb98d6b22009-08-16 18:52:58 +000040 # see SF bug #409651
Fred Drake91751142001-03-21 18:29:25 +000041 check('\\', r'[\]')
42 check('a', r'[!\]')
43 check('\\', r'[!\]', 0)
44
Gregory P. Smithb98d6b22009-08-16 18:52:58 +000045 # test that filenames with newlines in them are handled correctly.
46 # http://bugs.python.org/issue6665
47 check('foo\nbar', 'foo*')
48 check('foo\nbar\n', 'foo*')
49 check('\nfoo', 'foo*', False)
50 check('\n', '*')
51
Georg Brandl308e18b2010-02-07 12:34:26 +000052 def test_fnmatchcase(self):
53 check = self.check_match
Georg Brandl6eedef62010-02-08 00:04:54 +000054 check('AbC', 'abc', 0, fnmatchcase)
55 check('abc', 'AbC', 0, fnmatchcase)
Georg Brandl308e18b2010-02-07 12:34:26 +000056
R. David Murrayabd45532010-07-09 13:16:00 +000057 def test_cache_clearing(self):
58 # check that caches do not grow too large
59 # http://bugs.python.org/issue7846
60
61 # string pattern cache
62 for i in range(_MAXCACHE + 1):
63 fnmatch('foo', '?' * i)
64
65 self.assertLessEqual(len(_cache), _MAXCACHE)
Fred Drake91751142001-03-21 18:29:25 +000066
Fred Drake2e2be372001-09-20 21:33:42 +000067def test_main():
68 test_support.run_unittest(FnmatchTestCase)
69
70
71if __name__ == "__main__":
72 test_main()