Search code examples
pythonpytestfixtures

Pytest -Get one item from multiple returned values


I've e2e_te_data.json file which includes my 2 different test points. It means I will have 2 test case data and give the pytest and it will execute 2 different test cases.

`e2e_te_data.json

[{   "dataSource":"dataSource1",  
     "machineName":"MachineName_X", 
},

{`   "dataSource":"dataSource2",  
    "machineName":"MachineName_Y",
}]

--`-------This is my code:

 def read_test_data_from_json():
     JsonFile = open('..\\e2eTestData.json','r')
     h=[]    
     convertedJsonStr=[]
     json_input = JsonFile.read()
     parsedJsonStr = json.loads(json_input)  # Parse JSON string to Python dict
     for i in range(0, len(parsedJsonStr)):
         convertedJsonStr.append(json.dumps(parsedJsonStr[i]))
         h.append(parsedJsonStr[i]['machineName']) 
     return convertedJsonStr,h



@pytest.mark.parametrize("convertedJsonStr,h", (read_test_data_from_json()[0],read_test_data_from_json()[1]))
def test_GetFrequencyOfAllToolUsage(convertedJsonStr,h):
    objAPI=HTTPMethods()
    frequencyOfToolResultFromAPIRequest=objAPI.getFrequencyOfTools(read_test_data_from_json[0])
    print(h)

Value of convertedJsonstr variable

I want to get one item of convertedJsonStr and h returned from read_test_data_from_json method when it comes into test_GetFrequencyOfAllToolUsage method. But I see all items of convertedJsonStr and h as image above.


Solution

  • First Item

    def read_test_data_from_json():
         JsonFile = json.load(open('..\\e2eTestData.json','r'))
         # First item
        return JsonFile[0], JsonFile[0]["machineName"]
    

    Last item

    return JsonFile[-1], JsonFile[-1]["machineName"]

    Random item

    item = random.choice(JsonFile)
    return item, item["machineName"]