# Path: dragonpy/tests/test_base.py
# class Test6809_sbc09_Base(BaseCPUTestCase):
#     """
#     Run tests with the sbc09 ROM.
#     """
#     TEMP_FILE = os.path.join(
#         tempfile.gettempdir(),
#         f"DragonPy_sbc09_unittests_Py{sys.version_info[0]:d}.dat"
#     )
# 
#     @classmethod
#     def setUpClass(cls, cmd_args=None):
#         """
#         prerun ROM to complete initiate and ready for user input.
#         save the CPU state to speedup unittest
#         """
#         super().setUpClass()
# 
#         log.info(f"CPU state pickle file: {cls.TEMP_FILE!r}")
# #        if os.path.isfile(cls.TEMP_FILE):
# #            print("Delete CPU date file!")
# #            os.remove(cls.TEMP_FILE)
# 
#         cfg = SBC09Cfg(cls.UNITTEST_CFG_DICT)
# 
#         cls.user_input_queue = queue.Queue()
#         cls.display_callback = queue.Queue()
# 
#         cls.machine = Machine(
#             cfg,
#             periphery_class=SBC09PeripheryUnittest,
#             display_callback=cls.display_callback,
#             user_input_queue=cls.user_input_queue,
#         )
#         cls.cpu = cls.machine.cpu
#         cls.periphery = cls.machine.periphery
#         cls.periphery.setUp()
# 
#         try:
#             temp_file = open(cls.TEMP_FILE, "rb")
#         except OSError:
#             log.info("init machine...")
#             init_start = time.time()
#             cls.cpu.test_run(
#                 start=cls.cpu.program_counter.value,
#                 end=cfg.STARTUP_END_ADDR,
#             )
#             duration = time.time() - init_start
#             log.info("done in %iSec. it's %.2f cycles/sec. (current cycle: %i)" % (
#                 duration, float(cls.cpu.cycles / duration), cls.cpu.cycles
#             ))
# 
#             # Check if machine is ready
#             assert cls.periphery.output == (
#                 'Welcome to BUGGY version 1.0\r\n'
#             ), f"Outlines are: {repr(cls.periphery.output)}"
#             # Save CPU state
#             init_state = cls.cpu.get_state()
#             with open(cls.TEMP_FILE, "wb") as f:
#                 pickle.dump(init_state, f)
#                 log.info(f"Save CPU init state to: {cls.TEMP_FILE!r}")
#             cls.__init_state = init_state
#         else:
#             log.info(f"Load CPU init state from: {cls.TEMP_FILE!r}")
#             cls.__init_state = pickle.load(temp_file)
#             temp_file.close()
# 
# #         print_cpu_state_data(cls.__init_state)
# 
#     def setUp(self):
#         """ restore CPU/Periphery state to a fresh startup. """
#         self.periphery.setUp()
#         self.cpu.set_state(self.__init_state)
# #         print_cpu_state_data(self.cpu.get_state())
# 
#     def _run_until(self, terminator, count, max_ops):
#         old_cycles = self.cpu.cycles
#         last_output_len = 0
#         is_count = 0
#         for op_call_count in range(max_ops):
#             self.cpu.get_and_call_next_op()
# 
#             if self.periphery.output_len > last_output_len:
#                 last_output_len = self.periphery.output_len
# 
# #                 log.critical("output: %s", repr(self.periphery.output))
# 
#                 if self.periphery.output.endswith(terminator):
#                     is_count += 1
# 
#                     if is_count >= count:
#                         cycles = self.cpu.cycles - old_cycles
#                         output_lines = self.periphery.output.splitlines(True)  # with keepends
#                         return op_call_count, cycles, output_lines
# 
#         msg = "ERROR: Abort after %i op calls (%i cycles) %i %r found." % (
#             op_call_count, (self.cpu.cycles - old_cycles),
#             is_count, terminator,
#         )
#         raise self.failureException(msg)
# 
#     def _run_until_OK(self, OK_count=1, max_ops=5000):
#         return self._run_until(terminator="OK\r\n", count=OK_count, max_ops=max_ops)
# 
#     def _run_until_newlines(self, newline_count=1, max_ops=5000):
#         return self._run_until(terminator="\n", count=newline_count, max_ops=max_ops)


import logging
from dragonpy.tests.test_base import Test6809_sbc09_Base
from dragonpy.utils import srecord_utils
    Verify checksum and return the data from a srecord.
    If checksum failed, a Error will be raised.
    """
    assert isinstance(srec, str)
    blocks = [f"S{b}" for b in srec.split("S") if b]

    result = []
    for block in blocks:
        record_type, data_len, addr, data, checksum = srecord_utils.parse_srec(block)
        if record_type in ("S1", "S2", "S3"):  # Data lines
            result.append(data)
#        print record_type, data_len, addr, data, checksum

        raw_offset_srec = ''.join([record_type, data_len, addr, data])
        int_checksum = srecord_utils.compute_srec_checksum(raw_offset_srec)
        checksum2 = srecord_utils.int_to_padded_hex_byte(int_checksum)
        if not checksum == checksum2:
            raise ValueError(f"Wrong checksum {checksum} in line: {block}")

    return result


def split2chunks(seq, size):
    """
    >>> split2chunks("ABCEDFGH", 3)
    ['ABC', 'EDF', 'GH']
    """
    return [seq[pos:pos + size] for pos in range(0, len(seq), size)]



# Path: dragonpy/tests/test_base.py
# class Test6809_sbc09_Base(BaseCPUTestCase):
#     """
#     Run tests with the sbc09 ROM.
#     """
#     TEMP_FILE = os.path.join(
#         tempfile.gettempdir(),
#         f"DragonPy_sbc09_unittests_Py{sys.version_info[0]:d}.dat"
#     )
# 
#     @classmethod
#     def setUpClass(cls, cmd_args=None):
#         """
#         prerun ROM to complete initiate and ready for user input.
#         save the CPU state to speedup unittest
#         """
#         super().setUpClass()
# 
#         log.info(f"CPU state pickle file: {cls.TEMP_FILE!r}")
# #        if os.path.isfile(cls.TEMP_FILE):
# #            print("Delete CPU date file!")
# #            os.remove(cls.TEMP_FILE)
# 
#         cfg = SBC09Cfg(cls.UNITTEST_CFG_DICT)
# 
#         cls.user_input_queue = queue.Queue()
#         cls.display_callback = queue.Queue()
# 
#         cls.machine = Machine(
#             cfg,
#             periphery_class=SBC09PeripheryUnittest,
#             display_callback=cls.display_callback,
#             user_input_queue=cls.user_input_queue,
#         )
#         cls.cpu = cls.machine.cpu
#         cls.periphery = cls.machine.periphery
#         cls.periphery.setUp()
# 
#         try:
#             temp_file = open(cls.TEMP_FILE, "rb")
#         except OSError:
#             log.info("init machine...")
#             init_start = time.time()
#             cls.cpu.test_run(
#                 start=cls.cpu.program_counter.value,
#                 end=cfg.STARTUP_END_ADDR,
#             )
#             duration = time.time() - init_start
#             log.info("done in %iSec. it's %.2f cycles/sec. (current cycle: %i)" % (
#                 duration, float(cls.cpu.cycles / duration), cls.cpu.cycles
#             ))
# 
#             # Check if machine is ready
#             assert cls.periphery.output == (
#                 'Welcome to BUGGY version 1.0\r\n'
#             ), f"Outlines are: {repr(cls.periphery.output)}"
#             # Save CPU state
#             init_state = cls.cpu.get_state()
#             with open(cls.TEMP_FILE, "wb") as f:
#                 pickle.dump(init_state, f)
#                 log.info(f"Save CPU init state to: {cls.TEMP_FILE!r}")
#             cls.__init_state = init_state
#         else:
#             log.info(f"Load CPU init state from: {cls.TEMP_FILE!r}")
#             cls.__init_state = pickle.load(temp_file)
#             temp_file.close()
# 
# #         print_cpu_state_data(cls.__init_state)
# 
#     def setUp(self):
#         """ restore CPU/Periphery state to a fresh startup. """
#         self.periphery.setUp()
#         self.cpu.set_state(self.__init_state)
# #         print_cpu_state_data(self.cpu.get_state())
# 
#     def _run_until(self, terminator, count, max_ops):
#         old_cycles = self.cpu.cycles
#         last_output_len = 0
#         is_count = 0
#         for op_call_count in range(max_ops):
#             self.cpu.get_and_call_next_op()
# 
#             if self.periphery.output_len > last_output_len:
#                 last_output_len = self.periphery.output_len
# 
# #                 log.critical("output: %s", repr(self.periphery.output))
# 
#                 if self.periphery.output.endswith(terminator):
#                     is_count += 1
# 
#                     if is_count >= count:
#                         cycles = self.cpu.cycles - old_cycles
#                         output_lines = self.periphery.output.splitlines(True)  # with keepends
#                         return op_call_count, cycles, output_lines
# 
#         msg = "ERROR: Abort after %i op calls (%i cycles) %i %r found." % (
#             op_call_count, (self.cpu.cycles - old_cycles),
#             is_count, terminator,
#         )
#         raise self.failureException(msg)
# 
#     def _run_until_OK(self, OK_count=1, max_ops=5000):
#         return self._run_until(terminator="OK\r\n", count=OK_count, max_ops=max_ops)
# 
#     def _run_until_newlines(self, newline_count=1, max_ops=5000):
#         return self._run_until(terminator="\n", count=newline_count, max_ops=max_ops)


# Path: dragonpy/tests/test_sbc09.py
import logging
from dragonpy.tests.test_base import Test6809_sbc09_Base
from dragonpy.utils import srecord_utils

    Verify checksum and return the data from a srecord.
    If checksum failed, a Error will be raised.
    """
    assert isinstance(srec, str)
    blocks = [f"S{b}" for b in srec.split("S") if b]

    result = []
    for block in blocks:
        record_type, data_len, addr, data, checksum = srecord_utils.parse_srec(block)
        if record_type in ("S1", "S2", "S3"):  # Data lines
            result.append(data)
#        print record_type, data_len, addr, data, checksum

        raw_offset_srec = ''.join([record_type, data_len, addr, data])
        int_checksum = srecord_utils.compute_srec_checksum(raw_offset_srec)
        checksum2 = srecord_utils.int_to_padded_hex_byte(int_checksum)
        if not checksum == checksum2:
            raise ValueError(f"Wrong checksum {checksum} in line: {block}")

    return result


def split2chunks(seq, size):
    """
    >>> split2chunks("ABCEDFGH", 3)
    ['ABC', 'EDF', 'GH']
    """
    return [seq[pos:pos + size] for pos in range(0, len(seq), size)]



class Test_sbc09(Test6809_sbc09_Base):