Spaces:
Sleeping
Sleeping
File size: 2,843 Bytes
9e7b45f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | import unittest
from unittest.mock import patch
import os
import sys
import bcrypt
from flask import Flask
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from app.routes.api_routes import bp as api_bp
class FakeCollection:
def __init__(self, docs=None):
self.docs = docs or []
def find_one(self, query):
for doc in self.docs:
matched = True
for key, value in query.items():
if doc.get(key) != value:
matched = False
break
if matched:
return doc
return None
class ApiAuthContractTests(unittest.TestCase):
def setUp(self):
self.app = Flask(__name__)
self.app.config['SECRET_KEY'] = 'test-secret'
self.app.config['TESTING'] = True
self.app.register_blueprint(api_bp)
self.client = self.app.test_client()
@patch('app.routes.api_routes.get_collections')
def test_faculty_login_contract(self, mock_get_collections):
password = b'secret123'
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
mock_get_collections.return_value = {
'faculty': FakeCollection([
{
'email': 'teacher@example.com',
'name': 'Teacher One',
'role': 'teacher',
'password': hashed,
}
])
}
response = self.client.post(
'/api/auth/login/faculty',
json={'email': 'teacher@example.com', 'password': 'secret123'},
)
self.assertEqual(response.status_code, 200)
payload = response.get_json()
self.assertTrue(payload['success'])
self.assertIn('user', payload)
self.assertIn('role', payload)
self.assertIn('redirectPath', payload)
self.assertIn('errors', payload)
def test_whoami_anonymous(self):
response = self.client.get('/api/auth/whoami')
self.assertEqual(response.status_code, 200)
payload = response.get_json()
self.assertTrue(payload['success'])
self.assertFalse(payload['authenticated'])
self.assertIsNone(payload['role'])
@patch('app.routes.api_routes.get_collections')
def test_student_login_invalid_credentials(self, mock_get_collections):
mock_get_collections.return_value = {
'students': FakeCollection([])
}
response = self.client.post(
'/api/auth/login/student',
json={'roll_no': '22CS101', 'password': 'bad'},
)
self.assertEqual(response.status_code, 401)
payload = response.get_json()
self.assertFalse(payload['success'])
self.assertIn('errors', payload)
if __name__ == '__main__':
unittest.main()
|