HorseEndpointTest.java 9.74 KB
Newer Older
1 2 3 4 5
package at.ac.tuwien.sepm.assignment.individual.integration;

import static org.junit.jupiter.api.Assertions.*;

import at.ac.tuwien.sepm.assignment.individual.endpoint.dto.HorseDto;
6
import at.ac.tuwien.sepm.assignment.individual.enums.ERace;
7 8
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
9
import org.springframework.beans.factory.annotation.Value;
10 11
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
12
import org.springframework.core.ParameterizedTypeReference;
13 14
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.*;
15
import org.springframework.test.context.ActiveProfiles;
16
import org.springframework.web.client.HttpClientErrorException;
17 18
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
19
import org.springframework.web.client.RestTemplate;
20
import org.springframework.web.util.UriComponentsBuilder;
21

22
import java.io.File;
23
import java.sql.Date;
24
import java.util.List;
25 26 27 28

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class HorseEndpointTest {
29 30
    @Value("${spring.upload.path}")
    private String FILE_BASE_PATH;
31 32 33 34 35 36 37
    private static final RestTemplate REST_TEMPLATE = new RestTemplate();
    private static final String BASE_URL = "http://localhost:";
    private static final String HORSE_URL = "/horses";

    @LocalServerPort
    private int port;

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    @Test
    @DisplayName("Searching for all horses with no filters, given two horses should return HTTP 200 and both horses")
    public void searchingHorses_noFiltersGivenTwoHorses_shouldReturnStatus200AndHorses() {
        // Create the horses
        HorseDto newHorse = new HorseDto("Zephyr", "Nice horse", (short) 4, Date.valueOf("2020-01-01"), ERace.APPALOOSA, "files/test.png", Long.valueOf(0));

        HttpEntity<HorseDto> request = new HttpEntity<>(newHorse);
        ResponseEntity<HorseDto> firstHorse = REST_TEMPLATE
            .exchange(BASE_URL + port + HORSE_URL, HttpMethod.POST, request, HorseDto.class);

        newHorse = new HorseDto("Katrina", "Not a fast enough horse", (short) 3, Date.valueOf("2005-01-01"), ERace.PAINT, "files/example.png", Long.valueOf(0));

        request = new HttpEntity<>(newHorse);
        ResponseEntity<HorseDto> secondHorse = REST_TEMPLATE
            .exchange(BASE_URL + port + HORSE_URL, HttpMethod.POST, request, HorseDto.class);

        // Get all horses and save in list
        // https://stackoverflow.com/a/31947188
        ResponseEntity<List<HorseDto>> allHorses = REST_TEMPLATE
            .exchange(BASE_URL + port + HORSE_URL, HttpMethod.GET, null, new ParameterizedTypeReference<List<HorseDto>>() {});

        assertEquals(allHorses.getStatusCode(), HttpStatus.OK);
        assertTrue(allHorses.getBody().contains(firstHorse.getBody()));
        assertTrue(allHorses.getBody().contains(secondHorse.getBody()));
    }

    @Test
    @DisplayName("Searching for all horses with correct filters, given two horses should return HTTP 200 and one horse")
    public void searchingHorses_withCorrectFiltersGivenTwoHorses_shouldReturnStatus200AndHorse() {
        // Create the horses
        HorseDto newHorse = new HorseDto("Zephyr", "Nice horse", (short) 4, Date.valueOf("2020-01-01"), ERace.APPALOOSA, "files/test.png", Long.valueOf(0));

        HttpEntity<HorseDto> request = new HttpEntity<>(newHorse);
        ResponseEntity<HorseDto> firstHorse = REST_TEMPLATE
            .exchange(BASE_URL + port + HORSE_URL, HttpMethod.POST, request, HorseDto.class);

        newHorse = new HorseDto("Katrina", "Not a fast enough horse", (short) 3, Date.valueOf("2005-01-01"), ERace.PAINT, "files/example.png", Long.valueOf(0));

        request = new HttpEntity<>(newHorse);
        ResponseEntity<HorseDto> secondHorse = REST_TEMPLATE
            .exchange(BASE_URL + port + HORSE_URL, HttpMethod.POST, request, HorseDto.class);

        // Get all horses and save in list
        // https://stackoverflow.com/a/25434451
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(BASE_URL + port + HORSE_URL)
            .queryParam("name", "Zephyr")
            .queryParam("description", "Nice")
            .queryParam("score", "4")
            .queryParam("birthday", "2020-03-23")
            .queryParam("race", ERace.APPALOOSA.name());

        ResponseEntity<List<HorseDto>> allHorses = REST_TEMPLATE.exchange(
            builder.toUriString(),
            HttpMethod.GET,
            null,
            new ParameterizedTypeReference<List<HorseDto>>() {}
        );

        assertEquals(allHorses.getStatusCode(), HttpStatus.OK);
        assertTrue(allHorses.getBody().contains(firstHorse.getBody()));
    }

    @Test
    @DisplayName("Searching for all horses with incorrect filters, given two horses should return HTTP 400")
    public void searchingHorses_withIncorrectFiltersGivenTwoHorses_shouldReturnStatus400() {
        // Create the horses
        HorseDto newHorse = new HorseDto("Zephyr", "Nice horse", (short) 4, Date.valueOf("2020-01-01"), ERace.APPALOOSA, "files/test.png", Long.valueOf(0));

        HttpEntity<HorseDto> request = new HttpEntity<>(newHorse);
        ResponseEntity<HorseDto> firstHorse = REST_TEMPLATE
            .exchange(BASE_URL + port + HORSE_URL, HttpMethod.POST, request, HorseDto.class);

        newHorse = new HorseDto("Katrina", "Not a fast enough horse", (short) 3, Date.valueOf("2005-01-01"), ERace.PAINT, "files/example.png", Long.valueOf(0));

        request = new HttpEntity<>(newHorse);
        ResponseEntity<HorseDto> secondHorse = REST_TEMPLATE
            .exchange(BASE_URL + port + HORSE_URL, HttpMethod.POST, request, HorseDto.class);

        // Get all horses and save in list
        // https://stackoverflow.com/a/25434451
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(BASE_URL + port + HORSE_URL)
            .queryParam("name", "Zephyr")
            .queryParam("description", "Nice")
            .queryParam("score", "10")
            .queryParam("birthday", "test")
            .queryParam("race", "test");

        assertThrows(HttpClientErrorException.BadRequest.class, () ->
            REST_TEMPLATE
                .exchange(builder.toUriString(), HttpMethod.GET, null, new ParameterizedTypeReference<HorseDto>() {}));
    }

130 131 132
    @Test
    @DisplayName("Adding a new horse with the correct parameters will return HTTP 201 and the new HorseDto")
    public void addingNewHorse_correctParameters_shouldReturnStatus201AndHorse() {
133
        HorseDto newHorse = new HorseDto("Zephyr", "Nice horse", (short) 4, Date.valueOf("2020-01-01"), ERace.APPALOOSA, "files/test.png", null);
134 135 136 137 138 139 140 141 142 143 144

        HttpEntity<HorseDto> request = new HttpEntity<>(newHorse);
        ResponseEntity<HorseDto> response = REST_TEMPLATE
            .exchange(BASE_URL + port + HORSE_URL, HttpMethod.POST, request, HorseDto.class);

        // Compare everything except ids and timestamps
        assertEquals(response.getStatusCode(), HttpStatus.CREATED);
        assertEquals(newHorse.getName(), response.getBody().getName());
        assertEquals(newHorse.getDescription(), response.getBody().getDescription());
        assertEquals(newHorse.getScore(), response.getBody().getScore());
        assertEquals(newHorse.getBirthday().toString(), response.getBody().getBirthday().toString());
145
        assertEquals(newHorse.getImagePath(), response.getBody().getImagePath());
146 147
        assertEquals(newHorse.getOwner(), response.getBody().getOwner());
    }
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172

    @Test
    @DisplayName("Uploading an image in the correct format will return HTTP 201")
    public void addingNewImage_correctFormat_shouldReturnStatus201() {
        try {
            // More information:
            // https://www.baeldung.com/spring-rest-template-multipart-upload
            // https://github.com/spring-guides/gs-uploading-files/blob/master/complete/src/test/java/com/example/uploadingfiles/FileUploadIntegrationTests.java

            // Get the file
            ClassPathResource image = new ClassPathResource("horse.jpg", getClass());

            // Set the body
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", image);

            // Create the HTTP Entity
            HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(body);

            ResponseEntity<String> response = REST_TEMPLATE.postForEntity(BASE_URL + port + HORSE_URL + "/upload", request, String.class);
            assertEquals(HttpStatus.CREATED, response.getStatusCode());
        } finally {
            new File(FILE_BASE_PATH + "horse.jpg").delete();
        }
    }
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197

    @Test
    @DisplayName("Deleting an existing horse will return HTTP 204")
    public void deletingHorse_existing_shouldReturnStatus204() {
        // Create the horse
        HorseDto newHorse = new HorseDto("Zephyr", "Nice horse", (short) 4, Date.valueOf("2020-01-01"), ERace.APPALOOSA, "files/test.png", null);

        HttpEntity<HorseDto> request = new HttpEntity<>(newHorse);
        ResponseEntity<HorseDto> response = REST_TEMPLATE
            .exchange(BASE_URL + port + HORSE_URL, HttpMethod.POST, request, HorseDto.class);

        // Delete and test if deleted
        ResponseEntity res = REST_TEMPLATE
            .exchange(BASE_URL + port + HORSE_URL + '/' + response.getBody().getId(), HttpMethod.DELETE, null, new ParameterizedTypeReference<HorseDto>() {});

        assertEquals(res.getStatusCode(), HttpStatus.NO_CONTENT);
    }

    @Test
    @DisplayName("Deleting an nonexistent horse will return HTTP 404")
    public void deletingHorse_nonexistent_shouldReturnStatus404() {
        assertThrows(HttpClientErrorException.NotFound.class, () ->
            REST_TEMPLATE
                .exchange(BASE_URL + port + HORSE_URL + "/0", HttpMethod.DELETE, null, new ParameterizedTypeReference<HorseDto>() {}));
    }
198
}
199