0
0
Selenium Pythontesting~10 mins

Reading test data from JSON in Selenium Python - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test reads user login data from a JSON file and verifies successful login on a web page.

Test Code - Selenium
Selenium Python
import json
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class TestLoginWithJSON(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.get('https://example.com/login')

    def test_login(self):
        with open('testdata.json', 'r') as file:
            data = json.load(file)
        username = data['username']
        password = data['password']

        driver = self.driver
        WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'username')))
        driver.find_element(By.ID, 'username').send_keys(username)
        driver.find_element(By.ID, 'password').send_keys(password)
        driver.find_element(By.ID, 'login-btn').click()

        WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'welcome-msg')))
        welcome_text = driver.find_element(By.ID, 'welcome-msg').text
        self.assertIn('Welcome', welcome_text)

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

if __name__ == '__main__':
    unittest.main()
Execution Trace - 8 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensBrowser window opens at https://example.com/login page-PASS
2Reads username and password from testdata.json fileJSON file loaded with keys 'username' and 'password'-PASS
3Waits until username input field is presentUsername input field visible on login pagePresence of element located by ID 'username'PASS
4Enters username and password into input fieldsUsername and password fields filled with test data-PASS
5Clicks the login buttonLogin button clicked, page starts loading-PASS
6Waits until welcome message element is presentWelcome message element visible on pagePresence of element located by ID 'welcome-msg'PASS
7Checks that welcome message contains 'Welcome'Welcome message text retrievedAssert 'Welcome' in welcome message textPASS
8Test ends and browser closesBrowser window closed-PASS
Failure Scenario
Failing Condition: The JSON file is missing or malformed, or the login fails due to incorrect credentials
Execution Trace Quiz - 3 Questions
Test your understanding
At which step does the test read the login data from the JSON file?
AStep 6
BStep 4
CStep 2
DStep 1
Key Result
Reading test data from external JSON files helps separate test logic from data, making tests easier to maintain and reuse.