0

I would like to run test several times according to given list. I build the list according to a given file at the 'setup_module' section. Is it possible to do something like this?

data = []

def setup_module(module):
    with open('data.json') as config_file:
        configData = json.load(config_file)
    data = fillData(configData)

@pytest.mark.parametrize("data", data)
def test_data(data):
    for d in data:
        .
        .
        .

Thanks, Avi

Avi Elgal
  • 149
  • 1
  • 3
  • 9
  • The correct answer here depends crucially on a detail not mentioned in the question: do you need to prevent loading the file "data.json" at import time (i.e. during the test discovery stage), or is that OK? – wim Feb 13 '20 at 21:15
  • You can totally do that as long as data variable is an iterable. – SilentGuy Feb 14 '20 at 18:30
  • @wim it doesn't have to be during test discovery stage – Avi Elgal Feb 15 '20 at 08:53
  • @SilentGuy data is a list of objects. The problem is that data in the parametrize initialize before setup_module - data in test_data function is empty – Avi Elgal Feb 15 '20 at 08:58
  • @AviElgal You didn't really answer my question - is it OK to load "data.json" during test discovery? – wim Feb 15 '20 at 16:47
  • @wim Yes it's OK – Avi Elgal Feb 16 '20 at 06:56
  • In that case just delete the `setup_module` function, you don't need it. Load the data from file at the module scope. – wim Feb 16 '20 at 07:25
  • This What I did, I thought I can do it with setup_module as well. Thanks. – Avi Elgal Feb 16 '20 at 07:29
  • Use data as pytest attribute to make it available at the time of parametrization. ``` def setup_module(module): with open('data.json') as config_file: configData = json.load(config_file) pytest.data = fillData(configData) @pytest.mark.parametrize("data", pytest.data) def test_data(data): for d in data: ``` And, please don't reuse variable names. – SilentGuy Feb 16 '20 at 16:47

1 Answers1

-1

I am not sure about format of your data. you could do like this

  import pytest
  scenarios = [('first', {'attribute': 'value'}), ('second', {'attribute': 'value'})]

  @pytest.mark.parametrize("test_id,scenario",scenarios)
  def test_scenarios(test_id,scenario):
           assert scenario["attribute"] == "value"
Macintosh_89
  • 664
  • 8
  • 24