package com.krylov.refound.service; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.fasterxml.jackson.databind.ObjectMapper; import com.krylov.refound.dto.AddressInfo; import com.krylov.refound.exception.ApiException; import java.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.http.HttpStatus; class GeocodingServiceTest { private ValueOperations values; private GeocodingService service; @BeforeEach @SuppressWarnings("unchecked") void setUp() { StringRedisTemplate redis = mock(StringRedisTemplate.class); values = mock(ValueOperations.class); when(redis.opsForValue()).thenReturn(values); // Адрес, на котором ничего не слушает: тесты не должны ходить в настоящий Nominatim service = new GeocodingService(new ObjectMapper(), redis, "http://127.0.0.1:1", "test", Duration.ofSeconds(1)); } @Test void cachedAddressIsReturnedWithoutHttpCall() { when(values.get("geo:55.7558:37.6173")).thenReturn("{\"city\":\"Москва\",\"district\":\"Тверской район\"}"); AddressInfo info = service.getAddress("55.75580001", "37.61729999"); assertThat(info).isEqualTo(new AddressInfo("Москва", "Тверской район")); } @Test void busyThrottleSlotGives503() { when(values.setIfAbsent(eq("geo:throttle"), anyString(), any(Duration.class))).thenReturn(false); assertThatThrownBy(() -> service.getAddress("55.0", "37.0")) .isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE)); } @Test void coordinatesAreRoundedForCacheKey() { assertThat(GeocodingService.cacheKey("55.123456", "-37.1")).isEqualTo("geo:55.1235:-37.1000"); } }