Skip to content

Commit 9e44e3a

Browse files
committed
Refactor test modules
1 parent 82cbf3e commit 9e44e3a

File tree

5 files changed

+104
-167
lines changed

5 files changed

+104
-167
lines changed
Lines changed: 11 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -1,135 +1,50 @@
11
import shutil
2-
import subprocess
32

43
import pytest
5-
from django.contrib.auth import get_user_model
64
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
75
from selenium import webdriver
86
from selenium.webdriver.chrome.options import Options
97
from selenium.webdriver.chrome.service import Service
10-
from selenium.webdriver.common.by import By
11-
from selenium.webdriver.support import expected_conditions as EC
128
from selenium.webdriver.support.ui import WebDriverWait
139

10+
from .mixins import AuthenticationMixin
1411

15-
class BaseTestCase(StaticLiveServerTestCase):
12+
13+
class BaseTestCase(StaticLiveServerTestCase, AuthenticationMixin):
1614
"""Base class for all frontend tests using Selenium."""
1715

1816
@classmethod
1917
def setUpClass(cls):
2018
super().setUpClass()
2119

22-
# Verify ChromeDriver is available
20+
# Verify ChromeDriver and Chromium are available
2321
chromedriver_path = shutil.which("chromedriver")
22+
chromium_path = shutil.which("chromium")
23+
2424
if not chromedriver_path:
2525
pytest.fail("ChromeDriver not found. Please ensure chromium-driver is installed.")
26+
if not chromium_path:
27+
pytest.fail("Chromium not found. Please ensure chromium is installed.")
2628

27-
# # Set up Chrome options
29+
# Set up Chrome options
2830
chrome_options = Options()
2931
chrome_options.add_argument("--headless")
3032
chrome_options.add_argument("--no-sandbox")
3133
chrome_options.add_argument("--disable-dev-shm-usage")
32-
chrome_options.binary_location = "/usr/bin/chromium"
34+
chrome_options.binary_location = chromium_path
3335

3436
try:
35-
# Create service with explicit path
36-
service = Service(executable_path=chromedriver_path, log_path="/tmp/chromedriver.log")
37-
38-
# Initialize WebDriver with service and options
37+
service = Service(executable_path=chromedriver_path)
3938
cls.driver = webdriver.Chrome(service=service, options=chrome_options)
40-
4139
cls.driver.set_window_size(1920, 1080)
4240
cls.driver.implicitly_wait(10)
4341
cls.wait = WebDriverWait(cls.driver, 10)
4442

4543
except Exception as e:
46-
# Print debugging information
47-
subprocess.run(["which", "chromium"])
48-
subprocess.run(["which", "chromedriver"])
49-
subprocess.run(["chromium", "--version"])
50-
subprocess.run(["chromedriver", "--version"])
5144
pytest.fail(f"Failed to initialize ChromeDriver: {str(e)}")
5245

5346
@classmethod
5447
def tearDownClass(cls):
5548
if hasattr(cls, "driver"):
5649
cls.driver.quit()
5750
super().tearDownClass()
58-
59-
def setUp(self):
60-
"""Set up test case."""
61-
super().setUp()
62-
# Add any additional setup here
63-
64-
def create_test_user(self, username="test_user", password="test_password123", **kwargs):
65-
"""Create a test user for login testing."""
66-
User = get_user_model()
67-
68-
# Delete user if it already exists
69-
User.objects.filter(username=username).delete()
70-
71-
user_data = {
72-
"username": username,
73-
"is_active": True,
74-
"is_staff": True, # Ensure user is staff
75-
"is_superuser": False, # Ensure user is superuser
76-
}
77-
user_data.update(kwargs)
78-
79-
user = User.objects.create_user(**user_data)
80-
user.set_password(password)
81-
user.save()
82-
83-
# Verify user was created correctly
84-
print(f"\nCreated user: {username}")
85-
print(f"Is active: {user.is_active}")
86-
print(f"Is staff: {user.is_staff}")
87-
print(f"Is superuser: {user.is_superuser}")
88-
89-
return user, password
90-
91-
def login(self, username="test_user", password="test_password123"):
92-
"""
93-
Login helper method.
94-
Returns True if login successful, False otherwise.
95-
"""
96-
# Navigate to login page
97-
self.driver.get(f"{self.live_server_url}/accounts/login/")
98-
99-
try:
100-
# Wait for and fill username
101-
username_input = self.wait.until(EC.presence_of_element_located((By.NAME, "login")))
102-
username_input.send_keys(username)
103-
104-
# Fill password
105-
password_input = self.driver.find_element(By.NAME, "password")
106-
password_input.send_keys(password)
107-
108-
# Find and click the login button
109-
login_button = self.driver.find_element(By.CSS_SELECTOR, "button[type='submit']")
110-
login_button.click()
111-
112-
# Wait for successful login by checking for redirect
113-
self.wait.until(EC.url_changes("/accounts/login/"))
114-
115-
# Print debug information
116-
print(f"Current URL after login: {self.driver.current_url}")
117-
return True
118-
119-
except Exception as e:
120-
print(f"Login failed: {str(e)}")
121-
return False
122-
123-
def logout(self):
124-
"""Logout helper method."""
125-
try:
126-
# Click logout link/button (adjust selector based on your UI)
127-
logout_link = self.driver.find_element(By.CSS_SELECTOR, "a[href*='logout']")
128-
logout_link.click()
129-
130-
# Wait for redirect to login page
131-
self.wait.until(EC.presence_of_element_located((By.NAME, "username")))
132-
return True
133-
except Exception as e:
134-
print(f"Logout failed: {str(e)}")
135-
return False
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
from selenium.webdriver.common.by import By
2+
from selenium.webdriver.support import expected_conditions as EC
3+
4+
from ..factories import UserFactory
5+
6+
7+
class AuthenticationMixin:
8+
"""Mixin for authentication-related test methods."""
9+
10+
def create_test_user(self, username="test_user", password="test_password123", **kwargs):
11+
"""Create a test user using UserFactory."""
12+
# Delete user if it already exists
13+
UserFactory._meta.model.objects.filter(username=username).delete()
14+
15+
user = UserFactory(username=username, is_active=True, **kwargs)
16+
user.set_password(password)
17+
user.save()
18+
19+
return user, password
20+
21+
def login(self, username="test_user", password="test_password123"):
22+
"""
23+
Login helper method.
24+
Returns True if login successful, False otherwise.
25+
"""
26+
self.driver.get(f"{self.live_server_url}/accounts/login/")
27+
28+
try:
29+
username_input = self.wait.until(EC.presence_of_element_located((By.NAME, "login")))
30+
username_input.send_keys(username)
31+
32+
password_input = self.driver.find_element(By.NAME, "password")
33+
password_input.send_keys(password)
34+
35+
login_button = self.driver.find_element(By.CSS_SELECTOR, "button[type='submit']")
36+
login_button.click()
37+
38+
self.wait.until(EC.title_is("Collections | COSMOS"))
39+
return True
40+
41+
except Exception as e:
42+
print(f"Login failed: {str(e)}")
43+
return False
44+
45+
def logout(self):
46+
"""Logout helper method."""
47+
try:
48+
logout_link = self.driver.find_element(By.CSS_SELECTOR, "a[href='/accounts/logout/']")
49+
self.driver.execute_script("arguments[0].click();", logout_link)
50+
51+
self.wait.until(EC.presence_of_element_located((By.NAME, "login")))
52+
return True
53+
except Exception as e:
54+
print(f"Logout failed: {str(e)}")
55+
return False
Lines changed: 32 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from selenium.webdriver.common.by import By
2+
13
from .base import BaseTestCase
24

35

@@ -6,52 +8,49 @@ class TestAuthentication(BaseTestCase):
68

79
def setUp(self):
810
super().setUp()
9-
self.test_username = "test_user"
10-
self.test_password = "test_password123"
11-
self.user, _ = self.create_test_user(username=self.test_username, password=self.test_password)
11+
# Create test user with factory
12+
self.user, self.password = self.create_test_user(
13+
username="test_user", password="test_password123", is_staff=True
14+
)
1215

1316
def test_successful_login(self):
1417
"""Test successful login process."""
1518
# Attempt login
16-
login_success = self.login(self.test_username, self.test_password)
17-
assert login_success, "Login should be successful"
19+
login_success = self.login(self.user.username, self.password)
20+
assert login_success, "Login Failed"
1821

19-
# Verify we're on the dashboard or home page
20-
assert "Welcome back!" in self.driver.page_source
22+
# Verify successful login by checking welcome message
23+
assert "Welcome back!" in self.driver.page_source, "Welcome message not found"
2124

22-
# print(self.driver.page_source)
25+
def test_failed_login(self):
26+
"""Test login failure with incorrect credentials."""
27+
# Attempt login with wrong password
28+
login_success = self.login(self.user.username, "wrong_password")
29+
assert not login_success, "Login should fail with incorrect password"
2330

24-
# # Verify user menu is present
25-
# user_menu = self.wait.until(
26-
# EC.presence_of_element_located((By.CLASS_NAME, "user-menu"))
27-
# )
28-
# assert self.test_username in user_menu.text
31+
# Verify we're still on login page
32+
assert "/accounts/login/" in self.driver.current_url, "Should remain on login page"
2933

30-
# def test_failed_login(self):
31-
# """Test login failure with incorrect credentials."""
32-
# login_success = self.login(self.test_username, "wrong_password")
33-
# assert not login_success, "Login should fail with incorrect password"
34+
# Verify error message is displayed
35+
error_message = (self.driver.find_element(By.CLASS_NAME, "alert")).text
36+
assert "The username and/or password you specified are not correct" in error_message, "Error message not found"
3437

35-
# # Verify error message
36-
# error_message = self.wait.until(
37-
# EC.presence_of_element_located((By.CLASS_NAME, "alert-error"))
38-
# )
39-
# assert "Please enter a correct username and password" in error_message.text
38+
def test_logout(self):
39+
"""Test logout functionality."""
40+
# First login
41+
login_success = self.login(self.user.username, self.password)
42+
assert login_success, "Initial login failed"
4043

41-
# def test_logout(self):
42-
# """Test logout functionality."""
43-
# # First login
44-
# login_success = self.login(self.test_username, self.test_password)
45-
# assert login_success, "Login should be successful"
44+
# Verify we're logged in
45+
assert "Welcome back!" in self.driver.page_source, "Not properly logged in"
4646

47-
# # Then logout
48-
# logout_success = self.logout()
49-
# assert logout_success, "Logout should be successful"
47+
# Perform logout
48+
logout_success = self.logout()
49+
assert logout_success, "Logout failed"
5050

51-
# # Verify we're back at login page
52-
# assert "login" in self.driver.current_url.lower()
51+
# Verify redirect to login page
52+
assert "/accounts/login/" in self.driver.current_url, "Should redirect to login page after logout"
5353

5454
def tearDown(self):
5555
"""Clean up after each test."""
56-
self.user.delete()
5756
super().tearDown()

sde_collections/tests/frontend/test_collections.py

Lines changed: 6 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1+
# docker-compose -f local.yml run --rm django pytest -s sde_collections/tests/frontend/test_collections.py
2+
13
from selenium.webdriver.common.by import By
24
from selenium.webdriver.support import expected_conditions as EC
35

4-
from ..factories import CollectionFactory, UserFactory
6+
from ..factories import CollectionFactory
57
from .base import BaseTestCase
68

79

@@ -11,45 +13,27 @@ class TestCollections(BaseTestCase):
1113
def setUp(self):
1214
"""Set up test data."""
1315
super().setUp()
14-
# Create test user and collections
15-
self.user = UserFactory(is_staff=True)
16-
self.user.set_password("test_password123")
17-
self.user.save()
16+
self.user, self.password = self.create_test_user(is_staff=True)
1817

1918
# Create 3 test collections
2019
self.collections = [CollectionFactory(curated_by=self.user) for _ in range(3)]
21-
# Store collection names for verification
2220
self.collection_names = [collection.name for collection in self.collections]
2321

2422
def test_collections_display(self):
2523
"""Test that collections are displayed after login."""
26-
# Login
27-
self.login(self.user.username, "test_password123")
24+
self.login(self.user.username, self.password)
2825

2926
# Navigate to collections page
3027
self.driver.get(f"{self.live_server_url}/")
3128

32-
# Print page source for debugging
33-
# print(f"\nCurrent URL: {self.driver.current_url}")
34-
print(f"Page Source: {self.driver.page_source}")
35-
3629
# Wait for specific table to load using ID
3730
table = self.wait.until(EC.presence_of_element_located((By.ID, "collection_table")))
38-
39-
# Additional verification that it's the right table
4031
assert "table-striped dataTable" in table.get_attribute("class")
4132

42-
# Print debug info
43-
print(f"\nCurrent URL: {self.driver.current_url}")
44-
print(f"Table HTML: {table.get_attribute('outerHTML')}")
45-
46-
# Get all table text
47-
table_text = table.text
48-
4933
# Verify each collection name is present
34+
table_text = table.text
5035
for collection_name in self.collection_names:
5136
assert collection_name in table_text, f"Collection '{collection_name}' not found in table"
52-
print(f"Found collection: {collection_name}")
5337

5438
def tearDown(self):
5539
"""Clean up test data."""

sde_collections/tests/frontend/test_setup.py

Lines changed: 0 additions & 16 deletions
This file was deleted.

0 commit comments

Comments
 (0)