test_fnmatch.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. """Test cases for the fnmatch module."""
  2. from test import test_support
  3. import unittest
  4. from fnmatch import fnmatch, fnmatchcase, _MAXCACHE, _cache
  5. from fnmatch import fnmatch, fnmatchcase, _MAXCACHE, _cache, _purge
  6. class FnmatchTestCase(unittest.TestCase):
  7. def tearDown(self):
  8. _purge()
  9. def check_match(self, filename, pattern, should_match=1, fn=fnmatch):
  10. if should_match:
  11. self.assertTrue(fn(filename, pattern),
  12. "expected %r to match pattern %r"
  13. % (filename, pattern))
  14. else:
  15. self.assertTrue(not fn(filename, pattern),
  16. "expected %r not to match pattern %r"
  17. % (filename, pattern))
  18. def test_fnmatch(self):
  19. check = self.check_match
  20. check('abc', 'abc')
  21. check('abc', '?*?')
  22. check('abc', '???*')
  23. check('abc', '*???')
  24. check('abc', '???')
  25. check('abc', '*')
  26. check('abc', 'ab[cd]')
  27. check('abc', 'ab[!de]')
  28. check('abc', 'ab[de]', 0)
  29. check('a', '??', 0)
  30. check('a', 'b', 0)
  31. # these test that '\' is handled correctly in character sets;
  32. # see SF bug #409651
  33. check('\\', r'[\]')
  34. check('a', r'[!\]')
  35. check('\\', r'[!\]', 0)
  36. # test that filenames with newlines in them are handled correctly.
  37. # http://bugs.python.org/issue6665
  38. check('foo\nbar', 'foo*')
  39. check('foo\nbar\n', 'foo*')
  40. check('\nfoo', 'foo*', False)
  41. check('\n', '*')
  42. def test_fnmatchcase(self):
  43. check = self.check_match
  44. check('AbC', 'abc', 0, fnmatchcase)
  45. check('abc', 'AbC', 0, fnmatchcase)
  46. def test_cache_clearing(self):
  47. # check that caches do not grow too large
  48. # http://bugs.python.org/issue7846
  49. # string pattern cache
  50. for i in range(_MAXCACHE + 1):
  51. fnmatch('foo', '?' * i)
  52. self.assertLessEqual(len(_cache), _MAXCACHE)
  53. def test_main():
  54. test_support.run_unittest(FnmatchTestCase)
  55. if __name__ == "__main__":
  56. test_main()