|
| 1 | +package com.getyourguide.openapi.validation.filter; |
| 2 | + |
| 3 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 4 | +import static org.junit.jupiter.api.Assertions.assertFalse; |
| 5 | +import static org.junit.jupiter.api.Assertions.assertTrue; |
| 6 | + |
| 7 | +import java.io.IOException; |
| 8 | +import java.nio.charset.StandardCharsets; |
| 9 | +import org.junit.jupiter.api.Test; |
| 10 | +import org.springframework.mock.web.MockHttpServletResponse; |
| 11 | + |
| 12 | +class EventStreamAwareContentCachingResponseWrapperTest { |
| 13 | + |
| 14 | + private final MockHttpServletResponse response = new MockHttpServletResponse(); |
| 15 | + private final EventStreamAwareContentCachingResponseWrapper wrapper = |
| 16 | + new EventStreamAwareContentCachingResponseWrapper(response); |
| 17 | + |
| 18 | + @Test |
| 19 | + public void whenJsonResponseThenBodyIsCachedUntilCopied() throws IOException { |
| 20 | + wrapper.setContentType("application/json"); |
| 21 | + wrapper.getOutputStream().write("{}".getBytes(StandardCharsets.UTF_8)); |
| 22 | + wrapper.flushBuffer(); |
| 23 | + |
| 24 | + assertEquals("", response.getContentAsString()); |
| 25 | + assertFalse(response.isCommitted()); |
| 26 | + assertEquals("{}", new String(wrapper.getContentAsByteArray(), StandardCharsets.UTF_8)); |
| 27 | + |
| 28 | + wrapper.copyBodyToResponse(); |
| 29 | + |
| 30 | + assertEquals("{}", response.getContentAsString()); |
| 31 | + } |
| 32 | + |
| 33 | + @Test |
| 34 | + public void whenEventStreamThenEachWriteAndFlushReachesTheResponse() throws IOException { |
| 35 | + wrapper.setContentType("text/event-stream;charset=UTF-8"); |
| 36 | + wrapper.getOutputStream().write("data: first\n\n".getBytes(StandardCharsets.UTF_8)); |
| 37 | + wrapper.flushBuffer(); |
| 38 | + |
| 39 | + assertEquals("data: first\n\n", response.getContentAsString()); |
| 40 | + assertTrue(response.isCommitted()); |
| 41 | + assertEquals(0, wrapper.getContentSize()); |
| 42 | + } |
| 43 | + |
| 44 | + @Test |
| 45 | + public void whenEventStreamWrittenThroughWriterThenItReachesTheResponse() throws IOException { |
| 46 | + wrapper.setContentType("TEXT/EVENT-STREAM"); |
| 47 | + wrapper.getWriter().write("data: first\n\n"); |
| 48 | + wrapper.getWriter().flush(); |
| 49 | + |
| 50 | + assertEquals("data: first\n\n", response.getContentAsString()); |
| 51 | + assertEquals(0, wrapper.getContentSize()); |
| 52 | + } |
| 53 | +} |
0 commit comments