Skip to content

Commit

Permalink
Merge pull request #301 from SELab-2/frontend_testen
Browse files Browse the repository at this point in the history
Frontend testen
  • Loading branch information
LGDTimtou authored May 23, 2024
2 parents 6bb8f8a + cb7e8ae commit 57ced79
Show file tree
Hide file tree
Showing 101 changed files with 4,884 additions and 2,938 deletions.
71 changes: 34 additions & 37 deletions .github/workflows/django.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@ name: Django CI

on:
push:
branches: [ "develop", "tests", "main" ]
branches: ["develop", "tests", "main"]
pull_request:
branches: [ "develop", "tests", "main" ]

branches: ["develop", "tests", "main"]

jobs:
build:

runs-on: self-hosted

services:
Expand All @@ -25,37 +23,36 @@ jobs:

options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5


steps:
- uses: actions/checkout@v3
- name: Set up Python 3.10
uses: actions/setup-python@v3
with:
python-version: '3.10'
- name: Install Dependencies
run: |
python3 -m pip install --upgrade pip
pip install -r requirements.txt
- name: Linting API
run: |
cd api
flake8 .
cd ..
- name: Run Tests
env:
CLIENT_ID: ${{ secrets.CLIENT_ID }}
CLIENT_SECRET: ${{ secrets.CLIENT_SECRET }}
TENANT_ID: ${{ secrets.TENANT_ID }}
AD_URL: ${{ secrets.AD_URL }}
SECRET_KEY: ${{ secrets.SECRET_KEY }}
DB_NAME: ${{ secrets.DB_NAME }}
DB_USER: ${{ secrets.DB_USER }}
DB_PASSWORD: ${{ secrets.DB_PASSWORD }}
DB_HOST: ${{ secrets.DB_HOST }}
DB_PORT: ${{ secrets.DB_PORT }}
DB_ENGINE: ${{secrets.DB_ENGINE}}
run: |
python manage.py makemigrations api
python manage.py migrate api
python manage.py test
- uses: actions/checkout@v3
- name: Set up Python 3.10
uses: actions/setup-python@v3
with:
python-version: "3.10"
- name: Install Dependencies
run: |
python3 -m pip install --upgrade pip
pip install -r requirements.txt
- name: Linting API
run: |
cd api
flake8 .
cd ..
- name: Run Tests
env:
CLIENT_ID: ${{ secrets.CLIENT_ID }}
CLIENT_SECRET: ${{ secrets.CLIENT_SECRET }}
TENANT_ID: ${{ secrets.TENANT_ID }}
AD_URL: ${{ secrets.AD_URL }}
SECRET_KEY: ${{ secrets.SECRET_KEY }}
DB_NAME: ${{ secrets.DB_NAME }}
DB_USER: ${{ secrets.DB_USER }}
DB_PASSWORD: ${{ secrets.DB_PASSWORD }}
DB_HOST: ${{ secrets.DB_HOST }}
DB_PORT: ${{ secrets.DB_PORT }}
DB_ENGINE: ${{secrets.DB_ENGINE}}

run: |
python manage.py makemigrations api
python manage.py migrate api
python manage.py test
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,15 @@ Run het commando `flake8 .`. De output vertelt je waar de codestijl fout is. Om


### Testing:
## Backend testing:
Run het commando `./manage.py test` in de ***UGENT-4*** directory.
Om de coverage te raadplegen kan het commando `coverage run manage.py test -v 2 && coverage report && coverage html` gebruikt worden. Dit runt alle testen en toont per bestand de coverage. Ook wordt er voor elk bestand een html gemaakt waar je per lijn kan zien of die door de testen gecovered wordt.
## Frontend testing:
Door het commando `npm run cypress-component` uit te voeren, worden de component testen gerund.
Voor de end-to-end testen verloopt het een beetje anders:
- Eerst en vooral zorg je ervoor dat je een lokale backend en frontend hebt lopen. In axios.config verander je de baseURL naar `baseURL: 'http://localhost:8000/api/'`, dit zorgt ervoor dat de lokale backend wordt aangesproken. De e2e testen vereisen een lege databank.
- Met het commando `npm run cypress-component` open je een interactieve cypress browser. Hierin selecteer je e2e (je kan hier ook de component testen interactief runnen).
- Vervolgens open je een nieuwe terminal en run je het commando `sudo bash switch_test.sh true`. Hiermee zet je de test environment op voor een lesgever. Nu voer je de testen 'course', 'project' en 'groups' (in deze volgorde) uit.
- Hierna switchen we naar de test environment voor een student door 2 maal `sudo bash switch_test.sh` te runnen.
- In cypress voer je nu de 'group' en 'submission' testen uit (opnieuw in deze volgorde). Ten slotte zet je weer de test environment op voor een lesgever door 2 maal het commando `sudo bash switch_test.sh true` uit te voeren. Nu kan je in cypress de testen 'score' en 'archive' (in deze volgorde) uitvoeren.
- Alle e2e testen uitgevoerd en kan je de lokale backend en frontend stopzetten, de baseURL terug veranderen naar `baseURL: 'https://sel2-4.ugent.be/api/'` en de test omgeving verlaten met `sudo bash switch_test.sh`.
File renamed without changes.
73 changes: 73 additions & 0 deletions api/middleware/middleware_lesgever_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
from django.contrib.auth.models import User
from api.models.gebruiker import Gebruiker
from api.serializers.gebruiker import GebruikerSerializer
from api.serializers.template import TemplateSerializer
from django.core.files import File
import os


class AuthenticationUserMiddleware:
"""
Middleware voor authenticatie van gebruikers en het aanmaken van gebruikersindeling.
Args:
get_response (callable): De volgende middleware in de keten.
Returns:
HttpResponse: Een HTTP-response-object.
Raises:
Redirect: Redirect naar de inlog-URL als er geen autorisatiegegevens zijn.
"""

def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):

mail = "[email protected]"
try:
user = User.objects.get(username=mail)
except User.DoesNotExist:
user = User.objects.create_user(
username=mail,
email=mail,
first_name="Lesgever",
last_name="Testing",
)

request.user = user

try:
Gebruiker.objects.get(pk=request.user.id)
except Gebruiker.DoesNotExist:
directory_path = "api/base_templates"
for filename in os.listdir(directory_path):
file_path = os.path.join(directory_path, filename)
with open(file_path, "rb") as f:
django_file = File(f)
template_data = {"user": request.user.id, "bestand": django_file}
serializer = TemplateSerializer(data=template_data)
if serializer.is_valid():
serializer.save()

gebruiker_post_data = {
"user": request.user.id,
"subjects": [],
"is_lesgever": True,
}
serializer = GebruikerSerializer(data=gebruiker_post_data)
if serializer.is_valid():
serializer.save()

return self.get_response(request)


class DisableCSRFMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
setattr(request, "_dont_enforce_csrf_checks", True)
response = self.get_response(request)
return response
94 changes: 94 additions & 0 deletions api/middleware/middleware_original.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
from django.conf import settings
from django.shortcuts import redirect
from django.contrib.auth.models import User
from api.models.gebruiker import Gebruiker
from api.serializers.gebruiker import GebruikerSerializer
from api.serializers.template import TemplateSerializer
from django.core.files import File
import requests
import os

URL = "https://graph.microsoft.com/v1.0/me"


class AuthenticationUserMiddleware:
"""
Middleware voor authenticatie van gebruikers en het aanmaken van gebruikersindeling.
Args:
get_response (callable): De volgende middleware in de keten.
Returns:
HttpResponse: Een HTTP-response-object.
Raises:
Redirect: Redirect naar de inlog-URL als er geen autorisatiegegevens zijn.
"""

def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
if request.path in ["/oauth2/login", "/oauth2/callback"]:
return self.get_response(request)

if request.user.is_anonymous:
authorization = request.headers.get("Authorization")
if authorization:
headers = {
"Authorization": authorization,
"Content-Type": "application/json",
}

response = requests.get(url=URL, headers=headers)
json_data = response.json()
mail = json_data.get("mail")
first_name = json_data.get("givenName")
last_name = json_data.get("surname")
try:
user = User.objects.get(username=mail)
except User.DoesNotExist:
user = User.objects.create_user(
username=mail,
email=mail,
first_name=first_name,
last_name=last_name,
)

request.user = user
else:
return redirect(settings.LOGIN_URL)

try:
Gebruiker.objects.get(pk=request.user.id)
except Gebruiker.DoesNotExist:
directory_path = "api/base_templates"
for filename in os.listdir(directory_path):
file_path = os.path.join(directory_path, filename)
with open(file_path, "rb") as f:
django_file = File(f)
template_data = {"user": request.user.id, "bestand": django_file}
serializer = TemplateSerializer(data=template_data)
if serializer.is_valid():
serializer.save()

gebruiker_post_data = {
"user": request.user.id,
"subjects": [],
"is_lesgever": False,
}
serializer = GebruikerSerializer(data=gebruiker_post_data)
if serializer.is_valid():
serializer.save()

return self.get_response(request)


class DisableCSRFMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
setattr(request, "_dont_enforce_csrf_checks", True)
response = self.get_response(request)
return response
73 changes: 73 additions & 0 deletions api/middleware/middleware_student_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
from django.contrib.auth.models import User
from api.models.gebruiker import Gebruiker
from api.serializers.gebruiker import GebruikerSerializer
from api.serializers.template import TemplateSerializer
from django.core.files import File
import os


class AuthenticationUserMiddleware:
"""
Middleware voor authenticatie van gebruikers en het aanmaken van gebruikersindeling.
Args:
get_response (callable): De volgende middleware in de keten.
Returns:
HttpResponse: Een HTTP-response-object.
Raises:
Redirect: Redirect naar de inlog-URL als er geen autorisatiegegevens zijn.
"""

def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):

mail = "[email protected]"
try:
user = User.objects.get(username=mail)
except User.DoesNotExist:
user = User.objects.create_user(
username=mail,
email=mail,
first_name="Student",
last_name="Testing",
)

request.user = user

try:
Gebruiker.objects.get(pk=request.user.id)
except Gebruiker.DoesNotExist:
directory_path = "api/base_templates"
for filename in os.listdir(directory_path):
file_path = os.path.join(directory_path, filename)
with open(file_path, "rb") as f:
django_file = File(f)
template_data = {"user": request.user.id, "bestand": django_file}
serializer = TemplateSerializer(data=template_data)
if serializer.is_valid():
serializer.save()

gebruiker_post_data = {
"user": request.user.id,
"subjects": [],
"is_lesgever": False,
}
serializer = GebruikerSerializer(data=gebruiker_post_data)
if serializer.is_valid():
serializer.save()

return self.get_response(request)


class DisableCSRFMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
setattr(request, "_dont_enforce_csrf_checks", True)
response = self.get_response(request)
return response
5 changes: 2 additions & 3 deletions api/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,11 @@
"django.contrib.sessions.middleware.SessionMiddleware",
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
# "django.middleware.csrf.CsrfViewMiddleware",
"api.middleware.DisableCSRFMiddleware",
"api.middleware.middleware.DisableCSRFMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"api.middleware.AuthenticationUserMiddleware",
"api.middleware.middleware.AuthenticationUserMiddleware",
]

ROOT_URLCONF = "api.urls"
Expand Down
2 changes: 1 addition & 1 deletion api/tests/test_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from django.contrib.auth.models import User
from unittest.mock import patch
from api.models.gebruiker import Gebruiker
from api.middleware import AuthenticationUserMiddleware
from api.middleware.middleware import AuthenticationUserMiddleware
from django.contrib.auth.models import AnonymousUser
import jwt

Expand Down
1 change: 1 addition & 0 deletions frontend/frontend/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,4 @@ package-lock.json
*.sw?
./src/authConfig/authSecrets.ts
./package-lock.json
package-lock.json
Loading

0 comments on commit 57ced79

Please sign in to comment.