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') # Replace with actual login URL
self.wait = WebDriverWait(self.driver, 10)
def test_sql_injection_login(self):
driver = self.driver
wait = self.wait
# Locate username field and enter SQL injection string
username_field = wait.until(EC.visibility_of_element_located((By.ID, 'username')))
username_field.clear()
username_field.send_keys("' OR '1'='1")
# Locate password field and enter any password
password_field = driver.find_element(By.ID, 'password')
password_field.clear()
password_field.send_keys('password')
# Click the login button
login_button = driver.find_element(By.ID, 'loginBtn')
login_button.click()
# Wait for error message or login failure indication
error_message = wait.until(EC.visibility_of_element_located((By.ID, 'errorMsg')))
# Assert error message is displayed
self.assertTrue(error_message.is_displayed(), 'Error message should be displayed')
# Assert URL does not contain dashboard path
current_url = driver.current_url
self.assertNotIn('/dashboard', current_url, 'Should not navigate to dashboard on SQL injection')
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()This test script uses Selenium with Python's unittest framework.
setUp: Opens the browser and navigates to the login page.
test_sql_injection_login: Enters a classic SQL injection string in the username field and a dummy password, then clicks login.
It waits explicitly for the error message element to appear, ensuring the page has responded.
Assertions check that the error message is visible and the URL does not change to the dashboard, confirming login failure.
tearDown: Closes the browser after the test.
Explicit waits and meaningful locators (By.ID) are used for reliability and maintainability.