Skip to content

Commit

Permalink
wrote test cases
Browse files Browse the repository at this point in the history
  • Loading branch information
Chacoon3 committed Nov 8, 2023
1 parent 5320716 commit d2fb382
Show file tree
Hide file tree
Showing 9 changed files with 99 additions and 70 deletions.
2 changes: 1 addition & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"program": "${workspaceFolder}\\manage.py",
"args": ["runserver"],
"env": {
"BMGT435_INDEX": "http://localhost:5173", // for local testing
"APP_FRONTEND_HOST": "http://localhost:5173", // for local testing
},
"django": true,
"justMyCode": true
Expand Down
4 changes: 2 additions & 2 deletions bmgt435_elp/apis.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ def me(request: HttpRequest,) -> HttpResponse:
try:
resp = HttpResponse()
id = request.COOKIES.get('id', None)
user = BMGTUser.objects.get(id=id, activated=1, )
user = BMGTUser.objects.get(id=id, activated=True, )
resp.write(serialize_model_instance(user))
resp.status_code = Status.OK
except BMGTUser.DoesNotExist:
Expand Down Expand Up @@ -453,7 +453,7 @@ def system_status(request: HttpRequest) -> HttpResponse:
resp = HttpResponse()

count_users = BMGTUser.objects.count()
count_active_users = BMGTUser.objects.filter(activated=1).count()
count_active_users = BMGTUser.objects.filter(activated=True).count()
count_groups = BMGTGroup.objects.count()
count_cases = BMGTCase.objects.count()
count_case_records = BMGTCaseRecord.objects.count()
Expand Down
5 changes: 2 additions & 3 deletions bmgt435_elp/bmgtModels.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,8 @@ class BMGTUserRole(models.TextChoices):
did = models.CharField(max_length=60, auto_created=False, null=False, unique=True, db_index=True)
first_name = models.CharField(max_length=60, null=False)
last_name = models.CharField(max_length=60, null=False)
# stores the password hash
password = models.CharField(max_length=100, null=False, default="")
activated = models.IntegerField(choices=BinaryIntegerFlag.choices, default=BinaryIntegerFlag.FALSE, null=False,)
password = models.CharField(max_length=100, null=False, default="") # stores the password hash
activated = models.BooleanField(default=False, null=False)
role = models.CharField(choices=BMGTUserRole.choices, default=BMGTUserRole.USER, null=False, max_length=5)
group = models.ForeignKey(BMGTGroup, on_delete=models.SET_NULL, null=True)
semester = models.ForeignKey(BMGTSemester, on_delete=models.SET_NULL, null=True) # allow null for admin
Expand Down
6 changes: 3 additions & 3 deletions bmgt435_elp/middlewares.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

def CORSMiddleware(get_response):

origin = os.environ.get("APP_FRONTEND_HOST")
origin = os.environ.get("APP_FRONTEND_HOST",)

def config_cors_response(resp: HttpResponse):
resp["Access-Control-Allow-Origin"] = origin
Expand Down Expand Up @@ -52,12 +52,12 @@ def middleware(request: HttpRequest):
return get_response(request)

user_id = request.COOKIES.get('id', None)
if not user_id:
if user_id is None:
resp = HttpResponse(status=Status.NOT_FOUND)
resp.write("Failed to verify authentication!")
return resp
else:
user_query = BMGTUser.objects.filter(id=user_id, activated=1)
user_query = BMGTUser.objects.filter(id=user_id, activated=True)
if user_query.exists():
user = user_query.get()
request.bmgt_user = user # store the user info
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Generated by Django 4.2.1 on 2023-11-08 19:38

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('bmgt435_elp', '0005_bmgtsession'),
]

operations = [
migrations.AlterField(
model_name='bmgtuser',
name='activated',
field=models.BooleanField(default=False),
),
migrations.AlterField(
model_name='bmgtuser',
name='did',
field=models.CharField(db_index=True, max_length=60, unique=True),
),
migrations.DeleteModel(
name='BMGTSession',
),
]
124 changes: 64 additions & 60 deletions bmgt435_elp/test.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,59 @@
from django.test import TestCase, Client, RequestFactory
from .bmgtModels import *
from .apis import *
from typing import Callable
import json


def _clientSignUp(client:Client, did:str, password:str):
return client.post(
'bmgt435-service/api/auth/sign-up',
json.dumps({'did': did, 'password': password}),
def _signUp(did:str, password:str):
req = RequestFactory().post(
'/bmgt435-service/api/auth/sign-up',
json.dumps({'did':did, 'password':password}),
'application/json'
)
resp = AuthApi.sign_up(req)
return resp


def _clientSignIn(client:Client, did:str, password:str):
resp = client.post(
'bmgt435-service/api/auth/sign-in',
json.dumps({'did': did, 'password': password}),
def _signIn(did:str, password:str):
req = RequestFactory().post(
'/bmgt435-service/api/auth/sign-in',
json.dumps({'did':did, 'password':password}),
'application/json'
)
resp = AuthApi.sign_in(req)
return resp


def sendPost(url:str, method:Callable, data:dict, cookies:dict):
req = RequestFactory().post(
url,
json.dumps(data),
'application/json'
)
for key in cookies:
req.COOKIES[key] = cookies[key]
resp = method(req)
return resp


def sendGet(url:str, method:Callable, cookies:dict):
req = RequestFactory().get(
url,
)
for key in cookies:
req.COOKIES[key] = cookies[key]
resp = method(req)
return resp


class AppAuthTest(TestCase):
class TestSignUp(TestCase):

def setUp(self):
BMGTUser(first_name='first', last_name='last', did='did', role='admin').save()
BMGTUser(first_name='first321', last_name='last232', did='did232', role='user').save()
self.did = 'did'
self.password = 'pa3232.ssword'
BMGTUser.objects.create(first_name='first', last_name='last', did=self.did, role='admin')
BMGTUser.objects.create(first_name='first321', last_name='last232', did='did232', role='user')


def testQueryBmgtUser(self):
Expand All @@ -36,70 +64,44 @@ def testQueryBmgtUser(self):


def testSignUpPositive(self):
client = Client()
resp = client.post(
'/bmgt435-service/api/auth/sign-up',
json.dumps({'did': 'did', 'password': 'pa3232.ssword'}),
'application/json'
)
resp = _signUp(self.did, self.password)
user = BMGTUser.objects.get(did=self.did)
self.assertEqual(user.activated, True, 'user should be activated after sign up')
self.assertEqual(resp.status_code, 200)


def testSignUpNegative(self):
resp = Client().post(
'/bmgt435-service/api/auth/sign-up',
json.dumps({'did':'', 'password':""}),
'application/json'
)
resp = _signUp('', '')
self.assertNotEqual(resp.status_code, 200)
assert not BMGTUser.objects.filter(did='').exists()


def testSignUpNonExistentUser(self):
resp = Client().post(
'/bmgt435-service/api/auth/sign-up',
json.dumps({'did':'did323', 'password':"pass32132321.$"}),
'application/json'
)
resp = _signUp('did323', 'pass32132321.$')
self.assertNotEqual(resp.status_code, 200)


def testRepeatedSignUp(self):
client = Client()
resp = client.post(
'/bmgt435-service/api/auth/sign-up',
json.dumps({'did': 'did', 'password': 'pa3232.ssword'}),
'application/json'
)

resp= client.post(
'/bmgt435-service/api/auth/sign-up',
json.dumps({'did': 'did', 'password': 'pa3232.ssword'}),
'application/json'
)
self.assertNotEqual(resp.status_code, 200)
resp = _signUp(self.did, self.password)
self.assertEqual(resp.status_code, 200)
resp2= _signUp(self.did, self.password)
self.assertNotEqual(resp2.status_code, 200)


def testSignInPositive(self):
c = Client()
pwd = 'pa3232.ssword'
_clientSignUp(c, 'did', pwd)
resp = _clientSignIn(c, 'did', pwd)
did = 'did232'
pwd = 'pa3232..ssword'
_signUp(did, pwd)
self.assertEqual(BMGTUser.objects.get(did=did).activated, True, 'user should be activated after sign up')
resp = _signIn(did, pwd)
self.assertEqual(resp.status_code, 200)


def testSignInNegative(self):
c = Client()
c.post(
'bmgt435-service/api/auth/sign-up',
json.dumps({'did':'did', 'password':'pa3232.ssword'}),
'application/json'
)

resp = c.post(
'bmg435-service/api/auth/sign-in',
json.dumps({'did':'did', 'password':'pa3232.ssw2ord'}),
'application/json'
)
did = 'did'
pwd = 'pa3232.ssword'
_signUp(did, pwd)
resp = _signIn(did, 'pa3232.ssword2')
self.assertNotEqual(resp.status_code, 200)


Expand All @@ -112,13 +114,15 @@ def setUp(self):


def testUserMeAfterSignIn(self):
c = Client()
_clientSignUp(c, 'did', 'Grave11.')
_clientSignIn(c, 'did', 'Grave11.')
_signUp( 'did', 'Grave11.')
_signIn('did', 'Grave11.')

resp = c.get(
req = RequestFactory().get(
'bmgt435-service/api/users/me',
)
req.COOKIES['id'] = 1

resp = UserApi.me(req)
self.assertEqual(resp.status_code, 200)


Expand Down
Binary file modified db.sqlite3
Binary file not shown.
Binary file modified sim_server_django/__pycache__/settings.cpython-310.pyc
Binary file not shown.
2 changes: 1 addition & 1 deletion sim_server_django/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
print('Base dir is \t', BASE_DIR)


ALLOWED_HOSTS = ['app', 'localhost', AppConfig.APP_FRONTEND_HOST]
ALLOWED_HOSTS = ['app', 'localhost', '127.0.0.1', AppConfig.APP_FRONTEND_HOST]

CSRF_TRUSTED_ORIGINS = [
'http://localhost', f'http://{AppConfig.APP_FRONTEND_HOST}',
Expand Down

0 comments on commit d2fb382

Please sign in to comment.