1 | #!/usr/bin/env python
|
2 | # Copyright 2016 Andy Chu. All rights reserved.
|
3 | # Licensed under the Apache License, Version 2.0 (the "License");
|
4 | # you may not use this file except in compliance with the License.
|
5 | # You may obtain a copy of the License at
|
6 | #
|
7 | # http://www.apache.org/licenses/LICENSE-2.0
|
8 | """
|
9 | libc_test.py: Tests for libc.py
|
10 | """
|
11 |
|
12 | import unittest
|
13 |
|
14 | import libc # module under test
|
15 |
|
16 |
|
17 | class LibcTest(unittest.TestCase):
|
18 |
|
19 | def testFnmatch(self):
|
20 | print(dir(libc))
|
21 | # pattern, string, result
|
22 |
|
23 | cases = [
|
24 | ('', '', 1), # no pattern is valid
|
25 | ('a', 'a', 1),
|
26 | ('?', 'a', 1),
|
27 | ('\?', 'a', 0),
|
28 | ('\?', '?', 1),
|
29 | ('\\\\', '\\', 1),
|
30 | # What is another error? Invalid escape is OK?
|
31 | ('\\', '\\', 0), # no pattern is valid
|
32 |
|
33 | ('[[:alpha:]]', 'a', 1),
|
34 | ('[^[:alpha:]]', 'a', 0), # negate
|
35 | ('[[:alpha:]]', 'aa', 0), # exact match fails
|
36 |
|
37 | # Combining char class and a literal character
|
38 | ('[[:alpha:]7]', '7', 1),
|
39 | ('[[:alpha:]][[:alpha:]]', 'az', 1),
|
40 | ]
|
41 |
|
42 | for pat, s, expected in cases:
|
43 | actual = libc.fnmatch(pat, s)
|
44 | self.assertEqual(expected, actual)
|
45 |
|
46 | def testGlob(self):
|
47 | print('GLOB')
|
48 | print(libc.glob('*.py'))
|
49 |
|
50 | # This will not match anything!
|
51 | print(libc.glob('\\'))
|
52 | # This one will match a file named \
|
53 | print(libc.glob('\\\\'))
|
54 |
|
55 | def testRegex(self):
|
56 | #print(libc.regcomp(r'.*\.py'))
|
57 | self.assertEqual(True, libc.regex_parse(r'.*\.py'))
|
58 | self.assertEqual(False, libc.regex_parse(r'*'))
|
59 | self.assertEqual(False, libc.regex_parse('\\'))
|
60 | self.assertEqual(False, libc.regex_parse('{'))
|
61 |
|
62 | cases = [
|
63 | (r'.*\.py', 'foo.py', True),
|
64 | (r'.*\.py', 'abcd', False),
|
65 | # The match is unanchored
|
66 | (r'bc', 'abcd', True),
|
67 | # The match is unanchored
|
68 | (r'.c', 'abcd', True),
|
69 | ]
|
70 |
|
71 | for pat, s, expected in cases:
|
72 | actual = libc.regex_match(pat, s)
|
73 | self.assertEqual(expected, actual)
|
74 |
|
75 | # Error.
|
76 | print(libc.regex_match(r'*', 'abcd'))
|
77 |
|
78 |
|
79 | def testRegexReplace(self):
|
80 | cases = [
|
81 | (r'.\.py', 'X', 'foo.py', False, 'foX'),
|
82 | (r'^\.py', 'X', 'foo.py', False, 'foo.py'), # Anchored left
|
83 | (r'foo$', 'X', 'foo.py', False, 'foo.py'), # Anchored Right
|
84 | (r'o', 'X', 'foo.py', False, 'fXo.py'), # replace all
|
85 | (r'o', 'X', 'foo.py', True, 'fXX.py'), # replace all
|
86 | ]
|
87 | return
|
88 | for pat, replace, s, do_all, expected in cases:
|
89 | actual = libc.regex_replace(pat, replace, s, do_all)
|
90 | self.assertEqual(expected, actual)
|
91 |
|
92 |
|
93 | if __name__ == '__main__':
|
94 | unittest.main()
|