pytest is a testing framework for Python that helps write and run tests easily. It is used with Selenium to automate browser actions and verify web application behavior.
Click to reveal answer
beginner
How do you install pytest and Selenium in Python?
Use the command pip install pytest selenium in your terminal or command prompt to install both pytest and Selenium libraries.
Click to reveal answer
intermediate
What is a pytest fixture and how is it useful in Selenium tests?
A pytest fixture is a function that runs before a test to set up needed resources, like opening a browser. It helps reuse setup code and clean up after tests.
Click to reveal answer
intermediate
Show a simple pytest fixture example that opens and closes a Chrome browser using Selenium.
C. driver.quit() is never called because it is after return
D. webdriver.Chrome() is not imported correctly
Solution
Step 1: Check fixture function flow
The fixture returns driver before calling driver.quit(), so quit() never runs.
Step 2: Understand impact on test
Without quitting, browser stays open, causing resource leaks and flaky tests.
Final Answer:
driver.quit() is never called because it is after return -> Option C
Quick Check:
Code after return is ignored = D [OK]
Hint: Put cleanup code after yield, not after return [OK]
Common Mistakes:
Placing driver.quit() after return
Confusing @pytest.test with @pytest.fixture
Ignoring proper assertion syntax
5. You want to run a Selenium test with pytest that opens Firefox, navigates to a page, and checks a button is clickable. Which pytest fixture setup is best practice to ensure browser opens and closes properly?
hard
A. @pytest.fixture
def browser():
driver = webdriver.Firefox()
driver.quit()
yield driver
B. def browser():
driver = webdriver.Firefox()
return driver
driver.quit()
C. @pytest.fixture
def browser():
driver = webdriver.Firefox()
yield driver
D. @pytest.fixture
def browser():
driver = webdriver.Firefox()
yield driver
driver.quit()
Solution
Step 1: Review proper fixture structure for setup and teardown
Best practice is to create driver, yield it for test use, then quit after test finishes.
Step 2: Evaluate each option
@pytest.fixture
def browser():
driver = webdriver.Firefox()
yield driver
driver.quit() correctly uses yield and calls quit after test. def browser():
driver = webdriver.Firefox()
return driver
driver.quit() quits after return (never runs). @pytest.fixture
def browser():
driver = webdriver.Firefox()
driver.quit()
yield driver quits before yield (browser closed too early). @pytest.fixture
def browser():
driver = webdriver.Firefox()
yield driver never quits browser.