def sf_read(u_boot_console, env__sf_config, sf_params):
    """Helper function used to read and compute the CRC32 value of a section of
    SPI Flash memory.

    Args:
        u_boot_console: A U-Boot console connection.
        env__sf_config: The single SPI Flash device configuration on which to
            run the tests.
        sf_params: SPI Flash parameters.

    Returns:
        CRC32 value of SPI Flash section
    """

    addr = sf_params['ram_base']
    offset = env__sf_config['offset']
    count = sf_params['len']
    pattern = random.randint(0, 0xFF)
    crc_expected = env__sf_config.get('crc32', None)

    cmd = 'mw.b %08x %02x %x' % (addr, pattern, count)
    u_boot_console.run_command(cmd)
    crc_pattern = u_boot_utils.crc32(u_boot_console, addr, count)
    if crc_expected:
        assert crc_pattern != crc_expected

    cmd = 'sf read %08x %08x %x' % (addr, offset, count)
    response = u_boot_console.run_command(cmd)
    assert 'Read: OK' in response, 'Read operation failed'
    crc_readback = u_boot_utils.crc32(u_boot_console, addr, count)
    assert crc_pattern != crc_readback, 'sf read did not update RAM content.'
    if crc_expected:
        assert crc_readback == crc_expected

    return crc_readback
def sf_update(u_boot_console, env__sf_config, sf_params):
    """Helper function used to update a section of SPI Flash memory.

   Args:
        u_boot_console: A U-Boot console connection.
        env__sf_config: The single SPI Flash device configuration on which to
           run the tests.

    Returns:
        CRC32 value of SPI Flash section
    """

    addr = sf_params['ram_base']
    offset = env__sf_config['offset']
    count = sf_params['len']
    pattern = int(random.random() * 0xFF)

    cmd = 'mw.b %08x %02x %x' % (addr, pattern, count)
    u_boot_console.run_command(cmd)
    crc_pattern = u_boot_utils.crc32(u_boot_console, addr, count)

    cmd = 'sf update %08x %08x %x' % (addr, offset, count)
    u_boot_console.run_command(cmd)
    crc_readback = sf_read(u_boot_console, env__sf_config, sf_params)

    assert crc_readback == crc_pattern
def test_sf_erase(u_boot_console, env__sf_config):
    if not env__sf_config.get('writeable', False):
        pytest.skip('Flash config is tagged as not writeable')

    sf_params = sf_prepare(u_boot_console, env__sf_config)
    addr = sf_params['ram_base']
    offset = env__sf_config['offset']
    count = sf_params['len']

    cmd = 'sf erase %08x %x' % (offset, count)
    output = u_boot_console.run_command(cmd)
    assert 'Erased: OK' in output, 'Erase operation failed'

    cmd = 'mw.b %08x ff %x' % (addr, count)
    u_boot_console.run_command(cmd)
    crc_ffs = u_boot_utils.crc32(u_boot_console, addr, count)

    crc_read = sf_read(u_boot_console, env__sf_config, sf_params)
    assert crc_ffs == crc_read, 'Unexpected CRC32 after erase operation.'