len(test_data) +
                    16) == b'\xaa' * 8 + test_data + b'\xaa' * 8

                cur_tag = (cur_tag + 1) % tag_count

    await RisingEdge(dut.clk)
    await RisingEdge(dut.clk)


def cycle_pause():
    return itertools.cycle([1, 1, 1, 0])


if cocotb.SIM_NAME:

    factory = TestFactory(run_test_read)
    factory.add_option(("idle_inserter", "backpressure_inserter"),
                       [(None, None), (cycle_pause, cycle_pause)])
    factory.generate_tests()

# cocotb-test

tests_dir = os.path.dirname(__file__)
rtl_dir = os.path.abspath(os.path.join(tests_dir, '..', '..', 'rtl'))


@pytest.mark.parametrize("pcie_offset",
                         list(range(4)) + list(range(4096 - 4, 4096)))
@pytest.mark.parametrize("axis_pcie_data_width", [64, 128, 256, 512])
def test_pcie_us_axi_dma_rd(request, axis_pcie_data_width, pcie_offset):
    dut = "pcie_us_axi_dma_rd"
Example #2
0
    expected = calc_expected(width, wr_data, leak)
    assert len(
        m_axis.buffer) == test_size, f'{len(m_axis.buffer)} != {test_size}'
    assert len(s_axis.buffer) == len(
        expected), f'{len(s_axis.buffer)} != {len(expected)}'
    assert rd_data == expected, f'\n{rd_data}\n!=\n{expected}'


try:
    running_cocotb = True
    leak = int(os.environ['coco_param_leak'], 10)
except KeyError as e:
    running_cocotb = False

if running_cocotb:
    tf_test_data = TF(check_data)
    tf_test_data.add_option('leak', [leak])
    tf_test_data.add_option('burps_in', [False, True])
    tf_test_data.add_option('burps_out', [False, True])
    tf_test_data.generate_tests()


@pytest.mark.timeout(10)
@pytest.mark.parametrize("width, leak", [
    (8, 0),
    (8, 1),
    (8, 7),
    (8, 8),
])
def test_main(width, leak):
    os.environ['coco_param_leak'] = str(leak)
Example #3
0
        signal <= 0
        yield Timer(5000) # ps
        signal <= 1
        yield Timer(5000) # ps

# ==============================================================================
@cocotb.coroutine
def run_test(dut):
    """Setup testbench and run a test."""
    cocotb.fork(clock_gen(dut.c))
    tb = DFF_TB(dut, BinaryValue(0,1))
    clkedge = RisingEdge(dut.c)

    # Apply random input data by input_gen via BitDriver for 100 clock cycle.
    tb.start()
    for i in range(100):
        yield clkedge

    # Stop generation of input data. One more clock cycle is needed to capture
    # the resulting output of the DUT.
    tb.stop()
    yield clkedge

    # Print result of scoreboard.
    raise tb.scoreboard.result

# ==============================================================================
# Register test.
factory = TestFactory(run_test)
factory.generate_tests()
def size_list():
    return list(range(60, 128)) + [512, 1514] + [60] * 10


def incrementing_payload(length):
    return bytearray(itertools.islice(itertools.cycle(range(256)), length))


def cycle_en():
    return itertools.cycle([0, 0, 0, 1])


if cocotb.SIM_NAME:

    factory = TestFactory(run_test)
    factory.add_option("payload_lengths", [size_list])
    factory.add_option("payload_data", [incrementing_payload])
    factory.add_option("ifg", [12, 0])
    factory.add_option("enable_gen", [None, cycle_en])
    factory.add_option("mii_sel", [False, True])
    factory.generate_tests()

# cocotb-test

tests_dir = os.path.abspath(os.path.dirname(__file__))
rtl_dir = os.path.abspath(os.path.join(tests_dir, '..', '..', 'rtl'))
lib_dir = os.path.abspath(os.path.join(rtl_dir, '..', 'lib'))
axis_rtl_dir = os.path.abspath(os.path.join(lib_dir, 'axis', 'rtl'))

def size_list():
    return list(range(60, 128)) + [512, 1514, 9214] + [60] * 10


def incrementing_payload(length):
    return bytearray(itertools.islice(itertools.cycle(range(256)), length))


def cycle_en():
    return itertools.cycle([0, 0, 0, 1])


if cocotb.SIM_NAME:

    factory = TestFactory(run_test)
    factory.add_option("payload_lengths", [size_list])
    factory.add_option("payload_data", [incrementing_payload])
    factory.add_option("ifg", [12])
    factory.add_option("enable_dic", [True, False])
    factory.add_option("force_offset_start", [False, True])
    factory.generate_tests()

    factory = TestFactory(run_test_alignment)
    factory.add_option("payload_data", [incrementing_payload])
    factory.add_option("ifg", [12])
    factory.add_option("enable_dic", [True, False])
    factory.add_option("force_offset_start", [False, True])
    factory.generate_tests()

# cocotb-test
    if (dut.s != expected_s):
        raise TestFailure(
            """Error sum value,wrong value = {0}, expected value is {1}""".
            format(hex(int(dut.s.value)), hex(expected_s)))

    if (dut.c != expected_c):
        raise TestFailure(
            """Error carry value,wrong value = {0}, expected value is {1}""".
            format(hex(int(dut.c.value)), hex(expected_c)))


@cocotb.coroutine
def run_test(dut, a=0, b=0):

    print(hex(a))
    print(hex(b))
    expected_s = (a + b) & ((2**32) - 1)
    expected_c = ((a + b) >> 32) & 0x01

    setup_function(dut, a, b)
    yield calculate_result(dut, expected_s, expected_c)


n = 10
factory = TestFactory(run_test)

factory.add_option("a", np.random.randint(low=0, high=(2**32) - 1, size=n))
factory.add_option("b", np.random.randint(low=0, high=(2**32) - 1, size=n))
factory.generate_tests()
Example #7
0
    def O5(self):
        return eval(self.init.binstr[-1 - self.inputs.integer])

    @property
    def O6(self):
        return eval(self.init.binstr[-1 - self.inputs.integer])


@cocotb.coroutine
def lut_basic_test(dut, inputs):
    """Test for LUT options"""

    yield Timer(1)

    for i in range(6):
        setattr(dut, 'A%d' % (i + 1), inputs & (1 << i))
    yield Timer(1)
    model = LutModel(dut.INIT.value, inputs)

    if dut.O5 != model.O5 or dut.O6 != model.O6:
        raise TestFailure('No match (dut:model) O5(%d:%d) O6(%d:%d)' % \
                          (dut.O5, model.O5, dut.O6, model.O6))
    else:
        dut._log.info('Match')


factory = TestFactory(lut_basic_test)
input_permutations = range(2**6)
factory.add_option("inputs", input_permutations)
factory.generate_tests()
Example #8
0

def nonzero_incrementing_payload_zero_framed(length):
    return bytearray(
        [0] + list(itertools.islice(itertools.cycle(range(1, 256)), length)) +
        [0])


def prbs_payload(length):
    gen = prbs31()
    return bytearray([next(gen) for x in range(length)])


if cocotb.SIM_NAME:

    factory = TestFactory(run_test)
    factory.add_option("payload_lengths", [size_list])
    factory.add_option("payload_data", [
        zero_payload, nonzero_incrementing_payload,
        nonzero_incrementing_payload_zero_framed, prbs_payload
    ])
    factory.add_option("idle_inserter", [None, cycle_pause])
    factory.add_option("backpressure_inserter", [None, cycle_pause])
    factory.generate_tests()

# cocotb-test

tests_dir = os.path.dirname(__file__)
rtl_dir = os.path.abspath(os.path.join(tests_dir, '..', '..', 'rtl'))

    """Run an image file through the jpeg encoder and compare the result"""
    cocotb.fork(Clock(dut.clk, 100).start())
    #Overwriting debug (original) with the one from env
    debug = os.getenv('COCOTB_DEBUG') # None/1

    driver = ImageDriver(dut)
    monitor = JpegMonitor(dut)

    if debug:                                            # pragma: no cover
        driver.log.setLevel(logging.DEBUG)
        monitor.log.setLevel(logging.DEBUG)

    stimulus = Image.open(filename)
    yield driver.send(stimulus)
    output = yield monitor.wait_for_recv()

    if debug:                                            # pragma: no cover
        output.save(filename + "_process.jpg")

    difference = compare(stimulus, output)

    dut.log.info("Compressed image differs to original by %f%%" % (difference))

    if difference > threshold:                           # pragma: no cover
        raise TestFailure("Resulting image file was too different (%f > %f)" %
                          (difference, threshold))

tf = TestFactory(process_image)
tf.add_option("filename", [os.path.join('test_images', f)
                            for f in os.listdir('test_images')])
tf.generate_tests()
Example #10
0
        if errors:
            raise TestFailure("Error bounds exceeded.")
        else:
            raise TestSuccess("Test finished OK.")

    def start(self):
        self.drive_coro = cocotb.fork(self.drive_fft())
        self.read_coro = cocotb.fork(self.read_fft())

    @cocotb.coroutine
    def join(self):
        yield self.drive_coro.join()
        yield self.read_coro.join()

@cocotb.coroutine
def fft_test(dut, stimulus=FFTStimulus.STIM_SIN, mode=FFTMode.MODE_FFT, plot=False):
    error_spec = {}
    error_spec["offset"] = 3
    error_spec["rms"] = 6
    error_spec["gain"] = 3
    tb = FFTTestBench(dut, stimulus, mode, plot, error_spec_lsb=error_spec, num_ffts=10)    

    yield init_dut(dut)
    tb.start()
    yield tb.join()

tf = TestFactory(fft_test)
tf.add_option("stimulus", FFTStimulus)
tf.add_option("mode", FFTMode)
tf.generate_tests()
Example #11
0
import operator
from cocotb.regression import TestFactory
from spinal.RiscvTester.RiscvTester import  isaTestsMemory, isaTestsMulDiv, isaTestsBase, testIsa


factory = TestFactory(testIsa)
factory.add_option("iHexPath",  map(lambda x : "../" + x,reduce(operator.add, [isaTestsBase, isaTestsMemory, isaTestsMulDiv])))
factory.generate_tests()
Example #12
0
    for index, values in enumerate(data_generator(bits=len(dut.in1))):
        expected.append(sorted(values))

        yield RisingEdge(dut.clk)
        dut.in1 = values[0]
        dut.in2 = values[1]
        dut.in3 = values[2]
        dut.in4 = values[3]
        dut.in5 = values[4]

        yield ReadOnly()
        expect = expected.pop(0)

        if expect is None: continue


        got = [int(dut.out5), int(dut.out4), int(dut.out3),
               int(dut.out2), int(dut.out1)]

        if got != expect:
            dut.log.error('Expected %s' % expect)
            dut.log.error('Got %s' % got)
            raise TestFailure("Output didn't match")

    dut.log.info('Sucessfully sent %d cycles of data' % (index + 1))

# Generate permutations of the test
tests = TestFactory(run_test)
tests.add_option('data_generator', [random_data, corner_cases])
tests.generate_tests()
Example #13
0

def random_packet_sizes(min_size=1, max_size=150, npackets=10):
    """random string data of a random length"""
    for i in range(npackets):
        yield get_bytes(random.randint(min_size, max_size), random_data())


@cocotb.coroutine
def randomly_switch_config(csr):
    """Twiddle the byteswapping config register"""
    while True:
        yield csr.write(0, random.randint(0, 1))


factory = TestFactory(run_test)
factory.add_option("data_in",
                   [random_packet_sizes])
factory.add_option("config_coroutine",
                   [None, randomly_switch_config])
factory.add_option("idle_inserter",
                   [None, wave, intermittent_single_cycles, random_50_percent])
factory.add_option("backpressure_inserter",
                   [None, wave, intermittent_single_cycles, random_50_percent])
factory.generate_tests()

import cocotb.wavedrom


@cocotb.test()
def wavedrom_test(dut):
Example #14
0
        self.stopped = True


async def run_test(dut):
    """Setup testbench and run a test."""

    cocotb.fork(Clock(dut.c, 10, 'us').start(start_high=False))

    tb = DFF_TB(dut, init_val=BinaryValue(0))

    clkedge = RisingEdge(dut.c)

    # Apply random input data by input_gen via BitDriver for 100 clock cycles.
    tb.start()
    for _ in range(100):
        await clkedge

    # Stop generation of input data. One more clock cycle is needed to capture
    # the resulting output of the DUT.
    tb.stop()
    await clkedge

    # Print result of scoreboard.
    raise tb.scoreboard.result


# Register the test.
factory = TestFactory(run_test)
factory.generate_tests()
set_top_level("dff", "entity", "lib")
Example #15
0
    # TODO: Fragmentation is not implemented, so expect truncated packets
    tb.expect_memwrite(DMA_WND_START, header + endian_swap(payload[:224]))
    await with_timeout(tb.data_tx.send(payload, channel=channel), 1000, 'ns')
    await RisingEdge(dut.clk)
    cntr = await tb.csr.read(0x6) # csr_c2h_staging_counter
    assert cntr == 1, 'expected csr_c2h_staging_counter to be incremented to 1'
    await Timer(1000, 'ns')
    assert tb.dut.irq_c2h_avail == 1, 'expected irq_c2h_avail to be high'
    wptr = await tb.csr.read(0x2b) # c2h_dma_card_write_ptr
    await tb.csr.write(0x2a, wptr) # c2h_dma_host_read_ptr
    await Timer(100, 'ns')
    assert tb.dut.irq_c2h_avail == 0, 'expected irq_c2h_avail to be reset'
    raise tb.scoreboard.result


c2h_factory = TestFactory(run_c2h_dma_test)
# TODO:
# - Add packet fragmentation
c2h_factory.add_option('dwords', [1, 8, 15, 100, 512])
c2h_factory.add_option('channel', [0, 3])
c2h_factory.generate_tests()


@cocotb.test()
async def test_c2h_dma_pressure(dut):
    """Test C2H DMA pressure."""
    clock = Clock(dut.clk, 10, units='ns')
    cocotb.fork(clock.start())
    tb = TestC2H(dut)
    channel = 2
    await tb.reset()
Example #16
0
    return list(range(60, 128)) + [512, 1514] + [60] * 10


def incrementing_payload(length):
    return bytearray(itertools.islice(itertools.cycle(range(256)), length))


def cycle_en():
    return itertools.cycle([0, 0, 0, 1])


if cocotb.SIM_NAME:

    for test in [run_test_rx, run_test_tx]:

        factory = TestFactory(test)
        factory.add_option("payload_lengths", [size_list])
        factory.add_option("payload_data", [incrementing_payload])
        factory.add_option("ifg", [12])
        factory.add_option("speed", [100e6, 10e6])
        factory.generate_tests()

# cocotb-test

tests_dir = os.path.abspath(os.path.dirname(__file__))
rtl_dir = os.path.abspath(os.path.join(tests_dir, '..', '..', 'rtl'))
lib_dir = os.path.abspath(os.path.join(rtl_dir, '..', 'lib'))
axis_rtl_dir = os.path.abspath(os.path.join(lib_dir, 'axis', 'rtl'))


def test_eth_mac_mii(request):
Example #17
0
async def run_test(dut, config_clock):
    MAX_WIDTH = int(os.environ['PARAM_DATA_WIDTH'])
    TEST_RUNS = int(os.environ['TEST_RUNS'])
    await setup_dut(dut, config_clock)
    await reset_dut(dut)

    for i in range(TEST_RUNS):
        data = 2**random.randint(0,MAX_WIDTH)-1
        dut.async_i.setimmediatevalue(data)
        await ClockCycles(dut.clk_sync, 3)
        print(f"Expected ["+str(data)+"], dut.sync_o.value ["+str(dut.sync_o.value)+"]")
        assert data == dut.sync_o.value, "Unexpected 3FF behavior!"

if cocotb.SIM_NAME:
    factory = TestFactory(run_test)
    factory.add_option('config_clock', [0, 1])
    factory.generate_tests()

@pytest.mark.parametrize("width",[1,2,4,8])
def test_3ff(width):
    tests_dir = os.path.dirname(os.path.abspath(__file__))
    rtl_dir   = tests_dir
    dut = "cdc_3ff_sync"
    module = os.path.splitext(os.path.basename(__file__))[0]
    toplevel = dut
    verilog_sources = [
        os.path.join(rtl_dir, f"../src/{dut}.sv"),
    ]
    parameters = {}
    parameters['DATA_WIDTH'] = width
Example #18
0
import operator
from cocotb.regression import TestFactory
from spinal.RiscvTester.RiscvTester import  isaTestsMemory, isaTestsMulDiv, isaTestsBase, testIsa

from cocotblib.misc import cocotbXHack
cocotbXHack()

factory = TestFactory(testIsa)
factory.add_option("iHexPath",  reduce(operator.add, [isaTestsBase, isaTestsMemory, isaTestsMulDiv]))
factory.generate_tests()
Example #19
0
# Copyright cocotb contributors
# Licensed under the Revised BSD License, see LICENSE for details.
# SPDX-License-Identifier: BSD-3-Clause
"""
Tests of cocotb.regression.TestFactory functionality
"""
import cocotb
from cocotb.regression import TestFactory

testfactory_test_args = set()


async def run_testfactory_test(dut, arg1, arg2, arg3):
    testfactory_test_args.add((arg1, arg2, arg3))


factory = TestFactory(run_testfactory_test)
factory.add_option("arg1", ["a1v1", "a1v2"])
factory.add_option(("arg2", "arg3"), [("a2v1", "a3v1"), ("a2v2", "a3v2")])
factory.generate_tests()


@cocotb.test()
async def test_testfactory_verify_args(dut):
    assert testfactory_test_args == {
        ("a1v1", "a2v1", "a3v1"),
        ("a1v2", "a2v1", "a3v1"),
        ("a1v1", "a2v2", "a3v2"),
        ("a1v2", "a2v2", "a3v2"),
    }
    raise tb.scoreboard.result


def random_packet_sizes(min_size=1, max_size=150, npackets=10):
    """random string data of a random length"""
    for i in range(npackets):
        yield get_bytes(random.randint(min_size, max_size), random_data())


async def randomly_switch_config(csr):
    """Twiddle the byteswapping config register"""
    while True:
        await csr.write(0, random.randint(0, 1))


factory = TestFactory(run_test)
factory.add_option("data_in", [random_packet_sizes])
factory.add_option("config_coroutine", [None, randomly_switch_config])
factory.add_option("idle_inserter",
                   [None, wave, intermittent_single_cycles, random_50_percent])
factory.add_option("backpressure_inserter",
                   [None, wave, intermittent_single_cycles, random_50_percent])
factory.generate_tests()

import cocotb.wavedrom


@cocotb.test()
async def wavedrom_test(dut):
    """
    Generate a JSON wavedrom diagram of a trace and save it to wavedrom.json
        make_fvec(3.125, 3.125, 3.125),
        0,
    ),
    (  # Scalar 1
        fixed_from_float(1),
        make_fvec(1.25, 3.125, 0),
        make_fvec(1.25, 3.125, 0),
        0,
    ),
    (  # 32
        fixed_from_float(16),
        make_fvec(-1.96484375, 2.03515625, 2.0),
        make_fvec(-31.4375, 32.5625, 32.0),
        0,
    ),
]


@cocotb.coroutine
def run_test(dut, input_data):
    tb = ScalarMulTestbench(dut)

    op1, op2, result, overflow = input_data
    tb.set_inputs(op1, op2)

    yield tb.assert_result(result, overflow)


tests = TestFactory(run_test)
tests.add_option('input_data', inputs)
generate_tests_for(tests)
Example #22
0
import operator
from cocotb.regression import TestFactory
from spinal.RiscvTester.RiscvTester import isaTestsMemory, isaTestsMulDiv, isaTestsBase, testIsa

from cocotblib.misc import cocotbXHack
cocotbXHack()

factory = TestFactory(testIsa)
factory.add_option(
    "iHexPath",
    reduce(operator.add, [isaTestsBase, isaTestsMemory, isaTestsMulDiv]))
factory.generate_tests()
Example #23
0
def cycle_pause():
    return itertools.cycle([1, 1, 1, 0])


def size_list():
    return list(range(1, 128)) + [512, 1500, 9200] + [46] * 10


def incrementing_payload(length):
    return bytes(itertools.islice(itertools.cycle(range(256)), length))


if cocotb.SIM_NAME:

    factory = TestFactory(run_test)
    factory.add_option("pkt_type", [Ether, IP, UDP, TCP])
    factory.add_option("payload_lengths", [size_list])
    factory.add_option("payload_data", [incrementing_payload])
    factory.add_option("idle_inserter", [None, cycle_pause])
    factory.generate_tests()

# cocotb-test

tests_dir = os.path.dirname(__file__)
rtl_dir = os.path.abspath(os.path.join(tests_dir, '..', '..', 'rtl'))
lib_dir = os.path.abspath(os.path.join(rtl_dir, '..', 'lib'))
axi_rtl_dir = os.path.abspath(os.path.join(lib_dir, 'axi', 'rtl'))
axis_rtl_dir = os.path.abspath(os.path.join(lib_dir, 'axis', 'rtl'))
eth_rtl_dir = os.path.abspath(os.path.join(lib_dir, 'eth', 'rtl'))
pcie_rtl_dir = os.path.abspath(os.path.join(lib_dir, 'pcie', 'rtl'))
Example #24
0
    await RisingEdge(dut.clk)


def cycle_pause():
    return itertools.cycle([1, 1, 1, 0])


if cocotb.SIM_NAME:

    data_width = len(cocotb.top.s_axi_wdata)
    byte_lanes = data_width // 8
    max_burst_size = (byte_lanes-1).bit_length()

    for test in [run_test_write, run_test_read]:

        factory = TestFactory(test)
        factory.add_option("idle_inserter", [None, cycle_pause])
        factory.add_option("backpressure_inserter", [None, cycle_pause])
        factory.add_option("size", [None]+list(range(max_burst_size)))
        factory.generate_tests()

    factory = TestFactory(run_stress_test)
    factory.generate_tests()


# cocotb-test

tests_dir = os.path.abspath(os.path.dirname(__file__))
rtl_dir = os.path.abspath(os.path.join(tests_dir, '..', '..', 'rtl'))

Example #25
0
    await tb.reset()

    dut.m_axis_tready <= 1
    
    if backpressure_inserter is not None:
        tb.backpressure.start(backpressure_inserter())

    dut._log.info('Send Wt parsed from message')
    # Send in the packets
    for transaction in format_wt(codec):
        tb.s_axis.bus.tuser <= BinaryValue(80*'0'+little_endian_codec(codec)+32*'0')
        #transaction = format_wt_message(transaction, sha_type=sha_type)
        await tb.s_axis.send(transaction)

    dut._log.info('Wait for last outgoing transaction to be monitored')
    # Wait for last transmission
    while not (dut.m_axis_tlast.value and dut.m_axis_tvalid.value and dut.m_axis_tready.value):
        await RisingEdge(dut.axis_aclk)
    for _ in range(3):
        await RisingEdge(dut.axis_aclk)
    
    dut._log.info("DUT testbench finished!")

    raise tb.scoreboard.result

factory = TestFactory(run_test)
factory.add_option('codec', [0x12,0x13,0x09,0x10])
factory.add_option('data_in', [format_wt])
#factory.add_option('H_in', [random_hash_stream])
factory.generate_tests()

def size_list():
    data_width = max(len(cocotb.top.m_axis_tdata),
                     len(cocotb.top.s_axis_tdata))
    byte_width = data_width // 8
    return list(range(1, byte_width * 4 + 1)) + [512] + [1] * 64


def incrementing_payload(length):
    return bytearray(itertools.islice(itertools.cycle(range(256)), length))


if cocotb.SIM_NAME:

    factory = TestFactory(run_test)
    factory.add_option("payload_lengths", [size_list])
    factory.add_option("payload_data", [incrementing_payload])
    factory.add_option("idle_inserter", [None, cycle_pause])
    factory.add_option("backpressure_inserter", [None, cycle_pause])
    factory.generate_tests()

    for test in [
            run_test_tuser_assert, run_test_init_sink_pause,
            run_test_init_sink_pause_reset, run_test_overflow
    ]:

        factory = TestFactory(test)
        factory.generate_tests()

    factory = TestFactory(run_stress_test)
Example #27
0
    r = [random.getrandbits(width_a) for _ in range(15)]
    yield m_axis.send(r, burps=burps_in)
    yield s_axis.recv(1, burps=burps_out)

    m_axis.buffer[:] = []
    s_axis.buffer[:] = []
    rom.buffer[:] = []
    data_in = [random.getrandbits(width_a) for _ in range(test_size)]

    cocotb.fork(m_axis.send(data_in, burps_in))
    yield s_axis.recv(test_size, burps_out)

    check_output(m_axis.buffer, rom.buffer, s_axis.buffer, shift=shift)


tf_test_random = TF(check_data)
tf_test_random.add_option('burps_in', [False, True])
tf_test_random.add_option('burps_out', [False, True])
tf_test_random.add_option('dummy', [0] * 5)
tf_test_random.add_option('profile', ['random'])
tf_test_random.generate_tests(postfix='_random')

tf_test_limit = TF(check_data)
tf_test_limit.add_option('profile', ['limit'])
tf_test_limit.generate_tests(postfix='_limit')

tf_test_multiple = TF(check_multiple)
tf_test_multiple.add_option('burps_in', [False, True])
tf_test_multiple.add_option('burps_out', [False, True])
tf_test_multiple.add_option('dummy', [0] * 5)
tf_test_multiple.generate_tests()
Example #28
0
import cocotb
from cocotb.regression import TestFactory
from cocotb.triggers import NullTrigger

testfactory_test_names = set()
testfactory_test_args = set()
prefix = "".join(random.choices(string.ascii_letters, k=4))
postfix = "".join(random.choices(string.ascii_letters, k=4))


async def run_testfactory_test(dut, arg1, arg2, arg3):
    testfactory_test_names.add(cocotb.regression_manager._test.__qualname__)
    testfactory_test_args.add((arg1, arg2, arg3))


factory = TestFactory(run_testfactory_test)
factory.add_option("arg1", ["a1v1", "a1v2"])
factory.add_option(("arg2", "arg3"), [("a2v1", "a3v1"), ("a2v2", "a3v2")])
factory.generate_tests(prefix=prefix, postfix=postfix)


@cocotb.test()
async def test_testfactory_verify_args(dut):
    assert testfactory_test_args == {
        ("a1v1", "a2v1", "a3v1"),
        ("a1v2", "a2v1", "a3v1"),
        ("a1v1", "a2v2", "a3v2"),
        ("a1v2", "a2v2", "a3v2"),
    }
    assert testfactory_test_names == {
        f"{prefix}run_testfactory_test{postfix}_{i:03}"
            format(hex(int(dut.Mo[1].value)), hex(expected_Mo[1])))
    if (dut.Si[0] != expected_Si[0]):
        raise TestFailure(
            """Error Si_0 value,wrong value = {0}, expected value is {1}""".
            format(hex(int(dut.Si[0].value)), hex(expected_Si[0])))
    if (dut.Si[1] != expected_Si[1]):
        raise TestFailure(
            """Error Si_1 value,wrong value = {0}, expected value is {1}""".
            format(hex(int(dut.Si[1].value)), hex(expected_Si[1])))


@cocotb.coroutine
def run_test(dut, key=0):
    key = random.randint(0, (2**128) - 1)
    #print(hex(key))
    #key = 0
    twofish_SW = twofish.Twofish(key)
    expected_Me = twofish_SW.M_e
    expected_Mo = twofish_SW.M_o
    expected_Si = twofish_SW.S_i
    setup_function(dut, key)
    yield calculate_values(dut, expected_Me, expected_Mo, expected_Si)


n = 1
factory = TestFactory(run_test)

factory.add_option("key", np.random.randint(
    low=0, high=(2**32) - 1, size=n))  #array de 10 int aleatorios entre 0 y 31
factory.generate_tests()
Example #30
0
    return list(range(60, 128)) + [512, 1514, 9214] + [60] * 10


def incrementing_payload(length):
    return bytearray(itertools.islice(itertools.cycle(range(256)), length))


def cycle_en():
    return itertools.cycle([0, 0, 0, 1])


if cocotb.SIM_NAME:

    for test in [run_test_rx, run_test_tx]:

        factory = TestFactory(test)
        factory.add_option("payload_lengths", [size_list])
        factory.add_option("payload_data", [incrementing_payload])
        factory.add_option("ifg", [12, 0])
        factory.generate_tests()

    factory = TestFactory(run_test_tx_alignment)
    factory.add_option("payload_data", [incrementing_payload])
    factory.add_option("ifg", [12])
    factory.generate_tests()

# cocotb-test

tests_dir = os.path.abspath(os.path.dirname(__file__))
rtl_dir = os.path.abspath(os.path.join(tests_dir, '..', '..', 'rtl'))
lib_dir = os.path.abspath(os.path.join(rtl_dir, '..', 'lib'))
Example #31
0
    if backpressure_inserter is not None:
        tb.backpressure.start(backpressure_inserter())

    # Send in the packets
    for transaction in data_in():
        tb.s_axis.bus.tuser <= BinaryValue(80 * '0' +
                                           little_endian_codec(codec) +
                                           32 * '0')
        await tb.s_axis.send(transaction, tuser=get_bytes(16, random_data()))

    # Wait for last transmission
    await RisingEdge(dut.axis_aclk)
    while not (dut.m_axis_tlast.value and dut.m_axis_tvalid.value
               and dut.m_axis_tready.value):
        await RisingEdge(dut.axis_aclk)

    for _ in range(3):
        await RisingEdge(dut.axis_aclk)

    dut._log.info("DUT testbench finished!")

    raise tb.scoreboard.result


# Register the test.
factory = TestFactory(run_test)
factory.add_option("codec", [0x11, 0x12, 0x13])
factory.add_option("data_in", [random_message])
factory.add_option("backpressure_inserter", [None, random_50_percent])
factory.generate_tests()
Example #32
0
    return list(range(60, 128)) + [512, 1514, 9214] + [60] * 10


def incrementing_payload(length):
    return bytearray(itertools.islice(itertools.cycle(range(256)), length))


def cycle_en():
    return itertools.cycle([0, 0, 0, 1])


if cocotb.SIM_NAME:

    for test in [run_test_rx, run_test_tx]:

        factory = TestFactory(test)
        factory.add_option("payload_lengths", [size_list])
        factory.add_option("payload_data", [incrementing_payload])
        factory.add_option("ifg", [12])
        factory.generate_tests()

    factory = TestFactory(run_test_rx_frame_sync)
    factory.generate_tests()

# cocotb-test

tests_dir = os.path.abspath(os.path.dirname(__file__))
rtl_dir = os.path.abspath(os.path.join(tests_dir, '..', '..', 'rtl'))
lib_dir = os.path.abspath(os.path.join(rtl_dir, '..', 'lib'))
axis_rtl_dir = os.path.abspath(os.path.join(lib_dir, 'axis', 'rtl'))
Example #33
0
            iv = int.from_bytes(storage_file.read(16), byteorder='little')

            print(hex(key))
            print(hex(iv))

            setup_function(dut, key, iv, 0, 0)
            yield rst_function_test(dut)

            for j in range(0, n_blocks):
                print(j)
                plaintext = int.from_bytes(storage_file.read(16),
                                           byteorder='little')
                ciphertext = int.from_bytes(storage_file.read(16),
                                            byteorder='little')

                if (index == 0):
                    yield enc_dec_test(dut, j, plaintext, ciphertext)
                else:
                    yield enc_dec_test(dut, j, ciphertext, plaintext)

                yield rst_function_test(dut)

            n_blocks = int.from_bytes(storage_file.read(4), byteorder='little')


n = 2
factory = TestFactory(run_test)

factory.add_option("index", range(0,
                                  n))  #array de 10 int aleatorios entre 0 y 31
factory.generate_tests()
Example #34
0
    await RisingEdge(dut.clk)


def cycle_pause():
    return itertools.cycle([1, 1, 1, 0])


if cocotb.SIM_NAME:

    data_width = len(cocotb.top.s_axi_wdata)
    byte_lanes = data_width // 8
    max_burst_size = (byte_lanes - 1).bit_length()

    for test in [run_test_write, run_test_read]:

        factory = TestFactory(test)
        factory.add_option("idle_inserter", [None, cycle_pause])
        factory.add_option("backpressure_inserter", [None, cycle_pause])
        factory.add_option("size", [None] + list(range(max_burst_size)))
        factory.generate_tests()

    factory = TestFactory(run_stress_test)
    factory.generate_tests()

# cocotb-test

tests_dir = os.path.abspath(os.path.dirname(__file__))
rtl_dir = os.path.abspath(os.path.join(tests_dir, '..', '..', 'rtl'))


@pytest.mark.parametrize("delay", [0, 1])
Example #35
0
    for c in range(0, 5):
        yield RisingEdge(dut.clk)

    for c in range(0, 5):
        cnt = random.getrandbits(32)
        yield drv.set_count(cnt, ClockCycles(dut.clk, hold_cycles))
        exp = {
            "name": "set count",
        }

        for w in range(0, wait_cycles):
            exp["cntdwn"] = BinaryValue(cnt, bits=32, bigEndian=False)
            yield tb.expect(exp)
            yield RisingEdge(dut.clk)
            cnt = cnt + 1


random.seed(time.time())
clk_t = 2000
exit_on_fail = True

fact = TestFactory(tmr_test_set_count)
fact.add_option("hold_cycles", [1, 2, 3, 10])
fact.add_option("wait_cycles", [1, 2, 3, 10])
fact.generate_tests()

fact = TestFactory(tmr_test_alarm)
fact.add_option("lapse", [1, 2, 3, 10, 100])
fact.add_option("lapse_cycles", [1, 2, 3, 10])
fact.generate_tests()
Example #36
0
def size_list():
    return list(range(1, 16)) + [128]


def incrementing_payload(length):
    return bytearray(itertools.islice(itertools.cycle(range(256)), length))


def prbs_payload(length):
    gen = prbs31()
    return bytearray([next(gen) for x in range(length)])


if cocotb.SIM_NAME:

    factory = TestFactory(run_test)
    factory.add_option("payload_lengths", [size_list])
    factory.add_option("payload_data", [incrementing_payload, prbs_payload])
    factory.generate_tests()

# cocotb-test

tests_dir = os.path.abspath(os.path.dirname(__file__))
rtl_dir = os.path.abspath(os.path.join(tests_dir, '..', '..', 'rtl'))


def test_uart_tx(request):
    dut = "uart_tx"
    module = os.path.splitext(os.path.basename(__file__))[0]
    toplevel = dut
Example #37
0
import operator
from cocotb.regression import TestFactory
from spinal.RiscvTester.RiscvTester import  isaTestsMemory, isaTestsMulDiv, isaTestsBase, testIsa

from cocotblib.misc import cocotbXHack
cocotbXHack()

factory = TestFactory(testIsa)
factory.add_option("iHexPath",  map(lambda x : "../" + x,reduce(operator.add, [["../Pinsec/hex/dhrystone.hex"]])))
factory.generate_tests()