import pytest from unittest.mock import patch def test_login_json_success(client): """Test successful JSON login.""" mock_user = { 'id': 1, 'username': 'admin', 'role': 'admin' } with patch('src.routes.auth.authenticate_user', return_value=(True, mock_user)): response = client.post( '/login', json={'username': 'admin', 'password': 'password'}, headers={'Content-Type': 'application/json'} ) assert response.status_code == 200 data = response.get_json() assert data['status'] == 'success' assert data['user']['username'] == 'admin' # Verify session was set with client.session_transaction() as sess: assert sess['logged_in'] is True assert sess['username'] == 'admin' assert sess['role'] == 'admin' def test_login_json_failure(client): """Test failed JSON login.""" with patch('src.routes.auth.authenticate_user', return_value=(False, {'error': 'Invalid credentials'})): response = client.post( '/login', json={'username': 'admin', 'password': 'wrongpassword'}, headers={'Content-Type': 'application/json'} ) assert response.status_code == 401 assert 'Invalid credentials' in response.get_json()['error'] def test_logout(client): """Test logging out clears the session.""" with client.session_transaction() as sess: sess['logged_in'] = True sess['username'] = 'admin' response = client.get('/logout') assert response.status_code == 302 # Redirect to main.index with client.session_transaction() as sess: assert 'logged_in' not in sess assert 'username' not in sess def test_register_user_role(client): """Test registration with role 'user'.""" data = { 'username': 'newuser', 'password': 'password', 'email': 'newuser@example.com', 'role': 'user' } with patch('src.routes.auth.create_user', return_value=(True, {'id': 2, 'username': 'newuser', 'role': 'user'})), \ patch('src.routes.auth.send_notification_email') as mock_email: response = client.post('/register', data=data) assert response.status_code == 302 # Redirects to auth.login mock_email.assert_called_once() # Verify body contains role args = mock_email.call_args[0] assert 'user' in args[1] def test_register_admin_role(client): """Test registration with role 'admin'.""" data = { 'username': 'newadmin', 'password': 'password', 'email': 'newadmin@example.com', 'role': 'admin' } with patch('src.routes.auth.create_user', return_value=(True, {'id': 3, 'username': 'newadmin', 'role': 'admin'})), \ patch('src.routes.auth.send_notification_email') as mock_email: response = client.post('/register', data=data) assert response.status_code == 302 # Redirects to auth.login mock_email.assert_called_once() args = mock_email.call_args[0] assert 'admin' in args[1]