Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(108)

Side by Side Diff: native_client_sdk/src/tools/quote.py

Issue 11571032: [NaCl SDK] cleanup python unittests (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Created 8 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 #!/usr/bin/env python
2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
5
6 import optparse
7 import re
8 import sys
9
10
11 verbose = False
12
13
14 def quote(input_str, specials, escape='\\'):
15 """Returns a quoted version of |str|, where every character in the
16 iterable |specials| (usually a set or a string) and the escape
17 character |escape| is replaced by the original character preceded by
18 the escape character."""
19
20 assert len(escape) == 1
21
22 # Since escape is used in replacement pattern context, so we need to
23 # ensure that it stays a simple literal and cannot affect the \1
24 # that will follow it.
25 if escape == '\\':
26 escape = '\\\\'
27 if len(specials) > 0:
28 return re.sub(r'(' + r'|'.join(specials)+r'|'+escape + r')',
29 escape + r'\1', input_str)
30 return re.sub(r'(' + escape + r')', escape + r'\1', input_str)
31
32
33 def unquote(input_str, specials, escape='\\'):
34 """Splits the input string |input_str| where special characters in
35 the input |specials| are, if not quoted by |escape|, used as
36 delimiters to split the string. The returned value is a list of
37 strings of alternating non-specials and specials used to break the
38 string. The list will always begin with a possibly empty string of
39 non-specials, but may end with either specials or non-specials."""
40
41 assert len(escape) == 1
42
43 out = []
44 cur_out = []
45 cur_special = False
46 lit_next = False
47 for c in input_str:
48 if cur_special:
49 lit_next = (c == escape)
50 if c not in specials or lit_next:
51 cur_special = False
52 out.append(''.join(cur_out))
53 if not lit_next:
54 cur_out = [c]
55 else:
56 cur_out = []
57 else:
58 cur_out.append(c)
59 else:
60 if lit_next:
61 cur_out.append(c)
62 lit_next = False
63 else:
64 lit_next = c == escape
65 if c not in specials:
66 if not lit_next:
67 cur_out.append(c)
68 else:
69 out.append(''.join(cur_out))
70 cur_out = [c]
71 cur_special = True
72 out.append(''.join(cur_out))
73 return out
74
75
76 # Test code
77
78 def VerboseQuote(in_string, specials, *args, **kwargs):
79 if verbose:
80 sys.stdout.write('Invoking quote(%s, %s, %s)\n' %
81 (repr(in_string), repr(specials),
82 ', '.join([repr(a) for a in args] +
83 [repr(k) + ':' + repr(v)
84 for k, v in kwargs])))
85 return quote(in_string, specials, *args, **kwargs)
86
87
88 def VerboseUnquote(in_string, specials, *args, **kwargs):
89 if verbose:
90 sys.stdout.write('Invoking unquote(%s, %s, %s)\n' %
91 (repr(in_string), repr(specials),
92 ', '.join([repr(a) for a in args] +
93 [repr(k) + ':' + repr(v)
94 for k, v in kwargs])))
95 return unquote(in_string, specials, *args, **kwargs)
96
97
98 def TestGeneric(fn, in_args, expected_out_obj):
99 sys.stdout.write('[ RUN ] %s(%s, %s)\n' %
100 (fn.func_name, repr(in_args), repr(expected_out_obj)))
101 actual = apply(fn, in_args)
102 if actual != expected_out_obj:
103 sys.stdout.write('[ ERROR ] expected %s, got %s\n' %
104 (str(expected_out_obj), str(actual)))
105 return 1
106 sys.stdout.write('[ OK ]\n')
107 return 0
108
109
110 def TestInvertible(in_string, specials, escape='\\'):
111 sys.stdout.write('[ RUN ] TestInvertible(%s, %s, %s)\n' %
112 (repr(in_string), repr(specials), repr(escape)))
113 q = VerboseQuote(in_string, specials, escape)
114 qq = VerboseUnquote(q, specials, escape)
115 if in_string != ''.join(qq):
116 sys.stdout.write(('[ ERROR ] TestInvertible(%s, %s, %s) failed, '
117 'expected %s, got %s\n') %
118 (repr(in_string), repr(specials), repr(escape),
119 repr(in_string), repr(''.join(qq))))
120 return 1
121 return 0
122
123
124 def RunAllTests():
125 test_tuples = [[VerboseQuote,
126 ['foo, bar, baz, and quux too!', 'abc'],
127 'foo, \\b\\ar, \\b\\az, \\and quux too!'],
128 [VerboseQuote,
129 ['when \\ appears in the input', 'a'],
130 'when \\\\ \\appe\\ars in the input'],
131 [VerboseUnquote,
132 ['key\\:still_key:value\\:more_value', ':'],
133 ['key:still_key', ':', 'value:more_value']],
134 [VerboseUnquote,
135 ['about that sep\\ar\\ator in the beginning', 'ab'],
136 ['', 'ab', 'out th', 'a', 't separator in the ',
137 'b', 'eginning']],
138 [VerboseUnquote,
139 ['the rain in spain fall\\s ma\\i\\nly on the plains', 'ins'],
140 ['the ra', 'in', ' ', 'in', ' ', 's', 'pa', 'in',
141 ' falls mainly o', 'n', ' the pla', 'ins']],
142 ]
143 num_errors = 0
144 for func, in_args, expected in test_tuples:
145 num_errors += TestGeneric(func, in_args, expected)
146 num_errors += TestInvertible('abcdefg', 'bc')
147 num_errors += TestInvertible('a\\bcdefg', 'bc')
148 num_errors += TestInvertible('ab\\cdefg', 'bc')
149 num_errors += TestInvertible('\\ab\\cdefg', 'abc')
150 num_errors += TestInvertible('abcde\\fg', 'efg')
151 num_errors += TestInvertible('a\\b', '')
152 return num_errors
153
154
155 # Invoke this file directly for simple testing.
156
157 def main(argv):
158 global verbose
159 parser = optparse.OptionParser(
160 usage='Usage: %prog [options] word...')
161 parser.add_option('-s', '--special-chars', dest='special_chars', default=':',
162 help='Special characters to quote (default is ":")')
163 parser.add_option('-q', '--quote', dest='quote', default='\\',
164 help='Quote or escape character (default is "\")')
165 parser.add_option('-t', '--run-tests', dest='tests', action='store_true',
166 help='Run built-in tests\n')
167 parser.add_option('-v', '--verbose', dest='verbose', action='store_true',
168 help='Verbose test output')
169 options, args = parser.parse_args(argv)
170
171 if options.verbose:
172 verbose = True
173
174 num_errors = 0
175 if options.tests:
176 num_errors = RunAllTests()
177 for word in args:
178 q = quote(word, options.special_chars, options.quote)
179 qq = unquote(q, options.special_chars, options.quote)
180 sys.stdout.write('quote(%s) = %s, unquote(%s) = %s\n'
181 % (word, q, q, ''.join(qq)))
182 if word != ''.join(qq):
183 num_errors += 1
184 if num_errors > 0:
185 sys.stderr.write('[ FAILED ] %d test failures\n' % num_errors)
186 return num_errors
187
188 if __name__ == '__main__':
189 sys.exit(main(sys.argv[1:]))
190
OLDNEW
« no previous file with comments | « native_client_sdk/src/tools/create_nmf.py ('k') | native_client_sdk/src/tools/tests/httpd_test.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698