In this post, we will learn how we can use SeleniumBase Setup & Teardown methods to optimize our tests even further. If you are not familiar with setup & teardown concepts, essentially, it allows you to run certain steps before and after your actual test.
So, when you run the Setup method, it will trigger the steps BEFORE your test will run and the TearDown will run the steps AFTER your test has finished.
Setup Method
The setup method will run the steps before each of your tests. Let’s take a look at the sample code below –
def setUp(self): # Call the parent BaseCase class setup method super().setUp() print("RUNNING BEFORE EACH TEST") # LOGIN self.open("https://practice.automationbro.com/my-account") self.add_text("#username", "testuser") self.add_text("#password", "testuser123") self.click("button[name=login]") self.assert_text("Log out", ".woocommerce-MyAccount-content") # open home page self.open("https://practice.automationbro.com")
Typically, you would use your setup method for any repetitive code between your tests such as opening the page, test data creation or Login.
TearDown method
The tearDown method will run the steps after each of your tests has finished running. Let’s take a look at the sample code below –
def tearDown(self): print("RUNNING AFTER EACH TEST") # Logout self.open("https://practice.automationbro.com/my-account") self.click(".woocommerce-MyAccount-content a[href*=logout]") self.assert_element_visible("button[name=login]") # Call the parent BaseCase class tearDown method super().tearDown()
Typically, you would use tearDown method for actions such as taking screenshot after test has finished running, logging some data or for Logout.
Check out the video below to learn more about the Setup & TearDown methods –
To learn more about Selenium Python, check out the full tutorial series here for free!
I hope this post helped you out, let me know if you have any questions in the comments below!
Happy testing!