Last active
January 25, 2024 11:18
-
-
Save kazuhito-m/f6214ab82aac1ceb0a32e1a9e96794bc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.jupiter.api.Test; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import java.util.Map; | |
import java.util.UUID; | |
import java.util.function.Predicate; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
import static org.assertj.core.api.Assertions.assertThat; | |
/** | |
* 「UUIDかどうかのチェック」を正規表現で行った場合とUUIDクラスで行った場合の結果の違いを確認するテスト。 | |
*/ | |
class CheckUuidTest { | |
private static final Logger LOGGER = LoggerFactory.getLogger(CheckUuidTest.class); | |
@Test | |
void 同じか否か() { | |
Map<String, Predicate<String>> funcs = Map.of( | |
"UUIDのを使ったやつ", this::useUuid, | |
"正規表現使ったやつ", this::useRegex | |
); | |
Map<String, Boolean> cases = Map.of( | |
"", false, | |
"aBCdEf01-Ef01-234a-BcD5-E6f789012345", true, | |
"00000000-0000-0000-0000-00000000000", false, | |
"00000000-0000-0000-0000-", false, | |
"00000000-0000-0000-0000-0", false, // UUID型は許容する | |
"0-0-0-0-0", false, // UUID型は許容する | |
"00000000-0000-0000-0000-000000000001", true, | |
"00000000-0000-0000-0000-00000000000G", false, | |
"00000000-0000-0000-0000-000000000000", true | |
); | |
int i = 0; | |
for (var c : cases.entrySet()) { | |
LOGGER.debug("{}: value:{}, expect:{}", ++i, c.getKey(), c.getValue()); | |
for (var f : funcs.entrySet()) { | |
var actual = f.getValue().test(c.getKey()); | |
var expect = c.getValue().booleanValue(); | |
assertThat(actual) | |
.as(f.getKey() + "側のテスト-値:" + c.getKey() + ",期待値:" + expect) | |
.isEqualTo(expect); | |
} | |
} | |
} | |
private boolean useUuid(String text) { | |
// コレ付けるとほぼ一緒になる if (text.length() != 36) return false; | |
try { | |
UUID.fromString(text); | |
return true; | |
} catch (IllegalArgumentException e) { | |
return false; | |
} | |
} | |
private static final Pattern PATTERN_UUID = Pattern.compile("[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}"); | |
private boolean useRegex(String text) { | |
Matcher m = PATTERN_UUID.matcher(text); | |
return m.find(); | |
} | |
@Test | |
void 等号でStringやIntegerみたいに同一参照に成り得るのか() { | |
var uuid1 = UUID.fromString("00000000-0000-0000-0000-000000000000"); | |
var uuid2 = UUID.fromString("00000000-0000-0000-0000-000000000000"); | |
assertThat(uuid1 == uuid2).isFalse(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment