"""Authentication flow tests."""
import os
import sys
import unittest
import json
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
os.environ.setdefault('DATABASE_URL', 'sqlite:///test_auth.db')
os.environ.setdefault('SECRET_KEY', 'test-secret-key-for-testing')
from app import create_app
from app.models import db
class AuthTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = create_app()
cls.app.config['TESTING'] = True
cls.app.config['RATELIMIT_ENABLED'] = False
cls.client = cls.app.test_client()
with cls.app.app_context():
db.create_all()
def test_signup_and_login(self):
"""User can sign up and log in."""
email = 'test_auth_{}@example.com'.format(id(self))
# Sign up
resp = self.client.post('/api/auth/signup',
data=json.dumps({
'email': email,
'password': 'TestPassword123!',
'full_name': 'Test User'
}),
content_type='application/json')
self.assertEqual(resp.status_code, 200)
# Log in
resp = self.client.post('/api/auth/login',
data=json.dumps({'email': email, 'password': 'TestPassword123!'}),
content_type='application/json')
self.assertEqual(resp.status_code, 200)
data = resp.get_json()
self.assertTrue(data.get('success', False))
def test_login_wrong_password(self):
"""Login fails with wrong password."""
resp = self.client.post('/api/auth/login',
data=json.dumps({'email': 'nonexistent@test.com', 'password': 'wrong'}),
content_type='application/json')
self.assertEqual(resp.status_code, 401)
def test_logout(self):
"""Logout works without requiring auth."""
resp = self.client.post('/api/auth/logout')
self.assertEqual(resp.status_code, 200)
def test_unauthenticated_user_endpoint(self):
"""GET /api/auth/user returns null for unauthenticated."""
resp = self.client.get('/api/auth/user')
self.assertEqual(resp.status_code, 200)
# Should NOT be 401
if __name__ == '__main__':
unittest.main()