001package com.studentgui.apphelpers; 002 003import java.nio.file.Files; 004import java.nio.file.Path; 005 006import static org.junit.jupiter.api.Assertions.assertEquals; 007import static org.junit.jupiter.api.Assertions.assertNotNull; 008import static org.junit.jupiter.api.Assertions.assertTrue; 009import org.junit.jupiter.api.Test; 010 011import com.fasterxml.jackson.databind.JsonNode; 012import com.fasterxml.jackson.databind.ObjectMapper; 013import com.studentgui.apphelpers.dto.NotesPayload; 014 015/** 016 * Unit test for SessionJsonWriter to verify envelope and filename format. 017 */ 018public class SessionJsonWriterTest { 019 020 @Test 021 /** 022 * Validate that the session JSON writer emits the expected keys including 023 * the session id and the embedded payload structure used by the API. 024 */ 025 026 public void writeSessionJson_includesSessionIdAndPayload() throws Exception { 027 String student = "UnitTestStudent-" + System.nanoTime(); 028 int sessionId = 314159; 029 NotesPayload payload = new NotesPayload(sessionId, "unit test notes payload"); 030 031 Path out = SessionJsonWriter.writeSessionJson(student, "UnitTestPage", payload, sessionId); 032 assertNotNull(out, "writeSessionJson should return a path"); 033 assertTrue(Files.exists(out), "written file should exist"); 034 035 String fname = out.getFileName().toString(); 036 assertTrue(fname.contains("UnitTestPage"), "filename should contain page name"); 037 assertTrue(fname.contains("-session-" + sessionId), "filename should include session id segment"); 038 039 byte[] data = Files.readAllBytes(out); 040 ObjectMapper m = new ObjectMapper(); 041 JsonNode root = m.readTree(data); 042 assertEquals(student, root.get("student").asText()); 043 assertEquals("UnitTestPage", root.get("page").asText()); 044 assertTrue(root.has("sessionId")); 045 assertEquals(sessionId, root.get("sessionId").asInt()); 046 047 JsonNode payloadNode = root.get("payload"); 048 assertNotNull(payloadNode); 049 assertEquals("unit test notes payload", payloadNode.get("notes").asText()); 050 051 // cleanup - Files.deleteIfExists throws IOException; catch that specifically 052 try { Files.deleteIfExists(out); } catch (java.io.IOException ex) { /* best-effort cleanup */ } 053 } 054}