• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import io
2import itertools
3import shlex
4import string
5import unittest
6
7
8
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:-) ;-)|:|-|)|;|-|)|
71áéíóú|á|é|í|ó|ú|
72"""
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:-) ;-)|:-)|;-)|
135áéíóú|áéíóú|
136"""
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
149    def splitTest(self, data, comments):
150        for i in range(len(data)):
151            l = shlex.split(data[i][0], comments=comments)
152            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 = []
158        lex = shlex.shlex(io.StringIO(s))
159        tok = lex.get_token()
160        while tok:
161            ret.append(tok)
162            tok = lex.get_token()
163        return ret
164
165    def testSplitPosix(self):
166        """Test data splitting with posix parser"""
167        self.splitTest(self.posix_data, comments=True)
168
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
177    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']
187            for ss, ws in itertools.product(src, (False, True)):
188                s = shlex.shlex(ss, punctuation_chars=True)
189                s.whitespace_split = ws
190                result = list(s)
191                self.assertEqual(ref, result,
192                                 "While splitting '%s' [ws=%s]" % (ss, ws))
193
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']
203            for ss, ws in itertools.product(src, (False, True)):
204                s = shlex.shlex(ss, punctuation_chars=True)
205                s.whitespace_split = ws
206                result = list(s)
207                self.assertEqual(ref, result,
208                                 "While splitting '%s' [ws=%s]" % (ss, ws))
209
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']
219            for ss, ws in itertools.product(src, (False, True)):
220                s = shlex.shlex(ss, punctuation_chars=True)
221                result = list(s)
222                self.assertEqual(ref, result,
223                                 "While splitting '%s' [ws=%s]" % (ss, ws))
224
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', ')']
231        for ss, ws in itertools.product(src, (False, True)):
232            s = shlex.shlex(ss, punctuation_chars=True)
233            s.whitespace_split = ws
234            result = list(s)
235            self.assertEqual(ref, result,
236                             "While splitting '%s' [ws=%s]" % (ss, ws))
237
238    def testSyntaxSplitCustom(self):
239        """Test handling of syntax splitting with custom chars"""
240        ss = "~/a&&b-c --color=auto||d *.py?"
241        ref = ['~/a', '&', '&', 'b-c', '--color=auto', '||', 'd', '*.py?']
242        s = shlex.shlex(ss, punctuation_chars="|")
243        result = list(s)
244        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)
250
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
289    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
297    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
309    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
322    def testQuote(self):
323        safeunquoted = string.ascii_letters + string.digits + '@%_-+=:,./'
324        unicode_sample = '\xe9\xe0\xdf'  # e + acute accent, a + grave, sharp s
325        unsafe = '"`$\\!' + unicode_sample
326
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
337    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
356    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
363
364# 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__":
371    unittest.main()
372