示例#1
0
def test_result_code() -> None:
    """
    Verifies the properties of the Artifacts result code.
    """
    default_subject = nanaimo.Artifacts()
    assert 0 == int(default_subject)
    subject_1 = nanaimo.Artifacts(1)
    assert 1 == int(subject_1)
    subject_1.result_code = 2
    assert 2 == int(subject_1)
示例#2
0
def test_missing_artifact() -> None:
    """
    Verified that KeyError is not raised if an undefined artifact is accessed.
    """
    subject = nanaimo.Artifacts()
    assert subject.not_an_artifact is None
    assert 'not_an_artifact' not in subject
示例#3
0
    async def _updater(self, args: nanaimo.Namespace) -> nanaimo.Artifacts:
        lw_update_period = self.get_arg_covariant(args, 'update_period')
        if lw_update_period is not None:
            while True:
                await asyncio.sleep(lw_update_period)
                self._logger.info('still waiting...')

        return nanaimo.Artifacts()
示例#4
0
 async def _agitator(
         self, args: nanaimo.Namespace,
         monitor: nanaimo.connections.uart.ConcurrentUart
 ) -> nanaimo.Artifacts:
     lw_disturb_rate = self.get_arg_covariant(args, 'disturb_rate')
     lw_disruption = self.get_arg_covariant_or_fail(args, 'disruption')
     if lw_disturb_rate is not None:
         while True:
             await asyncio.sleep(lw_disturb_rate)
             self._logger.debug('About to disturb the uart...')
             await monitor.put_line(lw_disruption)
     return nanaimo.Artifacts()
示例#5
0
    async def on_gather(self, args: nanaimo.Namespace) -> nanaimo.Artifacts:
        if args.character_display_configure:
            self.configure()

        if args.character_display_clear:
            self.clear(display_default_message=False)

        if args.character_display_clear_to_default:
            self.clear(display_default_message=True)

        if args.character_display_write is not None:
            self.write(args.character_display_write)

        if args.character_display_status is not None:
            self.set_status(args.character_display_status)

        return nanaimo.Artifacts()
示例#6
0
    async def _matcher(
            self, args: nanaimo.Namespace,
            monitor: nanaimo.connections.uart.ConcurrentUart
    ) -> nanaimo.Artifacts:
        artifacts = nanaimo.Artifacts()
        lw_pattern = self.get_arg_covariant_or_fail(args, 'pattern')
        pattern = re.compile(lw_pattern)

        self._logger.info('Starting to look for pattern : %s', str(lw_pattern))
        while True:
            result = await monitor.get_line()
            result_stripped = result.rstrip()
            if len(result_stripped) > 0:
                self._logger.debug(result_stripped)
            match = pattern.search(result)
            if match:
                setattr(artifacts, 'match', match)
                setattr(artifacts, 'matched_line', result)
                break

        return artifacts
示例#7
0
    async def _do_command_from_args(self,
                                    uart: AbstractAsyncSerial,
                                    args: nanaimo.Namespace) -> nanaimo.Artifacts:
        artifacts = nanaimo.Artifacts(-1)

        if args.bk_command == '1':
            await self._up_or_down(True, uart, args, artifacts)
        elif args.bk_command == '0':
            await self._up_or_down(False, uart, args, artifacts)
        elif args.bk_command == 'r':
            _, artifacts.result_code = await self._do_command(uart, '\r\r\r\r', args.bk_command_timeout)
        elif args.bk_command == '?':
            display, artifacts.result_code = await self._get_display(uart, args.bk_command_timeout)
            if artifacts.result_code == 0:
                setattr(artifacts, 'display', display)
                setattr(artifacts, 'display_text', '{},{},{}'.format(
                    display[0], display[1], self.mode_to_text(int(display[1]))))
        else:
            self.logger.warning('command {} is not a valid Series1900BUart command.'.format(args.bk_command))

        return artifacts
示例#8
0
    async def on_gather(self, args: nanaimo.Namespace) -> nanaimo.Artifacts:
        """
        Create a delicious function in the artifacts to eat.

        +--------------+---------------------------+-----------------------------------------------+
        | **Returned Artifacts**                                                                   |
        +--------------+---------------------------+-----------------------------------------------+
        | key          | type                      | Notes                                         |
        +==============+===========================+===============================================+
        | eat          | Callable[[],None]         | A function that logs a message                |
        +--------------+---------------------------+-----------------------------------------------+
        | bar_{number} | str                       | A string formed from an argument              |
        |              |                           | ``bar_number``. This allows testing ordering  |
        |              |                           | of concurrent operations.                     |
        +--------------+---------------------------+-----------------------------------------------+
        """
        artifacts = nanaimo.Artifacts()
        self.logger.info("don't forget to eat your dessert.")
        setattr(artifacts, 'eat',
                functools.partial(self.logger.info, 'Nanaimo bars are yummy.'))
        setattr(artifacts, 'bar_{}'.format(args.bar_number), time.monotonic())
        return artifacts
示例#9
0
    async def on_gather(self, args: nanaimo.Namespace) -> nanaimo.Artifacts:
        saleae_host = self.get_arg_covariant_or_fail(args, 'saleae_host')
        saleae_port = self.get_arg_covariant_or_fail(args, 'saleae_port')

        self.logger.info('about to connect to {}:{}'.format(saleae_host, saleae_port))
        reader, writer = await asyncio.open_connection(host=saleae_host, port=saleae_port, loop=self.loop)

        writer.write('GET_ALL_SAMPLE_RATES\0'.encode('utf-8'))

        rx_buffer = ''
        while 'ACK' not in rx_buffer:
            rx_bytes = await reader.read(256)
            if rx_bytes is not None:
                rx_text = rx_bytes.decode('utf-8')
                self.logger.debug('rx: %s', rx_text)
                rx_buffer += rx_text
                # this is kind of crap. do way better.
                if 'NAK' == rx_buffer[0:3]:
                    self.logger.error('NAK')
                    break

        writer.close()
        await writer.wait_closed()
        return nanaimo.Artifacts()
示例#10
0
    async def on_gather(self, args: nanaimo.Namespace) -> nanaimo.Artifacts:
        """
        +--------------+---------------------------+-------------------------------------------------------------------+
        | **Artifacts**                                                                                                |
        |                                                                                                              |
        +--------------+---------------------------+-------------------------------------------------------------------+
        | key          | type                      | Notes                                                             |
        +==============+===========================+===================================================================+
        | ``cmd``      | str                       | The command used to execute the subprocess.                       |
        +--------------+---------------------------+-------------------------------------------------------------------+
        | ``logfile``  | Optional[pathlib.Path]    | A file containing stdout, stderr, and test logs                   |
        +--------------+---------------------------+-------------------------------------------------------------------+
        """
        artifacts = nanaimo.Artifacts()

        cmd = self.on_construct_command(args, artifacts)
        setattr(artifacts, 'cmd', cmd)

        logfile_handler = None  # type: typing.Optional[logging.FileHandler]

        logfile = self.get_arg_covariant(args, 'logfile')
        logfile_amend = bool(self.get_arg_covariant(args, 'logfile-amend'))
        logfile_fmt = self.get_arg_covariant(args, 'logfile-format')
        logfile_datefmt = self.get_arg_covariant(args, 'logfile-date-format')
        log_stdout = self.get_arg_covariant(args, 'log-stdout', False)
        log_stderr = self.get_arg_covariant(args, 'log-stderr', False)

        cwd = self.get_arg_covariant(args, 'cwd')

        if logfile is not None:
            setattr(artifacts, 'logfile', logfile)
            logfile_handler = logging.FileHandler(
                filename=str(logfile), mode=('a' if logfile_amend else 'w'))
            file_formatter = logging.Formatter(fmt=logfile_fmt,
                                               datefmt=logfile_datefmt)
            logfile_handler.setFormatter(file_formatter)
            self._logger.addHandler(logfile_handler)

        stdout_filter = self._stdout_filter
        stderr_filter = self._stderr_filter

        if stdout_filter is not None:
            self._logger.addFilter(stdout_filter)
        if stderr_filter is not None:
            self._logger.addFilter(stderr_filter)

        try:
            self._logger.debug(
                'About to execute command "%s" in a subprocess shell', cmd)

            proc = await asyncio.create_subprocess_shell(
                cmd,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
                cwd=cwd)  # type: asyncio.subprocess.Process

            if log_stdout or log_stderr:
                # Take the hit to route the pipes through our process
                stdout, stderr = await proc.communicate()

                if log_stdout and stdout:
                    self._log_bytes_like_as_lines(logging.INFO, stdout)
                if log_stderr and stderr:
                    self._log_bytes_like_as_lines(logging.ERROR, stderr)
            else:
                # Simply let the background process do it's thing and wait for it to finish.
                await self._wait_for_either_until_neither(
                    (proc.stdout
                     if proc.stdout is not None else self._NoopStreamReader()),
                    (proc.stderr
                     if proc.stderr is not None else self._NoopStreamReader()))

            await proc.wait()

            self._logger.debug('command "%s" exited with %i', cmd,
                               proc.returncode)

            artifacts.result_code = proc.returncode
            return artifacts
        finally:
            if stderr_filter is not None:
                self._logger.removeFilter(stderr_filter)
            if stdout_filter is not None:
                self._logger.removeFilter(stdout_filter)
            if logfile_handler is not None:
                self._logger.removeHandler(logfile_handler)
示例#11
0
def test_assert_success() -> None:
    nanaimo.pytest.plugin.assert_success(nanaimo.Artifacts(1))
示例#12
0
def test_create_artifacts() -> None:
    """
    Create an orphan Artifacts namespace
    """
    subject = nanaimo.Artifacts()
    assert 'foo' not in subject
示例#13
0
 async def on_gather(self,
                     args: nanaimo.Namespace) -> nanaimo.Artifacts:
     return nanaimo.Artifacts()