Why security testing protects users in Testing Fundamentals - Automation Benefits in Action
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 import unittest class TestSQLInjection(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.driver.get('https://example.com/login') self.wait = WebDriverWait(self.driver, 10) def test_sql_injection_login(self): driver = self.driver wait = self.wait username_input = wait.until(EC.visibility_of_element_located((By.ID, 'username'))) password_input = driver.find_element(By.ID, 'password') login_button = driver.find_element(By.ID, 'loginBtn') username_input.clear() username_input.send_keys("admin' OR '1'='1") password_input.clear() password_input.send_keys('anyPassword') login_button.click() # Wait for error message to appear error_message = wait.until(EC.visibility_of_element_located((By.ID, 'errorMsg'))) # Assert error message is shown self.assertIn('Invalid username or password', error_message.text) # Assert URL did not change to dashboard self.assertNotIn('/dashboard', driver.current_url) # Assert no database error text is visible page_source = driver.page_source.lower() self.assertNotIn('sql syntax', page_source) self.assertNotIn('database error', page_source) def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main()
This test script uses Selenium with Python's unittest framework to automate the manual test case.
In setUp, it opens the browser and navigates to the login page.
The test test_sql_injection_login enters a common SQL injection string in the username field and any password, then clicks login.
It waits explicitly for the error message element to appear, then asserts the error message text is correct, ensuring the login was rejected.
It also checks the URL to confirm the user was not redirected to a logged-in page.
Finally, it checks the page source to ensure no database error messages are shown, which would be a security risk.
The tearDown method closes the browser after the test.
This structure follows best practices: explicit waits, clear locators by ID, and meaningful assertions.
Now add data-driven testing with 3 different SQL injection inputs to verify the login form rejects all.