Skip to content

Commit af95d75

Browse files
test: DocGen-fixed pylint issues
1 parent 4bb9f5f commit af95d75

File tree

6 files changed

+130
-58
lines changed

6 files changed

+130
-58
lines changed

tests/e2e-test/base/base.py

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,33 @@ def validate_response_status(self, question_api=""):
4545
"response code is " + str(response.status) + " " + str(response.json())
4646
)
4747

48-
48+
49+
def validate_generate_response_status(self, question_api=""):
50+
load_dotenv() # Ensure environment variables are loaded
51+
# URL of the API endpoint
52+
url = f"{URL}/history/generate"
53+
54+
# Prepare headers
55+
headers = {
56+
"Content-Type": "application/json",
57+
"Accept": "*/*",
58+
}
59+
60+
# Payload (data) to be sent in the POST request
61+
payload = {
62+
"chat_type": "browse",
63+
"messages": [
64+
{
65+
"role": "user",
66+
"content": question_api, # Use the passed question
67+
}
68+
],
69+
}
70+
71+
# Make the POST request
72+
response = self.page.request.post(
73+
url, headers=headers, data=json.dumps(payload), timeout=120000
74+
)
75+
assert response.status == 200, (
76+
"response code is " + str(response.status) + " " + str(response.json())
77+
)

tests/e2e-test/config/constants.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,4 @@
2929

3030
# Response Text Data
3131
invalid_response = "I was unable to find content related to your query and could not generate a template. Please try again."
32+
invalid_response1 = "An error occurred. Answers can't be saved at this time. If the problem persists, please contact the site administrator."

tests/e2e-test/pages/draftPage.py

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
from base.base import BasePage
22
from pytest_check import check
3-
import time
4-
from collections import defaultdict
53

64

75
class DraftPage(BasePage):
@@ -23,10 +21,10 @@ def check_draft_sections(self, timeout: float = 180.0, poll_interval: float = 0.
2321
Scrolls into view if needed, retries until timeout.
2422
Raises clear errors if validation fails.
2523
"""
26-
from collections import defaultdict
2724
import time
28-
start_time = time.time()
25+
from collections import defaultdict
2926

27+
start_time = time.time()
3028

3129
while time.time() - start_time < timeout:
3230
section_elements = self.page.locator(self.Draft_Sections)
@@ -55,7 +53,10 @@ def check_draft_sections(self, timeout: float = 180.0, poll_interval: float = 0.
5553

5654
if not section_text:
5755
failed_sections[i] = "Empty"
58-
elif section_text in (self.invalid_response, self.invalid_response1):
56+
elif section_text in (
57+
self.invalid_response,
58+
self.invalid_response1,
59+
):
5960
failed_sections[i] = f"Invalid: {repr(section_text[:30])}"
6061

6162
except Exception as e:
@@ -68,7 +69,9 @@ def check_draft_sections(self, timeout: float = 180.0, poll_interval: float = 0.
6869
time.sleep(poll_interval)
6970

7071
else:
71-
raise TimeoutError(f"❌ Timeout: These sections did not load valid content: {failed_sections}")
72+
raise TimeoutError(
73+
f"❌ Timeout: These sections did not load valid content: {failed_sections}"
74+
)
7275

7376
# ✅ Final validations after loading
7477
for i in range(section_count):
@@ -81,10 +84,20 @@ def check_draft_sections(self, timeout: float = 180.0, poll_interval: float = 0.
8184
heading_text = heading.inner_text(timeout=3000).strip()
8285
content = section.input_value().strip()
8386

84-
print(f"[VALIDATING] Section {i}: '{heading_text}' → {repr(content[:60])}...")
87+
print(
88+
f"[VALIDATING] Section {i}: '{heading_text}' → {repr(content[:60])}..."
89+
)
8590

8691
with check:
8792
check.is_not_none(content, f"❌ Section '{heading_text}' is None")
8893
check.not_equal(content, "", f"❌ Section '{heading_text}' is empty")
89-
check.not_equal(content, self.invalid_response, f"❌ '{heading_text}' has invalid response")
90-
check.not_equal(content, self.invalid_response1, f"❌ '{heading_text}' has invalid response")
94+
check.not_equal(
95+
content,
96+
self.invalid_response,
97+
f"❌ '{heading_text}' has invalid response",
98+
)
99+
check.not_equal(
100+
content,
101+
self.invalid_response1,
102+
f"❌ '{heading_text}' has invalid response",
103+
)

tests/e2e-test/pages/generatePage.py

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
1+
from asyncio.log import logger
2+
13
from base.base import BasePage
24
from playwright.sync_api import expect
3-
from asyncio.log import logger
5+
46

57
class GeneratePage(BasePage):
68
GENERATE_DRAFT = "//button[@title='Generate Draft']"
79
TYPE_QUESTION = "//textarea[@placeholder='Type a new question...']"
810
SEND_BUTTON = "//div[@aria-label='Ask question button']"
9-
SHOW_CHAT_HISTORY_BUTTON="//span[text()='Show template history']"
11+
SHOW_CHAT_HISTORY_BUTTON = "//span[text()='Show template history']"
1012
HIDE_CHAT_HISTORY_BUTTON = "//span[text()='Hide Chat History']"
1113
CHAT_HISTORY_ITEM = "//body//div[@id='root']//div[@role='presentation']//div[@role='presentation']//div[1]//div[1]//div[1]//div[1]//div[1]//div[1]"
1214
SHOW_CHAT_HISTORY = "//span//i"
@@ -28,7 +30,25 @@ def enter_a_question(self, text):
2830
def click_send_button(self):
2931
# Type a question in the text area
3032
self.page.locator(self.SEND_BUTTON).click()
31-
self.page.wait_for_timeout(10000)
33+
locator = self.page.locator("//p[contains(text(),'Generating template...this may take up to 30 secon')]")
34+
stop_button = self.page.locator("//div[@aria-label='Stop generating']")
35+
36+
try:
37+
# Wait up to 60s for the element to become **hidden**
38+
locator.wait_for(state="hidden", timeout=60000)
39+
except TimeoutError:
40+
# Raise a custom failure if it's still visible after 60s
41+
raise AssertionError("❌ TIMED-OUT: Not recieved response within specific time limit.")
42+
43+
finally:
44+
# Always attempt to click the stop button after test fail
45+
if stop_button.is_visible():
46+
stop_button.click()
47+
print("Clicked on 'Stop generating' button after timeout.")
48+
else:
49+
print("'Stop generating' button not visible.")
50+
51+
self.page.wait_for_timeout(5000)
3252

3353
def click_generate_draft_button(self):
3454
# Type a question in the text area
@@ -52,15 +72,20 @@ def close_chat_history(self):
5272
hide_button.click()
5373
self.page.wait_for_timeout(2000)
5474
else:
55-
logger.info("Hide button not visible. Chat history might already be closed.")
75+
logger.info(
76+
"Hide button not visible. Chat history might already be closed."
77+
)
5678

5779
def delete_chat_history(self):
5880

5981
self.page.locator(self.SHOW_CHAT_HISTORY_BUTTON).click()
82+
self.page.wait_for_timeout(4000)
6083
chat_history = self.page.locator("//span[contains(text(),'No chat history.')]")
6184
if chat_history.is_visible():
6285
self.page.wait_for_load_state("networkidle")
63-
self.page.locator("button[title='Hide']").wait_for(state="visible", timeout=5000)
86+
self.page.locator("button[title='Hide']").wait_for(
87+
state="visible", timeout=5000
88+
)
6489
self.page.locator("button[title='Hide']").click()
6590

6691
else:
@@ -71,4 +96,3 @@ def delete_chat_history(self):
7196
self.page.locator(self.CHAT_HISTORY_CLOSE).click()
7297
self.page.wait_for_load_state("networkidle")
7398
self.page.wait_for_timeout(2000)
74-

tests/e2e-test/tests/conftest.py

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,11 @@
1-
from pathlib import Path
2-
import pytest
3-
from playwright.sync_api import sync_playwright
4-
from config.constants import *
5-
from slugify import slugify
6-
from dotenv import load_dotenv
7-
import os
8-
from py.xml import html # type: ignore
1+
import atexit
92
import io
103
import logging
4+
import os
5+
import pytest
116
from bs4 import BeautifulSoup
12-
import atexit
7+
from config.constants import URL
8+
from playwright.sync_api import sync_playwright
139

1410

1511
@pytest.fixture(scope="session")
@@ -26,11 +22,10 @@ def login_logout():
2622
# Wait for the login form to appear
2723
# page.wait_for_load_state('networkidle')
2824
# login to web url with username and password
29-
#login_page = LoginPage(page)
30-
#load_dotenv()
31-
#login_page.authenticate(os.getenv('user_name'),os.getenv('pass_word'))
25+
# login_page = LoginPage(page)
26+
# load_dotenv()
27+
# login_page.authenticate(os.getenv('user_name'),os.getenv('pass_word'))
3228
yield page
33-
3429
# perform close the browser
3530
browser.close()
3631

@@ -42,6 +37,7 @@ def pytest_html_report_title(report):
4237

4338
log_streams = {}
4439

40+
4541
@pytest.hookimpl(tryfirst=True)
4642
def pytest_runtest_setup(item):
4743
# Prepare StringIO for capturing logs
@@ -80,34 +76,39 @@ def pytest_runtest_makereport(item, call):
8076
else:
8177
report.description = ""
8278

79+
8380
def pytest_collection_modifyitems(items):
8481
for item in items:
85-
if hasattr(item, 'callspec'):
82+
if hasattr(item, "callspec"):
8683
prompt = item.callspec.params.get("prompt")
8784
if prompt:
88-
item._nodeid = prompt # This controls how the test name appears in the report
85+
item._nodeid = (
86+
prompt # This controls how the test name appears in the report
87+
)
88+
8989

9090
def rename_duration_column():
9191
report_path = os.path.abspath("report.html") # or your report filename
9292
if not os.path.exists(report_path):
9393
print("Report file not found, skipping column rename.")
9494
return
9595

96-
with open(report_path, 'r', encoding='utf-8') as f:
97-
soup = BeautifulSoup(f, 'html.parser')
96+
with open(report_path, "r", encoding="utf-8") as f:
97+
soup = BeautifulSoup(f, "html.parser")
9898

9999
# Find and rename the header
100-
headers = soup.select('table#results-table thead th')
100+
headers = soup.select("table#results-table thead th")
101101
for th in headers:
102-
if th.text.strip() == 'Duration':
103-
th.string = 'Execution Time'
104-
#print("Renamed 'Duration' to 'Execution Time'")
102+
if th.text.strip() == "Duration":
103+
th.string = "Execution Time"
104+
# print("Renamed 'Duration' to 'Execution Time'")
105105
break
106106
else:
107107
print("'Duration' column not found in report.")
108108

109-
with open(report_path, 'w', encoding='utf-8') as f:
109+
with open(report_path, "w", encoding="utf-8") as f:
110110
f.write(str(soup))
111111

112+
112113
# Register this function to run after everything is done
113-
atexit.register(rename_duration_column)
114+
atexit.register(rename_duration_column)

tests/e2e-test/tests/test_gp_docgen.py

Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,14 @@
11
import logging
22
import time
3-
import pytest
4-
from pytest_check import check
53

6-
from config.constants import (
7-
add_section,
8-
browse_question1,
9-
browse_question2,
10-
generate_question1,
11-
invalid_response,
12-
)
4+
import pytest
5+
from config.constants import (add_section, browse_question1, browse_question2,
6+
generate_question1, invalid_response, invalid_response1)
137
from pages.browsePage import BrowsePage
148
from pages.draftPage import DraftPage
159
from pages.generatePage import GeneratePage
1610
from pages.homePage import HomePage
11+
from pytest_check import check
1712

1813
logger = logging.getLogger(__name__)
1914

@@ -31,6 +26,7 @@ def setup_pages(login_logout):
3126

3227
# ---------- INDIVIDUAL TEST CASES ----------
3328

29+
3430
def test_load_home_and_navigate_to_browse_page(setup_pages, request):
3531
request.node._nodeid = "Validate Home Page is loaded and navigating to Browse Page"
3632
_, home, browse, *_ = setup_pages
@@ -45,7 +41,9 @@ def test_load_home_and_navigate_to_browse_page(setup_pages, request):
4541
raise
4642

4743
duration = time.time() - start
48-
logger.info(f"Test 'Home to Browse Page Navigation' completed in {duration:.2f} seconds.")
44+
logger.info(
45+
f"Test 'Home to Browse Page Navigation' completed in {duration:.2f} seconds."
46+
)
4947

5048

5149
@pytest.mark.parametrize("question", [browse_question1])
@@ -80,6 +78,7 @@ def test_browse_prompt2(setup_pages, question, request):
8078
logger.info(f"Entering Browse Question 2: {question}")
8179
browse.enter_a_question(question)
8280
browse.click_send_button()
81+
browse.validate_response_status(question_api=question)
8382
browse.click_expand_reference_in_response()
8483
browse.click_reference_link_in_response()
8584
browse.close_citation()
@@ -113,6 +112,7 @@ def test_delete_chat_history_before_generate_prompt1(setup_pages, request):
113112
MAX_RETRIES = 3
114113
RETRY_DELAY = 3 # seconds
115114

115+
116116
@pytest.mark.parametrize("question", [generate_question1])
117117
def test_generate_prompt(setup_pages, question, request):
118118
request.node._nodeid = f"Validate response for GENERATE Prompt1 : {question}"
@@ -128,22 +128,24 @@ def test_generate_prompt(setup_pages, question, request):
128128
logger.info(f"Attempt {attempt}: Entering Generate Question: {question}")
129129
generate.enter_a_question(question)
130130
generate.click_send_button()
131+
generate.validate_generate_response_status(question_api=question)
132+
131133

132134
time.sleep(2)
133135
response_text = page.locator("//p")
134-
latest_response = response_text.nth(response_text.count() - 1).text_content()
136+
latest_response = response_text.nth(
137+
response_text.count() - 1
138+
).text_content()
135139

136-
if latest_response != invalid_response:
137-
logger.info(f"Valid response received on attempt {attempt}")
138-
generate.validate_response_status(question_api=question)
140+
if latest_response not in [invalid_response, invalid_response1]:
141+
logger.info(f"Valid response received on attempt {attempt}")
139142
break
140143
else:
141144
logger.warning(f"Invalid response received on attempt {attempt}")
142145
if attempt == MAX_RETRIES:
143146
check.not_equal(
144-
invalid_response,
145-
latest_response,
146-
f"FAILED: Invalid response received after {MAX_RETRIES} attempts for: {question}"
147+
latest_response not in [invalid_response, invalid_response1],
148+
f"FAILED: Invalid response received after {MAX_RETRIES} attempts for: {question}",
147149
)
148150
else:
149151
time.sleep(RETRY_DELAY)
@@ -166,7 +168,7 @@ def test_add_section_prompt(setup_pages, question, request):
166168
logger.info(f"Entering Add Section Question: {question}")
167169
generate.enter_a_question(question)
168170
generate.click_send_button()
169-
browse.validate_response_status(question_api=question)
171+
browse.validate_generate_response_status(question_api=question)
170172
except Exception as e:
171173
logger.error(f"FAILED while validating Add Section Prompt '{question}': {e}")
172174
raise
@@ -191,7 +193,9 @@ def test_generate_draft_from_section_prompt(setup_pages, request):
191193
raise
192194

193195
duration = time.time() - start
194-
logger.info(f"Test 'Generate Draft and Validate Sections' completed in {duration:.2f} seconds.")
196+
logger.info(
197+
f"Test 'Generate Draft and Validate Sections' completed in {duration:.2f} seconds."
198+
)
195199

196200

197201
def test_show_chat_history_at_end(setup_pages, request):

0 commit comments

Comments
 (0)