blob: a21ccd2fdf44a71b9c5643f678f6ca76952ae2b9 [file] [log] [blame]
Éric Araujo9bce3112011-07-27 18:29:31 +02001import io
Evan56624a92019-06-02 05:09:22 +10002import itertools
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +00003import shlex
Éric Araujo9bce3112011-07-27 18:29:31 +02004import string
5import unittest
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +00006
Neal Norwitzaa1ac542003-04-17 23:04:22 +00007
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +00008
9# The original test data set was from shellwords, by Hartmut Goebel.
10
11data = r"""x|x|
12foo bar|foo|bar|
13 foo bar|foo|bar|
14 foo bar |foo|bar|
15foo bar bla fasel|foo|bar|bla|fasel|
16x y z xxxx|x|y|z|xxxx|
17\x bar|\|x|bar|
18\ x bar|\|x|bar|
19\ bar|\|bar|
20foo \x bar|foo|\|x|bar|
21foo \ x bar|foo|\|x|bar|
22foo \ bar|foo|\|bar|
23foo "bar" bla|foo|"bar"|bla|
24"foo" "bar" "bla"|"foo"|"bar"|"bla"|
25"foo" bar "bla"|"foo"|bar|"bla"|
26"foo" bar bla|"foo"|bar|bla|
27foo 'bar' bla|foo|'bar'|bla|
28'foo' 'bar' 'bla'|'foo'|'bar'|'bla'|
29'foo' bar 'bla'|'foo'|bar|'bla'|
30'foo' bar bla|'foo'|bar|bla|
31blurb foo"bar"bar"fasel" baz|blurb|foo"bar"bar"fasel"|baz|
32blurb foo'bar'bar'fasel' baz|blurb|foo'bar'bar'fasel'|baz|
33""|""|
34''|''|
35foo "" bar|foo|""|bar|
36foo '' bar|foo|''|bar|
37foo "" "" "" bar|foo|""|""|""|bar|
38foo '' '' '' bar|foo|''|''|''|bar|
39\""|\|""|
40"\"|"\"|
41"foo\ bar"|"foo\ bar"|
42"foo\\ bar"|"foo\\ bar"|
43"foo\\ bar\"|"foo\\ bar\"|
44"foo\\" bar\""|"foo\\"|bar|\|""|
45"foo\\ bar\" dfadf"|"foo\\ bar\"|dfadf"|
46"foo\\\ bar\" dfadf"|"foo\\\ bar\"|dfadf"|
47"foo\\\x bar\" dfadf"|"foo\\\x bar\"|dfadf"|
48"foo\x bar\" dfadf"|"foo\x bar\"|dfadf"|
49\''|\|''|
50'foo\ bar'|'foo\ bar'|
51'foo\\ bar'|'foo\\ bar'|
52"foo\\\x bar\" df'a\ 'df'|"foo\\\x bar\"|df'a|\|'df'|
53\"foo"|\|"foo"|
54\"foo"\x|\|"foo"|\|x|
55"foo\x"|"foo\x"|
56"foo\ "|"foo\ "|
57foo\ xx|foo|\|xx|
58foo\ x\x|foo|\|x|\|x|
59foo\ x\x\""|foo|\|x|\|x|\|""|
60"foo\ x\x"|"foo\ x\x"|
61"foo\ x\x\\"|"foo\ x\x\\"|
62"foo\ x\x\\""foobar"|"foo\ x\x\\"|"foobar"|
63"foo\ x\x\\"\''"foobar"|"foo\ x\x\\"|\|''|"foobar"|
64"foo\ x\x\\"\'"fo'obar"|"foo\ x\x\\"|\|'"fo'|obar"|
65"foo\ x\x\\"\'"fo'obar" 'don'\''t'|"foo\ x\x\\"|\|'"fo'|obar"|'don'|\|''|t'|
66'foo\ bar'|'foo\ bar'|
67'foo\\ bar'|'foo\\ bar'|
68foo\ bar|foo|\|bar|
69foo#bar\nbaz|foobaz|
70:-) ;-)|:|-|)|;|-|)|
Antoine Pitroud72402e2010-10-27 18:52:48 +000071áéíóú|á|é|í|ó|ú|
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +000072"""
73
74posix_data = r"""x|x|
75foo bar|foo|bar|
76 foo bar|foo|bar|
77 foo bar |foo|bar|
78foo bar bla fasel|foo|bar|bla|fasel|
79x y z xxxx|x|y|z|xxxx|
80\x bar|x|bar|
81\ x bar| x|bar|
82\ bar| bar|
83foo \x bar|foo|x|bar|
84foo \ x bar|foo| x|bar|
85foo \ bar|foo| bar|
86foo "bar" bla|foo|bar|bla|
87"foo" "bar" "bla"|foo|bar|bla|
88"foo" bar "bla"|foo|bar|bla|
89"foo" bar bla|foo|bar|bla|
90foo 'bar' bla|foo|bar|bla|
91'foo' 'bar' 'bla'|foo|bar|bla|
92'foo' bar 'bla'|foo|bar|bla|
93'foo' bar bla|foo|bar|bla|
94blurb foo"bar"bar"fasel" baz|blurb|foobarbarfasel|baz|
95blurb foo'bar'bar'fasel' baz|blurb|foobarbarfasel|baz|
96""||
97''||
98foo "" bar|foo||bar|
99foo '' bar|foo||bar|
100foo "" "" "" bar|foo||||bar|
101foo '' '' '' bar|foo||||bar|
102\"|"|
103"\""|"|
104"foo\ bar"|foo\ bar|
105"foo\\ bar"|foo\ bar|
106"foo\\ bar\""|foo\ bar"|
107"foo\\" bar\"|foo\|bar"|
108"foo\\ bar\" dfadf"|foo\ bar" dfadf|
109"foo\\\ bar\" dfadf"|foo\\ bar" dfadf|
110"foo\\\x bar\" dfadf"|foo\\x bar" dfadf|
111"foo\x bar\" dfadf"|foo\x bar" dfadf|
112\'|'|
113'foo\ bar'|foo\ bar|
114'foo\\ bar'|foo\\ bar|
115"foo\\\x bar\" df'a\ 'df"|foo\\x bar" df'a\ 'df|
116\"foo|"foo|
117\"foo\x|"foox|
118"foo\x"|foo\x|
119"foo\ "|foo\ |
120foo\ xx|foo xx|
121foo\ x\x|foo xx|
122foo\ x\x\"|foo xx"|
123"foo\ x\x"|foo\ x\x|
124"foo\ x\x\\"|foo\ x\x\|
125"foo\ x\x\\""foobar"|foo\ x\x\foobar|
126"foo\ x\x\\"\'"foobar"|foo\ x\x\'foobar|
127"foo\ x\x\\"\'"fo'obar"|foo\ x\x\'fo'obar|
128"foo\ x\x\\"\'"fo'obar" 'don'\''t'|foo\ x\x\'fo'obar|don't|
129"foo\ x\x\\"\'"fo'obar" 'don'\''t' \\|foo\ x\x\'fo'obar|don't|\|
130'foo\ bar'|foo\ bar|
131'foo\\ bar'|foo\\ bar|
132foo\ bar|foo bar|
133foo#bar\nbaz|foo|baz|
134:-) ;-)|:-)|;-)|
Antoine Pitroud72402e2010-10-27 18:52:48 +0000135áéíóú|áéíóú|
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000136"""
137
138class ShlexTest(unittest.TestCase):
139 def setUp(self):
140 self.data = [x.split("|")[:-1]
141 for x in data.splitlines()]
142 self.posix_data = [x.split("|")[:-1]
143 for x in posix_data.splitlines()]
144 for item in self.data:
145 item[0] = item[0].replace(r"\n", "\n")
146 for item in self.posix_data:
147 item[0] = item[0].replace(r"\n", "\n")
148
Gustavo Niemeyer48f3dcc2003-04-20 01:57:03 +0000149 def splitTest(self, data, comments):
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000150 for i in range(len(data)):
Gustavo Niemeyer48f3dcc2003-04-20 01:57:03 +0000151 l = shlex.split(data[i][0], comments=comments)
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000152 self.assertEqual(l, data[i][1:],
153 "%s: %s != %s" %
154 (data[i][0], l, data[i][1:]))
155
156 def oldSplit(self, s):
157 ret = []
Walter Dörwald2c849f22007-06-12 17:43:43 +0000158 lex = shlex.shlex(io.StringIO(s))
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000159 tok = lex.get_token()
160 while tok:
161 ret.append(tok)
162 tok = lex.get_token()
163 return ret
Tim Peters0eadaac2003-04-24 16:02:54 +0000164
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000165 def testSplitPosix(self):
166 """Test data splitting with posix parser"""
Tim Peters0eadaac2003-04-24 16:02:54 +0000167 self.splitTest(self.posix_data, comments=True)
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000168
169 def testCompat(self):
170 """Test compatibility interface"""
171 for i in range(len(self.data)):
172 l = self.oldSplit(self.data[i][0])
173 self.assertEqual(l, self.data[i][1:],
174 "%s: %s != %s" %
175 (self.data[i][0], l, self.data[i][1:]))
176
Vinay Sajipc1f974c2016-07-29 22:35:03 +0100177 def testSyntaxSplitAmpersandAndPipe(self):
178 """Test handling of syntax splitting of &, |"""
179 # Could take these forms: &&, &, |&, ;&, ;;&
180 # of course, the same applies to | and ||
181 # these should all parse to the same output
182 for delimiter in ('&&', '&', '|&', ';&', ';;&',
183 '||', '|', '&|', ';|', ';;|'):
184 src = ['echo hi %s echo bye' % delimiter,
185 'echo hi%secho bye' % delimiter]
186 ref = ['echo', 'hi', delimiter, 'echo', 'bye']
Evan56624a92019-06-02 05:09:22 +1000187 for ss, ws in itertools.product(src, (False, True)):
Vinay Sajipc1f974c2016-07-29 22:35:03 +0100188 s = shlex.shlex(ss, punctuation_chars=True)
Evan56624a92019-06-02 05:09:22 +1000189 s.whitespace_split = ws
Vinay Sajipc1f974c2016-07-29 22:35:03 +0100190 result = list(s)
Evan56624a92019-06-02 05:09:22 +1000191 self.assertEqual(ref, result,
192 "While splitting '%s' [ws=%s]" % (ss, ws))
Vinay Sajipc1f974c2016-07-29 22:35:03 +0100193
194 def testSyntaxSplitSemicolon(self):
195 """Test handling of syntax splitting of ;"""
196 # Could take these forms: ;, ;;, ;&, ;;&
197 # these should all parse to the same output
198 for delimiter in (';', ';;', ';&', ';;&'):
199 src = ['echo hi %s echo bye' % delimiter,
200 'echo hi%s echo bye' % delimiter,
201 'echo hi%secho bye' % delimiter]
202 ref = ['echo', 'hi', delimiter, 'echo', 'bye']
Evan56624a92019-06-02 05:09:22 +1000203 for ss, ws in itertools.product(src, (False, True)):
Vinay Sajipc1f974c2016-07-29 22:35:03 +0100204 s = shlex.shlex(ss, punctuation_chars=True)
Evan56624a92019-06-02 05:09:22 +1000205 s.whitespace_split = ws
Vinay Sajipc1f974c2016-07-29 22:35:03 +0100206 result = list(s)
Evan56624a92019-06-02 05:09:22 +1000207 self.assertEqual(ref, result,
208 "While splitting '%s' [ws=%s]" % (ss, ws))
Vinay Sajipc1f974c2016-07-29 22:35:03 +0100209
210 def testSyntaxSplitRedirect(self):
211 """Test handling of syntax splitting of >"""
212 # of course, the same applies to <, |
213 # these should all parse to the same output
214 for delimiter in ('<', '|'):
215 src = ['echo hi %s out' % delimiter,
216 'echo hi%s out' % delimiter,
217 'echo hi%sout' % delimiter]
218 ref = ['echo', 'hi', delimiter, 'out']
Evan56624a92019-06-02 05:09:22 +1000219 for ss, ws in itertools.product(src, (False, True)):
Vinay Sajipc1f974c2016-07-29 22:35:03 +0100220 s = shlex.shlex(ss, punctuation_chars=True)
221 result = list(s)
Evan56624a92019-06-02 05:09:22 +1000222 self.assertEqual(ref, result,
223 "While splitting '%s' [ws=%s]" % (ss, ws))
Vinay Sajipc1f974c2016-07-29 22:35:03 +0100224
225 def testSyntaxSplitParen(self):
226 """Test handling of syntax splitting of ()"""
227 # these should all parse to the same output
228 src = ['( echo hi )',
229 '(echo hi)']
230 ref = ['(', 'echo', 'hi', ')']
Evan56624a92019-06-02 05:09:22 +1000231 for ss, ws in itertools.product(src, (False, True)):
Vinay Sajipc1f974c2016-07-29 22:35:03 +0100232 s = shlex.shlex(ss, punctuation_chars=True)
Evan56624a92019-06-02 05:09:22 +1000233 s.whitespace_split = ws
Vinay Sajipc1f974c2016-07-29 22:35:03 +0100234 result = list(s)
Evan56624a92019-06-02 05:09:22 +1000235 self.assertEqual(ref, result,
236 "While splitting '%s' [ws=%s]" % (ss, ws))
Vinay Sajipc1f974c2016-07-29 22:35:03 +0100237
238 def testSyntaxSplitCustom(self):
239 """Test handling of syntax splitting with custom chars"""
Evan56624a92019-06-02 05:09:22 +1000240 ss = "~/a&&b-c --color=auto||d *.py?"
Vinay Sajipc1f974c2016-07-29 22:35:03 +0100241 ref = ['~/a', '&', '&', 'b-c', '--color=auto', '||', 'd', '*.py?']
Vinay Sajipc1f974c2016-07-29 22:35:03 +0100242 s = shlex.shlex(ss, punctuation_chars="|")
243 result = list(s)
Evan56624a92019-06-02 05:09:22 +1000244 self.assertEqual(ref, result, "While splitting '%s' [ws=False]" % ss)
245 ref = ['~/a&&b-c', '--color=auto', '||', 'd', '*.py?']
246 s = shlex.shlex(ss, punctuation_chars="|")
247 s.whitespace_split = True
248 result = list(s)
249 self.assertEqual(ref, result, "While splitting '%s' [ws=True]" % ss)
Vinay Sajipc1f974c2016-07-29 22:35:03 +0100250
251 def testTokenTypes(self):
252 """Test that tokens are split with types as expected."""
253 for source, expected in (
254 ('a && b || c',
255 [('a', 'a'), ('&&', 'c'), ('b', 'a'),
256 ('||', 'c'), ('c', 'a')]),
257 ):
258 s = shlex.shlex(source, punctuation_chars=True)
259 observed = []
260 while True:
261 t = s.get_token()
262 if t == s.eof:
263 break
264 if t[0] in s.punctuation_chars:
265 tt = 'c'
266 else:
267 tt = 'a'
268 observed.append((t, tt))
269 self.assertEqual(observed, expected)
270
271 def testPunctuationInWordChars(self):
272 """Test that any punctuation chars are removed from wordchars"""
273 s = shlex.shlex('a_b__c', punctuation_chars='_')
274 self.assertNotIn('_', s.wordchars)
275 self.assertEqual(list(s), ['a', '_', 'b', '__', 'c'])
276
277 def testPunctuationWithWhitespaceSplit(self):
278 """Test that with whitespace_split, behaviour is as expected"""
279 s = shlex.shlex('a && b || c', punctuation_chars='&')
280 # whitespace_split is False, so splitting will be based on
281 # punctuation_chars
282 self.assertEqual(list(s), ['a', '&&', 'b', '|', '|', 'c'])
283 s = shlex.shlex('a && b || c', punctuation_chars='&')
284 s.whitespace_split = True
285 # whitespace_split is True, so splitting will be based on
286 # white space
287 self.assertEqual(list(s), ['a', '&&', 'b', '||', 'c'])
288
Vinay Sajip61eda722017-01-15 10:06:52 +0000289 def testPunctuationWithPosix(self):
290 """Test that punctuation_chars and posix behave correctly together."""
291 # see Issue #29132
292 s = shlex.shlex('f >"abc"', posix=True, punctuation_chars=True)
293 self.assertEqual(list(s), ['f', '>', 'abc'])
294 s = shlex.shlex('f >\\"abc\\"', posix=True, punctuation_chars=True)
295 self.assertEqual(list(s), ['f', '>', '"abc"'])
296
Vinay Sajipc1f974c2016-07-29 22:35:03 +0100297 def testEmptyStringHandling(self):
298 """Test that parsing of empty strings is correctly handled."""
299 # see Issue #21999
300 expected = ['', ')', 'abc']
301 for punct in (False, True):
302 s = shlex.shlex("'')abc", posix=True, punctuation_chars=punct)
303 slist = list(s)
304 self.assertEqual(slist, expected)
305 expected = ["''", ')', 'abc']
306 s = shlex.shlex("'')abc", punctuation_chars=True)
307 self.assertEqual(list(s), expected)
308
Evan56624a92019-06-02 05:09:22 +1000309 def testUnicodeHandling(self):
310 """Test punctuation_chars and whitespace_split handle unicode."""
311 ss = "\u2119\u01b4\u2602\u210c\u00f8\u1f24"
312 # Should be parsed as one complete token (whitespace_split=True).
313 ref = ['\u2119\u01b4\u2602\u210c\u00f8\u1f24']
314 s = shlex.shlex(ss, punctuation_chars=True)
315 s.whitespace_split = True
316 self.assertEqual(list(s), ref)
317 # Without whitespace_split, uses wordchars and splits on all.
318 ref = ['\u2119', '\u01b4', '\u2602', '\u210c', '\u00f8', '\u1f24']
319 s = shlex.shlex(ss, punctuation_chars=True)
320 self.assertEqual(list(s), ref)
321
Éric Araujo9bce3112011-07-27 18:29:31 +0200322 def testQuote(self):
323 safeunquoted = string.ascii_letters + string.digits + '@%_-+=:,./'
Éric Araujo7fc03942011-08-09 23:18:06 +0200324 unicode_sample = '\xe9\xe0\xdf' # e + acute accent, a + grave, sharp s
325 unsafe = '"`$\\!' + unicode_sample
Éric Araujo9bce3112011-07-27 18:29:31 +0200326
327 self.assertEqual(shlex.quote(''), "''")
328 self.assertEqual(shlex.quote(safeunquoted), safeunquoted)
329 self.assertEqual(shlex.quote('test file name'), "'test file name'")
330 for u in unsafe:
331 self.assertEqual(shlex.quote('test%sname' % u),
332 "'test%sname'" % u)
333 for u in unsafe:
334 self.assertEqual(shlex.quote("test%s'name'" % u),
335 "'test%s'\"'\"'name'\"'\"''" % u)
336
Bo Baylesca804952019-05-29 03:06:12 -0500337 def testJoin(self):
338 for split_command, command in [
339 (['a ', 'b'], "'a ' b"),
340 (['a', ' b'], "a ' b'"),
341 (['a', ' ', 'b'], "a ' ' b"),
342 (['"a', 'b"'], '\'"a\' \'b"\''),
343 ]:
344 with self.subTest(command=command):
345 joined = shlex.join(split_command)
346 self.assertEqual(joined, command)
347
348 def testJoinRoundtrip(self):
349 all_data = self.data + self.posix_data
350 for command, *split_command in all_data:
351 with self.subTest(command=command):
352 joined = shlex.join(split_command)
353 resplit = shlex.split(joined)
354 self.assertEqual(split_command, resplit)
355
Vinay Sajip3b92ddb2019-09-11 13:39:52 +0100356 def testPunctuationCharsReadOnly(self):
357 punctuation_chars = "/|$%^"
358 shlex_instance = shlex.shlex(punctuation_chars=punctuation_chars)
359 self.assertEqual(shlex_instance.punctuation_chars, punctuation_chars)
360 with self.assertRaises(AttributeError):
361 shlex_instance.punctuation_chars = False
362
Bo Baylesca804952019-05-29 03:06:12 -0500363
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000364# Allow this test to be used with old shlex.py
365if not getattr(shlex, "split", None):
366 for methname in dir(ShlexTest):
367 if methname.startswith("test") and methname != "testCompat":
368 delattr(ShlexTest, methname)
369
370if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500371 unittest.main()