В документе они создали класс TestResult, которому, возможно, лучше всего следовать, однако мне не удалось это сделать или я не нашел хороших примеров для подражания. по этому отслеживайте свои успехи в unittest. Это лучший результат, который я получил:
Код: Выделить всё
import os
import json
import unittest
class TestModel(unittest.TestCase):
model_scores = {}
@classmethod
def setUpClass(cls):
cls.results = main()
cls.load_scores()
@classmethod
def load_scores(cls):
if os.path.exists(SCORES_FILE):
with open(SCORES_FILE, "r", encoding="utf-8") as f:
cls.model_scores = json.load(f)
else:
cls.model_scores = {}
@classmethod
def save_scores(cls):
with open(SCORES_FILE, "w", encoding="utf-8") as f:
json.dump(cls.model_scores, f, indent=4)
def update_model_score(self, model_name, method, success):
# Init
if model_name not in self.model_scores:
self.model_scores[model_name] = {"runs": 0}
self.model_scores[model_name]["runs"] += 1
if method not in self.model_scores[model_name].keys():
self.model_scores[model_name][method] = 0
if success:
self.model_scores[model_name][method] += 1
def test_format(self):
"""Test JSON Format"""
method = "test_format"
for model, output in self.results.items():
with self.subTest(model=model):
try:
self.assertTrue(
output.startswith("```json"),
f"String not starting with JSON format in {model}",
)
self.update_model_score(model, method, True)
except AssertionError:
self.update_model_score(model, method, False)
raise
def test_desired_output(self):
"""Test if there is desired strings inside"""
method = "test_desired_output"
check = ["some", "text"]
for model, output in self.results.items():
with self.subTest(model=model):
try:
for word in check:
self.assertIn(
word, output, f"{FILLER}Expected {word} in {model}"
)
self.update_model_score(model, method, True)
except AssertionError:
self.update_model_score(model, method, False)
raise
@classmethod
def tearDownClass(cls):
cls.save_scores()
def get_suite():
"""
Take every test and run with :
"""
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestModel))
return suite
def print_model_scores():
if os.path.exists(SCORES_FILE):
with open(SCORES_FILE, "r", encoding="utf-8") as f:
model_scores = json.load(f)
print("\nModel Scores:")
for model, scores in model_scores.items():
runs = scores.pop("runs")
all_runs = int(runs / (len(scores)))
print(f"Model: {model}, Total Runs: {all_runs}")
for method, success_count in scores.items():
success_rate = (
(success_count / all_runs) * 100 if all_runs > 0 else 0
)
print(
f" Method: {method}, Successes: {success_count}, Success Rate: {success_rate:.2f}%"
)
if __name__ == "__main__":
runner = unittest.TextTestRunner(verbosity=1)
runner.run(get_suite())
print_model_scores()
п>
Подробнее здесь: https://stackoverflow.com/questions/787 ... n-unittest