Selenium + Python · Lesson 36 of 43

0/43 done

Module 36: Test Lifecycle

36. Test Lifecycle Management, Setup & Teardown Patterns

15 minlesson

Your task

Implement safe_lifecycle_runner(driver_creator, test_func):

  1. driver = driver_creator().
  2. In try block, call test_func(driver).
  3. In finally block, call driver.quit().

Write it in the editor, then press Check answer (Ctrl + Enter).

Lifecycle Context Manager

python
from contextlib import contextmanager
from selenium import webdriver

@contextmanager
def get_browser():
    driver = webdriver.Chrome()
    driver.maximize_window()
    try:
        yield driver
    finally:
        driver.quit() # Guaranteed teardown!

Key Takeaways & Walkthrough Summary

Every test requires a clean, isolated browser environment. In this lesson, you will structure setup and teardown methods and build reusable context manager fixtures to guarantee driver.quit() always executes. Let's master the test lifecycle!

Part of the Selenium + Python course (Selenium with Python). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Why wrap driver.quit() in a finally block?

If an assertion fails or an unexpected exception occurs during the test, a finally block guarantees the browser process is still cleanly closed.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Python
Skip