0
0
Selenium Pythontesting~15 mins

Window size control in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Verify browser window size can be set and retrieved
Preconditions (3)
Step 1: Open the browser using Selenium WebDriver
Step 2: Navigate to 'https://example.com'
Step 3: Set the browser window size to width 1024 and height 768
Step 4: Retrieve the current window size
Step 5: Verify that the window size width is 1024 and height is 768
Step 6: Close the browser
✅ Expected Result: The browser window size is set to 1024x768 and verified successfully before closing the browser
Automation Requirements - Selenium with Python
Assertions Needed:
Assert that the window width equals 1024
Assert that the window height equals 768
Best Practices:
Use explicit waits if needed before assertions
Use try-finally or context management to ensure browser closes
Use By locators only if interacting with page elements (not needed here)
Keep code readable and modular
Automated Solution
Selenium Python
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import unittest

class TestWindowSize(unittest.TestCase):
    def setUp(self):
        options = Options()
        # options.add_argument('--headless')  # Uncomment to run headless
        self.driver = webdriver.Chrome(options=options)

    def test_window_size(self):
        driver = self.driver
        driver.get('https://example.com')

        # Set window size
        driver.set_window_size(1024, 768)

        # Get window size
        size = driver.get_window_size()

        # Assertions
        self.assertEqual(size['width'], 1024, f"Expected width 1024 but got {size['width']}")
        self.assertEqual(size['height'], 768, f"Expected height 768 but got {size['height']}")

    def tearDown(self):
        self.driver.quit()

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

This test uses Python's unittest framework with Selenium WebDriver.

setUp creates the browser instance before each test.

test_window_size navigates to example.com, sets the window size to 1024x768, then retrieves the size and asserts both width and height match the expected values.

tearDown closes the browser after the test to clean up.

This structure ensures the browser is always closed even if the test fails. Assertions include messages to help identify issues if the size is incorrect.

Common Mistakes - 4 Pitfalls
Not closing the browser after the test
Using hardcoded sleep instead of waiting for page load
Setting window size before navigating to a page
{'mistake': 'Using incorrect dictionary keys when retrieving window size', 'why_bad': 'Causes KeyError and test failure', 'correct_approach': "Use 'width' and 'height' keys exactly as returned by get_window_size()"}
Bonus Challenge

Now add data-driven testing with 3 different window sizes: (800x600), (1280x720), and (1920x1080)

Show Hint