Skip to content

Commit

Permalink
Added test_reporter_utils_csv_parser_*.py
Browse files Browse the repository at this point in the history
  • Loading branch information
wwakabobik committed Aug 29, 2024
1 parent c66bbe5 commit 3674308
Show file tree
Hide file tree
Showing 6 changed files with 235 additions and 39 deletions.
15 changes: 6 additions & 9 deletions testrail_api_reporter/utils/csv_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,11 @@ def save_history_data(self, filename=None, report=None):
date = datetime.today().strftime("%Y-%m-%d")
last_date = ""
mode = "r" if exists(filename) else "w"
try:
with open(filename, mode, encoding="utf-8") as csvfile:
if mode == "r":
for row in reversed(list(csv.reader(csvfile))):
last_date = f"{row[0]}-{row[1]}-{row[2]}"
break
except FileNotFoundError:
raise ValueError("Can't open report file, save history data aborted!") from FileNotFoundError
with open(filename, mode, encoding="utf-8") as csvfile:
if mode == "r":
for row in reversed(list(csv.reader(csvfile))):
last_date = f"{row[0]}-{row[1]}-{row[2]}"
break
if last_date != date:
self.___logger.debug("Last date in file: %s for %s", filename, last_date)
with open(filename, "a+", newline="", encoding="utf-8") as csvfile:
Expand All @@ -69,7 +66,7 @@ def save_history_data(self, filename=None, report=None):
else:
self.___logger.debug("Data already stored for today, skipping save")

def load_history_data(self, filename=None):
def load_history_data(self, filename=None) -> list[list[datetime], list[str], list[str], list[str]]:
"""
Load history data to CSV
Expand Down
66 changes: 65 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@
"""Conftest for testsuite"""

from os import path, remove
from random import randint

import pytest
from faker import Faker

from testrail_api_reporter.utils.case_stat import CaseStat # pylint: disable=import-error,no-name-in-module


@pytest.fixture
def create_test_file():
def create_test_file() -> str:
"""
Fixture to create random test file
Expand All @@ -25,3 +28,64 @@ def create_test_file():
remove(test_file)
except FileNotFoundError:
pass


@pytest.fixture
def random_stat() -> tuple[int, int, int, int]:
"""
Fixture to return tuple with random statistics
:return: tuple with random statistics
:rtype: tuple[int, int, int, int]
"""
total = randint(0, 32768)
automated = randint(0, 32768)
not_automated = randint(0, 32768)
not_applicable = randint(0, 32768)
return total, automated, not_automated, not_applicable


@pytest.fixture
def case_stat() -> CaseStat:
"""
Fixture to return object of CaseStat
:return: CaseStat
:rtype: CaseStat
"""
return CaseStat(Faker().word())


@pytest.fixture
def case_stat_random(case_stat, random_stat):
"""
Fixture to return object of CaseStat
:return: CaseStat with random statistics
:rtype: CaseStat
"""
total, automated, not_automated, not_applicable = random_stat
case_stat.set_total(total)
case_stat.set_automated(automated)
case_stat.set_not_automated(not_automated)
case_stat.set_not_applicable(not_applicable)
return case_stat


@pytest.fixture
def csv_file() -> str:
"""
Fixture to create random test file
:return: filename
"""
test_file = f"not_existing_{Faker().file_name(extension='csv')}"
with open(test_file, "w", encoding="utf-8") as file:
file.write("")
assert path.exists(test_file) is True
yield test_file
# Cleanup if not removed by tests
try:
remove(test_file)
except FileNotFoundError:
pass
66 changes: 37 additions & 29 deletions tests/utils/test_reporter_utils_case_stat.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
"""Tests for the reporter_utils module, сlass 'CaseStat'"""
"""Tests for the case_stat module, сlass 'CaseStat'"""

import pytest
from faker import Faker
Expand All @@ -19,6 +19,7 @@ def test_case_stat_init():
assert case_stat.not_automated == 0
assert case_stat.not_applicable == 0


def test_case_stat_name():
"""Check name attribute"""
name = fake.word()
Expand All @@ -30,71 +31,78 @@ def test_case_stat_name():
case_stat.set_name(new_name)
assert case_stat.get_name() == new_name, "Test case name does not match after change"

def test_case_stat_total():
"""Check total"""
name = fake.word()
case_stat = CaseStat(name)

def test_case_stat_total(case_stat):
"""Check total"""
total = fake.random_number()
case_stat.set_total(total)
assert case_stat.get_total() == total, "Total number of test cases does not match"

def test_case_stat_automated():
"""Check automated"""
name = fake.word()
case_stat = CaseStat(name)

def test_case_stat_automated(case_stat):
"""Check automated"""
automated = fake.random_number()
case_stat.set_automated(automated)
assert case_stat.get_automated() == automated, "Number of automated test cases does not match"

def test_case_stat_not_automated():
"""Check not automated"""
name = fake.word()
case_stat = CaseStat(name)

def test_case_stat_not_automated(case_stat):
"""Check not automated"""
not_automated = fake.random_number()
case_stat.set_not_automated(not_automated)
assert case_stat.get_not_automated() == not_automated, "Number of not automated test cases does not match"

def test_case_stat_not_applicable():
"""Check not applicable"""
name = fake.word()
case_stat = CaseStat(name)

def test_case_stat_not_applicable(case_stat):
"""Check not applicable"""
not_applicable = fake.random_number()
case_stat.set_not_applicable(not_applicable)
assert case_stat.get_not_applicable() == not_applicable, "Number of not applicable test cases does not match"


def test_case_stat_negative():
# Создаем экземпляр клас��а с именем теста
name = fake.word()
case_stat = CaseStat(name)

# Пытаемся установить отрицательное количество тестов
def test_case_stat_negative_total(case_stat):
"""Negative case for total"""
with pytest.raises(ValueError):
case_stat.set_total(-1)

# Пытаемся установить количество тестов не числовым значением

def test_case_stat_total_not_a_number(case_stat):
"""Negative case for total - incorrect type"""
with pytest.raises(TypeError):
case_stat.set_total("not a number")
case_stat.set_total("not a number") # type: ignore

# Повторяем для остальных сеттеров

def test_case_stat_negative_automated(case_stat):
"""Negative case for automated"""
with pytest.raises(ValueError):
case_stat.set_automated(-1)


def test_case_stat_automated_not_a_number(case_stat):
"""Negative case for automated - incorrect type"""
with pytest.raises(TypeError):
case_stat.set_automated("not a number")
case_stat.set_automated("not a number") # type: ignore


def test_case_stat_negative_not_automated(case_stat):
"""Negative case for not_automated"""
with pytest.raises(ValueError):
case_stat.set_not_automated(-1)


def test_case_stat_not_automated_not_a_number(case_stat):
"""Negative case for not automated - incorrect type"""
with pytest.raises(TypeError):
case_stat.set_not_automated("not a number")
case_stat.set_not_automated("not a number") # type: ignore


def test_case_stat_negative_not_applicable(case_stat):
"""Negative case for not applicable"""
with pytest.raises(ValueError):
case_stat.set_not_applicable(-1)


def test_case_stat_not_applicable_not_a_number(case_stat):
"""Negative case for not applicable - incorrect type"""
with pytest.raises(TypeError):
case_stat.set_not_applicable("not a number")
case_stat.set_not_applicable("not a number")
17 changes: 17 additions & 0 deletions tests/utils/test_reporter_utils_csv_parser_custom_logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# -*- coding: utf-8 -*-
"""Tests for the csv_parser module against custom logger"""

from logging import Logger, DEBUG, ERROR, FATAL, INFO, WARNING
from random import choice

from faker import Faker

from testrail_api_reporter.utils.csv_parser import CSVParser # pylint: disable=import-error,no-name-in-module


fake = Faker()


def test_custom_csv_logger():
"""Use custom logger"""
CSVParser(logger=Logger(name=fake.name(), level=choice((DEBUG, INFO, WARNING, ERROR, FATAL))))
50 changes: 50 additions & 0 deletions tests/utils/test_reporter_utils_csv_parser_load_history_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# -*- coding: utf-8 -*-
"""Tests for the csv_parser module, 'load_history' function"""

from datetime import datetime

import pytest
from faker import Faker

from testrail_api_reporter.utils.csv_parser import CSVParser # pylint: disable=import-error,no-name-in-module


fake = Faker()


def test_load_history_data(csv_file, random_stat):
"""Check load_history_data function"""
parser = CSVParser(filename=csv_file)

total, automated, not_automated, not_applicable = random_stat
year = fake.year()
month = fake.month()
day_of_month = fake.day_of_month()
with open(csv_file, "w") as f:
f.write(f"{year},{month},{day_of_month},{total},{automated},{not_automated},{not_applicable}\n")

data = parser.load_history_data()

assert data == [
[datetime(int(year), int(month), int(day_of_month))],
[str(total)],
[str(automated)],
[str(not_automated)],
[str(not_applicable)],
]


def test_load_history_data_no_filename(csv_file):
"""No filename is provided for load history"""
parser = CSVParser()

with pytest.raises(ValueError):
parser.load_history_data()


def test_load_history_data_file_not_found():
"""File not found error for load history"""
parser = CSVParser(filename="non_existent_file.csv")

with pytest.raises(ValueError):
parser.load_history_data()
60 changes: 60 additions & 0 deletions tests/utils/test_reporter_utils_csv_parser_save_history_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# -*- coding: utf-8 -*-
"""Tests for the csv_parser module'"""
from datetime import datetime

import pytest
from faker import Faker

from testrail_api_reporter.utils.csv_parser import CSVParser # pylint: disable=import-error,no-name-in-module

fake = Faker()


def test_save_history_data(csv_file, random_stat, case_stat):
"""Check save_history_data function"""
parser = CSVParser(filename=csv_file)

total, automated, not_automated, not_applicable = random_stat
case_stat.set_total(total)
case_stat.set_automated(automated)
case_stat.set_not_automated(not_automated)
case_stat.set_not_applicable(not_applicable)

parser.save_history_data(report=case_stat)

with open(csv_file, "r") as f:
data = f.read()
assert data == (
f"{datetime.today().strftime('%Y')},"
f"{datetime.today().strftime('%m')},"
f"{datetime.today().strftime('%d')},"
f"{total},{automated},{not_automated},{not_applicable}\n"
)


def test_save_history_data_no_filename(csv_file):
"""No filename provided for save history data"""
parser = CSVParser()

with pytest.raises(ValueError):
parser.save_history_data()


def test_save_history_data_no_report(csv_file):
"""No data for save history data"""
parser = CSVParser(filename=csv_file)

with pytest.raises(ValueError):
parser.save_history_data()


def test_save_history_data_already_stored(csv_file, random_stat, case_stat_random):
"""History already stored for such day for save history data"""
parser = CSVParser(filename=csv_file)

parser.save_history_data(report=case_stat_random)
parser.save_history_data(report=case_stat_random)

with open(csv_file, "r") as f:
data = f.read()
assert data.count("\n") == 1

0 comments on commit 3674308

Please sign in to comment.