| 1 | import test from "ava";
|
| 2 | import request from "supertest";
|
| 3 | import { createApp } from "../../src/create-app.js";
|
| 4 | import { setupTestDb, cleanupTestDb } from "../test-helper.js";
|
| 5 |
|
| 6 | let app;
|
| 7 | let db;
|
| 8 | let userId;
|
| 9 | let moodId;
|
| 10 |
|
| 11 | test.before(() => {
|
| 12 | db = setupTestDb();
|
| 13 | app = createApp(db);
|
| 14 | });
|
| 15 |
|
| 16 | test.beforeEach(async () => {
|
| 17 | cleanupTestDb();
|
| 18 |
|
| 19 | // Create a test user with unique email
|
| 20 | const uniqueEmail = `mood_${Date.now()}_${Math.random()}@example.com`;
|
| 21 | const userRes = await request(app)
|
| 22 | .post("/users")
|
| 23 | .send({
|
| 24 | email: uniqueEmail,
|
| 25 | password: "senha123",
|
| 26 | first_name: "Mood",
|
| 27 | last_name: "Tester"
|
| 28 | });
|
| 29 |
|
| 30 | if (userRes.status !== 201) {
|
| 31 | throw new Error(`Failed to create test user: ${JSON.stringify(userRes.body)}`);
|
| 32 | }
|
| 33 |
|
| 34 | userId = userRes.body.id;
|
| 35 |
|
| 36 | // Create a mood to update
|
| 37 | const moodRes = await request(app)
|
| 38 | .post("/mood")
|
| 39 | .send({
|
| 40 | user_id: userId,
|
| 41 | rating: 5,
|
| 42 | stress_level: 4,
|
| 43 | anxiety_level: 3,
|
| 44 | energy_level: 7,
|
| 45 | title: "Original mood",
|
| 46 | description: "Original description",
|
| 47 | recorded_at: new Date().toISOString(),
|
| 48 | mood_components: [
|
| 49 | { emotion: "joy", intensity: 6 },
|
| 50 | { emotion: "trust", intensity: 7 }
|
| 51 | ]
|
| 52 | });
|
| 53 |
|
| 54 | moodId = moodRes.body.id;
|
| 55 | });
|
| 56 |
|
| 57 | test.serial("Atualizar rating do mood", async (t) => {
|
| 58 | const res = await request(app)
|
| 59 | .put(`/mood/${moodId}`)
|
| 60 | .send({
|
| 61 | rating: 8
|
| 62 | });
|
| 63 |
|
| 64 | t.is(res.status, 200);
|
| 65 | t.true(res.body.success);
|
| 66 |
|
| 67 | // Verify update
|
| 68 | const mood = db.prepare("SELECT rating FROM mood WHERE id = ?").get(moodId);
|
| 69 | t.is(mood.rating, 8);
|
| 70 | });
|
| 71 |
|
| 72 | test.serial("Atualizar múltiplos níveis do mood", async (t) => {
|
| 73 | const res = await request(app)
|
| 74 | .put(`/mood/${moodId}`)
|
| 75 | .send({
|
| 76 | stress_level: 2,
|
| 77 | anxiety_level: 1,
|
| 78 | energy_level: 9
|
| 79 | });
|
| 80 |
|
| 81 | t.is(res.status, 200);
|
| 82 | t.true(res.body.success);
|
| 83 |
|
| 84 | // Verify updates
|
| 85 | const mood = db.prepare("SELECT stress_level, anxiety_level, energy_level FROM mood WHERE id = ?").get(moodId);
|
| 86 | t.is(mood.stress_level, 2);
|
| 87 | t.is(mood.anxiety_level, 1);
|
| 88 | t.is(mood.energy_level, 9);
|
| 89 | });
|
| 90 |
|
| 91 | test.serial("Atualizar título e descrição do mood", async (t) => {
|
| 92 | const res = await request(app)
|
| 93 | .put(`/mood/${moodId}`)
|
| 94 | .send({
|
| 95 | title: "Novo título",
|
| 96 | description: "Nova descrição detalhada"
|
| 97 | });
|
| 98 |
|
| 99 | t.is(res.status, 200);
|
| 100 | t.true(res.body.success);
|
| 101 |
|
| 102 | // Verify updates
|
| 103 | const mood = db.prepare("SELECT title, description FROM mood WHERE id = ?").get(moodId);
|
| 104 | t.is(mood.title, "Novo título");
|
| 105 | t.is(mood.description, "Nova descrição detalhada");
|
| 106 | });
|
| 107 |
|
| 108 | test.serial("Atualizar data do mood", async (t) => {
|
| 109 | const newDate = new Date('2024-01-15T10:00:00Z');
|
| 110 |
|
| 111 | const res = await request(app)
|
| 112 | .put(`/mood/${moodId}`)
|
| 113 | .send({
|
| 114 | recorded_at: newDate.toISOString()
|
| 115 | });
|
| 116 |
|
| 117 | t.is(res.status, 200);
|
| 118 | t.true(res.body.success);
|
| 119 |
|
| 120 | // Verify update
|
| 121 | const mood = db.prepare("SELECT recorded_at FROM mood WHERE id = ?").get(moodId);
|
| 122 | t.truthy(mood.recorded_at.includes('2024-01-15'));
|
| 123 | });
|
| 124 |
|
| 125 | test.serial("Atualizar componentes emocionais do mood", async (t) => {
|
| 126 | const res = await request(app)
|
| 127 | .put(`/mood/${moodId}`)
|
| 128 | .send({
|
| 129 | mood_components: [
|
| 130 | { emotion: "sad", intensity: 4 },
|
| 131 | { emotion: "fear", intensity: 3 },
|
| 132 | { emotion: "angry", intensity: 2 }
|
| 133 | ]
|
| 134 | });
|
| 135 |
|
| 136 | t.is(res.status, 200);
|
| 137 | t.true(res.body.success);
|
| 138 |
|
| 139 | // Verify old components were replaced
|
| 140 | const components = db.prepare("SELECT emotion, intensity FROM mood_components WHERE mood_id = ? ORDER BY emotion").all(moodId);
|
| 141 | t.is(components.length, 3);
|
| 142 |
|
| 143 | const emotions = components.map(c => c.emotion);
|
| 144 | t.true(emotions.includes('sad'));
|
| 145 | t.true(emotions.includes('fear'));
|
| 146 | t.true(emotions.includes('angry'));
|
| 147 | t.false(emotions.includes('joy')); // Old emotion should be gone
|
| 148 | t.false(emotions.includes('trust')); // Old emotion should be gone
|
| 149 | });
|
| 150 |
|
| 151 | test.serial("Remover todos os componentes emocionais enviando array vazio", async (t) => {
|
| 152 | const res = await request(app)
|
| 153 | .put(`/mood/${moodId}`)
|
| 154 | .send({
|
| 155 | mood_components: []
|
| 156 | });
|
| 157 |
|
| 158 | t.is(res.status, 200);
|
| 159 | t.true(res.body.success);
|
| 160 |
|
| 161 | // Verify components were deleted
|
| 162 | const components = db.prepare("SELECT * FROM mood_components WHERE mood_id = ?").all(moodId);
|
| 163 | t.is(components.length, 0);
|
| 164 | });
|
| 165 |
|
| 166 | test.serial("Atualização deve modificar a coluna de atualização", async (t) => {
|
| 167 | // Get original updated_at
|
| 168 | const originalMood = db.prepare("SELECT updated_at FROM mood WHERE id = ?")
|
| 169 | .get(moodId);
|
| 170 |
|
| 171 | // Wait a bit to ensure timestamp difference
|
| 172 | await new Promise(resolve => setTimeout(resolve, 1100));
|
| 173 |
|
| 174 | const res = await request(app)
|
| 175 | .put(`/mood/${moodId}`)
|
| 176 | .send({
|
| 177 | rating: 9
|
| 178 | });
|
| 179 |
|
| 180 | t.is(res.status, 200);
|
| 181 |
|
| 182 | // Verify updated_at changed
|
| 183 | const updatedMood = db.prepare("SELECT updated_at FROM mood WHERE id = ?")
|
| 184 | .get(moodId);
|
| 185 |
|
| 186 | t.not(updatedMood.updated_at, originalMood.updated_at);
|
| 187 | });
|
| 188 |
|
| 189 | test.serial("Falha ao atualizar humor inexistente", async (t) => {
|
| 190 | const res = await request(app)
|
| 191 | .put("/mood/99999")
|
| 192 | .send({
|
| 193 | rating: 8
|
| 194 | });
|
| 195 |
|
| 196 | t.is(res.status, 404);
|
| 197 | t.is(res.body.error, "Humor não encontrado");
|
| 198 | });
|
| 199 |
|
| 200 | test.serial("Falha ao atualizar com avaliação inválida", async (t) => {
|
| 201 | const res = await request(app)
|
| 202 | .put(`/mood/${moodId}`)
|
| 203 | .send({
|
| 204 | rating: 15
|
| 205 | });
|
| 206 |
|
| 207 | t.is(res.status, 400);
|
| 208 | t.is(res.body.error, "rating deve ser entre 1 e 10");
|
| 209 | });
|
| 210 |
|
| 211 | test.serial("Falha ao atualizar com nível de estresse inválido", async (t) => {
|
| 212 | const res = await request(app)
|
| 213 | .put(`/mood/${moodId}`)
|
| 214 | .send({
|
| 215 | stress_level: 0
|
| 216 | });
|
| 217 |
|
| 218 | t.is(res.status, 400);
|
| 219 | t.is(res.body.error, "stress_level deve ser entre 1 e 10");
|
| 220 | });
|
| 221 |
|
| 222 | test.serial("Falha ao atualizar com nível de ansiedade inválido", async (t) => {
|
| 223 | const res = await request(app)
|
| 224 | .put(`/mood/${moodId}`)
|
| 225 | .send({
|
| 226 | anxiety_level: 11
|
| 227 | });
|
| 228 |
|
| 229 | t.is(res.status, 400);
|
| 230 | t.is(res.body.error, "anxiety_level deve ser entre 1 e 10");
|
| 231 | });
|
| 232 |
|
| 233 | test.serial("Falha ao atualizar com nível de energia inválida", async (t) => {
|
| 234 | const res = await request(app)
|
| 235 | .put(`/mood/${moodId}`)
|
| 236 | .send({
|
| 237 | energy_level: -1
|
| 238 | });
|
| 239 |
|
| 240 | t.is(res.status, 400);
|
| 241 | t.is(res.body.error, "energy_level deve ser entre 1 e 10");
|
| 242 | });
|
| 243 |
|
| 244 | test.serial("Falha ao atualizar com data inválida", async (t) => {
|
| 245 | const res = await request(app)
|
| 246 | .put(`/mood/${moodId}`)
|
| 247 | .send({
|
| 248 | recorded_at: "data-invalida"
|
| 249 | });
|
| 250 |
|
| 251 | t.is(res.status, 400);
|
| 252 | t.is(res.body.error, "recorded_at deve ser uma data válida");
|
| 253 | });
|
| 254 |
|
| 255 | test.serial("Falha ao atualizar com data no futuro", async (t) => {
|
| 256 | const futureDate = new Date();
|
| 257 | futureDate.setDate(futureDate.getDate() + 1);
|
| 258 |
|
| 259 | const res = await request(app)
|
| 260 | .put(`/mood/${moodId}`)
|
| 261 | .send({
|
| 262 | recorded_at: futureDate.toISOString()
|
| 263 | });
|
| 264 |
|
| 265 | t.is(res.status, 400);
|
| 266 | t.is(res.body.error, "recorded_at não pode ser no futuro");
|
| 267 | });
|
| 268 |
|
| 269 | test.serial("Falha ao atualizar com emoção inválida nos componentes", async (t) => {
|
| 270 | const res = await request(app)
|
| 271 | .put(`/mood/${moodId}`)
|
| 272 | .send({
|
| 273 | mood_components: [
|
| 274 | { emotion: "invalid", intensity: 5 }
|
| 275 | ]
|
| 276 | });
|
| 277 |
|
| 278 | t.is(res.status, 400);
|
| 279 | t.regex(res.body.error, /Invalid emotion/);
|
| 280 | });
|
| 281 |
|
| 282 | test.serial("Falha ao atualizar com emoções duplicadas", async (t) => {
|
| 283 | const res = await request(app)
|
| 284 | .put(`/mood/${moodId}`)
|
| 285 | .send({
|
| 286 | mood_components: [
|
| 287 | { emotion: "joy", intensity: 5 },
|
| 288 | { emotion: "joy", intensity: 7 }
|
| 289 | ]
|
| 290 | });
|
| 291 |
|
| 292 | t.is(res.status, 400);
|
| 293 | t.regex(res.body.error, /Duplicate emotion/);
|
| 294 | });
|
| 295 |
|
| 296 | test.serial("Deletar humor existente", async (t) => {
|
| 297 | const res = await request(app).delete(`/mood/${moodId}`);
|
| 298 |
|
| 299 | t.is(res.status, 200);
|
| 300 | t.true(res.body.success);
|
| 301 | t.is(Number(res.body.deleted), Number(moodId));
|
| 302 |
|
| 303 | // Verify mood is deleted
|
| 304 | const mood = db.prepare("SELECT * FROM mood WHERE id = ?").get(moodId);
|
| 305 | t.falsy(mood);
|
| 306 | });
|
| 307 |
|
| 308 | test.serial("Deletar humor deve deletar seus componentes (em cascata)", async (t) => {
|
| 309 | // Verify components exist
|
| 310 | const componentsBefore = db.prepare("SELECT * FROM mood_components WHERE mood_id = ?").all(moodId);
|
| 311 | t.true(componentsBefore.length > 0);
|
| 312 |
|
| 313 | const res = await request(app).delete(`/mood/${moodId}`);
|
| 314 | t.is(res.status, 200);
|
| 315 |
|
| 316 | // Verify components are deleted
|
| 317 | const componentsAfter = db.prepare("SELECT * FROM mood_components WHERE mood_id = ?").all(moodId);
|
| 318 | t.is(componentsAfter.length, 0);
|
| 319 | });
|
| 320 |
|
| 321 | test.serial("Falha ao deletar mood inexistente", async (t) => {
|
| 322 | const res = await request(app).delete("/mood/99999");
|
| 323 |
|
| 324 | t.is(res.status, 404);
|
| 325 | t.is(res.body.error, "Humor não encontrado");
|
| 326 | });
|
| 327 |
|
| 328 | test.serial("Atualização parcial mantém valores não alterados", async (t) => {
|
| 329 | // Get original values
|
| 330 | const originalMood = db.prepare("SELECT * FROM mood WHERE id = ?").get(moodId);
|
| 331 |
|
| 332 | // Update only rating
|
| 333 | const res = await request(app)
|
| 334 | .put(`/mood/${moodId}`)
|
| 335 | .send({
|
| 336 | rating: 10
|
| 337 | });
|
| 338 |
|
| 339 | t.is(res.status, 200);
|
| 340 |
|
| 341 | // Verify only rating changed, others remained
|
| 342 | const updatedMood = db.prepare("SELECT * FROM mood WHERE id = ?").get(moodId);
|
| 343 | t.is(updatedMood.rating, 10);
|
| 344 | t.is(updatedMood.stress_level, originalMood.stress_level);
|
| 345 | t.is(updatedMood.anxiety_level, originalMood.anxiety_level);
|
| 346 | t.is(updatedMood.energy_level, originalMood.energy_level);
|
| 347 | t.is(updatedMood.title, originalMood.title);
|
| 348 | t.is(updatedMood.description, originalMood.description);
|
| 349 | });
|