Skip to content

Commit

Permalink
Merge pull request #497 from qxf2/add-method-to-color-text
Browse files Browse the repository at this point in the history
Added a method to colour a text and used it under conftest
  • Loading branch information
rohandudam authored Nov 19, 2024
2 parents a2dc44a + ec53c55 commit 24cc4b4
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 33 deletions.
72 changes: 39 additions & 33 deletions conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from page_objects.PageFactory import PageFactory # pylint: disable=import-error wrong-import-position
from utils import interactive_mode # pylint: disable=import-error wrong-import-position
from core_helpers.custom_pytest_plugins import CustomTerminalReporter # pylint: disable=import-error wrong-import-position
from core_helpers.logging_objects import Logging_Objects # pylint: disable=import-error wrong-import-position

load_dotenv()

Expand Down Expand Up @@ -51,11 +52,11 @@ def test_obj(base_url, browser, browser_version, os_version, os_name, remote_fla
#Setup TestRail reporting
if testrail_flag.lower()=='y':
if test_run_id is None:
test_obj.write('\033[91m'+"\n\nTestRail Integration Exception:"\
test_obj.write("\n\nTestRail Integration Exception:"\
" It looks like you are trying to use TestRail Integration without"\
" providing test run id. \nPlease provide a valid test run id along"\
" with test run command using --test_run_id and try again."\
" for eg: pytest --testrail_flag Y --test_run_id 100\n"+'\033[0m')
" for eg: pytest --testrail_flag Y --test_run_id 100\n", level='critical')
testrail_flag = 'N'
if test_run_id is not None:
test_obj.register_testrail()
Expand Down Expand Up @@ -92,15 +93,16 @@ def test_obj(base_url, browser, browser_version, os_version, os_name, remote_fla
else:
# Handle the case where the response is assumed to be a response object
if response.status_code == 200:
test_obj.write("Log file uploaded to BrowserStack session successfully.")
test_obj.write("Log file uploaded to BrowserStack session successfully.",
level='success')
else:
test_obj.write(f"Failed to upload log file. Status code:{response.status_code}",
level='error')
test_obj.write(response.text,level='error')

#Update test run status to respective BrowserStack session
if test_obj.pass_counter == test_obj.result_counter:
test_obj.write("Test Status: PASS")
test_obj.write("Test Status: PASS",level='success')
result_flag = test_obj.execute_javascript("""browserstack_executor:
{"action": "setSessionStatus",
"arguments": {"status":"passed", "reason": "All test cases passed"}}""")
Expand All @@ -123,15 +125,16 @@ def test_obj(base_url, browser, browser_version, os_version, os_name, remote_fla
test_obj.teardown()

except Exception as e: # pylint: disable=broad-exception-caught
print(f"Exception when trying to run test:{__file__}")
print(f"Python says:{str(e)}")
print(Logging_Objects.color_text(f"Exception when trying to run test:{__file__}","red"))
print(Logging_Objects.color_text(f"Python says:{str(e)}","red"))
if os.getenv('REMOTE_BROWSER_PLATFORM') == 'LT' and remote_flag.lower() == 'y':
test_obj.execute_javascript("lambda-status=error")
elif os.getenv('REMOTE_BROWSER_PLATFORM') == 'BS' and remote_flag.lower() == 'y':
test_obj.execute_javascript("""browserstack_executor: {"action": "setSessionStatus",
"arguments": {"status":"failed", "reason": "Exception occured"}}""")
if browser == "edge":
print(f"Selenium Manager requires administrator permissions to install Microsoft {browser} in Windows automatically ")
if browser.lower() == "edge":
print(Logging_Objects.color_text("Selenium Manager requires administrator permissions"\
" to install Microsoft Edge in Windows automatically."))

@pytest.fixture
def test_mobile_obj(mobile_os_name, mobile_os_version, device_name, app_package, app_activity, # pylint: disable=redefined-outer-name too-many-arguments too-many-locals
Expand Down Expand Up @@ -160,11 +163,11 @@ def test_mobile_obj(mobile_os_name, mobile_os_version, device_name, app_package,
#3. Setup TestRail reporting
if testrail_flag.lower()=='y':
if test_run_id is None:
test_mobile_obj.write('\033[91m'+"\n\nTestRail Integration Exception: "\
test_mobile_obj.write("\n\nTestRail Integration Exception: "\
"It looks like you are trying to use TestRail Integration "\
"without providing test run id. \nPlease provide a valid test run id "\
"along with test run command using --test_run_id and try again."\
" for eg: pytest --testrail_flag Y --test_run_id 100\n"+'\033[0m')
" for eg: pytest --testrail_flag Y --test_run_id 100\n",level='critical')
testrail_flag = 'N'
if test_run_id is not None:
test_mobile_obj.register_testrail()
Expand Down Expand Up @@ -193,14 +196,15 @@ def test_mobile_obj(mobile_os_name, mobile_os_version, device_name, app_package,
else:
# Handle the case where the response is assumed to be a response object
if response.status_code == 200:
test_mobile_obj.write("Log file uploaded to BrowserStack session successfully.")
test_mobile_obj.write("Log file uploaded to BrowserStack session successfully.",
level='success')
else:
test_mobile_obj.write("Failed to upload log file. "\
f"Status code: {response.status_code}",level='error')
test_mobile_obj.write(response.text,level='error')
#Update test run status to respective BrowserStack session
if test_mobile_obj.pass_counter == test_mobile_obj.result_counter:
test_mobile_obj.write("Test Status: PASS")
test_mobile_obj.write("Test Status: PASS",level='success')
result_flag = test_mobile_obj.execute_javascript("""browserstack_executor:
{"action": "setSessionStatus", "arguments": {"status":"passed",
"reason": "All test cases passed"}}""")
Expand All @@ -221,8 +225,8 @@ def test_mobile_obj(mobile_os_name, mobile_os_version, device_name, app_package,
test_mobile_obj.teardown()

except Exception as e: # pylint: disable=broad-exception-caught
print(f"Exception when trying to run test:{__file__}")
print(f"Python says:{str(e)}")
print(Logging_Objects.color_text(f"Exception when trying to run test:{__file__}","red"))
print(Logging_Objects.color_text(f"Python says:{str(e)}","red"))
if os.getenv('REMOTE_BROWSER_PLATFORM') == 'BS' and remote_flag.lower() == 'y':
test_mobile_obj.execute_javascript("""browserstack_executor:
{"action": "setSessionStatus", "arguments":
Expand All @@ -243,8 +247,8 @@ def test_api_obj(interactivemode_flag, testname, api_url): # pylint: disable=re
yield test_api_obj

except Exception as e: # pylint: disable=broad-exception-caught
print(f"Exception when trying to run test:{__file__}")
print(f"Python says:{str(e)}")
print(Logging_Objects.color_text(f"Exception when trying to run test:{__file__}","red"))
print(Logging_Objects.color_text(f"Python says:{str(e)}","red"))

def upload_test_logs_to_browserstack(log_name, session_url, appium_test = False):
"Upload log file to provided BrowserStack session"
Expand Down Expand Up @@ -452,11 +456,11 @@ def reportportal_service(request):
reportportal_pytest_service = request.node.config.py_test_service

except Exception as e: # pylint: disable=broad-exception-caught
print(f"Exception when trying to run test:{__file__}")
print(f"Python says:{str(e)}")
print(Logging_Objects.color_text(f"Exception when trying to run test:{__file__}","red"))
print(Logging_Objects.color_text(f"Python says:{str(e)}","red"))
solution = "It looks like you are trying to use report portal to run your test."\
"\nPlease make sure you have updated .env with the right credentials."
print(f"\033[92m\nSOLUTION: {solution}\n\033[0m")
print(Logging_Objects.color_text(f"\nSOLUTION: {solution}\n", "green"))

return reportportal_pytest_service

Expand Down Expand Up @@ -485,14 +489,15 @@ def pytest_sessionstart(session):
try:
os.remove(consolidated_log_file)
except OSError as error:
print(f"Error removing existing consolidated log file: {error}")
print(Logging_Objects.color_text(
f"Error removing existing consolidated log file: {error}"))

# Delete all temporary log files if present
for temp_log_file in glob.glob(os.path.join(source_directory, log_file_name)):
try:
os.remove(temp_log_file)
except OSError as error:
print(f"Error removing temporary log file: {error}")
print(Logging_Objects.color_text(f"Error removing temporary log file: {error}"))

def pytest_sessionfinish(session):
"""
Expand All @@ -519,11 +524,12 @@ def pytest_sessionfinish(session):
shutil.copyfileobj(source_file, final_log)
os.remove(file_name)
except FileNotFoundError as error:
print(f"Temporary log file not found: {error}")
print(Logging_Objects.color_text(f"Temporary log file not found: {error}"))
except Exception as error: # pylint: disable=broad-exception-caught
print(f"Error processing the temporary log file: {error}")
print(Logging_Objects.color_text(
f"Error processing the temporary log file: {error}"))
except OSError as error:
print(f"Error processing consolidated log file: {error}")
print(Logging_Objects.color_text(f"Error processing consolidated log file: {error}"))

@pytest.hookimpl(trylast=True)
def pytest_configure(config):
Expand Down Expand Up @@ -577,8 +583,8 @@ def pytest_configure(config):
config._inicache["rp_launch"]= os.getenv('report_portal_launch') # pylint: disable=protected-access

except Exception as e: # pylint: disable=broad-exception-caught
print(f"Exception when trying to run test:{__file__}")
print(f"Python says:{str(e)}")
print(Logging_Objects.color_text(f"Exception when trying to run test:{__file__}","red"))
print(Logging_Objects.color_text(f"Python says:{str(e)}","red"))

#Registering custom markers to supress warnings
config.addinivalue_line("markers", "GUI: mark a test as part of the GUI regression suite.")
Expand Down Expand Up @@ -606,11 +612,11 @@ def pytest_terminal_summary(terminalreporter):
from utils import gpt_summary_generator # pylint: disable=import-error,import-outside-toplevel
gpt_summary_generator.generate_gpt_summary()
except Exception as e: # pylint: disable=broad-exception-caught
print(f"Exception when trying to run test:{__file__}")
print(f"Python says:{str(e)}")
print(Logging_Objects.color_text(f"Exception when trying to run test:{__file__}","red"))
print(Logging_Objects.color_text(f"Python says:{str(e)}","red"))
solution = "It looks like you are trying to use email pytest report to run your test." \
"\nPlease make sure you have updated .env with the right credentials ."
print(f"\033[92m\nSOLUTION: {solution}\n\033[0m")
print(Logging_Objects.color_text(f"\nSOLUTION: {solution}\n","green"))


def pytest_generate_tests(metafunc):
Expand Down Expand Up @@ -676,8 +682,8 @@ def pytest_generate_tests(metafunc):
metafunc.parametrize("browser, browser_version", config_list_local)

except Exception as e: # pylint: disable=broad-exception-caught
print(f"Exception when trying to run test:{__file__}")
print(f"Python says:{str(e)}")
print(Logging_Objects.color_text(f"Exception when trying to run test:{__file__}","red"))
print(Logging_Objects.color_text(f"Python says:{str(e)}","red"))

def pytest_addoption(parser):
"Method to add the option to ini."
Expand Down Expand Up @@ -816,5 +822,5 @@ def pytest_addoption(parser):
help="Y or N. 'Y' if you want turn on element highlighter")

except Exception as e: # pylint: disable=broad-exception-caught
print(f"Exception when trying to run test:{__file__}")
print(f"Python says:{str(e)}")
print(Logging_Objects.color_text(f"Exception when trying to run test:{__file__}","red"))
print(Logging_Objects.color_text(f"Python says:{str(e)}","red"))
13 changes: 13 additions & 0 deletions core_helpers/logging_objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,19 @@ def __init__(self):
self.msg_list = []
self.exceptions = []

@staticmethod
def color_text(text, color ="red"):
colors = {
"red": "\033[91m",
"green": "\033[92m",
"yellow": "\033[93m",
"blue": "\033[94m",
"magenta": "\033[95m",
"cyan": "\033[96m",
"reset": "\033[0m"
}
return f"{colors.get(color, colors['reset'])}{text}{colors['reset']}"

def write_test_summary(self):
"Print out a useful, human readable summary"
if self.result_counter==self.pass_counter:
Expand Down

0 comments on commit 24cc4b4

Please sign in to comment.