some
This commit is contained in:
+438
@@ -0,0 +1,438 @@
|
||||
package net.wowmine.stickers;
|
||||
|
||||
import com.google.gson.JsonParser;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.PosixFileAttributeView;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
import net.wowmine.stickers.ChatHistory.Audience;
|
||||
import net.wowmine.stickers.ChatHistory.Draft;
|
||||
import net.wowmine.stickers.ChatHistory.Entry;
|
||||
import net.wowmine.stickers.ChatHistory.Kind;
|
||||
import net.wowmine.stickers.ChatHistory.Page;
|
||||
import net.wowmine.stickers.ChatHistory.Query;
|
||||
|
||||
/** Real temporary SQLite databases; no server, cache, network, or injected storage implementation. */
|
||||
public final class ChatArchiveTest {
|
||||
private static final UUID ALICE = UUID.fromString("00000000-0000-0000-0000-000000000001");
|
||||
private static final UUID BOB = UUID.fromString("00000000-0000-0000-0000-000000000002");
|
||||
private static final ZoneId ZONE = ZoneId.of("Europe/Moscow");
|
||||
private static final String HEADER = "[25Nov2026 12:34:56.789] [Server thread/INFO] "
|
||||
+ "[net.minecraft.server.MinecraftServer/]: ";
|
||||
|
||||
private ChatArchiveTest() {}
|
||||
|
||||
public static void main(String[] arguments) throws IOException, SQLException {
|
||||
try (var fixture = new Fixture()) {
|
||||
walksUnlimitedHistoryWithCompositeCursors(fixture.root.resolve("walk"));
|
||||
keepsByteLimitedPagesNavigable(fixture.root.resolve("budget"));
|
||||
enforcesAudienceForRowsAndAttachments(fixture.root.resolve("acl"));
|
||||
persistsDeduplicatedMediaWithoutSourceCache(fixture.root.resolve("persist"));
|
||||
rejectsInvalidMediaWithoutPartialWrites(fixture.root.resolve("invalid"));
|
||||
rollsBackMetadataMediaAndAudienceOnSqlFailure(fixture.root.resolve("rollback"));
|
||||
restrictsOnlyArchiveDirectoryPermissions(fixture.root.resolve("permissions"));
|
||||
importsOnlyWhitelistedPublicChatOnce(fixture.root.resolve("logs"));
|
||||
resumesPartialMigrationWithoutDuplicatesOrNewSessions(fixture.root.resolve("resume"));
|
||||
}
|
||||
System.out.println("CHAT_ARCHIVE_PASS");
|
||||
}
|
||||
|
||||
private static void walksUnlimitedHistoryWithCompositeCursors(Path root) throws IOException, SQLException {
|
||||
var expected = new ArrayList<Entry>();
|
||||
var aliceEntries = new ArrayList<Entry>();
|
||||
try (var archive = new ChatArchive(root)) {
|
||||
for (int index = 0; index < 17_013; index++) {
|
||||
// Insertion order differs from chronology; groups of seven exercise cursor ID ties.
|
||||
Draft draft = text(946_684_800_000L + ((17_012 - index) / 7) * 1000L, "row " + index);
|
||||
Audience audience = index % 251 == 0 ? ChatHistory.PUBLIC
|
||||
: new Audience(false, index % 509 == 0 ? Set.of(ALICE, BOB) : Set.of(BOB));
|
||||
Entry entry = new Entry(archive.append(draft, audience, new byte[0]), draft);
|
||||
expected.add(entry);
|
||||
if (audience.publicMessage() || audience.recipients().contains(ALICE)) {
|
||||
aliceEntries.add(entry);
|
||||
}
|
||||
}
|
||||
Draft oldest = text(0, "oldest");
|
||||
Entry first = new Entry(archive.append(oldest, ChatHistory.PUBLIC, new byte[0]), oldest);
|
||||
expected.add(first);
|
||||
aliceEntries.add(first);
|
||||
Comparator<Entry> chronological = Comparator.comparingLong((Entry entry) -> entry.message().time())
|
||||
.thenComparingLong(Entry::id);
|
||||
expected.sort(chronological);
|
||||
aliceEntries.sort(chronological);
|
||||
equal(expected, walk(archive, BOB, true));
|
||||
equal(expected, walk(archive, BOB, false));
|
||||
equal(aliceEntries, walk(archive, ALICE, true));
|
||||
equal(aliceEntries, walk(archive, ALICE, false));
|
||||
equal(expected.subList(0, 50), archive.page(BOB, Query.earliest()).entries());
|
||||
equal(expected.subList(expected.size() - 50, expected.size()), archive.page(BOB, Query.latest()).entries());
|
||||
long time = expected.get(8000).message().time();
|
||||
var atDate = archive.page(BOB, new Query(ChatHistory.Direction.AT_DATE, time, 0));
|
||||
List<Entry> beforeDate = expected.stream().filter(entry -> entry.message().time() <= time).toList();
|
||||
equal(beforeDate.subList(beforeDate.size() - 50, beforeDate.size()), atDate.entries());
|
||||
equal(true, atDate.hasOlder());
|
||||
equal(true, atDate.hasNewer());
|
||||
Page afterEnd = archive.page(ALICE, Query.after(aliceEntries.getLast().cursor()));
|
||||
equal(List.of(), afterEnd.entries());
|
||||
equal(true, afterEnd.hasOlder());
|
||||
equal(false, afterEnd.hasNewer());
|
||||
Page beforeStart = archive.page(ALICE, Query.before(aliceEntries.getFirst().cursor()));
|
||||
equal(List.of(), beforeStart.entries());
|
||||
equal(false, beforeStart.hasOlder());
|
||||
equal(true, beforeStart.hasNewer());
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Entry> walk(ChatArchive archive, UUID requester, boolean forward) throws SQLException {
|
||||
var result = new ArrayList<Entry>();
|
||||
Page page = archive.page(requester, forward ? Query.earliest() : Query.latest());
|
||||
while (true) {
|
||||
if (page.entries().isEmpty()) {
|
||||
throw new AssertionError("Nonempty history walk reached empty window");
|
||||
}
|
||||
if (forward) {
|
||||
equal(!result.isEmpty(), page.hasOlder());
|
||||
result.addAll(page.entries());
|
||||
} else {
|
||||
equal(!result.isEmpty(), page.hasNewer());
|
||||
result.addAll(0, page.entries());
|
||||
}
|
||||
boolean more = forward ? page.hasNewer() : page.hasOlder();
|
||||
if (!more) {
|
||||
break;
|
||||
}
|
||||
if (result.size() > 18_000) {
|
||||
throw new AssertionError("Cursor walk repeats entries");
|
||||
}
|
||||
page = archive.page(requester, forward ? Query.after(page.entries().getLast().cursor())
|
||||
: Query.before(page.entries().getFirst().cursor()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void keepsByteLimitedPagesNavigable(Path root) throws IOException, SQLException {
|
||||
try (var archive = new ChatArchive(root)) {
|
||||
var expected = new ArrayList<Entry>();
|
||||
for (int index = 0; index < 11; index++) {
|
||||
Draft draft = text(index, "\u00e9".repeat(32_750));
|
||||
expected.add(new Entry(archive.append(draft, ChatHistory.PUBLIC, new byte[0]), draft));
|
||||
}
|
||||
Page earliest = archive.page(ALICE, Query.earliest());
|
||||
equal(3, earliest.entries().size());
|
||||
equal(false, earliest.hasOlder());
|
||||
equal(true, earliest.hasNewer());
|
||||
Page latest = archive.page(ALICE, Query.latest());
|
||||
equal(3, latest.entries().size());
|
||||
equal(true, latest.hasOlder());
|
||||
equal(false, latest.hasNewer());
|
||||
equal(expected, walk(archive, ALICE, true));
|
||||
equal(expected, walk(archive, ALICE, false));
|
||||
}
|
||||
}
|
||||
|
||||
private static void enforcesAudienceForRowsAndAttachments(Path root) throws IOException, SQLException {
|
||||
byte[] voice = voice();
|
||||
try (var archive = new ChatArchive(root)) {
|
||||
Draft draft = media(10, Kind.VOICE, voice, 2);
|
||||
long privateId = archive.append(draft, new Audience(false, Set.of(ALICE)), voice);
|
||||
for (Query query : List.of(Query.earliest(), Query.latest(),
|
||||
new Query(ChatHistory.Direction.AT_DATE, 10, 0),
|
||||
Query.before(new ChatHistory.Cursor(20, Long.MAX_VALUE)),
|
||||
Query.after(new ChatHistory.Cursor(0, 1)))) {
|
||||
equal(new Page(List.of(), false, false), archive.page(BOB, query));
|
||||
}
|
||||
long publicId = archive.append(text(20, "public"), ChatHistory.PUBLIC, new byte[0]);
|
||||
equal(List.of(publicId), ids(archive.page(BOB, Query.earliest())));
|
||||
equal(List.of(privateId, publicId), ids(archive.page(ALICE, Query.earliest())));
|
||||
equal(false, archive.page(BOB, Query.earliest()).hasOlder());
|
||||
Page unauthorizedDate = archive.page(BOB, new Query(ChatHistory.Direction.AT_DATE, 10, 0));
|
||||
equal(List.of(), unauthorizedDate.entries());
|
||||
equal(false, unauthorizedDate.hasOlder());
|
||||
equal(true, unauthorizedDate.hasNewer());
|
||||
equal(true, archive.attachment(BOB, privateId).isEmpty());
|
||||
equal(true, archive.attachment(BOB, publicId).isEmpty());
|
||||
equal(true, archive.attachment(BOB, Long.MAX_VALUE).isEmpty());
|
||||
equal(Kind.VOICE, archive.attachment(ALICE, privateId).orElseThrow().kind());
|
||||
bytesEqual(voice, archive.attachment(ALICE, privateId).orElseThrow().bytes());
|
||||
}
|
||||
}
|
||||
|
||||
private static void persistsDeduplicatedMediaWithoutSourceCache(Path root) throws IOException, SQLException {
|
||||
byte[] sticker = png(2);
|
||||
Path cache = root.resolve("source-cache.png");
|
||||
Files.createDirectories(root);
|
||||
Files.write(cache, sticker);
|
||||
long id;
|
||||
long restrictedId;
|
||||
long voiceId;
|
||||
byte[] voice = voice();
|
||||
try (var archive = new ChatArchive(root)) {
|
||||
Draft draft = media(100, Kind.STICKER, Files.readAllBytes(cache), 2);
|
||||
id = archive.append(draft, ChatHistory.PUBLIC, sticker);
|
||||
restrictedId = archive.append(draft, new Audience(false, Set.of(ALICE)), sticker);
|
||||
voiceId = archive.append(media(101, Kind.VOICE, voice, 2), new Audience(false, Set.of(ALICE)), voice);
|
||||
equal(2L, count(root, "media"));
|
||||
}
|
||||
Files.delete(cache);
|
||||
try (var archive = new ChatArchive(root)) {
|
||||
var attachment = archive.attachment(BOB, id).orElseThrow();
|
||||
equal(Kind.STICKER, attachment.kind());
|
||||
equal(2, attachment.frames());
|
||||
bytesEqual(sticker, attachment.bytes());
|
||||
byte[] copy = attachment.bytes();
|
||||
copy[0] ^= 1;
|
||||
bytesEqual(sticker, attachment.bytes());
|
||||
equal(List.of(id), ids(archive.page(BOB, Query.latest())));
|
||||
equal(true, archive.attachment(BOB, restrictedId).isEmpty());
|
||||
equal(true, archive.attachment(BOB, voiceId).isEmpty());
|
||||
bytesEqual(voice, archive.attachment(ALICE, voiceId).orElseThrow().bytes());
|
||||
}
|
||||
}
|
||||
|
||||
private static void rejectsInvalidMediaWithoutPartialWrites(Path root) throws IOException, SQLException {
|
||||
try (var archive = new ChatArchive(root)) {
|
||||
byte[] png = png(1);
|
||||
byte[] voice = voice();
|
||||
rejects(IllegalArgumentException.class, () -> archive.append(text(0, "text"),
|
||||
ChatHistory.PUBLIC, new byte[] {1}));
|
||||
rejects(IllegalArgumentException.class, () -> archive.append(
|
||||
new Draft(0, ALICE, "Alice", Kind.STICKER, "{}", "0".repeat(64), 1), ChatHistory.PUBLIC, png));
|
||||
rejects(IOException.class, () -> archive.append(media(0, Kind.STICKER, png, 2), ChatHistory.PUBLIC, png));
|
||||
rejects(IOException.class, () -> archive.append(media(0, Kind.VOICE, voice, 1), ChatHistory.PUBLIC, voice));
|
||||
for (byte[] invalid : List.of(new byte[] {0, 0}, new byte[] {1, 1, 0}, new byte[] {0, 2, 1})) {
|
||||
rejects(IOException.class, () -> archive.append(media(0, Kind.VOICE, invalid, 1), ChatHistory.PUBLIC, invalid));
|
||||
}
|
||||
byte[] tooLarge = new byte[ChatHistory.MEDIA_BYTES + 1];
|
||||
rejects(IllegalArgumentException.class, () -> archive.append(
|
||||
media(0, Kind.VOICE, tooLarge, 1), ChatHistory.PUBLIC, tooLarge));
|
||||
equal(0L, count(root, "entries"));
|
||||
equal(0L, count(root, "media"));
|
||||
equal(0L, count(root, "recipients"));
|
||||
long id = archive.append(media(1, Kind.VOICE, voice, 2), ChatHistory.PUBLIC, voice);
|
||||
equal(List.of(id), ids(archive.page(ALICE, Query.latest())));
|
||||
}
|
||||
var closed = new ChatArchive(root);
|
||||
closed.close();
|
||||
rejects(SQLException.class, () -> closed.page(ALICE, Query.latest()));
|
||||
}
|
||||
|
||||
private static void rollsBackMetadataMediaAndAudienceOnSqlFailure(Path root) throws IOException, SQLException {
|
||||
try (var archive = new ChatArchive(root); Connection db = database(root)) {
|
||||
execute(db, "CREATE TRIGGER fail_acl BEFORE INSERT ON recipients BEGIN SELECT RAISE(ABORT,'fixture ACL failure'); END");
|
||||
byte[] voice = voice();
|
||||
rejects(SQLException.class, () -> archive.append(media(1, Kind.VOICE, voice, 2),
|
||||
new Audience(false, Set.of(ALICE, BOB)), voice));
|
||||
equal(0L, count(root, "entries"));
|
||||
equal(0L, count(root, "media"));
|
||||
equal(0L, count(root, "recipients"));
|
||||
execute(db, "DROP TRIGGER fail_acl");
|
||||
long id = archive.append(media(1, Kind.VOICE, voice, 2), new Audience(false, Set.of(ALICE)), voice);
|
||||
equal(List.of(id), ids(archive.page(ALICE, Query.earliest())));
|
||||
equal(List.of(), ids(archive.page(BOB, Query.earliest())));
|
||||
}
|
||||
}
|
||||
|
||||
private static void importsOnlyWhitelistedPublicChatOnce(Path root) throws IOException, SQLException {
|
||||
Path logs = Files.createDirectories(root.resolve("server-logs"));
|
||||
String message = "quote \" literal {\"clickEvent\":{}} backslash \\\\";
|
||||
List<String> lines = List.of(
|
||||
HEADER + "<Alice> " + message,
|
||||
HEADER + "[Not Secure] <Bob_2> second",
|
||||
HEADER + "Alice whispers to Bob: secret",
|
||||
HEADER + "[Alice -> Bob] secret",
|
||||
HEADER + "[Admin] announcement",
|
||||
HEADER + "<Alice> /say command",
|
||||
HEADER + "<Name-With-Dash> invalid",
|
||||
HEADER.replace("Server thread/INFO", "RCON Listener #1/INFO") + "<Alice> forged",
|
||||
HEADER.replace("Server thread/INFO", "Async Chat Thread/INFO") + "<Alice> forged",
|
||||
HEADER.replace("MinecraftServer/", "dedicated.DedicatedServer/") + "<Alice> forged",
|
||||
HEADER.replace("INFO", "WARN") + "<Alice> forged",
|
||||
HEADER.replace("25Nov", "31Nov") + "<Alice> invalid date",
|
||||
HEADER + "<Alice> " + "x".repeat(100_000),
|
||||
"continuation <Alice> untrusted",
|
||||
HEADER + "<Alice> after oversized");
|
||||
Files.write(logs.resolve("a.log"), lines);
|
||||
gzip(logs.resolve("b.log.gz"), HEADER + "<Carol> compressed\n");
|
||||
Files.writeString(logs.resolve("latest.log"), HEADER + "<Active> current server is still writing\n");
|
||||
Files.writeString(logs.resolve("debug.log"), HEADER + "<Duplicate> verbose copy of public log\n");
|
||||
Files.writeString(logs.resolve("ignore.txt"), HEADER + "<Ignored> ignored\n");
|
||||
try (var archive = new ChatArchive(root.resolve("archive"))) {
|
||||
equal(4, ArchiveLogImport.importOnce(archive, logs, ZONE));
|
||||
var entries = archive.page(BOB, Query.earliest()).entries();
|
||||
equal(List.of("Alice", "Bob_2", "Alice", "Carol"), entries.stream().map(entry -> entry.message().name()).toList());
|
||||
equal(message, JsonParser.parseString(entries.getFirst().message().body())
|
||||
.getAsJsonObject().get("text").getAsString());
|
||||
equal(Set.of("text"), JsonParser.parseString(entries.getFirst().message().body()).getAsJsonObject().keySet());
|
||||
equal(UUID.nameUUIDFromBytes("OfflinePlayer:Alice".getBytes(StandardCharsets.UTF_8)),
|
||||
entries.getFirst().message().author());
|
||||
equal(LocalDateTime.of(2026, 11, 25, 12, 34, 56, 789_000_000).atZone(ZONE).toInstant().toEpochMilli(),
|
||||
entries.getFirst().message().time());
|
||||
}
|
||||
Files.writeString(logs.resolve("a.log"), HEADER + "<NewSession> already live\n");
|
||||
try (var archive = new ChatArchive(root.resolve("archive"))) {
|
||||
equal(0, ArchiveLogImport.importOnce(archive, logs, ZONE));
|
||||
equal(4, archive.page(ALICE, Query.latest()).entries().size());
|
||||
}
|
||||
}
|
||||
|
||||
private static void resumesPartialMigrationWithoutDuplicatesOrNewSessions(Path root) throws IOException, SQLException {
|
||||
Path logs = Files.createDirectories(root.resolve("logs"));
|
||||
Path dbRoot = root.resolve("archive");
|
||||
Files.writeString(logs.resolve("old.log"), HEADER + "<Alice> first\n" + HEADER + "<Bob> second\n");
|
||||
try (var archive = new ChatArchive(dbRoot); Connection db = database(dbRoot)) {
|
||||
execute(db, """
|
||||
CREATE TRIGGER interrupt_import BEFORE INSERT ON entries WHEN NEW.name='Bob'
|
||||
BEGIN SELECT RAISE(ABORT,'fixture migration interruption'); END
|
||||
""");
|
||||
rejects(SQLException.class, () -> ArchiveLogImport.importOnce(archive, logs, ZONE));
|
||||
equal(List.of("Alice"), archive.page(ALICE, Query.latest()).entries().stream()
|
||||
.map(entry -> entry.message().name()).toList());
|
||||
execute(db, "DROP TRIGGER interrupt_import");
|
||||
}
|
||||
// Rotation/recompression preserves decompressed source identity; newly created sessions stay excluded.
|
||||
gzip(logs.resolve("rotated.log.gz"), Files.readString(logs.resolve("old.log")));
|
||||
Files.delete(logs.resolve("old.log"));
|
||||
Files.writeString(logs.resolve("latest.log"), HEADER + "<NewSession> do not import\n");
|
||||
try (var archive = new ChatArchive(dbRoot)) {
|
||||
equal(1, ArchiveLogImport.importOnce(archive, logs, ZONE));
|
||||
equal(List.of("Alice", "Bob"), archive.page(ALICE, Query.earliest()).entries().stream()
|
||||
.map(entry -> entry.message().name()).toList());
|
||||
equal(0, ArchiveLogImport.importOnce(archive, logs, ZONE));
|
||||
}
|
||||
}
|
||||
|
||||
private static Draft text(long time, String body) {
|
||||
var component = new com.google.gson.JsonObject();
|
||||
component.addProperty("text", body);
|
||||
return new Draft(time, ALICE, "Alice", Kind.TEXT, component.toString(), "", 0);
|
||||
}
|
||||
|
||||
private static void restrictsOnlyArchiveDirectoryPermissions(Path root) throws IOException, SQLException {
|
||||
Files.createDirectories(root);
|
||||
var parentPermissions = Files.getFileAttributeView(root, PosixFileAttributeView.class);
|
||||
var before = parentPermissions == null ? Set.of() : parentPermissions.readAttributes().permissions();
|
||||
Path archiveRoot = root.resolve("archive");
|
||||
try (var archive = new ChatArchive(archiveRoot)) {
|
||||
equal(List.of(), archive.page(ALICE, Query.latest()).entries());
|
||||
var permissions = Files.getFileAttributeView(archiveRoot, PosixFileAttributeView.class);
|
||||
if (permissions != null) {
|
||||
equal(PosixFilePermissions.fromString("rwx------"), permissions.readAttributes().permissions());
|
||||
equal(before, parentPermissions.readAttributes().permissions());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Draft media(long time, Kind kind, byte[] bytes, int frames) {
|
||||
return new Draft(time, ALICE, "Alice", kind, "{\"text\":\"media\"}", ChatArchive.sha256(bytes), frames);
|
||||
}
|
||||
|
||||
private static byte[] voice() {
|
||||
return VoiceFrames.encode(List.of(new byte[] {1, 2}, new byte[] {3, 4, 5}));
|
||||
}
|
||||
|
||||
private static byte[] png(int frames) throws IOException {
|
||||
var image = new BufferedImage(Math.min(frames, 8) * 128,
|
||||
((frames + Math.min(frames, 8) - 1) / Math.min(frames, 8)) * 128, BufferedImage.TYPE_INT_ARGB);
|
||||
try (var output = new ByteArrayOutputStream()) {
|
||||
if (!ImageIO.write(image, "png", output)) {
|
||||
throw new IOException("No PNG writer");
|
||||
}
|
||||
return output.toByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
private static void gzip(Path path, String text) throws IOException {
|
||||
try (var output = new GZIPOutputStream(Files.newOutputStream(path))) {
|
||||
output.write(text.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
|
||||
private static Connection database(Path root) throws SQLException {
|
||||
return DriverManager.getConnection("jdbc:sqlite:" + root.resolve("chat-archive.sqlite").toAbsolutePath());
|
||||
}
|
||||
|
||||
private static long count(Path root, String table) throws SQLException {
|
||||
try (Connection db = database(root); var sql = db.createStatement();
|
||||
var row = sql.executeQuery("SELECT count(*) FROM " + table)) {
|
||||
if (!row.next()) {
|
||||
throw new SQLException("Missing count row");
|
||||
}
|
||||
return row.getLong(1);
|
||||
}
|
||||
}
|
||||
|
||||
private static void execute(Connection db, String statement) throws SQLException {
|
||||
try (var sql = db.createStatement()) {
|
||||
sql.execute(statement);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Long> ids(Page page) {
|
||||
return page.entries().stream().map(Entry::id).toList();
|
||||
}
|
||||
|
||||
private static void equal(Object expected, Object actual) {
|
||||
if (!expected.equals(actual)) {
|
||||
throw new AssertionError("Expected " + expected + ", got " + actual);
|
||||
}
|
||||
}
|
||||
|
||||
private static void bytesEqual(byte[] expected, byte[] actual) {
|
||||
if (!Arrays.equals(expected, actual)) {
|
||||
throw new AssertionError("Archive changed binary media");
|
||||
}
|
||||
}
|
||||
|
||||
private static void rejects(Class<? extends Exception> expected, Action action) throws IOException, SQLException {
|
||||
try {
|
||||
action.run();
|
||||
} catch (IOException | SQLException | IllegalArgumentException error) {
|
||||
if (expected.isInstance(error)) {
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
throw new AssertionError("Expected rejection: " + expected.getSimpleName());
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface Action {
|
||||
void run() throws IOException, SQLException;
|
||||
}
|
||||
|
||||
private static final class Fixture implements AutoCloseable {
|
||||
private final Path root;
|
||||
|
||||
private Fixture() throws IOException {
|
||||
root = Files.createTempDirectory("wowmine-chat-archive-");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
try (var paths = Files.walk(root)) {
|
||||
for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) {
|
||||
Files.delete(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
package net.wowmine.stickers;
|
||||
|
||||
import io.netty.buffer.Unpooled;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
|
||||
/** Real wire contracts for long cursors, bounded metadata and independent media transfers. */
|
||||
public final class HistoryProtocolTest {
|
||||
private static final UUID AUTHOR = UUID.fromString("bb0c26de-752c-4f0f-b5da-8be7a5d46c91");
|
||||
|
||||
private HistoryProtocolTest() {}
|
||||
|
||||
public static void main(String[] arguments) {
|
||||
cursorsDoNotTruncateAcrossYearsOrIntegerLimits();
|
||||
pagesPreserveAllKindsAndNavigation();
|
||||
rejectsUnboundedMetadataBeforeReadingEntries();
|
||||
attachmentWirePreservesBytesAndLimits();
|
||||
System.out.println("HISTORY_PROTOCOL_PASS");
|
||||
}
|
||||
|
||||
private static void cursorsDoNotTruncateAcrossYearsOrIntegerLimits() {
|
||||
for (var query : List.of(ChatHistory.Query.latest(), ChatHistory.Query.earliest(),
|
||||
new ChatHistory.Query(ChatHistory.Direction.BEFORE, 946_684_800_000L, 4_294_967_299L),
|
||||
new ChatHistory.Query(ChatHistory.Direction.AFTER, 946_684_800_000L, 4_294_967_299L),
|
||||
new ChatHistory.Query(ChatHistory.Direction.AT_DATE, 4_102_444_800_000L, 0))) {
|
||||
var buffer = buffer();
|
||||
try {
|
||||
var original = new HistoryPackets.PageRequest(8_589_934_599L, query);
|
||||
HistoryPackets.PageRequest.CODEC.encode(buffer, original);
|
||||
equal(original, HistoryPackets.PageRequest.CODEC.decode(buffer));
|
||||
equal(0, buffer.readableBytes());
|
||||
} finally {
|
||||
buffer.release();
|
||||
}
|
||||
}
|
||||
rejects(() -> new ChatHistory.Query(ChatHistory.Direction.BEFORE, 1, 0));
|
||||
rejects(() -> new ChatHistory.Query(ChatHistory.Direction.AT_DATE, -1, 0));
|
||||
rejects(() -> new ChatHistory.Query(ChatHistory.Direction.LATEST, 1, 1));
|
||||
}
|
||||
|
||||
private static void pagesPreserveAllKindsAndNavigation() {
|
||||
var entries = List.of(
|
||||
entry(4_294_967_300L, 1, ChatHistory.Kind.TEXT, "{\"text\":\"old text\"}", "", 0),
|
||||
entry(4_294_967_301L, 1, ChatHistory.Kind.STICKER, "{\"text\":\"\"}", "a".repeat(64), 60),
|
||||
entry(4_294_967_302L, 2, ChatHistory.Kind.VOICE, "{\"text\":\"team\"}", "b".repeat(64), 15_000));
|
||||
var original = new HistoryPackets.PageReply(21, new ChatHistory.Page(entries, true, true));
|
||||
var buffer = buffer();
|
||||
try {
|
||||
HistoryPackets.PageReply.CODEC.encode(buffer, original);
|
||||
equal(original, HistoryPackets.PageReply.CODEC.decode(buffer));
|
||||
equal(0, buffer.readableBytes());
|
||||
} finally {
|
||||
buffer.release();
|
||||
}
|
||||
rejects(() -> new ChatHistory.Page(List.of(entries.get(2), entries.get(0)), false, false));
|
||||
}
|
||||
|
||||
private static void rejectsUnboundedMetadataBeforeReadingEntries() {
|
||||
var buffer = buffer();
|
||||
try {
|
||||
buffer.writeLong(1);
|
||||
buffer.writeVarInt(ChatHistory.PAGE_SIZE + 1);
|
||||
rejects(() -> HistoryPackets.PageReply.CODEC.decode(buffer));
|
||||
} finally {
|
||||
buffer.release();
|
||||
}
|
||||
var oversized = buffer();
|
||||
try {
|
||||
oversized.writeLong(1);
|
||||
oversized.writeVarInt(5);
|
||||
String body = "{\"text\":\"" + "\u03bb".repeat(30_000) + "\"}";
|
||||
for (int index = 0; index < 5; index++) {
|
||||
oversized.writeLong(index + 1);
|
||||
oversized.writeLong(index);
|
||||
oversized.writeUUID(AUTHOR);
|
||||
oversized.writeUtf("ArchiveQA", 64);
|
||||
oversized.writeEnum(ChatHistory.Kind.TEXT);
|
||||
oversized.writeUtf(body, ChatHistory.BODY_CHARACTERS);
|
||||
oversized.writeUtf("", 64);
|
||||
oversized.writeVarInt(0);
|
||||
}
|
||||
oversized.writeBoolean(false);
|
||||
oversized.writeBoolean(false);
|
||||
rejects(() -> HistoryPackets.PageReply.CODEC.decode(oversized));
|
||||
} finally {
|
||||
oversized.release();
|
||||
}
|
||||
}
|
||||
|
||||
private static void attachmentWirePreservesBytesAndLimits() {
|
||||
byte[] bytes = new byte[HistoryPackets.CHUNK_BYTES];
|
||||
Arrays.fill(bytes, (byte) 73);
|
||||
var original = new HistoryPackets.AttachmentChunk(91, "c".repeat(64), 0, bytes.length + 3, bytes);
|
||||
bytes[0] = 0;
|
||||
var buffer = buffer();
|
||||
try {
|
||||
HistoryPackets.AttachmentChunk.CODEC.encode(buffer, original);
|
||||
var decoded = HistoryPackets.AttachmentChunk.CODEC.decode(buffer);
|
||||
equal(91L, decoded.request());
|
||||
equal("c".repeat(64), decoded.id());
|
||||
equal(0, decoded.part());
|
||||
equal(HistoryPackets.CHUNK_BYTES + 3, decoded.totalBytes());
|
||||
if (!Arrays.equals(original.bytes(), decoded.bytes()) || decoded.bytes()[0] != 73) {
|
||||
throw new AssertionError("Archive attachment wire changed bytes or retained mutable input");
|
||||
}
|
||||
equal(0, buffer.readableBytes());
|
||||
} finally {
|
||||
buffer.release();
|
||||
}
|
||||
new HistoryPackets.AttachmentChunk(92, "d".repeat(64), 1, HistoryPackets.CHUNK_BYTES + 3, new byte[3]);
|
||||
rejects(() -> new HistoryPackets.AttachmentChunk(0, "a".repeat(64), 0, 1, new byte[1]));
|
||||
rejects(() -> new HistoryPackets.AttachmentChunk(1, "a".repeat(64), -1, 1, new byte[1]));
|
||||
rejects(() -> new HistoryPackets.AttachmentChunk(1, "a".repeat(64), 1, 1, new byte[1]));
|
||||
rejects(() -> new HistoryPackets.AttachmentChunk(1, "a".repeat(64), 0,
|
||||
ChatHistory.MEDIA_BYTES + 1, new byte[1]));
|
||||
rejects(() -> new HistoryPackets.AttachmentChunk(1, "../private", 0, 1, new byte[1]));
|
||||
rejects(() -> new HistoryPackets.AttachmentChunk(1, "a".repeat(64), 0, 10, new byte[9]));
|
||||
}
|
||||
|
||||
private static ChatHistory.Entry entry(long id, long time, ChatHistory.Kind kind,
|
||||
String body, String attachment, int frames) {
|
||||
return new ChatHistory.Entry(id, new ChatHistory.Draft(
|
||||
time, AUTHOR, "ArchiveQA", kind, body, attachment, frames));
|
||||
}
|
||||
|
||||
private static RegistryFriendlyByteBuf buffer() {
|
||||
return new RegistryFriendlyByteBuf(Unpooled.buffer(), RegistryAccess.EMPTY);
|
||||
}
|
||||
|
||||
private static void equal(Object expected, Object actual) {
|
||||
if (!expected.equals(actual)) {
|
||||
throw new AssertionError("Expected " + expected + " but got " + actual);
|
||||
}
|
||||
}
|
||||
|
||||
private static void rejects(Runnable action) {
|
||||
try {
|
||||
action.run();
|
||||
} catch (IllegalArgumentException expected) {
|
||||
return;
|
||||
}
|
||||
throw new AssertionError("Invalid archive protocol input accepted");
|
||||
}
|
||||
}
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
package net.wowmine.stickers;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import javax.imageio.ImageIO;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
|
||||
/** Runs against real codecs and files without a fake Minecraft server. */
|
||||
public final class StickerProtocolTest {
|
||||
private StickerProtocolTest() {}
|
||||
|
||||
public static void main(String[] arguments) throws IOException {
|
||||
acceptsPublicPackNames();
|
||||
rejectsNonPackNetworkTargets();
|
||||
chunkWirePreservesBytes();
|
||||
messageWirePreservesServerAuthor();
|
||||
rejectsMalformedChunks();
|
||||
servesOnlyCataloguedContentAddressedPngs();
|
||||
rejectsWrongAtlasDimensions();
|
||||
System.out.println("STICKER_PROTOCOL_PASS");
|
||||
}
|
||||
|
||||
private static void acceptsPublicPackNames() {
|
||||
for (String input : List.of("Pack_Name", "https://t.me/addstickers/Pack_Name",
|
||||
" https://t.me/addstickers/Pack_Name ")) {
|
||||
equal("Pack_Name", TelegramPack.fromInput(input).name());
|
||||
}
|
||||
}
|
||||
|
||||
private static void rejectsNonPackNetworkTargets() {
|
||||
for (String input : List.of("https://localhost/addstickers/Pack_Name",
|
||||
"https://t.me.attacker.test/addstickers/Pack_Name",
|
||||
"https://t.me:443/addstickers/Pack_Name",
|
||||
"https://user:secret@t.me/addstickers/Pack_Name",
|
||||
"https://t.me/addstickers/../secret", "https://t.me/addstickers/a%2fb",
|
||||
"https://t.me/addstickers/Pack_Name?redirect=localhost",
|
||||
"https://t.me/addstickers/Pack_Name#extra",
|
||||
"http://t.me/addstickers/Pack_Name", "file:///etc/passwd",
|
||||
"https://t.me/SomeUser", "https://t.me/addstickers/", "")) {
|
||||
rejects(() -> TelegramPack.fromInput(input));
|
||||
}
|
||||
}
|
||||
|
||||
private static void chunkWirePreservesBytes() {
|
||||
byte[] source = new byte[24_576];
|
||||
Arrays.fill(source, (byte) 37);
|
||||
RegistryFriendlyByteBuf buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), RegistryAccess.EMPTY);
|
||||
try {
|
||||
var original = new StickerPackets.AssetChunk("a".repeat(64), 0, 2, source);
|
||||
StickerPackets.AssetChunk.CODEC.encode(buffer, original);
|
||||
var received = StickerPackets.AssetChunk.CODEC.decode(buffer);
|
||||
equal(original.id(), received.id());
|
||||
equal(0, received.part());
|
||||
equal(2, received.total());
|
||||
if (!Arrays.equals(source, received.bytes()) || buffer.readableBytes() != 0) {
|
||||
throw new AssertionError("Chunk codec lost bytes or left an unread payload");
|
||||
}
|
||||
} finally {
|
||||
buffer.release();
|
||||
}
|
||||
}
|
||||
|
||||
private static void messageWirePreservesServerAuthor() {
|
||||
var original = new StickerPackets.StickerMessage(
|
||||
UUID.fromString("12345678-1234-1234-1234-123456789abc"), "StickerQA", "b".repeat(64));
|
||||
RegistryFriendlyByteBuf buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), RegistryAccess.EMPTY);
|
||||
try {
|
||||
StickerPackets.StickerMessage.CODEC.encode(buffer, original);
|
||||
equal(original, StickerPackets.StickerMessage.CODEC.decode(buffer));
|
||||
} finally {
|
||||
buffer.release();
|
||||
}
|
||||
}
|
||||
|
||||
private static void rejectsMalformedChunks() {
|
||||
String id = "a".repeat(64);
|
||||
rejects(() -> new StickerPackets.AssetChunk(id, -1, 1, new byte[1]));
|
||||
rejects(() -> new StickerPackets.AssetChunk(id, 1, 1, new byte[1]));
|
||||
rejects(() -> new StickerPackets.AssetChunk(id, 0, 87, new byte[24_576]));
|
||||
rejects(() -> new StickerPackets.AssetChunk(id, 0, 1, new byte[0]));
|
||||
rejects(() -> new StickerPackets.AssetChunk(id, 0, 1, new byte[24_577]));
|
||||
rejects(() -> new StickerPackets.AssetChunk(id, 0, 2, new byte[3]));
|
||||
rejects(() -> new StickerPackets.AssetRequest("../secret"));
|
||||
}
|
||||
|
||||
private static void servesOnlyCataloguedContentAddressedPngs() throws IOException {
|
||||
Path root = Files.createTempDirectory("wowmine-sticker-protocol-");
|
||||
try {
|
||||
byte[] png = png(128);
|
||||
String id = hash(png);
|
||||
Files.createDirectory(root.resolve("assets"));
|
||||
Path asset = root.resolve("assets").resolve(id + ".png");
|
||||
Files.write(asset, png);
|
||||
writeCatalog(root, List.of(new StickerCatalog.Sticker(id, "", 1)));
|
||||
if (!Arrays.equals(png, ServerCatalog.load(root).asset(id))) {
|
||||
throw new AssertionError("Server changed validated PNG bytes");
|
||||
}
|
||||
writeCatalog(root, List.of());
|
||||
rejectsIo(() -> ServerCatalog.load(root).asset(id));
|
||||
writeCatalog(root, List.of(new StickerCatalog.Sticker(id, "", 1)));
|
||||
png[png.length - 1] ^= 1;
|
||||
Files.write(asset, png);
|
||||
rejectsIo(() -> ServerCatalog.load(root).asset(id));
|
||||
} finally {
|
||||
removeFixture(root);
|
||||
}
|
||||
}
|
||||
|
||||
private static void rejectsWrongAtlasDimensions() throws IOException {
|
||||
Path root = Files.createTempDirectory("wowmine-sticker-dimensions-");
|
||||
try {
|
||||
byte[] png = png(64);
|
||||
String id = hash(png);
|
||||
Files.createDirectory(root.resolve("assets"));
|
||||
Files.write(root.resolve("assets").resolve(id + ".png"), png);
|
||||
writeCatalog(root, List.of(new StickerCatalog.Sticker(id, "", 1)));
|
||||
rejectsIo(() -> ServerCatalog.load(root).asset(id));
|
||||
} finally {
|
||||
removeFixture(root);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] png(int width) throws IOException {
|
||||
var image = new BufferedImage(width, 128, BufferedImage.TYPE_INT_ARGB);
|
||||
image.setRGB(0, 0, 0xff336699);
|
||||
try (var output = new java.io.ByteArrayOutputStream()) {
|
||||
if (!ImageIO.write(image, "png", output)) {
|
||||
throw new IOException("No PNG writer in test runtime");
|
||||
}
|
||||
return output.toByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
private static String hash(byte[] bytes) {
|
||||
try {
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
|
||||
} catch (NoSuchAlgorithmException error) {
|
||||
throw new AssertionError(error);
|
||||
}
|
||||
}
|
||||
|
||||
private static void writeCatalog(Path root, List<StickerCatalog.Sticker> stickers) throws IOException {
|
||||
var catalog = new StickerCatalog(1, List.of(new StickerCatalog.Pack("Fixture", "Fixture", stickers)));
|
||||
Files.writeString(root.resolve("catalog.json"), new Gson().toJson(catalog));
|
||||
}
|
||||
|
||||
private static void removeFixture(Path root) throws IOException {
|
||||
try (var paths = Files.walk(root)) {
|
||||
for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) {
|
||||
Files.delete(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void rejects(Runnable action) {
|
||||
try {
|
||||
action.run();
|
||||
} catch (IllegalArgumentException expected) {
|
||||
return;
|
||||
}
|
||||
throw new AssertionError("Invalid protocol input was accepted");
|
||||
}
|
||||
|
||||
private static void rejectsIo(IoAction action) throws IOException {
|
||||
try {
|
||||
action.run();
|
||||
} catch (IOException expected) {
|
||||
return;
|
||||
}
|
||||
throw new AssertionError("Invalid catalog asset was served");
|
||||
}
|
||||
|
||||
private static void equal(Object expected, Object actual) {
|
||||
if (!expected.equals(actual)) {
|
||||
throw new AssertionError("Expected " + expected + ", got " + actual);
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface IoAction {
|
||||
void run() throws IOException;
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
package net.wowmine.stickers;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/** Main-style protocol tests; exercises the real archive container, without an audio device. */
|
||||
public final class VoiceFramesTest {
|
||||
private VoiceFramesTest() {}
|
||||
|
||||
public static void main(String[] arguments) {
|
||||
preservesExactOpusBytesAndFrameOrder();
|
||||
acceptsMaximumDurationAndFrameSize();
|
||||
rejectsInvalidFrameInputs();
|
||||
rejectsMalformedContainers();
|
||||
snapshotsBothBoundaries();
|
||||
System.out.println("VOICE_FRAMES_PASS");
|
||||
}
|
||||
|
||||
private static void preservesExactOpusBytesAndFrameOrder() {
|
||||
List<byte[]> frames = List.of(new byte[] {(byte) 0xf8, (byte) 0xff, (byte) 0xfe},
|
||||
new byte[] {0, 1, (byte) 0x80});
|
||||
byte[] expected = {0x57, 0x56, 0x4f, 0x31, 0, 0, 0, 2,
|
||||
0, 3, (byte) 0xf8, (byte) 0xff, (byte) 0xfe, 0, 3, 0, 1, (byte) 0x80};
|
||||
equalBytes(expected, VoiceFrames.encode(frames));
|
||||
equalFrames(frames, VoiceFrames.decode(expected));
|
||||
}
|
||||
|
||||
private static void acceptsMaximumDurationAndFrameSize() {
|
||||
byte[] frame = new byte[ChatHistory.VOICE_FRAME_BYTES];
|
||||
for (int index = 0; index < frame.length; index++) {
|
||||
frame[index] = (byte) index;
|
||||
}
|
||||
List<byte[]> frames = Collections.nCopies(ChatHistory.VOICE_FRAMES, frame);
|
||||
byte[] packed = VoiceFrames.encode(frames);
|
||||
if (packed.length != 8 + ChatHistory.VOICE_FRAMES * (2 + frame.length)) {
|
||||
throw new AssertionError("Maximum voice container lost framing or payload bytes");
|
||||
}
|
||||
equalFrames(frames, VoiceFrames.decode(packed));
|
||||
}
|
||||
|
||||
private static void rejectsInvalidFrameInputs() {
|
||||
for (List<byte[]> frames : List.<List<byte[]>>of(
|
||||
List.of(),
|
||||
Collections.nCopies(ChatHistory.VOICE_FRAMES + 1, new byte[] {1}),
|
||||
List.of(new byte[0]),
|
||||
List.of(new byte[ChatHistory.VOICE_FRAME_BYTES + 1]),
|
||||
Arrays.asList(new byte[] {1}, null))) {
|
||||
rejects(() -> VoiceFrames.encode(frames));
|
||||
}
|
||||
rejects(() -> VoiceFrames.encode(null));
|
||||
}
|
||||
|
||||
private static void rejectsMalformedContainers() {
|
||||
byte[] valid = VoiceFrames.encode(List.of(new byte[] {1, 2}, new byte[] {3}));
|
||||
for (int length = 0; length < valid.length; length++) {
|
||||
byte[] truncated = Arrays.copyOf(valid, length);
|
||||
rejects(() -> VoiceFrames.decode(truncated));
|
||||
}
|
||||
for (int count : new int[] {0, -1, ChatHistory.VOICE_FRAMES + 1, Integer.MAX_VALUE}) {
|
||||
byte[] badCount = valid.clone();
|
||||
ByteBuffer.wrap(badCount).putInt(4, count);
|
||||
rejects(() -> VoiceFrames.decode(badCount));
|
||||
}
|
||||
for (int length : new int[] {0, ChatHistory.VOICE_FRAME_BYTES + 1, 65_535}) {
|
||||
byte[] badLength = valid.clone();
|
||||
ByteBuffer.wrap(badLength).putShort(8, (short) length);
|
||||
rejects(() -> VoiceFrames.decode(badLength));
|
||||
}
|
||||
byte[] unknownVersion = valid.clone();
|
||||
unknownVersion[3]++;
|
||||
rejects(() -> VoiceFrames.decode(unknownVersion));
|
||||
rejects(() -> VoiceFrames.decode(Arrays.copyOf(valid, valid.length + 1)));
|
||||
rejects(() -> VoiceFrames.decode(new byte[ChatHistory.MEDIA_BYTES + 1]));
|
||||
rejects(() -> VoiceFrames.decode(null));
|
||||
}
|
||||
|
||||
private static void snapshotsBothBoundaries() {
|
||||
byte[] source = {3, 7, 11};
|
||||
var frames = new ArrayList<byte[]>();
|
||||
frames.add(source);
|
||||
byte[] packed = VoiceFrames.encode(frames);
|
||||
source[0] = 99;
|
||||
frames.clear();
|
||||
List<byte[]> decoded = VoiceFrames.decode(packed);
|
||||
Arrays.fill(packed, (byte) 0);
|
||||
decoded.getFirst()[0] = 42;
|
||||
decoded.iterator().next()[1] = 42;
|
||||
equalFrames(List.of(new byte[] {3, 7, 11}), decoded);
|
||||
try {
|
||||
decoded.set(0, new byte[] {99});
|
||||
} catch (UnsupportedOperationException expected) {
|
||||
return;
|
||||
}
|
||||
throw new AssertionError("Decoded frame list permits structural mutation");
|
||||
}
|
||||
|
||||
private static void equalFrames(List<byte[]> expected, List<byte[]> actual) {
|
||||
if (expected.size() != actual.size()) {
|
||||
throw new AssertionError("Frame count changed");
|
||||
}
|
||||
for (int index = 0; index < expected.size(); index++) {
|
||||
equalBytes(expected.get(index), actual.get(index));
|
||||
}
|
||||
}
|
||||
|
||||
private static void equalBytes(byte[] expected, byte[] actual) {
|
||||
if (!Arrays.equals(expected, actual)) {
|
||||
throw new AssertionError("Voice bytes changed");
|
||||
}
|
||||
}
|
||||
|
||||
private static void rejects(Runnable action) {
|
||||
try {
|
||||
action.run();
|
||||
} catch (IllegalArgumentException expected) {
|
||||
return;
|
||||
}
|
||||
throw new AssertionError("Malformed voice data was accepted");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user