def test_basic(self): self.assertEqual(self.parse('echo hello'), Pipeline([Command(['echo', 'hello'], [])], False)) self.assertEqual(self.parse('echo ""'), Pipeline([Command(['echo', ''], [])], False)) self.assertEqual(self.parse("""echo -DFOO='a'"""), Pipeline([Command(['echo', '-DFOO=a'], [])], False)) self.assertEqual(self.parse('echo -DFOO="a"'), Pipeline([Command(['echo', '-DFOO=a'], [])], False))
def test_redirection(self): self.assertEqual(self.parse('echo hello > c'), Pipeline([Command(['echo', 'hello'], [((('>'),), 'c')])], False)) self.assertEqual(self.parse('echo hello > c >> d'), Pipeline([Command(['echo', 'hello'], [(('>',), 'c'), (('>>',), 'd')])], False)) self.assertEqual(self.parse('a 2>&1'), Pipeline([Command(['a'], [(('>&',2), '1')])], False))
def test_pipeline(self): self.assertEqual(self.parse('a | b'), Pipeline([Command(['a'], []), Command(['b'], [])], False)) self.assertEqual(self.parse('a | b | c'), Pipeline([Command(['a'], []), Command(['b'], []), Command(['c'], [])], False))
def parse_command(self): tok = self.lex() if not tok: raise ValueError("empty command!") if isinstance(tok, tuple): raise ValueError("syntax error near unexpected token %r" % tok[0]) args = [tok] redirects = [] while 1: tok = self.look() # EOF? if tok is None: break # If this is an argument, just add it to the current command. if isinstance(tok, str): args.append(self.lex()) continue # Otherwise see if it is a terminator. assert isinstance(tok, tuple) if tok[0] in ('|',';','&','||','&&'): break # Otherwise it must be a redirection. op = self.lex() arg = self.lex() if not arg: raise ValueError("syntax error near token %r" % op[0]) redirects.append((op, arg)) return Command(args, redirects)
def test_list(self): self.assertEqual(self.parse('a ; b'), Seq(Pipeline([Command(['a'], [])], False), ';', Pipeline([Command(['b'], [])], False))) self.assertEqual(self.parse('a & b'), Seq(Pipeline([Command(['a'], [])], False), '&', Pipeline([Command(['b'], [])], False))) self.assertEqual(self.parse('a && b'), Seq(Pipeline([Command(['a'], [])], False), '&&', Pipeline([Command(['b'], [])], False))) self.assertEqual(self.parse('a || b'), Seq(Pipeline([Command(['a'], [])], False), '||', Pipeline([Command(['b'], [])], False))) self.assertEqual(self.parse('a && b || c'), Seq(Seq(Pipeline([Command(['a'], [])], False), '&&', Pipeline([Command(['b'], [])], False)), '||', Pipeline([Command(['c'], [])], False))) self.assertEqual(self.parse('a; b'), Seq(Pipeline([Command(['a'], [])], False), ';', Pipeline([Command(['b'], [])], False)))