0
0
Selenium Pythontesting~15 mins

Logging setup in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Verify logging setup captures test execution details
Preconditions (2)
Step 1: Configure logging to write INFO level messages to a file named 'test.log'
Step 2: Start the Selenium WebDriver for Chrome
Step 3: Log the message 'Test started' before opening the webpage
Step 4: Navigate to 'https://example.com'
Step 5: Log the message 'Page opened successfully' after navigation
Step 6: Close the browser
Step 7: Log the message 'Test finished' after closing the browser
Step 8: Check the 'test.log' file for the logged messages
✅ Expected Result: The 'test.log' file contains the messages: 'Test started', 'Page opened successfully', and 'Test finished' in order
Automation Requirements - selenium with python unittest
Assertions Needed:
Verify the 'test.log' file exists after test execution
Verify the 'test.log' file contains the expected log messages in correct order
Best Practices:
Use Python's built-in logging module with proper configuration
Use explicit waits if needed (not required here as page is simple)
Use unittest framework for structuring the test
Ensure WebDriver is properly closed in tearDown method
Use assertions to verify log file content
Automated Solution
Selenium Python
import unittest
import logging
import os
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

class TestLoggingSetup(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        # Configure logging
        logging.basicConfig(
            filename='test.log',
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s',
            filemode='w'
        )

    def setUp(self):
        chrome_options = Options()
        chrome_options.add_argument('--headless')  # Run headless for test automation
        service = Service()
        self.driver = webdriver.Chrome(service=service, options=chrome_options)

    def test_logging(self):
        logging.info('Test started')
        self.driver.get('https://example.com')
        logging.info('Page opened successfully')
        self.assertIn('Example Domain', self.driver.title)

    def tearDown(self):
        self.driver.quit()
        logging.info('Test finished')

    @classmethod
    def tearDownClass(cls):
        # Verify log file content
        assert os.path.exists('test.log'), 'Log file does not exist'
        with open('test.log', 'r') as f:
            log_content = f.read()
        assert 'Test started' in log_content, 'Missing "Test started" log'
        assert 'Page opened successfully' in log_content, 'Missing "Page opened successfully" log'
        assert 'Test finished' in log_content, 'Missing "Test finished" log'

if __name__ == '__main__':
    unittest.main()

This test script uses Python's unittest framework to organize the test.

In setUpClass, logging is configured to write INFO level messages to test.log with timestamps.

The setUp method starts a headless Chrome browser for automation.

The test method logs 'Test started', opens the webpage, logs 'Page opened successfully', and asserts the page title contains 'Example Domain' to confirm navigation.

The tearDown method closes the browser and logs 'Test finished'.

Finally, tearDownClass verifies the log file exists and contains all expected messages in order.

This structure ensures logging captures key test steps and the test verifies the logging output as expected.

Common Mistakes - 4 Pitfalls
{'mistake': 'Not configuring logging before test starts', 'why_bad': "Logging messages won't be recorded if logging is not set up properly before usage.", 'correct_approach': 'Configure logging in setUpClass or before any logging calls.'}
Not closing the WebDriver properly
{'mistake': 'Checking log file content without ensuring file is flushed and closed', 'why_bad': 'Log messages might not be written yet, causing false test failures.', 'correct_approach': "Configure logging with filemode='w' and verify after test finishes."}
Hardcoding absolute paths for log file
Bonus Challenge

Now add data-driven testing with 3 different URLs and verify logging for each

Show Hint