Steven Teglman
Steven Teglman

Reputation: 107

How do I repeat a python PyTest multiple times, utilizing values carried over from the previous test

I'm trying to create a test which involves sending data to an external piece of hardware, rebooting that hardware, and asserting whether the hardware's data matches what was previously sent. This will be repeated 1000's of times, ultimately.

So the steps look like this:

  1. Query hardware for current running ID (the beforementioned data)
  2. Compare and assert it's still the same as id that was previously sent (or in the first test "id = 1)
  3. Create a new id (id += 1), save it somewhere, and then send it to the hardware.
  4. Repeat.

My question is how do I carry over this saved "id" between tests to compare? I was going to just read/write from a json as I've seen many people saying global variables are bad, but I'm not sure saving to a json is the best option.

Upvotes: 2

Views: 3016

Answers (1)

Roland Smith
Roland Smith

Reputation: 43495

One thing you could do is run a for-loop in the test.

def test_hardware():
    previous_id = 1
    set_hardware_id(1)
    for i in range(2, 100):
        current_id = get_hardware_id()
        # this fill fail at the first mismatch
        assert current_id == previous_id
        previous_id = current_id
        set_hardware_id(i)

If you want to run the whole test itself repeatedly, use the @pytest.mark.parametrize decorator.

@pytest.mark.parametrize("test_input", range(100))
def test_hardware(test_input):
    set_hardware_id(test_input)
    result = get_hardware_id()
    assert result == test_input

Upvotes: 5

Related Questions