193 lines
7.9 KiB
Dart
193 lines
7.9 KiB
Dart
// ignore_for_file: avoid_print
|
|
import 'package:flutter_test/flutter_test.dart';
|
|
import 'package:hidalyx_drluiscastro/core/network/api_client.dart';
|
|
import 'package:hidalyx_drluiscastro/features/patient/data/models/patient_model.dart';
|
|
import 'package:hidalyx_drluiscastro/features/patient/data/services/patient_service.dart';
|
|
import 'package:hidalyx_drluiscastro/features/patient_search/data/services/patient_search_service.dart';
|
|
|
|
void main() {
|
|
test('Directus Live Integration: Authenticate, create patient LUIS MIGUEL HIDALGO SALCEDO, and verify', () async {
|
|
final apiClient = ApiClient();
|
|
|
|
// 1. Iniciar sesión en Directus
|
|
print('\n[DIRECTUS TEST] 1. Autenticando con credenciales...');
|
|
final loginRes = await apiClient.dio.post(
|
|
'/auth/login',
|
|
data: {
|
|
'email': '[email protected]',
|
|
'password': 'LUIS',
|
|
},
|
|
);
|
|
expect(loginRes.statusCode, 200);
|
|
final token = loginRes.data['data']['access_token'] as String;
|
|
expect(token.isNotEmpty, isTrue);
|
|
apiClient.setAuthToken(token);
|
|
print('✅ [DIRECTUS TEST] Token obtenido correctamente: ${token.substring(0, 15)}...');
|
|
|
|
// 2. Verificar estado actual de la colección pacientes
|
|
print('\n[DIRECTUS TEST] 2. Consultando últimos pacientes en Directus...');
|
|
final listRes = await apiClient.dio.get('/items/pacientes?sort=-id&limit=5');
|
|
expect(listRes.statusCode, 200);
|
|
final currentList = listRes.data['data'] as List<dynamic>;
|
|
print('Últimos 5 pacientes en base de datos:');
|
|
for (final p in currentList) {
|
|
print(' -> ID: ${p['id']} | ${p['nombre']} ${p['apellido']} | Cédula: ${p['cedula']} | Reg: ${p['fec_reg']}');
|
|
}
|
|
|
|
// 3. Crear el paciente LUIS MIGUEL HIDALGO SALCEDO
|
|
print('\n[DIRECTUS TEST] 3. Creando paciente LUIS MIGUEL HIDALGO SALCEDO en Directus...');
|
|
final patientService = PatientService(client: apiClient);
|
|
|
|
final patientToCreate = PatientModel(
|
|
nombre: 'LUIS MIGUEL',
|
|
apellido: 'HIDALGO SALCEDO',
|
|
sexo: 'Masculino',
|
|
seguro: 'Sí',
|
|
estCivil: 'Soltero',
|
|
edad: '28',
|
|
cedula: '001-1234567-8',
|
|
telefono: '809-555-0199',
|
|
direccion: 'Santo Domingo, Distrito Nacional',
|
|
ocupacion: 'Ingeniero de Software',
|
|
fecReg: '18/09/2026',
|
|
fecUltcon: '18/09/2026',
|
|
motCons: '18/09/2026: Consulta preventiva general y chequeo urológico.',
|
|
hisEnfAct: '18/09/2026: Paciente asintomático, buen estado general.',
|
|
datNi: 'Ninguna',
|
|
datAdo: 'Ninguna',
|
|
datAdu: 'Ninguna',
|
|
datAlerg: 'Ninguna',
|
|
datTran: 'ninguna',
|
|
datCir: 'ninguna',
|
|
datAc: 'ninguno',
|
|
datOtrosp: 'ninguno',
|
|
datMad: 'Viva y sana',
|
|
datEsp: 'Viva y sana',
|
|
datPadre: 'Vivo y sano',
|
|
datHijos: 'Vivos y sanos',
|
|
datHer: 'Vivos y sanos',
|
|
datOtrosnp: 'Ningunos',
|
|
metDiagnRad: '',
|
|
datLab: '',
|
|
diagnDesc: 'Evaluación urológica de rutina.',
|
|
diagnDef: 'Sin hallazgos patológicos.',
|
|
fecProxcita: '18/10/2026',
|
|
tratamiento: '',
|
|
);
|
|
|
|
PatientModel created;
|
|
try {
|
|
created = await patientService.createPatient(patientToCreate);
|
|
print('✅ [DIRECTUS TEST] Paciente creado exitosamente en Directus con ID: ${created.id}');
|
|
print(' - Nombre completo: ${created.fullName}');
|
|
print(' - Cédula: ${created.cedula}');
|
|
print(' - Teléfono: ${created.telefono}');
|
|
print(' - Dirección: ${created.direccion}');
|
|
print(' - Fecha Registro: ${created.fecReg}');
|
|
print(' - Próxima Cita: ${created.fecProxcita}');
|
|
} catch (e) {
|
|
print('❌ [DIRECTUS TEST] Fallo al crear paciente: $e');
|
|
rethrow;
|
|
}
|
|
|
|
expect(created.id, isNotNull);
|
|
expect(created.id! > 0, isTrue);
|
|
|
|
// 4. Verificar obtención directa por ID
|
|
print('\n[DIRECTUS TEST] 4. Verificando getPatientById(${created.id})...');
|
|
final fetched = await patientService.getPatientById(created.id!);
|
|
print('✅ [DIRECTUS TEST] Paciente recuperado por ID:');
|
|
print(' - ID: ${fetched.id} | Nombre: ${fetched.fullName} | Diagnóstico: ${fetched.diagnDef}');
|
|
expect(fetched.nombre, 'LUIS MIGUEL');
|
|
expect(fetched.apellido, 'HIDALGO SALCEDO');
|
|
|
|
// 5. Verificar búsqueda mediante PatientSearchService
|
|
print('\n[DIRECTUS TEST] 5. Verificando búsqueda con PatientSearchService...');
|
|
final searchService = PatientSearchService(client: apiClient);
|
|
final searchResults = await searchService.searchPatients('LUIS MIGUEL HIDALGO');
|
|
print('Resultados de búsqueda para "LUIS MIGUEL HIDALGO": ${searchResults.length}');
|
|
for (final item in searchResults) {
|
|
print(' -> ID: ${item.id} | ${item.fullName} | Cédula: ${item.cedula}');
|
|
}
|
|
expect(searchResults.any((p) => p.id == created.id), isTrue);
|
|
|
|
print('\n🎉🎉🎉 [DIRECTUS TEST] TODO VERIFICADO Y CONFIRMADO EN DIRECTUS CON ÉXITO 🎉🎉🎉\n');
|
|
});
|
|
|
|
test('Directus Auth Refresh: login, refresh token, and verify new access token', () async {
|
|
final apiClient = ApiClient();
|
|
final loginRes = await apiClient.dio.post(
|
|
'/auth/login',
|
|
data: {
|
|
'email': '[email protected]',
|
|
'password': 'LUIS',
|
|
},
|
|
);
|
|
final initialAccessToken = loginRes.data['data']['access_token'] as String;
|
|
final refreshToken = loginRes.data['data']['refresh_token'] as String;
|
|
print('Initial access token: ${initialAccessToken.substring(0, 15)}...');
|
|
print('Refresh token: ${refreshToken.substring(0, 15)}...');
|
|
|
|
final refreshRes = await apiClient.dio.post(
|
|
'/auth/refresh',
|
|
data: {
|
|
'refresh_token': refreshToken,
|
|
'mode': 'json',
|
|
},
|
|
);
|
|
expect(refreshRes.statusCode, 200);
|
|
final newAccessToken = refreshRes.data['data']['access_token'] as String;
|
|
final newRefreshToken = refreshRes.data['data']['refresh_token'] as String?;
|
|
print('New access token: ${newAccessToken.substring(0, 15)}...');
|
|
print('New refresh token: ${newRefreshToken?.substring(0, 15)}...');
|
|
expect(newAccessToken.isNotEmpty, isTrue);
|
|
|
|
// Verify using new access token to query /users/me
|
|
apiClient.setAuthToken(newAccessToken);
|
|
final userRes = await apiClient.dio.get('/users/me');
|
|
expect(userRes.statusCode, 200);
|
|
print('✅ User verification with refreshed token: ${userRes.data['data']['email']}');
|
|
});
|
|
|
|
test('Directus Config: Authenticate, read configuration, and update', () async {
|
|
final apiClient = ApiClient();
|
|
print('\n[DIRECTUS CONFIG TEST] 1. Autenticando...');
|
|
final loginRes = await apiClient.dio.post(
|
|
'/auth/login',
|
|
data: {
|
|
'email': '[email protected]',
|
|
'password': 'LUIS',
|
|
},
|
|
);
|
|
expect(loginRes.statusCode, 200);
|
|
final token = loginRes.data['data']['access_token'] as String;
|
|
apiClient.setAuthToken(token);
|
|
|
|
print('\n[DIRECTUS CONFIG TEST] 2. Consultando configuracion actual...');
|
|
final configRes = await apiClient.dio.get('/items/configuracion');
|
|
expect(configRes.statusCode, 200);
|
|
final configData = configRes.data['data'] as Map<String, dynamic>;
|
|
print('Configuración actual:');
|
|
print(' -> Doctor: ${configData['nombre_doctor']}');
|
|
print(' -> Especialidad: ${configData['especialidad']}');
|
|
print(' -> Subespecialidad: ${configData['descrip_especialidad']}');
|
|
print(' -> Contacto: ${configData['descrip_general']}');
|
|
|
|
expect(configData['nombre_doctor'], isNotNull);
|
|
expect(configData['especialidad'], isNotNull);
|
|
|
|
print('\n[DIRECTUS CONFIG TEST] 3. Actualizando configuracion vía PATCH...');
|
|
final patchRes = await apiClient.dio.patch(
|
|
'/items/configuracion',
|
|
data: {
|
|
'nombre_doctor': configData['nombre_doctor'],
|
|
'especialidad': configData['especialidad'],
|
|
'descrip_especialidad': configData['descrip_especialidad'],
|
|
'descrip_general': configData['descrip_general'],
|
|
},
|
|
);
|
|
expect(patchRes.statusCode, 200);
|
|
print('✅ [DIRECTUS CONFIG TEST] Configuración confirmada y actualizada correctamente.');
|
|
});
|
|
}
|