package com.linkerbot.vibemake.common; import static org.assertj.core.api.Assertions.*; import org.junit.jupiter.api.Test; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.HashSet; import java.util.Set; class ProjectCodesTest { @Test void randomCodesAndOtherIdentifiersStaySeparate() { Set codes = new HashSet<>(); for (int i = 0; i < 10000; i++) { String code = ProjectCodes.next(); assertThat(code).matches("[0-9abcdefghjkmnpqrstvwxyz]{12}"); assertThat(codes.add(code)).isTrue(); } assertThat(Codes.next()).matches("[a-f0-9]{32}"); } @Test void importUsesExactlyFirstSixtySha256Bits() throws Exception { byte[] hash = MessageDigest.getInstance("SHA-256") .digest("github-import:v1:12345".getBytes(StandardCharsets.UTF_8)); BigInteger firstSixty = new BigInteger(1, hash).shiftRight(196); StringBuilder expected = new StringBuilder(); for (int i = 11; i >= 0; i--) expected.append( ProjectCodes.ALPHABET.charAt(firstSixty.shiftRight(i * 5).intValue() & 31)); assertThat(ProjectCodes.github(12345)).isEqualTo(expected.toString()); assertThat(ProjectCodes.github(12345)).isNotEqualTo(ProjectCodes.github(12346)); assertThatThrownBy(() -> ProjectCodes.github(0)) .isInstanceOf(IllegalArgumentException.class); } @Test void reimportsUseDistinctStableCodesWhilePreservingFirstImportCodes() { assertThat(ProjectCodes.github(12345, 0)).isEqualTo(ProjectCodes.github(12345)); assertThat(ProjectCodes.github(12345, 1)).isEqualTo(ProjectCodes.github(12345, 1)) .matches("[0-9abcdefghjkmnpqrstvwxyz]{12}") .isNotEqualTo(ProjectCodes.github(12345)) .isNotEqualTo(ProjectCodes.github(12345, 2)) .isNotEqualTo(ProjectCodes.github(12346, 1)); assertThatThrownBy(() -> ProjectCodes.github(12345, -1)) .isInstanceOf(IllegalArgumentException.class); } }