AsFileTest.java

/**
 * The MIT License
 *
 * Copyright for portions of unirest-java are held by Kong Inc (c) 2013.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package BehaviorTests;

import kong.unirest.core.HttpResponse;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import kong.unirest.core.Unirest;

import java.io.File;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

class AsFileTest extends BddTest {

    private final Path test = Paths.get("results.json");
    private final JacksonObjectMapper om = new JacksonObjectMapper();

    @Override @AfterEach
    public void tearDown() {
        try {
            Files.delete(test);
        } catch (Exception ignored) { }
    }

    @Test
    void canSaveContentsIntoFile() {
        var result = Unirest.get(MockServer.GET)
                .queryString("talking","heads")
                .queryString("param3", "���������������")
                .asFile(test.toString())
                .getBody();

        om.readValue(result, RequestCapture.class)
                .assertParam("talking", "heads")
                .assertParam("param3", "���������������")
                .assertStatus(200);

        assertEquals(test.toFile().getPath(), result.getPath());
    }

    @Test
    void canSaveContentsIntoFileAsync() throws Exception {
        var result = Unirest.get(MockServer.GET)
                .queryString("talking","heads")
                .queryString("param3", "���������������")
                .asFileAsync(test.toString())
                .get()
                .getBody();

        om.readValue(result, RequestCapture.class)
                .assertParam("talking", "heads")
                .assertParam("param3", "���������������")
                .assertStatus(200);

        assertEquals(test.toFile().getPath(), result.getPath());
    }

    @Test
    void canSaveContentsIntoFileAsyncWithCallback() throws Exception {
        Unirest.get(MockServer.GET)
                .queryString("talking","heads")
                .queryString("param3", "���������������")
                .asFileAsync(test.toString(), r -> {
                        om.readValue(r.getBody(), RequestCapture.class)
                            .assertParam("talking", "heads")
                            .assertParam("param3", "���������������")
                            .assertStatus(200);
                    assertEquals(test.toFile().getPath(), r.getBody().getPath());
                    asyncSuccess();
                });

        assertAsync();
    }

    @Test
    void canDownloadABinaryFile() throws Exception {
        var f1 = TestUtil.rezFile("/spidey.jpg");

        var f2 = Unirest.get(MockServer.BINARYFILE)
                .asFile(test.toString())
                .getBody();

        assertTrue(com.google.common.io.Files.equal(f1, f2));
    }

    @Test
    void byDefaultFailWhenAttemptingToOverride() {
        Unirest.get(MockServer.BINARYFILE)
                .asFile(test.toString());

        var f2 = Unirest.get(MockServer.BINARYFILE)
                .asFile(test.toString());

        assertTrue(f2.getParsingError().isPresent());
        assertThat(f2.getParsingError().get().getCause().getCause())
                .isInstanceOf(FileAlreadyExistsException.class);
    }

    @Test
    void canOverrideExistingFiles() {
        var f1 = Unirest.get(MockServer.BINARYFILE)
                .asFile(test.toString())
                .getBody();

        var f2 = Unirest.get(MockServer.BINARYFILE)
                .asFile(test.toString(), StandardCopyOption.REPLACE_EXISTING)
                .getBody();

        assertEquals(f1, f2);
    }

    @Test
    void canOverrideExistingFiles_Async() throws Exception {
        var f1 = Unirest.get(MockServer.BINARYFILE)
                .asFileAsync(test.toString())
                .get()
                .getBody();

        var f2 = Unirest.get(MockServer.BINARYFILE)
                .asFileAsync(test.toString(), StandardCopyOption.REPLACE_EXISTING)
                .get()
                .getBody();

        assertEquals(f1, f2);
    }

    @Test
    void dontReadFilesWhenInError() {
        var f1 = Unirest.get(MockServer.BINARYFILE)
                .downloadMonitor((field, fileName, bytesWritten, totalBytes) -> {
                    throw new RuntimeException("hey hey hey");
                })
                .asFile(test.toString());

        assertEquals("", f1.getParsingError().get().getOriginalBody());
    }
}