Fix flaky IpPrefixTest.

Test: IpPrefixTest passes
Bug: 32561414
Merged-In: Ib4bffe9d33a6d4f5c2bd97798073de0f66d77645

(cherry pick from commit f5ec69155d)

Change-Id: Ibaf11aae9b13af868bebff820c9e7615b63c8eb2
This commit is contained in:
Hugo Benichi
2016-11-10 22:45:56 +09:00
parent 59e6fc6d27
commit f9c61862cc

View File

@@ -18,14 +18,14 @@ package android.net;
import android.net.IpPrefix; import android.net.IpPrefix;
import android.os.Parcel; import android.os.Parcel;
import static android.test.MoreAsserts.assertNotEqual;
import android.test.suitebuilder.annotation.SmallTest; import android.test.suitebuilder.annotation.SmallTest;
import static org.junit.Assert.assertArrayEquals;
import java.net.InetAddress; import java.net.InetAddress;
import java.util.Random; import java.util.Random;
import junit.framework.TestCase; import junit.framework.TestCase;
import static android.test.MoreAsserts.assertNotEqual;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
public class IpPrefixTest extends TestCase { public class IpPrefixTest extends TestCase {
@@ -242,25 +242,42 @@ public class IpPrefixTest extends TestCase {
@SmallTest @SmallTest
public void testHashCode() { public void testHashCode() {
IpPrefix p; IpPrefix p = new IpPrefix(new byte[4], 0);
int oldCode = -1;
Random random = new Random(); Random random = new Random();
for (int i = 0; i < 100; i++) { for (int i = 0; i < 100; i++) {
final IpPrefix oldP = p;
if (random.nextBoolean()) { if (random.nextBoolean()) {
// IPv4. // IPv4.
byte[] b = new byte[4]; byte[] b = new byte[4];
random.nextBytes(b); random.nextBytes(b);
p = new IpPrefix(b, random.nextInt(33)); p = new IpPrefix(b, random.nextInt(33));
assertNotEqual(oldCode, p.hashCode());
oldCode = p.hashCode();
} else { } else {
// IPv6. // IPv6.
byte[] b = new byte[16]; byte[] b = new byte[16];
random.nextBytes(b); random.nextBytes(b);
p = new IpPrefix(b, random.nextInt(129)); p = new IpPrefix(b, random.nextInt(129));
assertNotEqual(oldCode, p.hashCode());
oldCode = p.hashCode();
} }
if (p.equals(oldP)) {
assertEquals(p.hashCode(), oldP.hashCode());
}
if (p.hashCode() != oldP.hashCode()) {
assertNotEqual(p, oldP);
}
}
}
@SmallTest
public void testHashCodeIsNotConstant() {
IpPrefix[] prefixes = {
new IpPrefix("2001:db8:f00::ace:d00d/127"),
new IpPrefix("192.0.2.0/23"),
new IpPrefix("::/0"),
new IpPrefix("0.0.0.0/0"),
};
for (int i = 0; i < prefixes.length; i++) {
for (int j = i + 1; j < prefixes.length; j++) {
assertNotEqual(prefixes[i].hashCode(), prefixes[j].hashCode());
}
} }
} }