I am new to test automation in Selenium Python. I was trying to automate a simple login test and I want to do some things in AfterClass method like in Selenium Java.
I have attached my code here.
test_login.py
import unittest
from helper_actions import load_page, type_username, type_password, click_login_button
from helper_assertions import get_welcome_text, read_error_message
class LoginTests(unittest.TestCase):
def setUp(self):
super().setUp()
print("Run before each methods")
load_page()
def test_valid_username_and_password(self):
print("test_valid_username_and_password")
type_username("admin")
type_password("Ptl@#321")
click_login_button()
assert get_welcome_text() == "Welcome Admin"
def test_valid_username_and_invalid_password(self):
print("test_valid_username_and_invalid_password")
type_username("admin")
type_password("admin")
click_login_button()
assert read_error_message() == "Invalid credentials"
def tearDown(self):
print("Run after each method")
super().tearDown()
if __name__ == "__main__":
unittest.main()
helper_actions.py
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
driver = webdriver.Chrome(service=ChromeService(
ChromeDriverManager().install()))
def load_page():
driver.get("http://hrm.pragmatictestlabs.com/")
def type_username(username):
driver.find_element(By.ID, "txtUsername").send_keys(username)
def type_password(password):
driver.find_element(By.ID, "txtPassword").send_keys(password)
def click_login_button():
driver.find_element(By.ID, "btnLogin").click()
helper_assertions.py
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
driver = webdriver.Chrome(service=ChromeService(
ChromeDriverManager().install()))
def get_welcome_text():
return driver.find_element(By.ID, "welcome").text
def read_error_message():
return driver.find_element(By.ID, "spanMessage").text
How can I add driver.quit()
at the end of the tests run?
CodePudding user response:
@Anupama Balasooriya you can use setUpClass() and tearDownClass() for your purpose. You can refer this link for details. https://docs.python.org/3/library/unittest.html