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 AdminPageAuthorizationTest(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.implicitly_wait(5)
# Precondition: User is logged in as regular user
self.login_as_regular_user()
def login_as_regular_user(self):
driver = self.driver
driver.get('https://example.com/login')
driver.find_element(By.ID, 'email').send_keys('user@example.com')
driver.find_element(By.ID, 'password').send_keys('UserPass123')
driver.find_element(By.ID, 'login-button').click()
# Wait until login completes by checking presence of logout button
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, 'logout-button'))
)
def test_access_admin_page_denied(self):
driver = self.driver
admin_url = 'https://example.com/admin/dashboard'
driver.get(admin_url)
# Wait for either error message or redirect
error_message_locator = (By.ID, 'access-denied-message')
try:
error_element = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located(error_message_locator)
)
error_text = error_element.text
except:
error_text = ''
# Assert current URL is not admin page URL
self.assertNotEqual(driver.current_url, admin_url, 'User should not access admin page URL')
# Assert error message is displayed
self.assertTrue(error_text != '', 'Access denied message should be visible')
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()This test script uses Selenium with Python's unittest framework.
setUp() logs in a regular user before each test.
The test_access_admin_page_denied method navigates to the admin page URL.
It waits explicitly for an access denied message to appear or for a redirect.
Assertions check that the URL is not the admin page and that an error message is visible.
Locators use IDs for clarity and maintainability.
Explicit waits avoid timing issues.
tearDown closes the browser after the test.