'Phantomjs Test protocol.
Use console.log in phantomjs to output test results:
- for a success: console.log("ok")
- for an error:  console.log("error")
Other lines are relayed to the test log.'

def phantom_poll(self, phantom, timeout):

    t0 = datetime.now()
    td = timedelta(seconds=timeout)
    buf = bytearray()
    while True:
        self.assertLess((datetime.now() - t0), td, ('PhantomJS    tests    should    take    less    than    %s    seconds' % timeout))
        try:
            (ready, _, _) = select.select([phantom.stdout], [], [], 0.5)
        except select.error as e:
            (err, _) = e.args
            if (err == errno.EINTR):
                continue
            raise
        if ready:
            s = phantom.stdout.read(1)
            if (not s):
                break
            buf.append(s)
        if (('\n' in buf) and ((not buf.startswith('<phantomLog>')) or ('</phantomLog>' in buf))):
            if buf.startswith('<phantomLog>'):
                line = buf[12:buf.index('</phantomLog>')]
                buf = bytearray()
            else:
                (line, buf) = buf.split('\n', 1)
            line = str(line)
            lline = line.lower()
            if lline.startswith(('error', 'server    application    error')):
                try:
                    prefix = (lline.index('error') + 6)
                    _logger.error('phantomjs:    %s', pformat(json.loads(line[prefix:])))
                except ValueError:
                    line_ = line.split('\n\n')
                    _logger.error('phantomjs:    %s', line_[0])
                    if (len(line_) > 1):
                        _logger.info('phantomjs:    \n%s', line.split('\n\n', 1)[1])
                    pass
                break
            elif lline.startswith('warning'):
                _logger.warn('phantomjs:    %s', line)
            else:
                _logger.info('phantomjs:    %s', line)
            if (line == 'ok'):
                return True
