Skip to content

Commit

Permalink
0.2 - fix testing
Browse files Browse the repository at this point in the history
  • Loading branch information
wwakabobik committed Oct 17, 2023
1 parent 57d5871 commit 47328fd
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 49 deletions.
2 changes: 1 addition & 1 deletion examples/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@
Description:
This file is init file for examples package.
"""
"""
2 changes: 1 addition & 1 deletion examples/image_generation/test_leonardo.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import asyncio
import json

from leonardo_api import LeonardoAsync as Leonardo
from leonardo_api.src.leonardo_api.leonardo_async import Leonardo


async def main():
Expand Down
10 changes: 4 additions & 6 deletions examples/speak_and_hear/test_gpt.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ async def tts_sentence_task():
if sentence[-1] in punctuation_marks:
await tts_queue.put(sentence)
sentence = ""
except Exception as error:
except Exception: # pylint: disable=broad-except
pass


Expand All @@ -111,7 +111,7 @@ async def tts_worker():
if sentence:
await tts.process(sentence)
tts_queue.task_done()
except Exception as error:
except Exception: # pylint: disable=broad-except
pass


Expand All @@ -122,8 +122,7 @@ async def get_user_input():
user_input = input()
if user_input.lower() == "[done]":
break
else:
await ask_chat(user_input)
await ask_chat(user_input)
except KeyboardInterrupt:
break

Expand All @@ -142,12 +141,11 @@ async def main():
transcript = await gpt.transcript(file=f, language="en")
else:
transcript = CustomTranscriptor(language="en-US").transcript()
pass
if transcript:
print(f"User: {transcript}")
# translate = CustomTranslator(source='ru', target='en').translate(transcript)
# print(translate)
response = await ask_chat(transcript)
await ask_chat(transcript)
except KeyboardInterrupt:
break

Expand Down
53 changes: 29 additions & 24 deletions examples/test_generator/pom_case_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@


class PomTestCaseGenerator:
""" Class for generating test files and page objects from json data """
def __init__(self, url=''):
"""Class for generating test files and page objects from json data"""

def __init__(self, url=""):
"""
General init.
Expand All @@ -22,7 +23,7 @@ def set_url(self, url):
"""
self.url = url

def ___create_pom_file(self, file_name, page_objects, url='', pom_folder='pom'):
def ___create_pom_file(self, file_name, page_objects, url="", pom_folder="pom"):
"""
Create page object model file.
Expand All @@ -35,19 +36,19 @@ def ___create_pom_file(self, file_name, page_objects, url='', pom_folder='pom'):
url = self.url
if not os.path.exists(pom_folder):
os.makedirs(pom_folder)
with open(f'{pom_folder}/page_{file_name}.py', 'w', encoding='utf-8') as pom_file:
pom_file.write('from selenium.webdriver.common.by import By\n')
pom_file.write('from selenium.webdriver.support.ui import WebDriverWait\n')
pom_file.write('from selenium.webdriver.support import expected_conditions as EC\n\n\n')
with open(f"{pom_folder}/page_{file_name}.py", "w", encoding="utf-8") as pom_file:
pom_file.write("from selenium.webdriver.common.by import By\n")
pom_file.write("from selenium.webdriver.support.ui import WebDriverWait\n")
pom_file.write("from selenium.webdriver.support import expected_conditions as EC\n\n\n")
pom_file.write(f'class Page{"".join(word.capitalize() for word in file_name.split("_"))}:\n')
pom_file.write(f' def __init__(self, driver):\n')
pom_file.write(" def __init__(self, driver):\n")
pom_file.write(f' self.url = "{url}"\n')
pom_file.write(f' self.driver = driver\n\n')
pom_file.write(" self.driver = driver\n\n")
for method in page_objects:
pom_file.write(f' {method}\n\n')
pom_file.write(f" {method}\n\n")

@staticmethod
def ___create_test_file(file_name, tests, pom_folder='pom', tests_folder='tests'):
def ___create_test_file(file_name, tests, pom_folder="pom", tests_folder="tests"):
"""
Create test file.
Expand All @@ -56,19 +57,23 @@ def ___create_test_file(file_name, tests, pom_folder='pom', tests_folder='tests'
:param pom_folder: (str) Folder for page object model files.
:param tests_folder: (str) Folder for test files.
"""
with open(f'{tests_folder}/test_{file_name}.py', 'w') as test_file:
test_file.write('import pytest\n\n')
test_file.write(f'from {pom_folder}.{os.path.splitext(f"page_{file_name}")[0]} import Page'
f'{"".join(word.capitalize() for word in file_name.split("_"))}\n\n\n')
with open(f"{tests_folder}/test_{file_name}.py", "w", encoding="utf-8") as test_file:
test_file.write("import pytest\n\n")
test_file.write(
f'from {pom_folder}.{os.path.splitext(f"page_{file_name}")[0]} import Page'
f'{"".join(word.capitalize() for word in file_name.split("_"))}\n\n\n'
)
test_file.write('@pytest.fixture(scope="function")\n')
test_file.write('def page(driver):\n')
test_file.write(f' page_under_test = Page{"".join(word.capitalize() for word in file_name.split("_"))}(driver)\n')
test_file.write(f' driver.get(page_under_test.url)\n')
test_file.write(f' return page_under_test\n\n\n')
test_file.write("def page(driver):\n")
test_file.write(
f' page_under_test = Page{"".join(word.capitalize() for word in file_name.split("_"))}(driver)\n'
)
test_file.write(" driver.get(page_under_test.url)\n")
test_file.write(" return page_under_test\n\n\n")
for test in tests:
test_file.write(f'{test}\n\n\n')
test_file.write(f"{test}\n\n\n")

def create_files_from_json(self, json_data, url='', pom_folder='pom', tests_folder='tests'):
def create_files_from_json(self, json_data, url="", pom_folder="pom", tests_folder="tests"):
"""
Create test and page object model files from json data.
Expand All @@ -80,6 +85,6 @@ def create_files_from_json(self, json_data, url='', pom_folder='pom', tests_fold
if not url:
url = self.url
parsed_url = urlparse(unquote(url))
file_name = parsed_url.path.strip('/').replace('/', '_') or 'index'
self.___create_test_file(file_name, json_data['tests'], pom_folder=f"..pom", tests_folder=tests_folder)
self.___create_pom_file(file_name, json_data['page_objects'], url, pom_folder=pom_folder)
file_name = parsed_url.path.strip("/").replace("/", "_") or "index"
self.___create_test_file(file_name, json_data["tests"], pom_folder="..pom", tests_folder=tests_folder)
self.___create_pom_file(file_name, json_data["page_objects"], url, pom_folder=pom_folder)
36 changes: 19 additions & 17 deletions examples/test_generator/pytest_runner.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""This module runs pytest and returns the results in JSON format."""
import io
import json
from os import remove

import json
import pytest

from utils.page_retriever import PageRetriever
Expand All @@ -19,27 +19,30 @@ def run_tests(test_files, add_failed_html=True, add_failure_reasons=True, count_
:return: JSON with results.
"""
pytest.main(["-q", "--json-report", "--json-report-file=test_report.json", "-n=4", "-rfEx --tb=none -p no:warnings -p no:logging"] + test_files)
pytest.main(
[
"-q",
"--json-report",
"--json-report-file=test_report.json",
"-n=4",
"-rfEx --tb=none -p no:warnings -p no:logging",
]
+ test_files
)

with open('test_report.json', encoding='utf-8') as json_file:
with open("test_report.json", encoding="utf-8") as json_file:
data = json.load(json_file)

results = {
"passed": [],
"failed": [],
"error": [],
"failure details": {},
"failed_pages": {}
}
results = {"passed": [], "failed": [], "error": [], "failure details": {}, "failed_pages": {}}

for test in data['tests']:
node_name = test['nodeid'].split('::')[1]
if test['outcome'] == 'passed':
for test in data["tests"]:
node_name = test["nodeid"].split("::")[1]
if test["outcome"] == "passed":
results["passed"].append(node_name)
elif test['outcome'] == 'failed' or test['outcome'] == 'error':
results[test['outcome']].append(node_name)
elif test["outcome"] == "failed" or test["outcome"] == "error":
results[test["outcome"]].append(node_name)
if add_failure_reasons:
results["failure details"][node_name] = {node_name: test['call']['crash']}
results["failure details"][node_name] = {node_name: test["call"]["crash"]}
if add_failed_html:
if len(results["failed_pages"]) < count_of_htmls:
results["failed_pages"][node_name] = {node_name: parse_error_page(node_name)}
Expand All @@ -59,7 +62,6 @@ def parse_error_page(node_name):
"""
parser = PageRetriever()
try:
formatted_content = ''
file_name = f"{node_name}.html"
with open(file_name, "r", encoding="utf-8") as file:
formatted_content = parser.remove_script_tags(parser.extract_body_content(file))
Expand Down

0 comments on commit 47328fd

Please sign in to comment.