1"""Test cases for the fnmatch module."""
2
3import unittest
4
5from fnmatch import fnmatch, fnmatchcase, translate, filter
6
7class FnmatchTestCase(unittest.TestCase):
8
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
19    def test_fnmatch(self):
20        check = self.check_match
21        check('abc', 'abc')
22        check('abc', '?*?')
23        check('abc', '???*')
24        check('abc', '*???')
25        check('abc', '???')
26        check('abc', '*')
27        check('abc', 'ab[cd]')
28        check('abc', 'ab[!de]')
29        check('abc', 'ab[de]', 0)
30        check('a', '??', 0)
31        check('a', 'b', 0)
32
33        # these test that '\' is handled correctly in character sets;
34        # see SF bug #409651
35        check('\\', r'[\]')
36        check('a', r'[!\]')
37        check('\\', r'[!\]', 0)
38
39        # test that filenames with newlines in them are handled correctly.
40        # http://bugs.python.org/issue6665
41        check('foo\nbar', 'foo*')
42        check('foo\nbar\n', 'foo*')
43        check('\nfoo', 'foo*', False)
44        check('\n', '*')
45
46    def test_mix_bytes_str(self):
47        self.assertRaises(TypeError, fnmatch, 'test', b'*')
48        self.assertRaises(TypeError, fnmatch, b'test', '*')
49        self.assertRaises(TypeError, fnmatchcase, 'test', b'*')
50        self.assertRaises(TypeError, fnmatchcase, b'test', '*')
51
52    def test_fnmatchcase(self):
53        check = self.check_match
54        check('AbC', 'abc', 0, fnmatchcase)
55        check('abc', 'AbC', 0, fnmatchcase)
56
57    def test_bytes(self):
58        self.check_match(b'test', b'te*')
59        self.check_match(b'test\xff', b'te*\xff')
60        self.check_match(b'foo\nbar', b'foo*')
61
62class TranslateTestCase(unittest.TestCase):
63
64    def test_translate(self):
65        self.assertEqual(translate('*'), r'(?s:.*)\Z')
66        self.assertEqual(translate('?'), r'(?s:.)\Z')
67        self.assertEqual(translate('a?b*'), r'(?s:a.b.*)\Z')
68        self.assertEqual(translate('[abc]'), r'(?s:[abc])\Z')
69        self.assertEqual(translate('[]]'), r'(?s:[]])\Z')
70        self.assertEqual(translate('[!x]'), r'(?s:[^x])\Z')
71        self.assertEqual(translate('[^x]'), r'(?s:[\^x])\Z')
72        self.assertEqual(translate('[x'), r'(?s:\[x)\Z')
73
74
75class FilterTestCase(unittest.TestCase):
76
77    def test_filter(self):
78        self.assertEqual(filter(['a', 'b'], 'a'), ['a'])
79
80
81if __name__ == "__main__":
82    unittest.main()
83