def run_from_apbridge(svc, host, test, size, iteration, verbose, apb):

    csv_path = 'apb_{}_{}_{}.csv'.format(test, size, iteration)

    # gbl is using a slightly different name
    apb_test_cmd = APB_CMD.format(test.replace('transfer', 'xfer'),
                                  size, iteration)

    info(csv_path, test, size, apb_test_cmd)

    svcfd = fdpexpect.fdspawn(svc.fd, timeout=5)

    f = fdpexpect.fdspawn(apb.fd, timeout=5)

    info('Create CSV file ({})'.format(csv_path))

    with open(csv_path, "w") as fd:

        count = 1

        try:
            for pwrm, cmds in PWRM_TO_CMDS:

                info('\nTest ({}) - {}\n'.format(count, pwrm))

                for cmd in cmds:
                    exec_svc_cmd(svcfd, cmd)

                if verbose:
                    # insert the test name into the CSV file
                    # TODO: add a new column into the CSV instead of new row
                    call(['ssh', ssh_host,
                          'echo "{}" >> {}'.format(pwrm, csv_path)])

                fd.write('{},{},{},{}\n'.format(
                          strftime("%c"),
                          test,
                          size,
                          gbl_stats(f, apb_test_cmd)))
                fd.write('{},{},{},{}\n'.format(
                          strftime("%c"),
                          test,
                          size,
                          gbl_stats(f, apb_test_cmd)))
                fd.write('{},{},{},{}\n'.format(
                          strftime("%c"),
                          test,
                          size,
                          gbl_stats(f, apb_test_cmd)))

                count += 1

        except KeyboardInterrupt:
            info('\nKeyboardInterrupt')
Beispiel #2
0
def set_speed(device):
    '''set air speed'''

    port = serial.Serial(device, opts.baudrate, timeout=0,
                     dsrdtr=opts.dsrdtr, rtscts=opts.rtscts, xonxoff=opts.xonxoff)

    ser = fdpexpect.fdspawn(port.fileno(), logfile=sys.stdout)
    ser.send('+++')
    time.sleep(1)
    ser.send('\r\nATI\r\n')
    try:
        ser.expect(['OK','SiK .* on HM-TRP'], timeout=2)
    except fdpexpect.TIMEOUT:
        print("timeout")
        return
    ser.send('ATS2=%u\r\n' % opts.speed)
    ser.expect('OK')
    ser.send('AT&W\r\n')
    ser.expect('OK')
    ser.send('ATI5\r\n')
    time.sleep(0.2)
    ser.read_nonblocking(100)
    ser.send('ATZ\r\n')
    time.sleep(1)
    port.close()
Beispiel #3
0
def load(device, baud, program):
    """ Load a bitlash program onto the Arduino. """
    serialport = serial.Serial(device, baud, timeout=0)
    c = fdpexpect.fdspawn(serialport.fd)
    #c.logfile_read = sys.stdout
    # synch with the command prompt
    c.sendline('')
    waitprompt(c)
    # do stuff
    if(program.find('\n')>=0):
        #program is many lines
        text = program.split('\n')
        for line in text:
            line = line.strip()
            print(line)
            if (len(line) > 0) and (line[0] != '#'):
                c.sendline(line)
                waitprompt(c)
                print("waiting for prompt after twinkle")
    else:
        #program is one line
        if (len(program) > 0) and (program[0] != '#'):
            c.sendline(program)
            waitprompt(c)
    c.close()
    print("Done")
    return None
def get_connection(timeout, init_dtr=None, *args, **kwargs):
    if init_dtr is not None:
        kwargs['dsrdtr'] = True
    try:
        conn = serial.Serial(*args, **kwargs)
    except serial.SerialException as e:
        raise HostError(e.message)
    if init_dtr is not None:
        conn.setDTR(init_dtr)
    conn.nonblocking()
    conn.flushOutput()
    target = fdpexpect.fdspawn(conn.fileno(), timeout=timeout)
    target.logfile_read = PexpectLogger('read')
    target.logfile_send = PexpectLogger('send')

    # Monkey-patching sendline to introduce a short delay after
    # chacters are sent to the serial. If two sendline s are issued
    # one after another the second one might start putting characters
    # into the serial device before the first one has finished, causing
    # corruption. The delay prevents that.
    tsln = target.sendline

    def sendline(x):
        tsln(x)
        time.sleep(0.1)

    target.sendline = sendline
    return target, conn
def getIpRouterMesh(port, baudrate):
    IpRouter = ""
    try:
        ser = serial.Serial(port, baudrate)
    except IOError:
        return IpRouter

    if ser.isOpen():
        reader = fdpexpect.fdspawn(ser, 'wb', timeout=90)
        reader.send("\x03")
        reader.send("ifconfig\x0D")
        try:
            reader.expect("br-lan")
            reader.expect("inet addr:")
            contentLine = reader.readline()
            ipFound = contentLine.split("Bcast", 1)[0]
            ipFound = ipFound.replace(" ", "")
            IpRouter = ipFound
            # regex = re.compile(r"\d+.\d+.\d+.\d+")  #Ne marcche pas en attendant j ai remplace par un split
            #print ("VALEUR DE REGEX  ="),regex
            #ipFound = regex.match(contentLine)
            #listMeshIP.append(ipFound) # Add IP
        except pexpect.TIMEOUT:
            success = False
        except pexpect.EOF:
            print("Unexpected EOF reached. Aborting.")
            return False
        reader.close()
    # ser.close() # close port
    else:
        print("Serial port not open" + ser.name)
    return IpRouter
Beispiel #6
0
	def autosync(self):
		'''use AT&UPDATE to put modem in update mode'''
		import fdpexpect, time
		ser = fdpexpect.fdspawn(self.port.fileno(), logfile=sys.stdout)
		self.port.setBaudrate(self.atbaudrate)
		print("Trying autosync")
		ser.send('\r\n')
		time.sleep(1.0)
		ser.send('+++')
		try:
			ser.expect('OK', timeout=1.1)
		except fdpexpect.TIMEOUT:
			# may already be in AT mode
			pass
		for i in range(5):
			ser.send('\r\nATI\r\n')
			try:
				ser.expect('SiK .* on', timeout=0.5)
				ser.send('\r\n')
				time.sleep(0.2)
				ser.send('AT&UPDATE\r\n')
				time.sleep(0.7)
				if self.atbaudrate != 115200:
					self.port.setBaudrate(115200)
				return True
			except fdpexpect.TIMEOUT:
				continue
		self.port.setBaudrate(115200)
		return False
Beispiel #7
0
    def collect_data(self, machine):
        fh = machine.get_output()


        self.console = fdpexpect.fdspawn(fh, timeout=self.test_timeout)
        self.console.logfile = tempfile.NamedTemporaryFile()

        while self.boot_attempts < MAX_BOOT_ATTEMPTS:
            index = self.console.expect(["Barrelfish CPU driver starting", 
                                 pexpect.TIMEOUT, pexpect.EOF],
                                 timeout=self.boot_timeout)
            if index == 0:
                self.boot_phase = False
                break
            if index == 1:
                self.console.logfile.write(BOOT_TIMEOUT_LINE_RETRY)
                self.reboot(machine)
            if index == 2:
                self.console.logfile.write(BOOT_TIMEOUT_LINE_FAIL)

        if not self.boot_phase:
            machine.force_write(self.console)
            try:
                self.interact()
            except (pexpect.TIMEOUT, OSError), e:
                self.console.logfile.seek(0)
                print "Interaction timed out:"
                print ''.join(self.console.logfile.readlines())
                raise e
Beispiel #8
0
def show_regs(device):
    '''show S registers'''
    port = serial.Serial(device, opts.baudrate, timeout=0,
                     dsrdtr=opts.dsrdtr, rtscts=opts.rtscts, xonxoff=opts.xonxoff)
    ser = fdpexpect.fdspawn(port.fileno(), logfile=sys.stdout)
    ser.send('+++')
    time.sleep(1)
    ser.send('\r\nATI\r\n')
    try:
        ser.expect(['OK','SiK .* on HM-TRP'], timeout=2)
    except fdpexpect.TIMEOUT:
        print("timeout")
        return
    ser.send('ATI5\r\n')
    time.sleep(0.2)
    ser.read_nonblocking(300)
    ser.send('ATI6\r\n')
    time.sleep(0.2)
    ser.read_nonblocking(300)
    ser.send('ATI7\r\n')
    time.sleep(0.2)
    ser.read_nonblocking(300)
    ser.send('ATO\r\n')
    print("")
    time.sleep(1)
    port.close()
 def do_open(self, s):
     """Open the serial port, e.g.:\nopen /dev/tty.usbserial-A3000PrP"""
     self.serial.port = s
     self.serial.baudrate = 9600
     self.serial.open()
     print('Opening serial port %s' % s)
     # start pexpect
     self.ffd=fdpexpect.fdspawn(self.serial.fd)
Beispiel #10
0
 def _kick_user(self, fd, cname):
     child = fdpexpect.fdspawn(fd)
     child.expect('>INFO:OpenVPN')
     child.sendline('kill %s' %cname)
     index = child.expect(['SUCCESS', 'ERROR'])
     child.sendline('exit')
     child.close()
     return index == 0
 def test_maxread (self):
     fd = os.open ('TESTDATA.txt', os.O_RDONLY)
     s = fdpexpect.fdspawn (fd)
     s.maxread = 100
     s.expect('2')
     s.expect ('This is the end of test data:')
     s.expect (pexpect.EOF)
     assert s.before == ' END\n'
Beispiel #12
0
 def _get_status_text(self, fd):
     child = fdpexpect.fdspawn(fd)
     child.expect('>INFO:OpenVPN')
     child.sendline('status')
     child.expect('END')
     data = child.before.strip()
     child.sendline('exit')
     child.close()
     return data
Beispiel #13
0
 def connect(self, unused_credential):
     timeout = self.timeouts.connect
     try:
         self._c = telnetlib.Telnet(str(self.address), self.port, timeout)
         self._expect = fdpexpect.fdspawn(self._c.fileno())
     except socket.error, e:
         raise notch.agent.errors.ConnectError(
             'Error connecting to %s. %s: %s'
             % (str(self.address), e.__class__.__name__, str(e)))
Beispiel #14
0
	def __init__(self, port="/dev/ttyUSB0", baudrate=115200,
				 prompt="[[email protected]]# "):
		self.serial = serial.Serial(port, baudrate, timeout=1)
		self.serial.flushInput()
		self.serial.flushOutput()
		self.ffd = fdpexpect.fdspawn(self.serial.fd, timeout=60)
		self.prompt = prompt
		# assume that because we flushed, we are at a bare prompt
		CommBase.__init__(self)
    def initialize_serial_device(self, serial_device_port=None, file_log=None):
        """Initialize a serial console device with the device under test

        Args:
          serial_device_port: device file on the host computer under /dev/ that the serial
             device is attached to (i.e. ttyUSB1)
          file_log: file to log serial console messages
        Returns:
          nothing
        Raises:
          nothing
        """
        self.serial_device = os.open(serial_device_port, os.O_RDWR | os.O_NONBLOCK | os.O_NOCTTY)

        if file_log:
            self.child = fdpexpect.fdspawn(self.serial_device, logfile=file_log)
        else:
            self.child = fdpexpect.fdspawn(self.serial_device)
Beispiel #16
0
    def _initalize_pexpect(self):

        # Initalize serial port
        self.serial = serial.Serial(self.config['serial']['port'], self.config['serial']['baud'], self.config['serial']['bits'], self.config['serial']['parity'], timeout=None)
        self.fd = self.serial.fileno()

        # Flush current contents of serial Input buffer
        self.serial.flushInput()

        # Pass file descriptor for open serial port to pexpect
        self.switch = fdpexpect.fdspawn(self.fd)

        # Debugging
        # self.switch.logfile = sys.stdout

        # Wait for switch to finish booting and try to get
        # us into enable mode
        timeout_tries = 0

        sys.stdout.write("Waiting for switch")
        sys.stdout.flush()

        while True:
            self.switch.sendline("\r\n")

            res = self._do_expect_prompt(10)

            if res == 0:
                self.switch.sendline('no')
            elif res == 1:
                self.switch.sendline('enable')
            elif res == 2:
                # we're good to go
                break
            elif res == 3:
                self.switch.sendline('exit')
            elif res in [4, 5]:
                raise CIOSProvisionException('Auth prompt encountered. Switch already configured?')
            elif res == 6:
                raise CIOSProvisionException('Unexpected and unhandled prompt received from switch.\n{0}'.format(self.switch.before))
            elif res == 7:
                sys.stdout.write('.')
                sys.stdout.flush()
                # Five minutes of trying (10 * 30)
                if timeout_tries > 30:
                    raise CIOSProvisionException("Timeout after five minutes.  Check switch and serial link.\n{0}".format(self.switch.before))
                timeout_tries += 1

        # Newline after waiting finishes
        print("")

        # Clean up the expect buffer on our way out or things will
        # get confused in future _do_line usage
        self.switch.expect(['$', fdpexpect.TIMEOUT], timeout=1)
Beispiel #17
0
def Open_serial():
    global ser
    ser = serial.Serial(port,9600)
    ser.flushInput()
    time.sleep(1)


    global child
    fd = os.open(port, os.O_RDWR|os.O_NONBLOCK|os.O_NOCTTY)
    child = fdpexpect.fdspawn(fd) # Note integer fd is used instead of usual string.
    child.logfile_read = sys.stdout
    child.logfile_send = sys.stdout
def open_serial_connection(timeout, get_conn=False, init_dtr=None, *args, **kwargs):
    """
    Opens a serial connection to a device.

    :param timeout: timeout for the fdpexpect spawn object.
    :param conn: ``bool`` that specfies whether the underlying connection
                 object should be yielded as well.
    :param init_dtr: specifies the initial DTR state stat should be set.

    All arguments are passed into the __init__ of serial.Serial. See
    pyserial documentation for details:

        http://pyserial.sourceforge.net/pyserial_api.html#serial.Serial

    :returns: a pexpect spawn object connected to the device.
              See: http://pexpect.sourceforge.net/pexpect.html

    """
    if init_dtr is not None:
        kwargs['dsrdtr'] = True
    try:
        conn = serial.Serial(*args, **kwargs)
    except serial.SerialException as e:
        raise HostError(e.message)
    if init_dtr is not None:
        conn.setDTR(init_dtr)
    conn.nonblocking()
    conn.flushOutput()
    target = fdpexpect.fdspawn(conn.fileno(), timeout=timeout)
    target.logfile_read = PexpectLogger('read')
    target.logfile_send = PexpectLogger('send')

    # Monkey-patching sendline to introduce a short delay after
    # chacters are sent to the serial. If two sendline s are issued
    # one after another the second one might start putting characters
    # into the serial device before the first one has finished, causing
    # corruption. The delay prevents that.
    tsln = target.sendline

    def sendline(x):
        tsln(x)
        time.sleep(0.1)

    target.sendline = sendline

    if get_conn:
        yield target, conn
    else:
        yield target

    target.close()  # Closes the file descriptor used by the conn.
    del conn
Beispiel #19
0
 def __enter__(self):
     self.lock.acquire()
     self.fd = os.open(self.serial_port, os.O_RDWR|os.O_NONBLOCK|os.O_NOCTTY)
     attr_list = termios.tcgetattr(self.fd)
     attr_list[1] &= ~termios.ONLCR
     attr_list[3] &= ~termios.ECHO
     attr_list[3] &= ~termios.ICANON
     attr_list[4] = self.baud_rate
     attr_list[5] = self.baud_rate
     attr_list[6][termios.VTIME] = 5
     termios.tcsetattr(self.fd, termios.TCSAFLUSH, attr_list)
     
     return fdpexpect.fdspawn(self.fd)
def load(device, baud, program):
    serialport = serial.Serial(device, baud, timeout=0)
    c = fdpexpect.fdspawn(serialport.fd)
    # c.logfile_read = sys.stdout
    # synch with the command prompt
    c.sendline("")
    waitprompt(c)
    # do stuff
    for line in program:
        line = line.strip()
        if (len(line) > 0) and (line[0] != "#"):
            c.sendline(line)
            waitprompt(c)
    c.close()
def run_python_module(context, module, target):
    logfile = None
    if hasattr(context, "stdout_capture"):
        logfile = context.stdout_capture

    fullname = "{}.{}".format(module, target)

    _io, pipeio = pty.openpty()

    def run_script(_pipe, _io, ctx):
        sys.stdout = os.fdopen(_pipe, "w")
        sys.stderr = os.fdopen(_pipe, "w")
        sys.stdin = os.fdopen(_pipe, "r")
        # Explicitly open the tty to make it become a controlling tty.
        tmp_fd = os.open(os.ttyname(_pipe), os.O_RDWR)
        os.close(tmp_fd)
        os.setsid()

        try:
            from features.steps import mp_setup

            mp_setup(ctx)
        except ImportError:
            pass
        try:
            from setproctitle import setproctitle

            setproctitle("python process: {}".format(fullname))
        except ImportError:
            pass
        for name, value in ctx.environ.iteritems():
            os.environ[name] = value
        os.chdir(ctx.cwd)
        sys.argv = ["-"]
        if ctx.args:
            sys.argv += shlex.split(ctx.args)
        else:
            sys.argv = ["me"]
        getattr(import_module(module), target)()

    proc = Process(target=run_script, args=(pipeio, _io, context))
    proc.start()

    os.close(pipeio)

    context.child = fdpexpect.fdspawn(_io, logfile=logfile)
    context.child.__proc = proc
    context.child.__io = _io
    context.children[fullname] = context.child
Beispiel #22
0
 def __init__(self, device, baudrate=57600, debug=False,
              dsrdtr=False, rtscts=False, xonxoff=False):
     # Initialize object data members
     self.is_command = False		# Track if we've entered command mode
     self.is_remote = False		# Track if operating on remote radio
     self.read_timeout = 5		# Max time to wait for data
     
     logfile=None
     if debug:
         logfile=sys.stdout
     
     # Initialize the serial connection
     # Note: we pass the buck on raised exceptions
     self.port = serial.Serial(device, baudrate=baudrate, timeout=0, 
                               dsrdtr=dsrdtr, rtscts=rtscts, xonxoff=xonxoff)
     self.ser = fdpexpect.fdspawn(self.port.fileno(), logfile=logfile)
Beispiel #23
0
def Initialize(device):
  "Set up the board to a known state and connect pexpect to it.  Return the pexpect object."
  g_power.Off()

  SetupSerial(device)

  print "Connecting to serial device...",
  fd = os.open(device, os.O_RDWR|os.O_NONBLOCK|os.O_NOCTTY)

  print fd
  m = fdpexpect.fdspawn(fd)


  print "Waiting for embedded device to be switched on..."
  g_power.On()
  return m
Beispiel #24
0
def load(device, baud, program):
    """ Load a bitlash program onto the Arduino. """
    serialport = serial.Serial(device, baud, timeout=0)
    c = fdpexpect.fdspawn(serialport.fd)
    #c.logfile_read = sys.stdout
    # synch with the command prompt
    c.sendline('')
    waitprompt(c)
    # do stuff
    for line in program:
        line = line.strip()
        if (len(line) > 0) and (line[0] != '#'):
            c.sendline(line)
            waitprompt(c)
    c.close()
    return None
Beispiel #25
0
def load(device, baud, setup, loop):
    serialport = serial.Serial(device, baud, timeout=0)
    c = fdpexpect.fdspawn(serialport.fd)
    c.sendline('')
    waitprompt(c)
    for line in setup.splitlines():
        line = line.strip()
        if (len(line) > 0) and (line[0] != '#'):
            c.sendline(line)
            waitprompt(c)
    while True:
        for line in loop.splitlines():
            line = line.strip()
            if (len(line) > 0) and (line[0] != '#'):
                c.sendline(line)
                waitprompt(c)
    c.close() # unreachable ...
Beispiel #26
0
def update_mode(device):
    '''put a HM-TRP into update mode'''
    port = serial.Serial(device, opts.baudrate, timeout=0,
                     dsrdtr=opts.dsrdtr, rtscts=opts.rtscts, xonxoff=opts.xonxoff)
    ser = fdpexpect.fdspawn(port.fileno(), logfile=sys.stdout)
    ser.send('+++')
    time.sleep(1)
    ser.send('\r\nATI\r\n')
    try:
        ser.expect(['OK','SiK .* on HM-TRP'], timeout=2)
    except fdpexpect.TIMEOUT:
        print("timeout")
        return
    ser.send('AT&UPDATE\r\n')
    try:
        buf = ser.read_nonblocking(100, timeout=1)
    except pexpect.TIMEOUT:
        pass
    port.close()
Beispiel #27
0
    def init_jsbsim(self):
        cmd = (
            "JSBSim --realtime --suspend --nice --simulation-rate=1000 --logdirectivefile=data/flightgear.xml --script=%s"
            % self.script
        )
        if self.options:
            cmd += " %s" % self.options

        jsb = pexpect.spawn(cmd, logfile=sys.stdout, timeout=10)
        jsb.delaybeforesend = 0
        util.pexpect_autoclose(jsb)
        i = jsb.expect(["Successfully bound to socket for input on port (\d+)", "Could not bind to socket for input"])
        if i == 1:
            print ("Failed to start JSBSim - is another copy running?")
            sys.exit(1)
        jsb_out_address = self.interpret_address("127.0.0.1:%u" % int(jsb.match.group(1)))
        jsb.expect("Creating UDP socket on port (\d+)")
        jsb_in_address = self.interpret_address("127.0.0.1:%u" % int(jsb.match.group(1)))
        jsb.expect("Successfully connected to socket for output")
        jsb.expect("JSBSim Execution beginning")

        # setup output to jsbsim
        print ("JSBSim console on %s" % str(jsb_out_address))
        jsb_out = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        jsb_out.connect(jsb_out_address)
        jsb_console = fdpexpect.fdspawn(jsb_out.fileno(), logfile=sys.stdout)
        jsb_console.delaybeforesend = 0
        jsb_console.logfile = None

        # setup input from jsbsim
        print ("JSBSim FG FDM input on %s" % str(jsb_in_address))
        jsb_in = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        jsb_in.bind(jsb_in_address)
        jsb_in.setblocking(0)

        # set class data
        self.jsb = jsb
        self.jsb_in = jsb_in
        self.jsb_out = jsb_out
        self.jsb_console = jsb_console
        self.fdm = fgFDM.fgFDM()
Beispiel #28
0
def rssi(device):
    port = serial.Serial(device, opts.baudrate, timeout=0,
                     dsrdtr=opts.dsrdtr, rtscts=opts.rtscts, xonxoff=opts.xonxoff)
    ser = fdpexpect.fdspawn(port.fileno(), logfile=sys.stdout)
    ser.send('+++')
    time.sleep(1)
    ser.send('\r\nATI\r\n')
    try:
        ser.expect(['OK','SiK .* on HM-TRP'], timeout=2)
    except fdpexpect.TIMEOUT:
        print("timeout")
        return
    ser.send('AT&F\r\n')
    try:
        ser.expect(['OK'], timeout=2)
    except fdpexpect.TIMEOUT:
        print("timeout")
        return
    
    ser.send('AT&T=RSSI\r\n')
    
    ctr = 0
    
    while ctr < 200:
    	try:
	        count = port.inWaiting()
	        if count == 0:
        	    	count = 1
        	buf = port.read(count)
        	if len(buf) == 0:
            		continue
        	sys.stdout.write(buf)
            	sys.stdout.flush()
        	ctr = ctr + 1
        	
    	except KeyboardInterrupt:
	        sys.exit(0)
	        
    port.close()
def run_from_apbridge(svc, host, test, size, verbose, apb):

    csv_path = 'apb_%s_%s_1000.csv' % (test, size)

    # gbl is using a slightly different name
    apb_test_cmd = APB_CMD % (test.replace('transfer', 'xfer'), size)

    info(csv_path, test, size, apb_test_cmd)

    f = fdpexpect.fdspawn(apb.fd, timeout=5)

    print('Create CSV file (%s)' % csv_path)

    with open(csv_path, "w") as fd:

        count = 1

        try:
            for pwrm, cmds in PWRM_TO_CMDS:

                print('\nTest (%d) - ' % count + pwrm + '\n')

                for cmd in cmds:
                    exec_cmd(svc, cmd)

                if verbose:
                    # insert the test name into the CSV file
                    # TODO: add a new column into the CSV instead of new row
                    call(['ssh', ssh_host, 'echo "%s" >> %s' % (pwrm, csv_path)])

                fd.write('%s,%s,%s,%s\n' % (strftime("%c"), test, size, gbl_stats(f, apb_test_cmd)))
                fd.write('%s,%s,%s,%s\n' % (strftime("%c"), test, size, gbl_stats(f, apb_test_cmd)))
                fd.write('%s,%s,%s,%s\n' % (strftime("%c"), test, size, gbl_stats(f, apb_test_cmd)))

                count += 1

        except KeyboardInterrupt:
            info('\nKeyboardInterrupt')
    def start(self):
        self.report = []
        main = None  # Placeholder for the main test
        others = []  # Holds other tests
        for test in self.tree.xpath('./ar:Test', namespaces={
            'ar': 'http://moodlegradetool.com/advanced_regex'}):  # Get all test nodes
            if (not 'file' in test.attrib) and not main:  # See if this is the first test with out a filename
                main = test  # Set it to be the main test
            else:
                others.append((test, test.get('file')))  # Append every other test to the others

        if not main: raise ValueError("Could not find the main test")

        java_cls = self.clsName if not hasattr(self, 'main') else self.main  # Get the main java class
        self._out = StringIO.StringIO()  # Make a stringIO to hold the output
        proc = pexpect.spawn('java', [java_cls], logfile=self._out, cwd=self.cwd)  # Spawn the java program

        self.do_test(proc, main)  # Do the main test

        for test, fname in others:  # Do the other tests
            with open(self.cwd + '/' + fname, 'r') as f:  # Open the associated file
                fexp = fdpexpect.fdspawn(f)  # Spawn an expect instance for the file
                self.do_test(fexp, test)  # Do the test