Untitled

 avatar
unknown
plain_text
5 months ago
2.4 kB
2
Indexable
import spock.lang.Specification
import javax.activation.DataHandler
import java.nio.file.Files
import java.nio.file.Path
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream

class PolicyNotesAttachmentServiceTest extends Specification {

    @TempDir
    Path tempDir

    PolicyNotesAttachmentService policyNotesAttachmentService = new PolicyNotesAttachmentService()

    def "zip with no files inside"() {
        given:
        // Prepare an empty zip file for this test case
        File emptyZipFile = Files.createTempFile(tempDir, "empty", ".zip").toFile()
        DataHandler dataHandler = new DataHandler(emptyZipFile.toURI().toURL())

        when:
        def fileContents = policyNotesAttachmentService.getFilesFromZip(dataHandler)

        then:
        fileContents.isEmpty()
    }

    def "zip with single file"() {
        given:
        // Create a temporary zip file with a single file inside
        File zipFile = createZipFileWithEntries(tempDir, ["file1.txt": "This is the content of file1"])

        DataHandler dataHandler = new DataHandler(zipFile.toURI().toURL())

        when:
        def fileContents = policyNotesAttachmentService.getFilesFromZip(dataHandler)

        then:
        fileContents.size() == 1
        fileContents[0] == "This is the content of file1\n"
    }

    def "zip with multiple files"() {
        given:
        // Create a temporary zip file with multiple files inside
        File zipFile = createZipFileWithEntries(tempDir, [
                "file1.txt": "Content of file1",
                "file2.txt": "Content of file2"
        ])

        DataHandler dataHandler = new DataHandler(zipFile.toURI().toURL())

        when:
        def fileContents = policyNotesAttachmentService.getFilesFromZip(dataHandler)

        then:
        fileContents.size() == 2
        fileContents.contains("Content of file1\n")
        fileContents.contains("Content of file2\n")
    }

    private File createZipFileWithEntries(Path tempDir, Map<String, String> files) {
        File zipFile = Files.createTempFile(tempDir, "testfile", ".zip").toFile()
        ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile))
        files.each { fileName, fileContent ->
            zipOut.putNextEntry(new ZipEntry(fileName))
            zipOut.write(fileContent.bytes)
            zipOut.closeEntry()
        }
        zipOut.close()
        return zipFile
    }
}
Editor is loading...
Leave a Comment