1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
|
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.testing.SerializableTester.reserialize;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.testing.CollectionTestSuiteBuilder;
import com.google.common.collect.testing.ListTestSuiteBuilder;
import com.google.common.collect.testing.MapInterfaceTest;
import com.google.common.collect.testing.MapTestSuiteBuilder;
import com.google.common.collect.testing.MinimalSet;
import com.google.common.collect.testing.SampleElements.Colliders;
import com.google.common.collect.testing.SampleElements.Unhashables;
import com.google.common.collect.testing.UnhashableObject;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import com.google.common.collect.testing.google.MapGenerators.ImmutableMapCopyOfEntriesGenerator;
import com.google.common.collect.testing.google.MapGenerators.ImmutableMapCopyOfEnumMapGenerator;
import com.google.common.collect.testing.google.MapGenerators.ImmutableMapCopyOfGenerator;
import com.google.common.collect.testing.google.MapGenerators.ImmutableMapEntryListGenerator;
import com.google.common.collect.testing.google.MapGenerators.ImmutableMapGenerator;
import com.google.common.collect.testing.google.MapGenerators.ImmutableMapKeyListGenerator;
import com.google.common.collect.testing.google.MapGenerators.ImmutableMapUnhashableValuesGenerator;
import com.google.common.collect.testing.google.MapGenerators.ImmutableMapValueListGenerator;
import com.google.common.collect.testing.google.MapGenerators.ImmutableMapValuesAsSingletonSetGenerator;
import com.google.common.testing.EqualsTester;
import com.google.common.testing.NullPointerTester;
import com.google.common.testing.SerializableTester;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Tests for {@link ImmutableMap}.
*
* @author Kevin Bourrillion
* @author Jesse Wilson
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("AlwaysThrows")
public class ImmutableMapTest extends TestCase {
@GwtIncompatible // suite
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTestSuite(ImmutableMapTest.class);
suite.addTest(
MapTestSuiteBuilder.using(new ImmutableMapGenerator())
.withFeatures(
CollectionSize.ANY,
CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS,
CollectionFeature.KNOWN_ORDER,
MapFeature.REJECTS_DUPLICATES_AT_CREATION,
CollectionFeature.ALLOWS_NULL_QUERIES)
.named("ImmutableMap")
.createTestSuite());
suite.addTest(
MapTestSuiteBuilder.using(new ImmutableMapCopyOfGenerator())
.withFeatures(
CollectionSize.ANY,
CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS,
CollectionFeature.KNOWN_ORDER,
CollectionFeature.ALLOWS_NULL_QUERIES)
.named("ImmutableMap.copyOf[Map]")
.createTestSuite());
suite.addTest(
MapTestSuiteBuilder.using(new ImmutableMapCopyOfEntriesGenerator())
.withFeatures(
CollectionSize.ANY,
MapFeature.REJECTS_DUPLICATES_AT_CREATION,
CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS,
CollectionFeature.KNOWN_ORDER,
CollectionFeature.ALLOWS_NULL_QUERIES)
.named("ImmutableMap.copyOf[Iterable<Entry>]")
.createTestSuite());
suite.addTest(
MapTestSuiteBuilder.using(new ImmutableMapCopyOfEnumMapGenerator())
.withFeatures(
CollectionSize.ANY,
CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS,
CollectionFeature.KNOWN_ORDER,
CollectionFeature.ALLOWS_NULL_QUERIES)
.named("ImmutableMap.copyOf[EnumMap]")
.createTestSuite());
suite.addTest(
MapTestSuiteBuilder.using(new ImmutableMapValuesAsSingletonSetGenerator())
.withFeatures(
CollectionSize.ANY,
MapFeature.REJECTS_DUPLICATES_AT_CREATION,
CollectionFeature.KNOWN_ORDER,
CollectionFeature.ALLOWS_NULL_QUERIES)
.named("ImmutableMap.asMultimap.asMap")
.createTestSuite());
suite.addTest(
CollectionTestSuiteBuilder.using(new ImmutableMapUnhashableValuesGenerator())
.withFeatures(
CollectionSize.ANY,
CollectionFeature.KNOWN_ORDER,
CollectionFeature.ALLOWS_NULL_QUERIES)
.named("ImmutableMap.values, unhashable")
.createTestSuite());
suite.addTest(
ListTestSuiteBuilder.using(new ImmutableMapKeyListGenerator())
.named("ImmutableMap.keySet.asList")
.withFeatures(
CollectionSize.ANY,
CollectionFeature.SERIALIZABLE,
CollectionFeature.REJECTS_DUPLICATES_AT_CREATION,
CollectionFeature.ALLOWS_NULL_QUERIES)
.createTestSuite());
suite.addTest(
ListTestSuiteBuilder.using(new ImmutableMapEntryListGenerator())
.named("ImmutableMap.entrySet.asList")
.withFeatures(
CollectionSize.ANY,
CollectionFeature.SERIALIZABLE,
CollectionFeature.REJECTS_DUPLICATES_AT_CREATION,
CollectionFeature.ALLOWS_NULL_QUERIES)
.createTestSuite());
suite.addTest(
ListTestSuiteBuilder.using(new ImmutableMapValueListGenerator())
.named("ImmutableMap.values.asList")
.withFeatures(
CollectionSize.ANY,
CollectionFeature.SERIALIZABLE,
CollectionFeature.ALLOWS_NULL_QUERIES)
.createTestSuite());
return suite;
}
public abstract static class AbstractMapTests<K, V> extends MapInterfaceTest<K, V> {
public AbstractMapTests() {
super(false, false, false, false, false);
}
@Override
protected Map<K, V> makeEmptyMap() {
throw new UnsupportedOperationException();
}
private static final Joiner JOINER = Joiner.on(", ");
@Override
protected void assertMoreInvariants(Map<K, V> map) {
// TODO: can these be moved to MapInterfaceTest?
for (Entry<K, V> entry : map.entrySet()) {
assertEquals(entry.getKey() + "=" + entry.getValue(), entry.toString());
}
assertEquals("{" + JOINER.join(map.entrySet()) + "}", map.toString());
assertEquals("[" + JOINER.join(map.entrySet()) + "]", map.entrySet().toString());
assertEquals("[" + JOINER.join(map.keySet()) + "]", map.keySet().toString());
assertEquals("[" + JOINER.join(map.values()) + "]", map.values().toString());
assertEquals(MinimalSet.from(map.entrySet()), map.entrySet());
assertEquals(Sets.newHashSet(map.keySet()), map.keySet());
}
}
public static class MapTests extends AbstractMapTests<String, Integer> {
@Override
protected Map<String, Integer> makeEmptyMap() {
return ImmutableMap.of();
}
@Override
protected Map<String, Integer> makePopulatedMap() {
return ImmutableMap.of("one", 1, "two", 2, "three", 3);
}
@Override
protected String getKeyNotInPopulatedMap() {
return "minus one";
}
@Override
protected Integer getValueNotInPopulatedMap() {
return -1;
}
}
public static class SingletonMapTests extends AbstractMapTests<String, Integer> {
@Override
protected Map<String, Integer> makePopulatedMap() {
return ImmutableMap.of("one", 1);
}
@Override
protected String getKeyNotInPopulatedMap() {
return "minus one";
}
@Override
protected Integer getValueNotInPopulatedMap() {
return -1;
}
}
@GwtIncompatible // SerializableTester
public static class ReserializedMapTests extends AbstractMapTests<String, Integer> {
@Override
protected Map<String, Integer> makePopulatedMap() {
return SerializableTester.reserialize(ImmutableMap.of("one", 1, "two", 2, "three", 3));
}
@Override
protected String getKeyNotInPopulatedMap() {
return "minus one";
}
@Override
protected Integer getValueNotInPopulatedMap() {
return -1;
}
}
public static class MapTestsWithBadHashes extends AbstractMapTests<Object, Integer> {
@Override
protected Map<Object, Integer> makeEmptyMap() {
throw new UnsupportedOperationException();
}
@Override
protected Map<Object, Integer> makePopulatedMap() {
Colliders colliders = new Colliders();
return ImmutableMap.of(
colliders.e0(), 0,
colliders.e1(), 1,
colliders.e2(), 2,
colliders.e3(), 3);
}
@Override
protected Object getKeyNotInPopulatedMap() {
return new Colliders().e4();
}
@Override
protected Integer getValueNotInPopulatedMap() {
return 4;
}
}
@GwtIncompatible // GWT's ImmutableMap emulation is backed by java.util.HashMap.
public static class MapTestsWithUnhashableValues
extends AbstractMapTests<Integer, UnhashableObject> {
@Override
protected Map<Integer, UnhashableObject> makeEmptyMap() {
return ImmutableMap.of();
}
@Override
protected Map<Integer, UnhashableObject> makePopulatedMap() {
Unhashables unhashables = new Unhashables();
return ImmutableMap.of(0, unhashables.e0(), 1, unhashables.e1(), 2, unhashables.e2());
}
@Override
protected Integer getKeyNotInPopulatedMap() {
return 3;
}
@Override
protected UnhashableObject getValueNotInPopulatedMap() {
return new Unhashables().e3();
}
}
@GwtIncompatible // GWT's ImmutableMap emulation is backed by java.util.HashMap.
public static class MapTestsWithSingletonUnhashableValue extends MapTestsWithUnhashableValues {
@Override
protected Map<Integer, UnhashableObject> makePopulatedMap() {
Unhashables unhashables = new Unhashables();
return ImmutableMap.of(0, unhashables.e0());
}
}
public static class CreationTests extends TestCase {
public void testEmptyBuilder() {
ImmutableMap<String, Integer> map = new Builder<String, Integer>().buildOrThrow();
assertEquals(Collections.<String, Integer>emptyMap(), map);
}
public void testSingletonBuilder() {
ImmutableMap<String, Integer> map =
new Builder<String, Integer>().put("one", 1).buildOrThrow();
assertMapEquals(map, "one", 1);
}
public void testBuilder() {
ImmutableMap<String, Integer> map =
new Builder<String, Integer>()
.put("one", 1)
.put("two", 2)
.put("three", 3)
.put("four", 4)
.put("five", 5)
.buildOrThrow();
assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
}
@GwtIncompatible
public void testBuilderExactlySizedReusesArray() {
ImmutableMap.Builder<Integer, Integer> builder = ImmutableMap.builderWithExpectedSize(10);
Object[] builderArray = builder.alternatingKeysAndValues;
for (int i = 0; i < 10; i++) {
builder.put(i, i);
}
Object[] builderArrayAfterPuts = builder.alternatingKeysAndValues;
RegularImmutableMap<Integer, Integer> map =
(RegularImmutableMap<Integer, Integer>) builder.buildOrThrow();
Object[] mapInternalArray = map.alternatingKeysAndValues;
assertSame(builderArray, builderArrayAfterPuts);
assertSame(builderArray, mapInternalArray);
}
public void testBuilder_orderEntriesByValue() {
ImmutableMap<String, Integer> map =
new Builder<String, Integer>()
.orderEntriesByValue(Ordering.natural())
.put("three", 3)
.put("one", 1)
.put("five", 5)
.put("four", 4)
.put("two", 2)
.buildOrThrow();
assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
}
public void testBuilder_orderEntriesByValueAfterExactSizeBuild() {
Builder<String, Integer> builder =
new Builder<String, Integer>(2).put("four", 4).put("one", 1);
ImmutableMap<String, Integer> keyOrdered = builder.buildOrThrow();
ImmutableMap<String, Integer> valueOrdered =
builder.orderEntriesByValue(Ordering.natural()).buildOrThrow();
assertMapEquals(keyOrdered, "four", 4, "one", 1);
assertMapEquals(valueOrdered, "one", 1, "four", 4);
}
public void testBuilder_orderEntriesByValue_usedTwiceFails() {
ImmutableMap.Builder<String, Integer> builder =
new Builder<String, Integer>().orderEntriesByValue(Ordering.natural());
try {
builder.orderEntriesByValue(Ordering.natural());
fail("Expected IllegalStateException");
} catch (IllegalStateException expected) {
}
}
@GwtIncompatible // we haven't implemented this
public void testBuilder_orderEntriesByValue_keepingLast() {
ImmutableMap.Builder<String, Integer> builder =
new Builder<String, Integer>()
.orderEntriesByValue(Ordering.natural())
.put("three", 3)
.put("one", 1)
.put("five", 5)
.put("four", 3)
.put("four", 5)
.put("four", 4) // this should win because it's last
.put("two", 2);
assertMapEquals(
builder.buildKeepingLast(), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
try {
builder.buildOrThrow();
fail("Expected exception from duplicate keys");
} catch (IllegalArgumentException expected) {
}
}
@GwtIncompatible // we haven't implemented this
public void testBuilder_orderEntriesByValue_keepingLast_builderSizeFieldPreserved() {
ImmutableMap.Builder<String, Integer> builder =
new Builder<String, Integer>()
.orderEntriesByValue(Ordering.natural())
.put("one", 1)
.put("one", 1);
assertMapEquals(builder.buildKeepingLast(), "one", 1);
try {
builder.buildOrThrow();
fail("Expected exception from duplicate keys");
} catch (IllegalArgumentException expected) {
}
}
public void testBuilder_withImmutableEntry() {
ImmutableMap<String, Integer> map =
new Builder<String, Integer>().put(Maps.immutableEntry("one", 1)).buildOrThrow();
assertMapEquals(map, "one", 1);
}
public void testBuilder_withImmutableEntryAndNullContents() {
Builder<String, Integer> builder = new Builder<>();
try {
builder.put(Maps.immutableEntry("one", (Integer) null));
fail();
} catch (NullPointerException expected) {
}
try {
builder.put(Maps.immutableEntry((String) null, 1));
fail();
} catch (NullPointerException expected) {
}
}
private static class StringHolder {
String string;
}
public void testBuilder_withMutableEntry() {
ImmutableMap.Builder<String, Integer> builder = new Builder<>();
final StringHolder holder = new StringHolder();
holder.string = "one";
Entry<String, Integer> entry =
new AbstractMapEntry<String, Integer>() {
@Override
public String getKey() {
return holder.string;
}
@Override
public Integer getValue() {
return 1;
}
};
builder.put(entry);
holder.string = "two";
assertMapEquals(builder.buildOrThrow(), "one", 1);
}
public void testBuilderPutAllWithEmptyMap() {
ImmutableMap<String, Integer> map =
new Builder<String, Integer>()
.putAll(Collections.<String, Integer>emptyMap())
.buildOrThrow();
assertEquals(Collections.<String, Integer>emptyMap(), map);
}
public void testBuilderPutAll() {
Map<String, Integer> toPut = new LinkedHashMap<>();
toPut.put("one", 1);
toPut.put("two", 2);
toPut.put("three", 3);
Map<String, Integer> moreToPut = new LinkedHashMap<>();
moreToPut.put("four", 4);
moreToPut.put("five", 5);
ImmutableMap<String, Integer> map =
new Builder<String, Integer>().putAll(toPut).putAll(moreToPut).buildOrThrow();
assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
}
public void testBuilderReuse() {
Builder<String, Integer> builder = new Builder<>();
ImmutableMap<String, Integer> mapOne = builder.put("one", 1).put("two", 2).buildOrThrow();
ImmutableMap<String, Integer> mapTwo = builder.put("three", 3).put("four", 4).buildOrThrow();
assertMapEquals(mapOne, "one", 1, "two", 2);
assertMapEquals(mapTwo, "one", 1, "two", 2, "three", 3, "four", 4);
}
public void testBuilderPutNullKeyFailsAtomically() {
Builder<String, Integer> builder = new Builder<>();
try {
builder.put(null, 1);
fail();
} catch (NullPointerException expected) {
}
builder.put("foo", 2);
assertMapEquals(builder.buildOrThrow(), "foo", 2);
}
public void testBuilderPutImmutableEntryWithNullKeyFailsAtomically() {
Builder<String, Integer> builder = new Builder<>();
try {
builder.put(Maps.immutableEntry((String) null, 1));
fail();
} catch (NullPointerException expected) {
}
builder.put("foo", 2);
assertMapEquals(builder.buildOrThrow(), "foo", 2);
}
// for GWT compatibility
static class SimpleEntry<K, V> extends AbstractMapEntry<K, V> {
public K key;
public V value;
SimpleEntry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
}
public void testBuilderPutMutableEntryWithNullKeyFailsAtomically() {
Builder<String, Integer> builder = new Builder<>();
try {
builder.put(new SimpleEntry<String, Integer>(null, 1));
fail();
} catch (NullPointerException expected) {
}
builder.put("foo", 2);
assertMapEquals(builder.buildOrThrow(), "foo", 2);
}
public void testBuilderPutNullKey() {
Builder<String, Integer> builder = new Builder<>();
try {
builder.put(null, 1);
fail();
} catch (NullPointerException expected) {
}
}
public void testBuilderPutNullValue() {
Builder<String, Integer> builder = new Builder<>();
try {
builder.put("one", null);
fail();
} catch (NullPointerException expected) {
}
}
public void testBuilderPutNullKeyViaPutAll() {
Builder<String, Integer> builder = new Builder<>();
try {
builder.putAll(Collections.<String, Integer>singletonMap(null, 1));
fail();
} catch (NullPointerException expected) {
}
}
public void testBuilderPutNullValueViaPutAll() {
Builder<String, Integer> builder = new Builder<>();
try {
builder.putAll(Collections.<String, Integer>singletonMap("one", null));
fail();
} catch (NullPointerException expected) {
}
}
public void testPuttingTheSameKeyTwiceThrowsOnBuild() {
Builder<String, Integer> builder =
new Builder<String, Integer>()
.put("one", 1)
.put("one", 1); // throwing on this line might be better but it's too late to change
try {
builder.buildOrThrow();
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testBuildKeepingLast_allowsOverwrite() {
Builder<Integer, String> builder =
new Builder<Integer, String>()
.put(1, "un")
.put(2, "deux")
.put(70, "soixante-dix")
.put(70, "septante")
.put(70, "seventy")
.put(1, "one")
.put(2, "two");
ImmutableMap<Integer, String> map = builder.buildKeepingLast();
assertMapEquals(map, 1, "one", 2, "two", 70, "seventy");
}
public void testBuildKeepingLast_smallTableSameHash() {
String key1 = "QED";
String key2 = "R&D";
assertThat(key1.hashCode()).isEqualTo(key2.hashCode());
ImmutableMap<String, Integer> map =
ImmutableMap.<String, Integer>builder()
.put(key1, 1)
.put(key2, 2)
.put(key1, 3)
.put(key2, 4)
.buildKeepingLast();
assertMapEquals(map, key1, 3, key2, 4);
}
// The java7 branch has different code depending on whether the entry indexes fit in a byte,
// short, or int. The small table in testBuildKeepingLast_allowsOverwrite will test the byte
// case. This method tests the short case.
public void testBuildKeepingLast_shortTable() {
Builder<Integer, String> builder = ImmutableMap.builder();
Map<Integer, String> expected = new LinkedHashMap<>();
for (int i = 0; i < 1000; i++) {
// Truncate to even key, so we have put(0, "0") then put(0, "1"). Half the entries are
// duplicates.
Integer key = i & ~1;
String value = String.valueOf(i);
builder.put(key, value);
expected.put(key, value);
}
ImmutableMap<Integer, String> map = builder.buildKeepingLast();
assertThat(map).hasSize(500);
assertThat(map).containsExactlyEntriesIn(expected).inOrder();
}
// This method tests the int case.
public void testBuildKeepingLast_bigTable() {
Builder<Integer, String> builder = ImmutableMap.builder();
Map<Integer, String> expected = new LinkedHashMap<>();
for (int i = 0; i < 200_000; i++) {
// Truncate to even key, so we have put(0, "0") then put(0, "1"). Half the entries are
// duplicates.
Integer key = i & ~1;
String value = String.valueOf(i);
builder.put(key, value);
expected.put(key, value);
}
ImmutableMap<Integer, String> map = builder.buildKeepingLast();
assertThat(map).hasSize(100_000);
assertThat(map).containsExactlyEntriesIn(expected).inOrder();
}
@GwtIncompatible // Pattern, Matcher
public void testBuilder_keepingLast_thenOrThrow() {
ImmutableMap.Builder<String, Integer> builder =
new Builder<String, Integer>()
.put("three", 3)
.put("one", 1)
.put("five", 5)
.put("four", 3)
.put("four", 5)
.put("four", 4) // this should win because it's last
.put("two", 2);
assertMapEquals(
builder.buildKeepingLast(), "three", 3, "one", 1, "five", 5, "four", 4, "two", 2);
try {
builder.buildOrThrow();
fail("Expected exception from duplicate keys");
} catch (IllegalArgumentException expected) {
// We don't really care which values the exception message contains, but they should be
// different from each other. If buildKeepingLast() collapsed duplicates, that might end up
// not being true.
Pattern pattern =
Pattern.compile("Multiple entries with same key: four=(.*) and four=(.*)");
assertThat(expected).hasMessageThat().matches(pattern);
Matcher matcher = pattern.matcher(expected.getMessage());
assertThat(matcher.matches()).isTrue();
assertThat(matcher.group(1)).isNotEqualTo(matcher.group(2));
}
}
public void testOf() {
assertMapEquals(ImmutableMap.of("one", 1), "one", 1);
assertMapEquals(ImmutableMap.of("one", 1, "two", 2), "one", 1, "two", 2);
assertMapEquals(
ImmutableMap.of("one", 1, "two", 2, "three", 3), "one", 1, "two", 2, "three", 3);
assertMapEquals(
ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4),
"one",
1,
"two",
2,
"three",
3,
"four",
4);
assertMapEquals(
ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5),
"one",
1,
"two",
2,
"three",
3,
"four",
4,
"five",
5);
assertMapEquals(
ImmutableMap.of(
"one", 1,
"two", 2,
"three", 3,
"four", 4,
"five", 5,
"six", 6),
"one",
1,
"two",
2,
"three",
3,
"four",
4,
"five",
5,
"six",
6);
assertMapEquals(
ImmutableMap.of(
"one", 1,
"two", 2,
"three", 3,
"four", 4,
"five", 5,
"six", 6,
"seven", 7),
"one",
1,
"two",
2,
"three",
3,
"four",
4,
"five",
5,
"six",
6,
"seven",
7);
assertMapEquals(
ImmutableMap.of(
"one", 1,
"two", 2,
"three", 3,
"four", 4,
"five", 5,
"six", 6,
"seven", 7,
"eight", 8),
"one",
1,
"two",
2,
"three",
3,
"four",
4,
"five",
5,
"six",
6,
"seven",
7,
"eight",
8);
assertMapEquals(
ImmutableMap.of(
"one", 1,
"two", 2,
"three", 3,
"four", 4,
"five", 5,
"six", 6,
"seven", 7,
"eight", 8,
"nine", 9),
"one",
1,
"two",
2,
"three",
3,
"four",
4,
"five",
5,
"six",
6,
"seven",
7,
"eight",
8,
"nine",
9);
assertMapEquals(
ImmutableMap.of(
"one", 1,
"two", 2,
"three", 3,
"four", 4,
"five", 5,
"six", 6,
"seven", 7,
"eight", 8,
"nine", 9,
"ten", 10),
"one",
1,
"two",
2,
"three",
3,
"four",
4,
"five",
5,
"six",
6,
"seven",
7,
"eight",
8,
"nine",
9,
"ten",
10);
}
public void testOfNullKey() {
try {
ImmutableMap.of(null, 1);
fail();
} catch (NullPointerException expected) {
}
try {
ImmutableMap.of("one", 1, null, 2);
fail();
} catch (NullPointerException expected) {
}
}
public void testOfNullValue() {
try {
ImmutableMap.of("one", null);
fail();
} catch (NullPointerException expected) {
}
try {
ImmutableMap.of("one", 1, "two", null);
fail();
} catch (NullPointerException expected) {
}
}
public void testOfWithDuplicateKey() {
try {
ImmutableMap.of("one", 1, "one", 1);
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testCopyOfEmptyMap() {
ImmutableMap<String, Integer> copy =
ImmutableMap.copyOf(Collections.<String, Integer>emptyMap());
assertEquals(Collections.<String, Integer>emptyMap(), copy);
assertSame(copy, ImmutableMap.copyOf(copy));
}
public void testCopyOfSingletonMap() {
ImmutableMap<String, Integer> copy = ImmutableMap.copyOf(Collections.singletonMap("one", 1));
assertMapEquals(copy, "one", 1);
assertSame(copy, ImmutableMap.copyOf(copy));
}
public void testCopyOf() {
Map<String, Integer> original = new LinkedHashMap<>();
original.put("one", 1);
original.put("two", 2);
original.put("three", 3);
ImmutableMap<String, Integer> copy = ImmutableMap.copyOf(original);
assertMapEquals(copy, "one", 1, "two", 2, "three", 3);
assertSame(copy, ImmutableMap.copyOf(copy));
}
// TODO(b/172823566): Use mainline testToImmutableMap once CollectorTester is usable to java7.
public void testToImmutableMap_java7_combine() {
ImmutableMap.Builder<String, Integer> zis =
ImmutableMap.<String, Integer>builder().put("one", 1);
ImmutableMap.Builder<String, Integer> zat =
ImmutableMap.<String, Integer>builder().put("two", 2).put("three", 3);
assertMapEquals(zis.combine(zat).build(), "one", 1, "two", 2, "three", 3);
}
// TODO(b/172823566): Use mainline testToImmutableMap once CollectorTester is usable to java7.
public void testToImmutableMap_exceptionOnDuplicateKey_java7_combine() {
ImmutableMap.Builder<String, Integer> zis =
ImmutableMap.<String, Integer>builder().put("one", 1).put("two", 2);
ImmutableMap.Builder<String, Integer> zat =
ImmutableMap.<String, Integer>builder().put("two", 22).put("three", 3);
try {
zis.combine(zat).build();
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {
// expected
}
}
public static void hashtableTestHelper(ImmutableList<Integer> sizes) {
for (int size : sizes) {
Builder<Integer, Integer> builder = ImmutableMap.builderWithExpectedSize(size);
for (int i = 0; i < size; i++) {
Integer integer = i;
builder.put(integer, integer);
}
ImmutableMap<Integer, Integer> map = builder.build();
assertEquals(size, map.size());
int entries = 0;
for (Integer key : map.keySet()) {
assertEquals(entries, key.intValue());
assertSame(key, map.get(key));
entries++;
}
assertEquals(size, entries);
}
}
public void testByteArrayHashtable() {
hashtableTestHelper(ImmutableList.of(2, 89));
}
public void testShortArrayHashtable() {
hashtableTestHelper(ImmutableList.of(90, 22937));
}
public void testIntArrayHashtable() {
hashtableTestHelper(ImmutableList.of(22938));
}
}
public void testNullGet() {
ImmutableMap<String, Integer> map = ImmutableMap.of("one", 1);
assertNull(map.get(null));
}
public void testAsMultimap() {
ImmutableMap<String, Integer> map =
ImmutableMap.of("one", 1, "won", 1, "two", 2, "too", 2, "three", 3);
ImmutableSetMultimap<String, Integer> expected =
ImmutableSetMultimap.of("one", 1, "won", 1, "two", 2, "too", 2, "three", 3);
assertEquals(expected, map.asMultimap());
}
public void testAsMultimapWhenEmpty() {
ImmutableMap<String, Integer> map = ImmutableMap.of();
ImmutableSetMultimap<String, Integer> expected = ImmutableSetMultimap.of();
assertEquals(expected, map.asMultimap());
}
public void testAsMultimapCaches() {
ImmutableMap<String, Integer> map = ImmutableMap.of("one", 1);
ImmutableSetMultimap<String, Integer> multimap1 = map.asMultimap();
ImmutableSetMultimap<String, Integer> multimap2 = map.asMultimap();
assertEquals(1, multimap1.asMap().size());
assertSame(multimap1, multimap2);
}
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
NullPointerTester tester = new NullPointerTester();
tester.testAllPublicStaticMethods(ImmutableMap.class);
tester.testAllPublicInstanceMethods(new ImmutableMap.Builder<Object, Object>());
tester.testAllPublicInstanceMethods(ImmutableMap.of());
tester.testAllPublicInstanceMethods(ImmutableMap.of("one", 1));
tester.testAllPublicInstanceMethods(ImmutableMap.of("one", 1, "two", 2, "three", 3));
}
private static <K, V> void assertMapEquals(Map<K, V> map, Object... alternatingKeysAndValues) {
Map<Object, Object> expected = new LinkedHashMap<>();
for (int i = 0; i < alternatingKeysAndValues.length; i += 2) {
expected.put(alternatingKeysAndValues[i], alternatingKeysAndValues[i + 1]);
}
assertThat(map).containsExactlyEntriesIn(expected).inOrder();
}
private static class IntHolder implements Serializable {
public int value;
public IntHolder(int value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
return (o instanceof IntHolder) && ((IntHolder) o).value == value;
}
@Override
public int hashCode() {
return value;
}
private static final long serialVersionUID = 5;
}
public void testMutableValues() {
IntHolder holderA = new IntHolder(1);
IntHolder holderB = new IntHolder(2);
Map<String, IntHolder> map = ImmutableMap.of("a", holderA, "b", holderB);
holderA.value = 3;
assertTrue(map.entrySet().contains(Maps.immutableEntry("a", new IntHolder(3))));
Map<String, Integer> intMap = ImmutableMap.of("a", 3, "b", 2);
assertEquals(intMap.hashCode(), map.entrySet().hashCode());
assertEquals(intMap.hashCode(), map.hashCode());
}
@GwtIncompatible // SerializableTester
public void testViewSerialization() {
Map<String, Integer> map = ImmutableMap.of("one", 1, "two", 2, "three", 3);
LenientSerializableTester.reserializeAndAssertLenient(map.entrySet());
LenientSerializableTester.reserializeAndAssertLenient(map.keySet());
Collection<Integer> reserializedValues = reserialize(map.values());
assertEquals(Lists.newArrayList(map.values()), Lists.newArrayList(reserializedValues));
assertTrue(reserializedValues instanceof ImmutableCollection);
}
@GwtIncompatible // SerializableTester
public void testKeySetIsSerializable_regularImmutableMap() {
class NonSerializableClass {}
Map<String, NonSerializableClass> map =
RegularImmutableMap.create(1, new Object[] {"one", new NonSerializableClass()});
Set<String> set = map.keySet();
LenientSerializableTester.reserializeAndAssertLenient(set);
}
@GwtIncompatible // SerializableTester
public void testValuesCollectionIsSerializable_regularImmutableMap() {
class NonSerializableClass {}
Map<NonSerializableClass, String> map =
RegularImmutableMap.create(1, new Object[] {new NonSerializableClass(), "value"});
Collection<String> collection = map.values();
LenientSerializableTester.reserializeAndAssertElementsEqual(collection);
}
// TODO: Re-enable this test after moving to new serialization format in ImmutableMap.
@GwtIncompatible // SerializableTester
@SuppressWarnings("unchecked")
public void ignore_testSerializationNoDuplication_regularImmutableMap() throws Exception {
// Tests that searializing a map, its keySet, and values only writes the underlying data once.
Object[] entries = new Object[2000];
for (int i = 0; i < entries.length; i++) {
entries[i] = i;
}
ImmutableMap<Integer, Integer> map = RegularImmutableMap.create(entries.length / 2, entries);
Set<Integer> keySet = map.keySet();
Collection<Integer> values = map.values();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bytes);
oos.writeObject(map);
oos.flush();
int mapSize = bytes.size();
oos.writeObject(keySet);
oos.writeObject(values);
oos.close();
int finalSize = bytes.size();
assertThat(finalSize - mapSize).isLessThan(100);
}
public void testEquals() {
new EqualsTester()
.addEqualityGroup(
ImmutableMap.of(),
ImmutableMap.builder().buildOrThrow(),
ImmutableMap.ofEntries(),
map())
.addEqualityGroup(
ImmutableMap.of(1, 1),
ImmutableMap.builder().put(1, 1).buildOrThrow(),
ImmutableMap.ofEntries(entry(1, 1)),
map(1, 1))
.addEqualityGroup(
ImmutableMap.of(1, 1, 2, 2),
ImmutableMap.builder().put(1, 1).put(2, 2).buildOrThrow(),
ImmutableMap.ofEntries(entry(1, 1), entry(2, 2)),
map(1, 1, 2, 2))
.addEqualityGroup(
ImmutableMap.of(1, 1, 2, 2, 3, 3),
ImmutableMap.builder().put(1, 1).put(2, 2).put(3, 3).buildOrThrow(),
ImmutableMap.ofEntries(entry(1, 1), entry(2, 2), entry(3, 3)),
map(1, 1, 2, 2, 3, 3))
.addEqualityGroup(
ImmutableMap.of(1, 4, 2, 2, 3, 3),
ImmutableMap.builder().put(1, 4).put(2, 2).put(3, 3).buildOrThrow(),
ImmutableMap.ofEntries(entry(1, 4), entry(2, 2), entry(3, 3)),
map(1, 4, 2, 2, 3, 3))
.addEqualityGroup(
ImmutableMap.of(1, 1, 2, 4, 3, 3),
ImmutableMap.builder().put(1, 1).put(2, 4).put(3, 3).buildOrThrow(),
ImmutableMap.ofEntries(entry(1, 1), entry(2, 4), entry(3, 3)),
map(1, 1, 2, 4, 3, 3))
.addEqualityGroup(
ImmutableMap.of(1, 1, 2, 2, 3, 4),
ImmutableMap.builder().put(1, 1).put(2, 2).put(3, 4).buildOrThrow(),
ImmutableMap.ofEntries(entry(1, 1), entry(2, 2), entry(3, 4)),
map(1, 1, 2, 2, 3, 4))
.addEqualityGroup(
ImmutableMap.of(1, 2, 2, 3, 3, 1),
ImmutableMap.builder().put(1, 2).put(2, 3).put(3, 1).buildOrThrow(),
ImmutableMap.ofEntries(entry(1, 2), entry(2, 3), entry(3, 1)),
map(1, 2, 2, 3, 3, 1))
.addEqualityGroup(
ImmutableMap.of(1, 1, 2, 2, 3, 3, 4, 4),
ImmutableMap.builder().put(1, 1).put(2, 2).put(3, 3).put(4, 4).buildOrThrow(),
ImmutableMap.ofEntries(entry(1, 1), entry(2, 2), entry(3, 3), entry(4, 4)),
map(1, 1, 2, 2, 3, 3, 4, 4))
.addEqualityGroup(
ImmutableMap.of(1, 1, 2, 2, 3, 3, 4, 4, 5, 5),
ImmutableMap.builder().put(1, 1).put(2, 2).put(3, 3).put(4, 4).put(5, 5).buildOrThrow(),
ImmutableMap.ofEntries(entry(1, 1), entry(2, 2), entry(3, 3), entry(4, 4), entry(5, 5)),
map(1, 1, 2, 2, 3, 3, 4, 4, 5, 5))
.testEquals();
}
public void testOfEntriesNull() {
Entry<Integer, Integer> nullKey = entry(null, 23);
try {
ImmutableMap.ofEntries(nullKey);
fail();
} catch (NullPointerException expected) {
}
Entry<Integer, Integer> nullValue = entry(23, null);
try {
ImmutableMap.ofEntries(nullValue);
fail();
} catch (NullPointerException expected) {
}
}
private static <T> Map<T, T> map(T... keysAndValues) {
assertThat(keysAndValues.length % 2).isEqualTo(0);
LinkedHashMap<T, T> map = new LinkedHashMap<>();
for (int i = 0; i < keysAndValues.length; i += 2) {
T key = keysAndValues[i];
T value = keysAndValues[i + 1];
T old = map.put(key, value);
assertWithMessage("Key %s set to %s and %s", key, value, old).that(old).isNull();
}
return map;
}
private static <T> Entry<T, T> entry(T key, T value) {
return new AbstractMap.SimpleImmutableEntry<>(key, value);
}
}
|