Files
mtusi2026lab5/src/test/java/com/example/mtusi_messenger/service/AttachmentServiceTest.java
T
2026-11-19 07:57:14 +03:00

202 lines
8.0 KiB
Java

package com.example.mtusi_messenger.service;
import com.example.mtusi_messenger.exception.ApiException;
import com.example.mtusi_messenger.model.Attachment;
import com.example.mtusi_messenger.model.Chat;
import com.example.mtusi_messenger.repository.AttachmentRepository;
import com.example.mtusi_messenger.queue.AttachmentJobPublisher;
import com.example.mtusi_messenger.storage.ObjectStorage;
import com.example.mtusi_messenger.storage.ObjectStorageException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import java.io.ByteArrayInputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
class AttachmentServiceTest {
private final UUID chatId = UUID.randomUUID();
private final UUID ownerId = UUID.randomUUID();
private AttachmentRepository repository;
private ChatService chats;
private InMemoryStorage storage;
private AttachmentJobPublisher publisher;
private AttachmentService service;
private byte[] png;
@BeforeEach
void setUp() throws Exception {
repository = mock(AttachmentRepository.class);
chats = mock(ChatService.class);
storage = new InMemoryStorage();
publisher = mock(AttachmentJobPublisher.class);
TransactionTemplate transaction = mock(TransactionTemplate.class);
when(transaction.execute(any())).thenAnswer(invocation -> {
@SuppressWarnings("unchecked")
TransactionCallback<Object> callback = invocation.getArgument(0);
return callback.doInTransaction(mock(TransactionStatus.class));
});
when(chats.getAccessible(chatId, ownerId)).thenReturn(
new Chat(chatId, "test", List.of(ownerId), Instant.now()));
when(repository.saveQueued(any(), any())).thenAnswer(invocation -> invocation.getArgument(0));
service = new AttachmentService(repository, chats, storage, publisher, transaction,
10_485_760, 40_000_000, 3, 10_000, false);
png = Files.readAllBytes(Path.of("tests", "fixtures", "sample.png"));
}
@Test
void stagesValidPngAndPublishesDurableJob() {
Attachment attachment = service.upload(chatId, ownerId, "photo.png", "image/png",
png.length, new ByteArrayInputStream(png));
assertEquals("photo.png", attachment.filename());
assertEquals("image/png", attachment.contentType());
assertEquals(png.length, attachment.sizeBytes());
assertTrue(attachment.objectKey().matches("attachments/[0-9a-f-]+/original"));
assertTrue(attachment.stagingKey().matches("staging/[0-9a-f-]+/original"));
assertEquals("queued", attachment.status());
assertFalse(attachment.objectKey().contains("photo.png"));
assertArrayEquals(png, storage.objects.get(attachment.stagingKey()));
assertFalse(storage.objects.containsKey(attachment.objectKey()));
verify(repository).saveQueued(eq(attachment), any());
verify(publisher).publish(any());
}
@Test
void rejectsMimeSpoofingBeforeS3Write() {
ApiException error = assertThrows(ApiException.class, () -> service.upload(
chatId, ownerId, "photo.jpg", "image/jpeg", png.length,
new ByteArrayInputStream(png)));
assertEquals(HttpStatus.UNSUPPORTED_MEDIA_TYPE, error.status());
assertTrue(storage.objects.isEmpty());
}
@Test
void rejectsOversizedBodyBeforeReadingIt() {
ApiException error = assertThrows(ApiException.class, () -> service.upload(
chatId, ownerId, "photo.png", "image/png", 10_485_761,
new ByteArrayInputStream(png)));
assertEquals(HttpStatus.PAYLOAD_TOO_LARGE, error.status());
assertTrue(storage.objects.isEmpty());
}
@Test
void rejectsAttachmentFromAnotherChat() {
UUID attachmentId = UUID.randomUUID();
when(repository.findAllByIdsInChat(chatId, List.of(attachmentId))).thenReturn(List.of());
ApiException error = assertThrows(ApiException.class,
() -> service.validateForMessage(chatId, List.of(attachmentId)));
assertEquals(HttpStatus.NOT_FOUND, error.status());
}
@Test
void surfacesS3OutageWithoutWritingMetadata() {
storage.failure = true;
assertThrows(ObjectStorageException.class, () -> service.upload(
chatId, ownerId, "photo.png", "image/png", png.length,
new ByteArrayInputStream(png)));
verify(repository, never()).saveQueued(any(), any());
}
@Test
void interruptedRequestDoesNotCreateS3Object() {
java.io.InputStream source = new java.io.InputStream() {
private int position;
@Override
public int read() throws IOException {
if (position >= 16_384) {
throw new IOException("client disconnected");
}
return png[position++];
}
};
ApiException error = assertThrows(ApiException.class, () -> service.upload(
chatId, ownerId, "photo.png", "image/png", -1, source));
assertEquals(HttpStatus.BAD_REQUEST, error.status());
assertTrue(storage.objects.isEmpty());
verify(repository, never()).saveQueued(any(), any());
}
@Test
void databaseFailureCompensatesAlreadyWrittenS3Object() {
when(repository.saveQueued(any(), any())).thenThrow(new IllegalStateException("database commit failed"));
assertThrows(IllegalStateException.class, () -> service.upload(
chatId, ownerId, "photo.png", "image/png", png.length,
new ByteArrayInputStream(png)));
assertTrue(storage.objects.isEmpty(), "compensating delete must remove the orphan");
}
@Test
void downloadsOnlyAfterChatAuthorization() {
Attachment attachment = new Attachment(UUID.randomUUID(), chatId, ownerId, "photo.png",
"image/png", png.length, "a".repeat(64), "attachments/key/original",
Instant.now(), Instant.now());
when(repository.findById(attachment.id())).thenReturn(Optional.of(attachment));
storage.objects.put(attachment.objectKey(), png);
AttachmentService.Download download = service.download(attachment.id(), ownerId);
verify(chats).getAccessible(chatId, ownerId);
assertArrayEquals(png, download.bytes());
}
private static final class InMemoryStorage implements ObjectStorage {
private final Map<String, byte[]> objects = new HashMap<>();
private boolean failure;
@Override
public void put(String objectKey, byte[] bytes, String contentType) {
if (failure) throw new ObjectStorageException("S3 unavailable", new IOExceptionForTest());
objects.put(objectKey, bytes.clone());
}
@Override
public byte[] get(String objectKey) {
if (failure) throw new ObjectStorageException("S3 unavailable", new IOExceptionForTest());
return objects.get(objectKey).clone();
}
@Override
public void delete(String objectKey) {
objects.remove(objectKey);
}
@Override
public List<StoredObject> list(String prefix) {
return objects.entrySet().stream()
.filter(entry -> entry.getKey().startsWith(prefix))
.map(entry -> new StoredObject(entry.getKey(), Instant.now(), entry.getValue().length))
.toList();
}
}
private static final class IOExceptionForTest extends RuntimeException {
}
}