I would like to write each test result to excel file. I am using data-driven by pytest to execute all rows in worksheet. But I don't know how to write the test result to each row. Had someone similar experience? May you give advice? Thanks very much!
file 1: read_excel.py
class ReadExcel:
def __init__(self, file_name, sheet_name):
self.file_name = os.path.join(rc.DATA_PATH, file_name)
self.sheet_name = sheet_name
def open(self):
self.wb = openpyxl.load_workbook(self.file_name)
self.sh = self.wb[self.sheet_name]
def close(self):
self.wb.close()
def read_data(self):
"""read rows"""
self.open()
rows = list(self.sh.rows)
titles = []
for t in rows[0]:
title = t.value
titles.append(title)
cases = []
for row in rows[1:]:
case = []
for r in row:
case.append(r.value)
cases.append(dict(zip(titles, case)))
self.close()
return cases
def write_data(self, row, column, msg):
self.open()
self.sh.cell(row=row, column=column, value=msg)
self.wb.save(self.file_name)
self.close()
file2: test_sample.py
class TestSample:
sheet = ReadExcel('test_data.xlsx', 'test_data')
rows = sheet.read_data()
test_result = []
i=2
@pytest.fixture(scope='function', params=rows)
def _test_data(self, request):
return request.param
def test_write_result(self, drivers, _test_data):
# get all required test data from excel
test_case_no = _test_data['TEST CASE_NO.']
# I want to write each test result to the excel file, but below code does not work, it only write the second row
self.sheet.write_data(self.i, 2, "pass")
self.i = self.i + 1
test_data.xlsx
|TEST CASE_NO.|TEST RESULT|
| 1 | |
| 2 | |
| 3 | |
pytest-csv works for me and love it
Firstly install:
then instead of
pytest....typepy.test --csv tests.csvin command line (terminal)Maybe not exactly XLSX, but CSV also is fine
Documentation: https://github.com/nicoulaj/pytest-csv