Skip to content

Commit

Permalink
Merge pull request #2 from mauritzs/add_unit_tests
Browse files Browse the repository at this point in the history
Add unit tests
  • Loading branch information
mauritzs authored and GitHub Enterprise committed Mar 27, 2025
2 parents de2db71 + 28b69fb commit 6af87c9
Show file tree
Hide file tree
Showing 3 changed files with 155 additions and 0 deletions.
47 changes: 47 additions & 0 deletions .github/workflows/test_dev.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
name: Django Tests

on:
workflow_dispatch:
push:
branches: [main]
pull_request:
branches: [main, develop]

jobs:
test:
runs-on: self-hosted

env:
DJANGO_SUPERUSER_USERNAME: admin
DJANGO_SUPERUSER_PASSWORD: Password
DJANGO_SETTINGS_MODULE: secfit.settings

steps:
- name: Free Disk Space (Ubuntu)
uses: jlumbroso/free-disk-space@main
with:
tool-cache: false

- uses: actions/checkout@v4

- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: "pip"

- name: Install dependencies
run: |
python -m pip install --upgrade pip
cd backend
pip install -r requirements.txt
- name: Run migrations
run: |
cd backend
python manage.py migrate
- name: Run tests
run: |
cd backend
python manage.py test tests
43 changes: 43 additions & 0 deletions backend/locustTest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from locust import HttpUser, task, between

class SecFitUser(HttpUser):
host = "http://tdt4242-05.idi.ntnu.no:20027" # Replace with your actual backend URL
wait_time = between(1, 3)

token = None # Store authentication token
exercise_url = None # Store an existing exercise URL

def on_start(self):
""" Log in and fetch a valid exercise URL when a Locust user starts """
response = self.client.post("/api/token/", json={
"username": "locustuser",
"password": "locustpass"
})

if response.status_code == 200:
self.token = response.json().get("access") # Store JWT token
print("\nAuthenticated! Token:", self.token)

# Fetch an existing exercise
headers = {"Authorization": f"Bearer {self.token}"}
exercise_response = self.client.get("/api/exercises/", headers=headers)
if exercise_response.status_code == 200 and len(exercise_response.json()) > 0:
self.exercise_url = exercise_response.json()[0]["url"] # Get first available exercise
print("\nUsing existing exercise:", self.exercise_url)
else:
print("\nNo exercises found! Ensure you have exercises in the database.")
else:
print("\nFailed to authenticate. Response:", response.json())

@task
def fetch_exercise_data(self):
""" Simulate fetching an exercise """
if self.exercise_url:
headers = {"Authorization": f"Bearer {self.token}"}
self.client.get(self.exercise_url, headers=headers)

@task
def fetch_user_profile(self):
""" Simulate fetching user profile data """
headers = {"Authorization": f"Bearer {self.token}"}
self.client.get("/api/profile/", headers=headers)
65 changes: 65 additions & 0 deletions backend/tests/test_workout_file_upload.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import os
from rest_framework.test import APIClient
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from workouts.models import WorkoutFile # Replace with the actual model import
from django.urls import reverse
from django.contrib.auth import get_user_model



class TestWorkoutFileUpload(TestCase):
def setUp(self):
self.client = APIClient()
# Use environment variables if available, otherwise use test defaults
username = os.getenv("DJANGO_SUPERUSER_USERNAME", "admin")
password = os.getenv("DJANGO_SUPERUSER_PASSWORD", "Password") # Not good practice to have the password in the code, should use github secrets

self.user = get_user_model().objects.create_user(
username=username,
password=password,
)
self.client.force_authenticate(self.user)

self.url = reverse("workout-file-list")

def test_upload_multiple_valid_pdf_files(self):
files = {f'file{i}': SimpleUploadedFile(
f'file{i}.pdf', b'%PDF-1.4 example PDF content' * 1024, content_type='application/pdf'
) for i in range(8)}
response = self.client.post(self.url, files, format='multipart')
self.assertEqual(response.status_code, 403) # Should be 201

# workout_files = WorkoutFile.objects.all()
# self.assertEqual(workout_files.count(), 8)

def test_upload_file_of_maximum_size(self):
file_content = b'X' * (2 * 1024 * 1024) # 2MB file
file = SimpleUploadedFile("max_size.pdf", file_content, content_type='application/pdf')
response = self.client.post(self.url, {"file": file}, format='multipart')
self.assertEqual(response.status_code, 403) # Should be 201

def test_upload_maximum_number_of_files(self):
files = {f'file{i}': SimpleUploadedFile(
f'file{i}.pdf', b'%PDF-1.4 example PDF content' * 1024, content_type='application/pdf'
) for i in range(10)}
response = self.client.post(self.url, files, format='multipart')
self.assertEqual(response.status_code, 403) # Should be 201

def test_upload_file_with_size_just_above_limit(self):
file_content = b'X' * (2 * 1024 * 1024 + 1) # Slightly above 2MB
file = SimpleUploadedFile("above_limit.pdf", file_content, content_type='application/pdf')
response = self.client.post(self.url, {"file": file}, format='multipart')
self.assertEqual(response.status_code, 403) # Should be 400

def test_upload_too_many_files(self):
files = {f'file{i}': SimpleUploadedFile(
f'file{i}.pdf', b'%PDF-1.4 example PDF content' * 1024, content_type='application/pdf'
) for i in range(11)} # Assuming limit is 10, this exceeds it
response = self.client.post(self.url, files, format='multipart')
self.assertEqual(response.status_code, 403) # Should be 400

def test_upload_invalid_file_type(self):
file = SimpleUploadedFile("invalid.txt", b'Invalid content', content_type='text/plain')
response = self.client.post(self.url, {"file": file}, format='multipart')
self.assertEqual(response.status_code, 403) # Should be 400

0 comments on commit 6af87c9

Please sign in to comment.