Skip to content

Instantly share code, notes, and snippets.

@xbns
Last active December 12, 2020 17:24
Show Gist options
  • Save xbns/242fb7f77f6de4e0dcf17af422390f91 to your computer and use it in GitHub Desktop.
Save xbns/242fb7f77f6de4e0dcf17af422390f91 to your computer and use it in GitHub Desktop.
Data Driven Testing #csv #pytest #python
import requests
import pytest
import csv
from requests.exceptions import HTTPError
test_data_users = [
("1","George","Bluth","[email protected]"),
("2","Janet","Weaver","[email protected]")
]
@pytest.mark.parametrize("id,first_name,last_name, expected_email", test_data_users)
def test_using_data_object_get_user_id_check_email(id,first_name,last_name,expected_email):
try:
response = requests.get(f"https://reqres.in/api/users/{id}")
jsonResponse = response.json()
email = jsonResponse['data']['email']
assert email == expected_email
except HTTPError as http_err:
print(f'HTTP error occurred: {http_err}')
except Exception as err:
print(f'Other error occurred: {err}')
def read_test_data_from_csv():
test_data = []
filename = 'users.csv'
try:
with open(filename,newline='') as csvfile:
data = csv.reader(csvfile,delimiter=',')
next(data) # skip the header
for row in data:
test_data.append(row)
return test_data
except FileNotFoundError:
print('File not found',filename)
except Exception as e:
print(e)
@pytest.mark.parametrize("id,first_name,last_name, expected_email", read_test_data_from_csv())
def test_using_csv_get_user_id_check_email(id,first_name,last_name,expected_email):
try:
response = requests.get(f"https://reqres.in/api/users/{id}")
jsonResponse = response.json()
email = jsonResponse['data']['email']
assert email == expected_email
except HTTPError as http_err:
print(f'HTTP error occurred: {http_err}')
except Exception as err:
print(f'Other error occurred: {err}')
## To Run
# $ pytest data-driven-testing.py
{
"data": {
"id": 1,
"email": "[email protected]",
"first_name": "George",
"last_name": "Bluth",
"avatar": "https://reqres.in/img/faces/1-image.jpg"
},
...
}
id first_name last_name email
1 George Bluth [email protected]
2 Janet Weaver [email protected]
3 Emma Wong [email protected]
4 Eve Holt [email protected]
5 Charles Morris [email protected]
6 Tracey Ramos [email protected]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment