Files
nahodka-back/src/test/java/com/krylov/refound/service/GeocodingServiceTest.java
SlimusMinus 3dcd27d08a Keep network calls out of post transactions; cache and throttle geocoding
- PostService.create/update geocode and upload photos before opening the DB
  transaction (TransactionTemplate); uploaded files are removed if the
  transaction fails, so a DB connection is no longer held while waiting for
  Nominatim or MinIO.
- GeocodingService: configurable URL and User-Agent (geocoding.*), results
  cached in Redis for 30 days by coordinates rounded to ~11 m, and a
  cluster-wide 1 request/s slot (geo:throttle) as the public Nominatim policy
  requires; city/district are cut to the column sizes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:41:03 +03:00

59 lines
2.2 KiB
Java

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<String, String> 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");
}
}