package at.gv.egiz.moazs; import at.gv.egiz.moazs.backend.SaveResponseToFileSink; import at.gv.egiz.moazs.repository.DeliveryRepository; import at.gv.egiz.moazs.scheme.Marshaller; import at.gv.egiz.moazs.scheme.RequestStatusResponse; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Collection; import static at.gv.zustellung.msg.xsd.DeliveryRequestStatusType.Success.successBuilder; import static at.gv.zustellung.msg.xsd.DeliveryRequestStatusType.deliveryRequestStatusTypeBuilder; import static java.util.Optional.of; import static org.apache.commons.io.FileUtils.readFileToString; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class SaveResponseToFileSinkTest { private static final Logger log = LoggerFactory.getLogger(SaveResponseToFileSinkTest.class); private SaveResponseToFileSink sink; private final String root = "./target/tmp/SaveResponseToFileSinkTestOut"; @Mock private DeliveryRepository repository; @Mock private Marshaller marshaller; @Before public void setup() { sink = new SaveResponseToFileSink(marshaller, repository); deleteRoot(); } private void deleteRoot() { try { FileUtils.deleteDirectory(new File(root)); } catch (IOException e) { log.warn("Could not delete {}", root); } } @Test public void saveRequestToFiles() { var fileContent = "some content"; var status = setupMocks(fileContent); sink.save(status, root) .thenRun(() -> assertFilesCreatedAndContentMatches(fileContent)); } private void assertFilesCreatedAndContentMatches(String fileContent) { var rootFolder = new File(root); Collection files = FileUtils.listFiles(rootFolder, null, true); assertThat(rootFolder.exists()).isTrue(); assertThat(rootFolder.isDirectory()).isTrue(); assertThat(files).isNotEmpty(); files.stream() .map(file -> readFile(file)) .forEach(content -> assertThat(content).isEqualTo(fileContent)); } private String readFile(File file) { try { return readFileToString(file, StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } } private RequestStatusResponse setupMocks(String fileContent) { var appDeliveryID = "app-delivery-id"; var responseID = RequestStatusResponse.getResponseID(appDeliveryID); when(repository.retrieveBinaryResponse(responseID)) .thenReturn(of(fileContent.getBytes(StandardCharsets.UTF_8))); when(marshaller.marshallXml(any())).thenReturn(fileContent); var success = successBuilder() .withAppDeliveryID(appDeliveryID) .build(); var status = deliveryRequestStatusTypeBuilder() .withSuccess(success) .build(); return new RequestStatusResponse(status); } }