|
| 1 | +package com.onurdesk.iris.service; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 4 | +import com.google.zxing.BarcodeFormat; |
| 5 | +import com.google.zxing.WriterException; |
| 6 | +import com.google.zxing.client.j2se.MatrixToImageWriter; |
| 7 | +import com.google.zxing.common.BitMatrix; |
| 8 | +import com.google.zxing.qrcode.QRCodeWriter; |
| 9 | +import com.onurdesk.iris.dto.QrCodeGenerationRequestDto; |
| 10 | +import org.junit.jupiter.api.BeforeEach; |
| 11 | +import org.junit.jupiter.api.Test; |
| 12 | +import org.junit.jupiter.api.extension.ExtendWith; |
| 13 | +import org.mockito.ArgumentCaptor; |
| 14 | +import org.mockito.InjectMocks; |
| 15 | +import org.mockito.Mock; |
| 16 | +import org.mockito.MockedStatic; |
| 17 | +import org.mockito.Mockito; |
| 18 | +import org.mockito.junit.jupiter.MockitoExtension; |
| 19 | +import org.springframework.http.HttpHeaders; |
| 20 | +import org.springframework.http.HttpStatus; |
| 21 | +import org.springframework.http.ResponseEntity; |
| 22 | +import org.springframework.mock.web.MockHttpServletResponse; |
| 23 | +import org.springframework.web.multipart.MultipartFile; |
| 24 | + |
| 25 | +import javax.imageio.ImageIO; |
| 26 | +import jakarta.servlet.ServletOutputStream; |
| 27 | +import java.awt.image.BufferedImage; |
| 28 | +import java.io.ByteArrayInputStream; |
| 29 | +import java.io.ByteArrayOutputStream; |
| 30 | +import java.io.IOException; |
| 31 | +import java.io.InputStream; |
| 32 | + |
| 33 | +import static org.junit.jupiter.api.Assertions.*; |
| 34 | +import static org.mockito.ArgumentMatchers.any; |
| 35 | +import static org.mockito.ArgumentMatchers.anyInt; |
| 36 | +import static org.mockito.ArgumentMatchers.anyString; |
| 37 | +import static org.mockito.Mockito.*; |
| 38 | + |
| 39 | +@ExtendWith(MockitoExtension.class) |
| 40 | +class QrCodeServiceTests { |
| 41 | + |
| 42 | + @InjectMocks |
| 43 | + private QrCodeService qrCodeService; |
| 44 | + |
| 45 | + private QrCodeGenerationRequestDto sampleDto; |
| 46 | + private ObjectMapper objectMapper = new ObjectMapper(); |
| 47 | + |
| 48 | + @BeforeEach |
| 49 | + void setUp() { |
| 50 | + sampleDto = QrCodeGenerationRequestDto.builder() |
| 51 | + .title("Test QR") |
| 52 | + .message("This is a test payload") // Assuming 'payload' maps to 'message' in DTO based on schema |
| 53 | + .generatedByName("JUnit") // Assuming 'generatedBy' maps to 'generatedByName' |
| 54 | + .generatedForName("Test Target") // Adding a value for this field |
| 55 | + .build(); |
| 56 | + } |
| 57 | + |
| 58 | + @Test |
| 59 | + void testGenerateQrCode_success() throws IOException, WriterException { |
| 60 | + MockHttpServletResponse mockResponse = new MockHttpServletResponse(); |
| 61 | + |
| 62 | + qrCodeService.generate(sampleDto, mockResponse); |
| 63 | + |
| 64 | + assertEquals("attachment;filename=Test_QR.png", mockResponse.getHeader(HttpHeaders.CONTENT_DISPOSITION)); |
| 65 | + assertEquals("image/png", mockResponse.getContentType()); // MatrixToImageWriter sets this implicitly |
| 66 | + |
| 67 | + // Verify the output stream contains PNG data (basic check for non-empty) |
| 68 | + assertTrue(mockResponse.getContentAsByteArray().length > 0); |
| 69 | + |
| 70 | + // Further verification could involve trying to read the byte array as an image |
| 71 | + // and potentially decoding it, but that might be too much for a unit test. |
| 72 | + // For now, we trust that if MatrixToImageWriter.writeToStream ran without error |
| 73 | + // and produced bytes, it's likely correct. |
| 74 | + |
| 75 | + // We can also try to verify the content of the QR code if we mock the writer part. |
| 76 | + // Let's try to capture the string passed to the QRCodeWriter.encode |
| 77 | + // This requires QRCodeWriter to be a mock or using a static mock for MatrixToImageWriter |
| 78 | + // For simplicity, the current check on headers and non-empty output is a good start. |
| 79 | + } |
| 80 | + |
| 81 | + @Test |
| 82 | + void testGenerateQrCode_nullDto() { |
| 83 | + MockHttpServletResponse mockResponse = new MockHttpServletResponse(); |
| 84 | + assertThrows(NullPointerException.class, () -> { |
| 85 | + // The ObjectMapper().writeValueAsString(null) will throw NullPointerException |
| 86 | + qrCodeService.generate(null, mockResponse); |
| 87 | + }); |
| 88 | + } |
| 89 | + |
| 90 | + @Test |
| 91 | + void testGenerateQrCode_emptyTitleInDto() throws IOException, WriterException { |
| 92 | + MockHttpServletResponse mockResponse = new MockHttpServletResponse(); |
| 93 | + QrCodeGenerationRequestDto dtoWithEmptyTitle = QrCodeGenerationRequestDto.builder() |
| 94 | + .title("") // Empty title |
| 95 | + .message("Some payload") |
| 96 | + .generatedByName("JUnit") |
| 97 | + .generatedForName("Test Target") |
| 98 | + .build(); |
| 99 | + |
| 100 | + qrCodeService.generate(dtoWithEmptyTitle, mockResponse); |
| 101 | + |
| 102 | + // Expecting "attachment;filename=.png" or similar, depending on implementation logic for empty title |
| 103 | + assertEquals("attachment;filename=.png", mockResponse.getHeader(HttpHeaders.CONTENT_DISPOSITION)); |
| 104 | + assertTrue(mockResponse.getContentAsByteArray().length > 0); |
| 105 | + } |
| 106 | + |
| 107 | + |
| 108 | + @Test |
| 109 | + void testReadQrCode_success() throws Exception { |
| 110 | + // 1. Prepare a valid QR code image as byte array |
| 111 | + String originalContent = objectMapper.writeValueAsString(sampleDto); |
| 112 | + QRCodeWriter qrCodeWriter = new QRCodeWriter(); |
| 113 | + BitMatrix bitMatrix = qrCodeWriter.encode(originalContent, BarcodeFormat.QR_CODE, 200, 200); |
| 114 | + ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream(); |
| 115 | + MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream); |
| 116 | + byte[] qrCodeBytes = pngOutputStream.toByteArray(); |
| 117 | + |
| 118 | + // 2. Mock MultipartFile |
| 119 | + MultipartFile multipartFile = mock(MultipartFile.class); |
| 120 | + when(multipartFile.getInputStream()).thenReturn(new ByteArrayInputStream(qrCodeBytes)); |
| 121 | + |
| 122 | + // 3. Call read method |
| 123 | + ResponseEntity<?> responseEntity = qrCodeService.read(multipartFile); |
| 124 | + |
| 125 | + // 4. Assertions |
| 126 | + assertNotNull(responseEntity); |
| 127 | + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); |
| 128 | + assertTrue(responseEntity.getBody() instanceof QrCodeGenerationRequestDto); |
| 129 | + QrCodeGenerationRequestDto resultDto = (QrCodeGenerationRequestDto) responseEntity.getBody(); |
| 130 | + assertEquals(sampleDto.getTitle(), resultDto.getTitle()); |
| 131 | + assertEquals(sampleDto.getMessage(), resultDto.getMessage()); // Changed from getPayload to getMessage |
| 132 | + assertEquals(sampleDto.getGeneratedByName(), resultDto.getGeneratedByName()); // Changed from getGeneratedBy |
| 133 | + } |
| 134 | + |
| 135 | + @Test |
| 136 | + void testReadQrCode_invalidImageFormat() throws IOException { |
| 137 | + MultipartFile multipartFile = mock(MultipartFile.class); |
| 138 | + // Simulate a file that is not a valid image (e.g., random bytes) |
| 139 | + byte[] invalidImageBytes = "This is not an image".getBytes(); |
| 140 | + when(multipartFile.getInputStream()).thenReturn(new ByteArrayInputStream(invalidImageBytes)); |
| 141 | + |
| 142 | + // ImageIO.read is expected to return null for non-image formats it doesn't understand |
| 143 | + // which will then cause NullPointerException in BufferedImageLuminanceSource constructor |
| 144 | + assertThrows(NullPointerException.class, () -> { |
| 145 | + qrCodeService.read(multipartFile); |
| 146 | + }, "Should throw NullPointerException when ImageIO.read returns null for invalid image format that is not decodable by ImageIO"); |
| 147 | + } |
| 148 | + |
| 149 | + @Test |
| 150 | + void testReadQrCode_notAQrCode() throws IOException { |
| 151 | + // Create a valid PNG image, but not a QR code (e.g., a blank image) |
| 152 | + BufferedImage blankImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); |
| 153 | + ByteArrayOutputStream baos = new ByteArrayOutputStream(); |
| 154 | + ImageIO.write(blankImage, "png", baos); |
| 155 | + byte[] blankImageBytes = baos.toByteArray(); |
| 156 | + |
| 157 | + MultipartFile multipartFile = mock(MultipartFile.class); |
| 158 | + when(multipartFile.getInputStream()).thenReturn(new ByteArrayInputStream(blankImageBytes)); |
| 159 | + |
| 160 | + // Expect NotFoundException because MultiFormatReader won't find a QR code |
| 161 | + assertThrows(com.google.zxing.NotFoundException.class, () -> { |
| 162 | + qrCodeService.read(multipartFile); |
| 163 | + }); |
| 164 | + } |
| 165 | + |
| 166 | + @Test |
| 167 | + void testReadQrCode_ioExceptionOnInputStream() throws IOException { |
| 168 | + MultipartFile multipartFile = mock(MultipartFile.class); |
| 169 | + when(multipartFile.getInputStream()).thenThrow(new IOException("Failed to read input stream")); |
| 170 | + |
| 171 | + assertThrows(IOException.class, () -> { |
| 172 | + qrCodeService.read(multipartFile); |
| 173 | + }); |
| 174 | + } |
| 175 | + |
| 176 | + @Test |
| 177 | + void testReadQrCode_unexpectedContent() throws Exception { |
| 178 | + // 1. Prepare a QR code with content that is not a valid JSON for QrCodeGenerationRequestDto |
| 179 | + String nonJsonContent = "Just some plain text, not JSON"; |
| 180 | + QRCodeWriter qrCodeWriter = new QRCodeWriter(); |
| 181 | + BitMatrix bitMatrix = qrCodeWriter.encode(nonJsonContent, BarcodeFormat.QR_CODE, 200, 200); |
| 182 | + ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream(); |
| 183 | + MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream); |
| 184 | + byte[] qrCodeBytes = pngOutputStream.toByteArray(); |
| 185 | + |
| 186 | + // 2. Mock MultipartFile |
| 187 | + MultipartFile multipartFile = mock(MultipartFile.class); |
| 188 | + when(multipartFile.getInputStream()).thenReturn(new ByteArrayInputStream(qrCodeBytes)); |
| 189 | + |
| 190 | + // 3. Call read method and expect a Jackson mapping/parsing exception |
| 191 | + // The service tries to map result.getText() to QrCodeGenerationRequestDto.class |
| 192 | + // This will fail if the text is not a JSON representation of that DTO. |
| 193 | + assertThrows(com.fasterxml.jackson.core.JsonProcessingException.class, () -> { // Changed to broader JsonProcessingException |
| 194 | + qrCodeService.read(multipartFile); |
| 195 | + }); |
| 196 | + } |
| 197 | +} |
0 commit comments