1from __future__ import absolute_import
2
3# System modules
4import os
5import sys
6
7# Third-party modules
8import six
9
10# LLDB Modules
11import lldb
12from .lldbtest import *
13from . import lldbutil
14from lldbsuite.test.decorators import *
15
16@skipIfRemote
17@skipIfWindows  # llvm.org/pr22274: need a pexpect replacement for windows
18class PExpectTest(TestBase):
19
20    NO_DEBUG_INFO_TESTCASE = True
21    PROMPT = "(lldb) "
22
23    def expect_prompt(self):
24        self.child.expect_exact(self.PROMPT)
25
26    def launch(self, executable=None, extra_args=None, timeout=60,
27               dimensions=None, run_under=None, post_spawn=None):
28        logfile = getattr(sys.stdout, 'buffer',
29                            sys.stdout) if self.TraceOn() else None
30
31        args = []
32        if run_under is not None:
33            args += run_under
34        args += [lldbtest_config.lldbExec, '--no-lldbinit', '--no-use-colors']
35        for cmd in self.setUpCommands():
36            args += ['-O', cmd]
37        if executable is not None:
38            args += ['--file', executable]
39        if extra_args is not None:
40            args.extend(extra_args)
41
42        env = dict(os.environ)
43        env["TERM"] = "vt100"
44        env["HOME"] = self.getBuildDir()
45
46        import pexpect
47        self.child = pexpect.spawn(
48                args[0], args=args[1:], logfile=logfile,
49                timeout=timeout, dimensions=dimensions, env=env)
50
51        if post_spawn is not None:
52            post_spawn()
53        self.expect_prompt()
54        for cmd in self.setUpCommands():
55            self.child.expect_exact(cmd)
56            self.expect_prompt()
57        if executable is not None:
58            self.child.expect_exact("target create")
59            self.child.expect_exact("Current executable set to")
60            self.expect_prompt()
61
62    def expect(self, cmd, substrs=None):
63        self.assertNotIn('\n', cmd)
64        # If 'substrs' is a string then this code would just check that every
65        # character of the string is in the output.
66        assert not isinstance(substrs, six.string_types), \
67            "substrs must be a collection of strings"
68
69        self.child.sendline(cmd)
70        if substrs is not None:
71            for s in substrs:
72                self.child.expect_exact(s)
73        self.expect_prompt()
74
75    def quit(self, gracefully=True):
76        self.child.sendeof()
77        self.child.close(force=not gracefully)
78        self.child = None
79
80    def cursor_forward_escape_seq(self, chars_to_move):
81        """
82        Returns the escape sequence to move the cursor forward/right
83        by a certain amount of characters.
84        """
85        return b"\x1b\[" + str(chars_to_move).encode("utf-8") + b"C"
86