import static org.mockito.Mockito.when;
import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
import android.system.Os;
-import android.test.AndroidTestCase;
+
import com.android.server.IpSecService;
+
import java.net.InetAddress;
import java.net.UnknownHostException;
+
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
/** Unit tests for {@link IpSecManager}. */
@SmallTest
-@RunWith(JUnit4.class)
+@RunWith(AndroidJUnit4.class)
public class IpSecManagerTest {
private static final int TEST_UDP_ENCAP_PORT = 34567;
import static android.net.NetworkStats.IFACE_ALL;
import static android.net.NetworkStats.TAG_NONE;
import static android.net.NetworkStats.UID_ALL;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
-import android.test.suitebuilder.annotation.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.test.filters.SmallTest;
import com.google.android.collect.Sets;
-import junit.framework.TestCase;
-
import java.util.HashSet;
+import org.junit.runner.RunWith;
+import org.junit.Test;
+
+@RunWith(AndroidJUnit4.class)
@SmallTest
-public class NetworkStatsTest extends TestCase {
+public class NetworkStatsTest {
private static final String TEST_IFACE = "test0";
private static final String TEST_IFACE2 = "test2";
private static final int TEST_UID = 1001;
private static final long TEST_START = 1194220800000L;
+ @Test
public void testFindIndex() throws Exception {
final NetworkStats stats = new NetworkStats(TEST_START, 5)
.addValues(TEST_IFACE, 100, SET_DEFAULT, TAG_NONE, METERED_NO, ROAMING_NO, 1024L,
ROAMING_NO));
}
+ @Test
public void testFindIndexHinted() {
final NetworkStats stats = new NetworkStats(TEST_START, 3)
.addValues(TEST_IFACE, 100, SET_DEFAULT, TAG_NONE, METERED_NO, ROAMING_NO, 1024L,
}
}
+ @Test
public void testAddEntryGrow() throws Exception {
final NetworkStats stats = new NetworkStats(TEST_START, 4);
ROAMING_YES, 7L, 70L, 5L, 50L, 11);
}
+ @Test
public void testCombineExisting() throws Exception {
final NetworkStats stats = new NetworkStats(TEST_START, 10);
256L, 2L, 256L, 2L, 6);
}
+ @Test
public void testSubtractIdenticalData() throws Exception {
final NetworkStats before = new NetworkStats(TEST_START, 2)
.addValues(TEST_IFACE, 100, SET_DEFAULT, TAG_NONE, 1024L, 8L, 0L, 0L, 11)
0L, 0L, 0L, 0);
}
+ @Test
public void testSubtractIdenticalRows() throws Exception {
final NetworkStats before = new NetworkStats(TEST_START, 2)
.addValues(TEST_IFACE, 100, SET_DEFAULT, TAG_NONE, 1024L, 8L, 0L, 0L, 11)
1L, 4L, 1L, 8);
}
+ @Test
public void testSubtractNewRows() throws Exception {
final NetworkStats before = new NetworkStats(TEST_START, 2)
.addValues(TEST_IFACE, 100, SET_DEFAULT, TAG_NONE, 1024L, 8L, 0L, 0L, 11)
1024L, 8L, 1024L, 8L, 20);
}
+ @Test
public void testSubtractMissingRows() throws Exception {
final NetworkStats before = new NetworkStats(TEST_START, 2)
.addValues(TEST_IFACE, UID_ALL, SET_DEFAULT, TAG_NONE, 1024L, 0L, 0L, 0L, 0)
assertEquals(4L, result.getTotalBytes());
}
+ @Test
public void testTotalBytes() throws Exception {
final NetworkStats iface = new NetworkStats(TEST_START, 2)
.addValues(TEST_IFACE, UID_ALL, SET_DEFAULT, TAG_NONE, 128L, 0L, 0L, 0L, 0L)
assertEquals(96L, uidRoaming.getTotalBytes());
}
+ @Test
public void testGroupedByIfaceEmpty() throws Exception {
final NetworkStats uidStats = new NetworkStats(TEST_START, 3);
final NetworkStats grouped = uidStats.groupedByIface();
assertEquals(0, grouped.size());
}
+ @Test
public void testGroupedByIfaceAll() throws Exception {
final NetworkStats uidStats = new NetworkStats(TEST_START, 3)
.addValues(IFACE_ALL, 100, SET_ALL, TAG_NONE, METERED_NO, ROAMING_NO, 128L, 8L, 0L,
384L, 24L, 0L, 6L, 0L);
}
+ @Test
public void testGroupedByIface() throws Exception {
final NetworkStats uidStats = new NetworkStats(TEST_START, 7)
.addValues(TEST_IFACE, 100, SET_DEFAULT, TAG_NONE, METERED_NO, ROAMING_NO, 128L, 8L,
1024L, 64L, 0L, 0L, 0L);
}
+ @Test
public void testAddAllValues() {
final NetworkStats first = new NetworkStats(TEST_START, 5)
.addValues(TEST_IFACE, 100, SET_DEFAULT, TAG_NONE, METERED_YES, ROAMING_NO, 32L, 0L,
32L, 0L, 0L, 0L, 0L);
}
+ @Test
public void testGetTotal() {
final NetworkStats stats = new NetworkStats(TEST_START, 7)
.addValues(TEST_IFACE, 100, SET_DEFAULT, TAG_NONE, METERED_NO, ROAMING_NO, 128L, 8L,
assertValues(stats.getTotal(null, ifaces), 1024L, 64L, 0L, 0L, 0L);
}
+ @Test
public void testWithoutUid() throws Exception {
final NetworkStats before = new NetworkStats(TEST_START, 3)
.addValues(TEST_IFACE, 100, SET_DEFAULT, TAG_NONE, 128L, 8L, 0L, 2L, 20L)
8L, 0L, 0L, 0L);
}
+ @Test
public void testClone() throws Exception {
final NetworkStats original = new NetworkStats(TEST_START, 5)
.addValues(TEST_IFACE, 100, SET_DEFAULT, TAG_NONE, 128L, 8L, 0L, 2L, 20L)
assertEquals(128L + 512L, clone.getTotalBytes());
}
+ @Test
public void testAddWhenEmpty() throws Exception {
final NetworkStats red = new NetworkStats(TEST_START, -1);
final NetworkStats blue = new NetworkStats(TEST_START, 5)
red.combineAllValues(blue);
}
+ @Test
public void testMigrateTun() throws Exception {
final int tunUid = 10030;
final String tunIface = "tun0";
// interface by the vpn app before it's sent out of the underlying interface. The VPN app should
// not be charged for the echoed data but it should still be charged for any extra data it sends
// via the underlying interface.
+ @Test
public void testMigrateTun_VpnAsLoopback() {
final int tunUid = 10030;
final String tunIface = "tun0";
package android.net;
-import android.os.Parcel;
-import android.test.suitebuilder.annotation.SmallTest;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
-import junit.framework.TestCase;
+import android.os.Parcel;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.test.filters.SmallTest;
-import static org.junit.Assert.assertArrayEquals;
+import org.junit.runner.RunWith;
+import org.junit.Test;
-public class UidRangeTest extends TestCase {
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class UidRangeTest {
static {
System.loadLibrary("frameworksnettestsjni");
private static native int getStart(byte[] inParcel);
private static native int getStop(byte[] inParcel);
- @SmallTest
+ @Test
public void testNativeParcelUnparcel() {
UidRange original = new UidRange(1234, Integer.MAX_VALUE);
assertArrayEquals(inParcel, outParcel);
}
- @SmallTest
+ @Test
public void testIndividualNativeFields() {
UidRange original = new UidRange(0x11115678, 0x22224321);
byte[] originalBytes = marshall(original);
assertEquals(original.stop, getStop(originalBytes));
}
- @SmallTest
+ @Test
public void testSingleItemUidRangeAllowed() {
new UidRange(123, 123);
new UidRange(0, 0);
new UidRange(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
- @SmallTest
+ @Test
public void testNegativeUidsDisallowed() {
try {
new UidRange(-2, 100);
}
}
- @SmallTest
+ @Test
public void testStopLessThanStartDisallowed() {
final int x = 4195000;
try {
package android.net.apf;
+import static android.system.OsConstants.*;
+import static com.android.internal.util.BitUtils.bytesToBEInt;
+import static com.android.internal.util.BitUtils.put;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.verify;
+
import android.net.LinkAddress;
import android.net.LinkProperties;
import android.net.NetworkUtils;
import android.os.ConditionVariable;
import android.os.Parcelable;
import android.os.SystemClock;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.test.filters.SmallTest;
import android.system.ErrnoException;
import android.system.Os;
-import android.test.AndroidTestCase;
import android.text.format.DateUtils;
-import android.test.suitebuilder.annotation.SmallTest;
-import static android.system.OsConstants.*;
import com.android.frameworks.tests.net.R;
import com.android.internal.util.HexDump;
-import static com.android.internal.util.BitUtils.bytesToBEInt;
-import static com.android.internal.util.BitUtils.put;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import static org.mockito.Mockito.atLeastOnce;
-import static org.mockito.Mockito.verify;
import java.io.File;
import java.io.FileDescriptor;
* Build, install and run with:
* runtest frameworks-net -c android.net.apf.ApfTest
*/
-public class ApfTest extends AndroidTestCase {
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class ApfTest {
private static final int TIMEOUT_MS = 500;
@Mock IpConnectivityLog mLog;
- @Override
+ @Before
public void setUp() throws Exception {
- super.setUp();
MockitoAnnotations.initMocks(this);
// Load up native shared library containing APF interpreter exposed via JNI.
System.loadLibrary("frameworksnettestsjni");
* generating bytecode for that program and running it through the
* interpreter to verify it functions correctly.
*/
- @SmallTest
+ @Test
public void testApfInstructions() throws IllegalInstructionException {
// Empty program should pass because having the program counter reach the
// location immediately after the program indicates the packet should be
* Generate some BPF programs, translate them to APF, then run APF and BPF programs
* over packet traces and verify both programs filter out the same packets.
*/
- @SmallTest
+ @Test
public void testApfAgainstBpf() throws Exception {
String[] tcpdump_filters = new String[]{ "udp", "tcp", "icmp", "icmp6", "udp port 53",
"arp", "dst 239.255.255.250", "arp or tcp or udp port 53", "net 192.168.1.0/24",
private static final byte[] ANOTHER_IPV4_ADDR = {10, 0, 0, 2};
private static final byte[] IPV4_ANY_HOST_ADDR = {0, 0, 0, 0};
- @SmallTest
+ @Test
public void testApfFilterIPv4() throws Exception {
MockIpManagerCallback ipManagerCallback = new MockIpManagerCallback();
LinkAddress link = new LinkAddress(InetAddress.getByAddress(MOCK_IPV4_ADDR), 19);
apfFilter.shutdown();
}
- @SmallTest
+ @Test
public void testApfFilterIPv6() throws Exception {
final int[] ethTypeBlackList = {};
MockIpManagerCallback ipManagerCallback = new MockIpManagerCallback();
apfFilter.shutdown();
}
- @SmallTest
+ @Test
public void testApfFilterMulticast() throws Exception {
final byte[] unicastIpv4Addr = {(byte)192,0,2,63};
final byte[] broadcastIpv4Addr = {(byte)192,0,2,(byte)255};
apfFilter.shutdown();
}
- @SmallTest
+ @Test
public void testApfFilter802_3() throws Exception {
MockIpManagerCallback ipManagerCallback = new MockIpManagerCallback();
LinkAddress link = new LinkAddress(InetAddress.getByAddress(MOCK_IPV4_ADDR), 19);
apfFilter.shutdown();
}
- @SmallTest
+ @Test
public void testApfFilterEthTypeBL() throws Exception {
MockIpManagerCallback ipManagerCallback = new MockIpManagerCallback();
LinkAddress link = new LinkAddress(InetAddress.getByAddress(MOCK_IPV4_ADDR), 19);
assertDrop(program, garpReply());
}
- @SmallTest
+ @Test
public void testApfFilterArp() throws Exception {
final int[] ethTypeBlackList = {};
MockIpManagerCallback ipManagerCallback = new MockIpManagerCallback();
// Test that when ApfFilter is shown the given packet, it generates a program to filter it
// for the given lifetime.
- private void testRaLifetime(TestApfFilter apfFilter, MockIpManagerCallback ipManagerCallback,
+ private void verifyRaLifetime(TestApfFilter apfFilter, MockIpManagerCallback ipManagerCallback,
ByteBuffer packet, int lifetime) throws IOException, ErrnoException {
// Verify new program generated if ApfFilter witnesses RA
ipManagerCallback.resetApfProgramWait();
ipManagerCallback.assertNoProgramUpdate();
}
- @SmallTest
+ @Test
public void testApfFilterRa() throws Exception {
MockIpManagerCallback ipManagerCallback = new MockIpManagerCallback();
final int[] ethTypeBlackList = {};
basePacket.put(IPV6_ALL_NODES_ADDRESS);
assertPass(program, basePacket.array());
- testRaLifetime(apfFilter, ipManagerCallback, basePacket, ROUTER_LIFETIME);
+ verifyRaLifetime(apfFilter, ipManagerCallback, basePacket, ROUTER_LIFETIME);
verifyRaEvent(new RaEvent(ROUTER_LIFETIME, -1, -1, -1, -1, -1));
ByteBuffer newFlowLabelPacket = ByteBuffer.wrap(new byte[ICMP6_RA_OPTION_OFFSET]);
prefixOptionPacket.putInt(
ICMP6_RA_OPTION_OFFSET + ICMP6_PREFIX_OPTION_VALID_LIFETIME_OFFSET,
PREFIX_VALID_LIFETIME);
- testRaLifetime(apfFilter, ipManagerCallback, prefixOptionPacket, PREFIX_PREFERRED_LIFETIME);
+ verifyRaLifetime(
+ apfFilter, ipManagerCallback, prefixOptionPacket, PREFIX_PREFERRED_LIFETIME);
verifyRaEvent(new RaEvent(
ROUTER_LIFETIME, PREFIX_VALID_LIFETIME, PREFIX_PREFERRED_LIFETIME, -1, -1, -1));
rdnssOptionPacket.put((byte)(ICMP6_4_BYTE_OPTION_LEN / 8));
rdnssOptionPacket.putInt(
ICMP6_RA_OPTION_OFFSET + ICMP6_4_BYTE_LIFETIME_OFFSET, RDNSS_LIFETIME);
- testRaLifetime(apfFilter, ipManagerCallback, rdnssOptionPacket, RDNSS_LIFETIME);
+ verifyRaLifetime(apfFilter, ipManagerCallback, rdnssOptionPacket, RDNSS_LIFETIME);
verifyRaEvent(new RaEvent(ROUTER_LIFETIME, -1, -1, -1, RDNSS_LIFETIME, -1));
ByteBuffer routeInfoOptionPacket = ByteBuffer.wrap(
routeInfoOptionPacket.put((byte)(ICMP6_4_BYTE_OPTION_LEN / 8));
routeInfoOptionPacket.putInt(
ICMP6_RA_OPTION_OFFSET + ICMP6_4_BYTE_LIFETIME_OFFSET, ROUTE_LIFETIME);
- testRaLifetime(apfFilter, ipManagerCallback, routeInfoOptionPacket, ROUTE_LIFETIME);
+ verifyRaLifetime(apfFilter, ipManagerCallback, routeInfoOptionPacket, ROUTE_LIFETIME);
verifyRaEvent(new RaEvent(ROUTER_LIFETIME, -1, -1, ROUTE_LIFETIME, -1, -1));
ByteBuffer dnsslOptionPacket = ByteBuffer.wrap(
dnsslOptionPacket.put((byte)(ICMP6_4_BYTE_OPTION_LEN / 8));
dnsslOptionPacket.putInt(
ICMP6_RA_OPTION_OFFSET + ICMP6_4_BYTE_LIFETIME_OFFSET, DNSSL_LIFETIME);
- testRaLifetime(apfFilter, ipManagerCallback, dnsslOptionPacket, ROUTER_LIFETIME);
+ verifyRaLifetime(apfFilter, ipManagerCallback, dnsslOptionPacket, ROUTER_LIFETIME);
verifyRaEvent(new RaEvent(ROUTER_LIFETIME, -1, -1, -1, -1, DNSSL_LIFETIME));
// Verify that current program filters all five RAs:
* copy that resource into the app's data directory and return the path to it.
*/
private String stageFile(int rawId) throws Exception {
- File file = new File(getContext().getFilesDir(), "staged_file");
+ File file = new File(InstrumentationRegistry.getContext().getFilesDir(), "staged_file");
new File(file.getParent()).mkdirs();
InputStream in = null;
OutputStream out = null;
try {
- in = getContext().getResources().openRawResource(rawId);
+ in = InstrumentationRegistry.getContext().getResources().openRawResource(rawId);
out = new FileOutputStream(file);
Streams.copy(in, out);
} finally {
buffer.position(original);
}
- @SmallTest
+ @Test
public void testRaParsing() throws Exception {
final int maxRandomPacketSize = 512;
final Random r = new Random();
}
}
- @SmallTest
+ @Test
public void testRaProcessing() throws Exception {
final int maxRandomPacketSize = 512;
final Random r = new Random();
private native static boolean compareBpfApf(String filter, String pcap_filename,
byte[] apf_program);
- @SmallTest
+ @Test
public void testBroadcastAddress() throws Exception {
assertEqualsIp("255.255.255.255", ApfFilter.ipv4BroadcastAddress(IPV4_ANY_HOST_ADDR, 0));
assertEqualsIp("0.0.0.0", ApfFilter.ipv4BroadcastAddress(IPV4_ANY_HOST_ADDR, 32));
package android.net.dhcp;
+import static android.net.dhcp.DhcpPacket.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
import android.net.DhcpResults;
import android.net.LinkAddress;
import android.net.NetworkUtils;
import android.net.metrics.DhcpErrorEvent;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.test.filters.SmallTest;
import android.system.OsConstants;
-import android.test.suitebuilder.annotation.SmallTest;
+
import com.android.internal.util.HexDump;
+
import java.net.Inet4Address;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
-import junit.framework.TestCase;
-import static android.net.dhcp.DhcpPacket.*;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
-public class DhcpPacketTest extends TestCase {
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class DhcpPacketTest {
private static Inet4Address SERVER_ADDR = v4Address("192.0.2.1");
private static Inet4Address CLIENT_ADDR = v4Address("192.0.2.234");
return (Inet4Address) NetworkUtils.numericToInetAddress(addrString);
}
+ @Before
public void setUp() {
DhcpPacket.testOverrideVendorId = "android-dhcp-???";
DhcpPacket.testOverrideHostname = "android-01234567890abcde";
assertEquals(expectedVendorInfo, offerPacket.mVendorInfo);
}
- @SmallTest
+ @Test
public void testDomainName() throws Exception {
byte[] nullByte = new byte[] { 0x00 };
byte[] twoNullBytes = new byte[] { 0x00, 0x00 };
assertEquals(leaseTimeMillis, offerPacket.getLeaseTimeMillis());
}
- @SmallTest
+ @Test
public void testLeaseTime() throws Exception {
byte[] noLease = null;
byte[] tooShortLease = new byte[] { 0x00, 0x00 };
}
}
- @SmallTest
+ @Test
public void testIpAddress() throws Exception {
byte[] slash11Netmask = new byte[] { (byte) 0xff, (byte) 0xe0, 0x00, 0x00 };
byte[] slash24Netmask = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, 0x00 };
assertEquals(mtu, dhcpResults.mtu);
}
- @SmallTest
+ @Test
public void testOffer1() throws Exception {
- // TODO: Turn all of these into golden files. This will probably require modifying
- // Android.mk appropriately, making this into an AndroidTestCase, and adding code to read
- // the golden files from the test APK's assets via mContext.getAssets().
+ // TODO: Turn all of these into golden files. This will probably require using
+ // android.support.test.InstrumentationRegistry for obtaining a Context object
+ // to read such golden files, along with an appropriate Android.mk.
final ByteBuffer packet = ByteBuffer.wrap(HexDump.hexStringToByteArray(
// IP header.
"451001480000000080118849c0a89003c0a89ff7" +
null, "192.168.144.3", null, 7200, false, 0, dhcpResults);
}
- @SmallTest
+ @Test
public void testOffer2() throws Exception {
final ByteBuffer packet = ByteBuffer.wrap(HexDump.hexStringToByteArray(
// IP header.
assertTrue(dhcpResults.hasMeteredHint());
}
- @SmallTest
+ @Test
public void testBadIpPacket() throws Exception {
final byte[] packet = HexDump.hexStringToByteArray(
// IP header.
fail("Dhcp packet parsing should have failed");
}
- @SmallTest
+ @Test
public void testBadDhcpPacket() throws Exception {
final byte[] packet = HexDump.hexStringToByteArray(
// IP header.
fail("Dhcp packet parsing should have failed");
}
- @SmallTest
+ @Test
public void testBadTruncatedOffer() throws Exception {
final byte[] packet = HexDump.hexStringToByteArray(
// IP header.
fail("Dhcp packet parsing should have failed");
}
- @SmallTest
+ @Test
public void testBadOfferWithoutACookie() throws Exception {
final byte[] packet = HexDump.hexStringToByteArray(
// IP header.
fail("Dhcp packet parsing should have failed");
}
- @SmallTest
+ @Test
public void testOfferWithBadCookie() throws Exception {
final byte[] packet = HexDump.hexStringToByteArray(
// IP header.
assertEquals(Integer.toHexString(expected), Integer.toHexString(got));
}
- @SmallTest
+ @Test
public void testTruncatedOfferPackets() throws Exception {
final byte[] packet = HexDump.hexStringToByteArray(
// IP header.
}
}
- @SmallTest
+ @Test
public void testRandomPackets() throws Exception {
final int maxRandomPacketSize = 512;
final Random r = new Random();
null, "192.168.144.3", null, 7200, false, expectedMtu, dhcpResults);
}
- @SmallTest
+ @Test
public void testMtu() throws Exception {
final ByteBuffer packet = ByteBuffer.wrap(HexDump.hexStringToByteArray(
// IP header.
checkMtu(packet, 0, mtuBytes(-1));
}
- @SmallTest
+ @Test
public void testBadHwaddrLength() throws Exception {
final ByteBuffer packet = ByteBuffer.wrap(HexDump.hexStringToByteArray(
// IP header.
assertEquals(expectedClientMac, HexDump.toHexString(offerPacket.getClientMac()));
}
- @SmallTest
+ @Test
public void testPadAndOverloadedOptionsOffer() throws Exception {
// A packet observed in the real world that is interesting for two reasons:
//
null, "1.1.1.1", null, 43200, false, 0, dhcpResults);
}
- @SmallTest
+ @Test
public void testBug2111() throws Exception {
final ByteBuffer packet = ByteBuffer.wrap(HexDump.hexStringToByteArray(
// IP header.
"domain123.co.uk", "192.0.2.254", null, 49094, false, 0, dhcpResults);
}
- @SmallTest
+ @Test
public void testBug2136() throws Exception {
final ByteBuffer packet = ByteBuffer.wrap(HexDump.hexStringToByteArray(
// Ethernet header.
"lancs.ac.uk", "10.32.255.128", null, 7200, false, 0, dhcpResults);
}
- @SmallTest
+ @Test
public void testUdpServerAnySourcePort() throws Exception {
final ByteBuffer packet = ByteBuffer.wrap(HexDump.hexStringToByteArray(
// Ethernet header.
"wvm.edu", "10.1.105.252", null, 86400, false, 0, dhcpResults);
}
- @SmallTest
+ @Test
public void testUdpInvalidDstPort() throws Exception {
final ByteBuffer packet = ByteBuffer.wrap(HexDump.hexStringToByteArray(
// Ethernet header.
} catch (ParseException expected) {}
}
- @SmallTest
+ @Test
public void testMultipleRouters() throws Exception {
final ByteBuffer packet = ByteBuffer.wrap(HexDump.hexStringToByteArray(
// Ethernet header.
null, "192.171.189.2", null, 28800, false, 0, dhcpResults);
}
- @SmallTest
+ @Test
public void testDiscoverPacket() throws Exception {
short secs = 7;
int transactionId = 0xdeadbeef;
import static android.net.netlink.StructNlMsgHdr.NLM_F_REQUEST;
import static android.net.netlink.StructNlMsgHdr.NLM_F_ACK;
import static android.net.netlink.StructNlMsgHdr.NLM_F_REPLACE;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import android.net.netlink.NetlinkConstants;
import android.net.netlink.NetlinkErrorMessage;
import android.net.netlink.NetlinkMessage;
import android.net.netlink.StructNlMsgErr;
-import android.test.suitebuilder.annotation.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.test.filters.SmallTest;
import android.util.Log;
+
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
-import junit.framework.TestCase;
+
+import org.junit.runner.RunWith;
+import org.junit.Test;
+
import libcore.util.HexEncoding;
-public class NetlinkErrorMessageTest extends TestCase {
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class NetlinkErrorMessageTest {
private final String TAG = "NetlinkErrorMessageTest";
// Hexadecimal representation of packet capture.
public static final byte[] NLM_ERROR_OK =
HexEncoding.decode(NLM_ERROR_OK_HEX.toCharArray(), false);
- @SmallTest
+ @Test
public void testParseNlmErrorOk() {
final ByteBuffer byteBuffer = ByteBuffer.wrap(NLM_ERROR_OK);
byteBuffer.order(ByteOrder.LITTLE_ENDIAN); // For testing.
package android.net.netlink;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
import android.net.netlink.NetlinkSocket;
import android.net.netlink.RtNetlinkNeighborMessage;
import android.net.netlink.StructNdMsg;
import android.net.netlink.StructNlMsgHdr;
-import android.test.suitebuilder.annotation.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.test.filters.SmallTest;
import android.system.ErrnoException;
import android.system.NetlinkSocketAddress;
import android.system.OsConstants;
import android.util.Log;
+
import java.io.InterruptedIOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
-import junit.framework.TestCase;
+
+import org.junit.runner.RunWith;
+import org.junit.Test;
-public class NetlinkSocketTest extends TestCase {
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class NetlinkSocketTest {
private final String TAG = "NetlinkSocketTest";
- @SmallTest
+ @Test
public void testBasicWorkingGetNeighborsQuery() throws Exception {
NetlinkSocket s = new NetlinkSocket(OsConstants.NETLINK_ROUTE);
assertNotNull(s);
s.close();
}
- @SmallTest
+ @Test
public void testRepeatedCloseCallsAreQuiet() throws Exception {
// Create a working NetlinkSocket.
NetlinkSocket s = new NetlinkSocket(OsConstants.NETLINK_ROUTE);
package android.net.netlink;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
import android.net.netlink.NetlinkConstants;
import android.net.netlink.NetlinkMessage;
import android.net.netlink.RtNetlinkNeighborMessage;
import android.net.netlink.StructNdMsg;
import android.net.netlink.StructNlMsgHdr;
-import android.test.suitebuilder.annotation.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.test.filters.SmallTest;
import android.system.OsConstants;
import android.util.Log;
-import libcore.util.HexEncoding;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
-import junit.framework.TestCase;
+import org.junit.runner.RunWith;
+import org.junit.Test;
+
+import libcore.util.HexEncoding;
-public class RtNetlinkNeighborMessageTest extends TestCase {
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class RtNetlinkNeighborMessageTest {
private final String TAG = "RtNetlinkNeighborMessageTest";
// Hexadecimal representation of packet capture.
public static final byte[] RTM_GETNEIGH_RESPONSE =
HexEncoding.decode(RTM_GETNEIGH_RESPONSE_HEX.replaceAll(" ", "").toCharArray(), false);
- @SmallTest
+ @Test
public void testParseRtmDelNeigh() {
final ByteBuffer byteBuffer = ByteBuffer.wrap(RTM_DELNEIGH);
byteBuffer.order(ByteOrder.LITTLE_ENDIAN); // For testing.
assertEquals(InetAddress.parseNumericAddress("192.168.159.254"), destination);
}
- @SmallTest
+ @Test
public void testParseRtmNewNeigh() {
final ByteBuffer byteBuffer = ByteBuffer.wrap(RTM_NEWNEIGH);
byteBuffer.order(ByteOrder.LITTLE_ENDIAN); // For testing.
assertEquals(InetAddress.parseNumericAddress("fe80::86c9:b2ff:fe6a:ed4b"), destination);
}
- @SmallTest
+ @Test
public void testParseRtmGetNeighResponse() {
final ByteBuffer byteBuffer = ByteBuffer.wrap(RTM_GETNEIGH_RESPONSE);
byteBuffer.order(ByteOrder.LITTLE_ENDIAN); // For testing.
assertEquals(14, messageCount);
}
- @SmallTest
+ @Test
public void testCreateRtmNewNeighMessage() {
final int seqNo = 2635;
final int ifIndex = 14;
import static android.net.util.BlockingSocketReader.DEFAULT_RECV_BUF_SIZE;
import static android.system.OsConstants.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import android.os.Handler;
import android.os.HandlerThread;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
import android.system.ErrnoException;
import android.system.Os;
import android.system.StructTimeval;
-import libcore.io.IoBridge;
-
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import junit.framework.TestCase;
+import org.junit.runner.RunWith;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import libcore.io.IoBridge;
/**
* Tests for BlockingSocketReader.
*
* @hide
*/
-public class BlockingSocketReaderTest extends TestCase {
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class BlockingSocketReaderTest {
static final InetAddress LOOPBACK6 = Inet6Address.getLoopbackAddress();
static final StructTimeval TIMEO = StructTimeval.fromMillis(500);
}
};
- @Override
+ @Before
public void setUp() {
resetLatch();
mLocalSocket = null;
mHandlerThread.start();
}
- @Override
+ @After
public void tearDown() throws Exception {
if (mReceiver != null) {
mHandlerThread.getThreadHandler().post(() -> { mReceiver.stop(); });
sender.close();
}
+ @Test
public void testBasicWorking() throws Exception {
final Handler h = mHandlerThread.getThreadHandler();
mReceiver = new UdpLoopbackReader(h);
public FileDescriptor createFd() { return null; }
}
+ @Test
public void testMinimalRecvBufSize() throws Exception {
final Handler h = mHandlerThread.getThreadHandler();
package android.net.util;
import static android.net.util.NetworkConstants.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
-import libcore.util.HexEncoding;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.test.filters.SmallTest;
-import junit.framework.TestCase;
+import org.junit.runner.RunWith;
+import org.junit.Test;
+import libcore.util.HexEncoding;
/**
* Tests for ConnectivityPacketSummary.
*
* @hide
*/
-public class ConnectivityPacketSummaryTest extends TestCase {
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class ConnectivityPacketSummaryTest {
private static final byte[] MYHWADDR = {
asByte(0x80), asByte(0x7a), asByte(0xbf), asByte(0x6f), asByte(0x48), asByte(0xf3)
};
return ConnectivityPacketSummary.summarize(MYHWADDR, bytes);
}
+ @Test
public void testParseICMPv6DADProbe() {
final String packet =
// Ethernet
assertEquals(expected, getSummary(packet));
}
+ @Test
public void testParseICMPv6RS() {
final String packet =
// Ethernet
assertEquals(expected, getSummary(packet));
}
+ @Test
public void testParseICMPv6RA() {
final String packet =
// Ethernet
assertEquals(expected, getSummary(packet));
}
+ @Test
public void testParseICMPv6NS() {
final String packet =
// Ethernet
assertEquals(expected, getSummary(packet));
}
+ @Test
public void testInvalidICMPv6NDLength() {
final String packet =
// Ethernet
assertEquals(expected, getSummary(packet));
}
+ @Test
public void testParseICMPv6NA() {
final String packet =
// Ethernet
assertEquals(expected, getSummary(packet));
}
+ @Test
public void testParseARPRequest() {
final String packet =
// Ethernet
assertEquals(expected, getSummary(packet));
}
+ @Test
public void testParseARPReply() {
final String packet =
// Ethernet
assertEquals(expected, getSummary(packet));
}
+ @Test
public void testParseDHCPv4Discover() {
final String packet =
// Ethernet
assertTrue(getSummary(packet).startsWith(expectedPrefix));
}
+ @Test
public void testParseDHCPv4Offer() {
final String packet =
// Ethernet
assertTrue(getSummary(packet).startsWith(expectedPrefix));
}
+ @Test
public void testParseDHCPv4Request() {
final String packet =
// Ethernet
assertTrue(getSummary(packet).startsWith(expectedPrefix));
}
+ @Test
public void testParseDHCPv4Ack() {
final String packet =
// Ethernet
package android.net.util;
-import android.net.util.IpUtils;
-import android.test.suitebuilder.annotation.SmallTest;
+import static org.junit.Assert.assertEquals;
-import java.nio.ByteBuffer;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.test.filters.SmallTest;
-import junit.framework.TestCase;
+import java.nio.ByteBuffer;
+import org.junit.runner.RunWith;
+import org.junit.Test;
-public class IpUtilsTest extends TestCase {
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class IpUtilsTest {
private static final int IPV4_HEADER_LENGTH = 20;
private static final int IPV6_HEADER_LENGTH = 40;
// "hello")
// print JavaPacketDefinition(str(packet))
- @SmallTest
+ @Test
public void testIpv6TcpChecksum() throws Exception {
// packet = (scapy.IPv6(src="2001:db8::1", dst="2001:db8::2", tc=0x80) /
// scapy.TCP(sport=12345, dport=7,
assertEquals(0, IpUtils.tcpChecksum(packet, 0, IPV6_HEADER_LENGTH, transportLen));
}
- @SmallTest
+ @Test
public void testIpv4UdpChecksum() {
// packet = (scapy.IP(src="192.0.2.1", dst="192.0.2.2", tos=0x40) /
// scapy.UDP(sport=32012, dport=4500) /
import static android.net.NetworkStats.TAG_NONE;
import static android.net.NetworkStats.UID_ALL;
import static com.android.server.NetworkManagementSocketTagger.kernelToTag;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
import android.content.res.Resources;
import android.net.NetworkStats;
import android.net.TrafficStats;
+import android.support.test.InstrumentationRegistry;
import android.support.test.filters.SmallTest;
-import android.test.AndroidTestCase;
+import android.support.test.runner.AndroidJUnit4;
import com.android.frameworks.tests.net.R;
import libcore.io.IoUtils;
import libcore.io.Streams;
+import org.junit.runner.RunWith;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
/**
* Tests for {@link NetworkStatsFactory}.
*/
+@RunWith(AndroidJUnit4.class)
@SmallTest
-public class NetworkStatsFactoryTest extends AndroidTestCase {
+public class NetworkStatsFactoryTest {
private File mTestProc;
private NetworkStatsFactory mFactory;
- @Override
+ @Before
public void setUp() throws Exception {
- super.setUp();
-
- mTestProc = new File(getContext().getFilesDir(), "proc");
+ mTestProc = new File(InstrumentationRegistry.getContext().getFilesDir(), "proc");
if (mTestProc.exists()) {
IoUtils.deleteContents(mTestProc);
}
mFactory = new NetworkStatsFactory(mTestProc);
}
- @Override
+ @After
public void tearDown() throws Exception {
mFactory = null;
if (mTestProc.exists()) {
IoUtils.deleteContents(mTestProc);
}
-
- super.tearDown();
}
+ @Test
public void testNetworkStatsDetail() throws Exception {
final NetworkStats stats = parseDetailedStats(R.raw.xt_qtaguid_typical);
assertStatsEntry(stats, "rmnet2", 10001, SET_DEFAULT, 0x0, 1125899906842624L, 984L);
}
+ @Test
public void testKernelTags() throws Exception {
assertEquals(0, kernelToTag("0x0000000000000000"));
assertEquals(0x32, kernelToTag("0x0000003200000000"));
assertEquals(TrafficStats.TAG_SYSTEM_DOWNLOAD, kernelToTag("0xffffff0100000000"));
}
+ @Test
public void testNetworkStatsWithSet() throws Exception {
final NetworkStats stats = parseDetailedStats(R.raw.xt_qtaguid_typical);
assertEquals(70, stats.size());
assertStatsEntry(stats, "rmnet1", 10021, SET_FOREGROUND, 0x30100000, 742L, 3L, 1265L, 3L);
}
+ @Test
public void testNetworkStatsSingle() throws Exception {
stageFile(R.raw.xt_qtaguid_iface_typical, file("net/xt_qtaguid/iface_stat_all"));
assertStatsEntry(stats, "test2", UID_ALL, SET_ALL, TAG_NONE, 1L, 2L, 3L, 4L);
}
+ @Test
public void testNetworkStatsXt() throws Exception {
stageFile(R.raw.xt_qtaguid_iface_fmt_typical, file("net/xt_qtaguid/iface_stat_fmt"));
assertStatsEntry(stats, "rmnet2", UID_ALL, SET_ALL, TAG_NONE, 4968L, 35L, 3081L, 39L);
}
+ @Test
public void testDoubleClatAccounting() throws Exception {
NetworkStatsFactory.noteStackedIface("v4-wlan0", "wlan0");
NetworkStatsFactory.noteStackedIface("v4-wlan0", null);
}
+ @Test
public void testDoubleClatAccounting100MBDownload() throws Exception {
// Downloading 100mb from an ipv4 only destination in a foreground activity
InputStream in = null;
OutputStream out = null;
try {
- in = getContext().getResources().openRawResource(rawId);
+ in = InstrumentationRegistry.getContext().getResources().openRawResource(rawId);
out = new FileOutputStream(file);
Streams.copy(in, out);
} finally {
assertEquals("unexpected txBytes", txBytes, entry.txBytes);
assertEquals("unexpected txPackets", txPackets, entry.txPackets);
}
-
}
import static android.net.ConnectivityManager.getNetworkTypeName;
import static android.net.NetworkCapabilities.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
import static com.android.internal.util.TestUtils.waitForIdleHandler;
-
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.eq;
import android.os.SystemClock;
import android.os.UserHandle;
import android.provider.Settings;
-import android.test.AndroidTestCase;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
import android.test.mock.MockContentResolver;
-import android.test.suitebuilder.annotation.SmallTest;
import android.text.TextUtils;
import android.util.ArraySet;
import android.util.Log;
import com.android.server.net.NetworkPinner;
import com.android.server.net.NetworkPolicyManagerInternal;
+import org.junit.After;
+import org.junit.Before;
import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate;
+
/**
* Tests for {@link ConnectivityService}.
*
* Build, install and run with:
* runtest frameworks-net -c com.android.server.ConnectivityServiceTest
*/
-public class ConnectivityServiceTest extends AndroidTestCase {
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class ConnectivityServiceTest {
private static final String TAG = "ConnectivityServiceTest";
private static final int TIMEOUT_MS = 500;
private MockNetworkAgent mWiFiNetworkAgent;
private MockNetworkAgent mCellNetworkAgent;
private MockNetworkAgent mEthernetNetworkAgent;
+ private Context mContext;
// This class exists to test bindProcessToNetwork and getBoundNetworkForProcess. These methods
// do not go through ConnectivityService but talk to netd directly, so they don't automatically
waitForIdle(TIMEOUT_MS);
}
- @SmallTest
+ @Test
public void testWaitForIdle() {
final int attempts = 50; // Causes the test to take about 200ms on bullhead-eng.
// Don't overlap test NetIDs with real NetIDs as binding sockets to real networks
// can have odd side-effects, like network validations succeeding.
- final Network[] networks = ConnectivityManager.from(getContext()).getAllNetworks();
+ Context context = InstrumentationRegistry.getContext();
+ final Network[] networks = ConnectivityManager.from(context).getAllNetworks();
boolean overlaps = false;
for (Network network : networks) {
if (netId == network.netId) {
fail("ConditionVariable was blocked for more than " + TIMEOUT_MS + "ms");
}
- @Override
+ @Before
public void setUp() throws Exception {
- super.setUp();
+ mContext = InstrumentationRegistry.getContext();
// InstrumentationTestRunner prepares a looper, but AndroidJUnitRunner does not.
// http://b/25897652 .
Looper.prepare();
}
- mServiceContext = new MockContext(getContext());
+ mServiceContext = new MockContext(InstrumentationRegistry.getContext());
LocalServices.removeServiceForTest(NetworkPolicyManagerInternal.class);
LocalServices.addService(
NetworkPolicyManagerInternal.class, mock(NetworkPolicyManagerInternal.class));
mock(IpConnectivityLog.class));
mService.systemReady();
- mCm = new WrappedConnectivityManager(getContext(), mService);
+ mCm = new WrappedConnectivityManager(InstrumentationRegistry.getContext(), mService);
mCm.bindProcessToNetwork(null);
// Ensure that the default setting for Captive Portals is used for most tests
setMobileDataAlwaysOn(false);
}
+ @After
public void tearDown() throws Exception {
setMobileDataAlwaysOn(false);
if (mCellNetworkAgent != null) {
mEthernetNetworkAgent.disconnect();
mEthernetNetworkAgent = null;
}
- super.tearDown();
}
private static int transportToLegacyType(int transport) {
return cv;
}
+ @Test
public void testNetworkTypes() {
// Ensure that our mocks for the networkAttributes config variable work as expected. If they
// don't, then tests that depend on CONNECTIVITY_ACTION broadcasts for these network types
assertTrue(mCm.isNetworkSupported(TYPE_ETHERNET));
}
- @SmallTest
+ @Test
public void testLingering() throws Exception {
verifyNoNetwork();
mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
verifyNoNetwork();
}
- @SmallTest
+ @Test
public void testValidatedCellularOutscoresUnvalidatedWiFi() throws Exception {
// Test bringing up unvalidated WiFi
mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI);
verifyNoNetwork();
}
- @SmallTest
+ @Test
public void testUnvalidatedWifiOutscoresUnvalidatedCellular() throws Exception {
// Test bringing up unvalidated cellular.
mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
verifyNoNetwork();
}
- @SmallTest
+ @Test
public void testUnlingeringDoesNotValidate() throws Exception {
// Test bringing up unvalidated WiFi.
mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI);
NET_CAPABILITY_VALIDATED));
}
- @SmallTest
+ @Test
public void testCellularOutscoresWeakWifi() throws Exception {
// Test bringing up validated cellular.
mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
verifyActiveNetwork(TRANSPORT_WIFI);
}
- @SmallTest
+ @Test
public void testReapingNetwork() throws Exception {
// Test bringing up WiFi without NET_CAPABILITY_INTERNET.
// Expect it to be torn down immediately because it satisfies no requests.
waitFor(cv);
}
- @SmallTest
+ @Test
public void testCellularFallback() throws Exception {
// Test bringing up validated cellular.
mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
verifyActiveNetwork(TRANSPORT_WIFI);
}
- @SmallTest
+ @Test
public void testWiFiFallback() throws Exception {
// Test bringing up unvalidated WiFi.
mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI);
}
}
- @SmallTest
+ @Test
public void testStateChangeNetworkCallbacks() throws Exception {
final TestNetworkCallback genericNetworkCallback = new TestNetworkCallback();
final TestNetworkCallback wifiNetworkCallback = new TestNetworkCallback();
assertNoCallbacks(genericNetworkCallback, wifiNetworkCallback, cellNetworkCallback);
}
- @SmallTest
+ @Test
public void testMultipleLingering() {
NetworkRequest request = new NetworkRequest.Builder()
.clearCapabilities().addCapability(NET_CAPABILITY_NOT_METERED)
mCm.unregisterNetworkCallback(trackDefaultCallback);
}
- @SmallTest
+ @Test
public void testExplicitlySelected() {
NetworkRequest request = new NetworkRequest.Builder()
.clearCapabilities().addCapability(NET_CAPABILITY_INTERNET)
handlerThread.quit();
}
- @SmallTest
+ @Test
public void testNetworkFactoryRequests() throws Exception {
tryNetworkFactoryRequests(NET_CAPABILITY_MMS);
tryNetworkFactoryRequests(NET_CAPABILITY_SUPL);
// Skipping VALIDATED and CAPTIVE_PORTAL as they're disallowed.
}
- @SmallTest
+ @Test
public void testNoMutableNetworkRequests() throws Exception {
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, new Intent("a"), 0);
NetworkRequest request1 = new NetworkRequest.Builder()
assertException(() -> { mCm.requestNetwork(request2, pendingIntent); }, expected);
}
- @SmallTest
+ @Test
public void testMMSonWiFi() throws Exception {
// Test bringing up cellular without MMS NetworkRequest gets reaped
mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
verifyActiveNetwork(TRANSPORT_WIFI);
}
- @SmallTest
+ @Test
public void testMMSonCell() throws Exception {
// Test bringing up cellular without MMS
mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
verifyActiveNetwork(TRANSPORT_CELLULAR);
}
- @SmallTest
+ @Test
public void testCaptivePortal() {
final TestNetworkCallback captivePortalCallback = new TestNetworkCallback();
final NetworkRequest captivePortalRequest = new NetworkRequest.Builder()
validatedCallback.expectCallback(CallbackState.LOST, mWiFiNetworkAgent);
}
- @SmallTest
+ @Test
public void testCaptivePortalApp() {
final TestNetworkCallback captivePortalCallback = new TestNetworkCallback();
final NetworkRequest captivePortalRequest = new NetworkRequest.Builder()
mCm.unregisterNetworkCallback(captivePortalCallback);
}
- @SmallTest
+ @Test
public void testAvoidOrIgnoreCaptivePortals() {
final TestNetworkCallback captivePortalCallback = new TestNetworkCallback();
final NetworkRequest captivePortalRequest = new NetworkRequest.Builder()
return new NetworkRequest.Builder().addTransportType(TRANSPORT_WIFI);
}
- @SmallTest
+ @Test
public void testNetworkSpecifier() {
NetworkRequest rEmpty1 = newWifiRequestBuilder().build();
NetworkRequest rEmpty2 = newWifiRequestBuilder().setNetworkSpecifier((String) null).build();
assertNoCallbacks(cEmpty1, cEmpty2, cEmpty3, cFoo, cBar);
}
- @SmallTest
+ @Test
public void testInvalidNetworkSpecifier() {
try {
NetworkRequest.Builder builder = new NetworkRequest.Builder();
}
}
- @SmallTest
+ @Test
public void testNetworkSpecifierUidSpoofSecurityException() {
class UidAwareNetworkSpecifier extends NetworkSpecifier implements Parcelable {
@Override
}
}
- @SmallTest
+ @Test
public void testRegisterDefaultNetworkCallback() throws Exception {
final TestNetworkCallback defaultNetworkCallback = new TestNetworkCallback();
mCm.registerDefaultNetworkCallback(defaultNetworkCallback);
defaultNetworkCallback.expectCallback(CallbackState.LOST, mCellNetworkAgent);
}
- @SmallTest
+ @Test
public void testAdditionalStateCallbacks() throws Exception {
// File a network request for mobile.
final TestNetworkCallback cellNetworkCallback = new TestNetworkCallback();
return nc.hasCapability(NET_CAPABILITY_FOREGROUND);
}
- @SmallTest
+ @Test
public void testBackgroundNetworks() throws Exception {
// Create a background request. We can't do this ourselves because ConnectivityService
// doesn't have an API for it. So just turn on mobile data always on.
return false;
}
- @SmallTest
+ @Test
public void testMobileDataAlwaysOn() throws Exception {
final TestNetworkCallback cellNetworkCallback = new TestNetworkCallback();
final NetworkRequest cellRequest = new NetworkRequest.Builder()
handlerThread.quit();
}
- @SmallTest
+ @Test
public void testAvoidBadWifiSetting() throws Exception {
final ContentResolver cr = mServiceContext.getContentResolver();
final WrappedMultinetworkPolicyTracker tracker = mService.getMultinetworkPolicyTracker();
assertTrue(tracker.shouldNotifyWifiUnvalidated());
}
- @SmallTest
+ @Test
public void testAvoidBadWifi() throws Exception {
final ContentResolver cr = mServiceContext.getContentResolver();
final WrappedMultinetworkPolicyTracker tracker = mService.getMultinetworkPolicyTracker();
mCm.unregisterNetworkCallback(defaultCallback);
}
- @SmallTest
+ @Test
public void testMeteredMultipathPreferenceSetting() throws Exception {
final ContentResolver cr = mServiceContext.getContentResolver();
final WrappedMultinetworkPolicyTracker tracker = mService.getMultinetworkPolicyTracker();
* Validate that a satisfied network request does not trigger onUnavailable() once the
* time-out period expires.
*/
- @SmallTest
+ @Test
public void testSatisfiedNetworkRequestDoesNotTriggerOnUnavailable() {
NetworkRequest nr = new NetworkRequest.Builder().addTransportType(
NetworkCapabilities.TRANSPORT_WIFI).build();
* Validate that a satisfied network request followed by a disconnected (lost) network does
* not trigger onUnavailable() once the time-out period expires.
*/
- @SmallTest
+ @Test
public void testSatisfiedThenLostNetworkRequestDoesNotTriggerOnUnavailable() {
NetworkRequest nr = new NetworkRequest.Builder().addTransportType(
NetworkCapabilities.TRANSPORT_WIFI).build();
* callback is called when time-out expires. Then validate that if network request is
* (somehow) satisfied - the callback isn't called later.
*/
- @SmallTest
+ @Test
public void testTimedoutNetworkRequest() {
NetworkRequest nr = new NetworkRequest.Builder().addTransportType(
NetworkCapabilities.TRANSPORT_WIFI).build();
* Validate that when a network request is unregistered (cancelled), no posterior event can
* trigger the callback.
*/
- @SmallTest
+ @Test
public void testNoCallbackAfterUnregisteredNetworkRequest() {
NetworkRequest nr = new NetworkRequest.Builder().addTransportType(
NetworkCapabilities.TRANSPORT_WIFI).build();
return mWiFiNetworkAgent.getNetwork();
}
- @SmallTest
+ @Test
public void testPacketKeepalives() throws Exception {
InetAddress myIPv4 = InetAddress.getByName("192.0.2.129");
InetAddress notMyIPv4 = InetAddress.getByName("192.0.2.35");
callback3.expectStopped();
}
- @SmallTest
+ @Test
public void testGetCaptivePortalServerUrl() throws Exception {
String url = mCm.getCaptivePortalServerUrl();
assertEquals("http://connectivitycheck.gstatic.com/generate_204", url);
assertEquals(mCellNetworkAgent.getNetwork(), mCm.getActiveNetwork());
}
- @SmallTest
+ @Test
public void testNetworkPinner() {
NetworkRequest wifiRequest = new NetworkRequest.Builder()
.addTransportType(TRANSPORT_WIFI)
assertPinnedToWifiWithCellDefault();
}
- @SmallTest
+ @Test
public void testNetworkCallbackMaximum() {
final int MAX_REQUESTS = 100;
final int CALLBACKS = 90;
}
}
- @SmallTest
+ @Test
public void testNetworkInfoOfTypeNone() {
ConditionVariable broadcastCV = waitForConnectivityBroadcasts(1);
}
}
- @SmallTest
+ @Test
public void testDeprecatedAndUnsupportedOperations() throws Exception {
final int TYPE_NONE = ConnectivityManager.TYPE_NONE;
assertNull(mCm.getNetworkInfo(TYPE_NONE));
assertException(() -> { mCm.requestRouteToHostAddress(TYPE_NONE, null); }, unsupported);
}
- @SmallTest
+ @Test
public void testLinkPropertiesEnsuresDirectlyConnectedRoutes() {
final NetworkRequest networkRequest = new NetworkRequest.Builder()
.addTransportType(TRANSPORT_WIFI).build();
import android.os.Binder;
import android.os.ParcelFileDescriptor;
import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
import android.system.ErrnoException;
import android.system.Os;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
/** Unit tests for {@link IpSecService}. */
@SmallTest
-@RunWith(JUnit4.class)
+@RunWith(AndroidJUnit4.class)
public class IpSecServiceTest {
private static final int DROID_SPI = 0xD1201D;
package com.android.server.connectivity;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.anyBoolean;
+import static org.mockito.Mockito.anyInt;
+import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.reset;
+
import android.app.PendingIntent;
import android.content.Context;
import android.content.res.Resources;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkMisc;
-import android.test.suitebuilder.annotation.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.test.filters.SmallTest;
import android.text.format.DateUtils;
+
import com.android.internal.R;
import com.android.server.ConnectivityService;
import com.android.server.connectivity.NetworkNotificationManager;
import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
-import junit.framework.TestCase;
+
+import org.junit.runner.RunWith;
+import org.junit.Before;
+import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.anyBoolean;
-import static org.mockito.Mockito.anyInt;
-import static org.mockito.Mockito.eq;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-import static org.mockito.Mockito.reset;
-
-public class LingerMonitorTest extends TestCase {
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class LingerMonitorTest {
static final String CELLULAR = "CELLULAR";
static final String WIFI = "WIFI";
@Mock NetworkNotificationManager mNotifier;
@Mock Resources mResources;
+ @Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(mCtx.getResources()).thenReturn(mResources);
mMonitor = new TestableLingerMonitor(mCtx, mNotifier, HIGH_DAILY_LIMIT, HIGH_RATE_LIMIT);
}
- @SmallTest
+ @Test
public void testTransitions() {
setNotificationSwitch(transition(WIFI, CELLULAR));
NetworkAgentInfo nai1 = wifiNai(100);
assertFalse(mMonitor.isNotificationEnabled(nai2, nai1));
}
- @SmallTest
+ @Test
public void testNotificationOnLinger() {
setNotificationSwitch(transition(WIFI, CELLULAR));
setNotificationType(LingerMonitor.NOTIFY_TYPE_NOTIFICATION);
verifyNotification(from, to);
}
- @SmallTest
+ @Test
public void testToastOnLinger() {
setNotificationSwitch(transition(WIFI, CELLULAR));
setNotificationType(LingerMonitor.NOTIFY_TYPE_TOAST);
verifyToast(from, to);
}
- @SmallTest
+ @Test
public void testNotificationClearedAfterDisconnect() {
setNotificationSwitch(transition(WIFI, CELLULAR));
setNotificationType(LingerMonitor.NOTIFY_TYPE_NOTIFICATION);
verify(mNotifier, times(1)).clearNotification(100);
}
- @SmallTest
+ @Test
public void testNotificationClearedAfterSwitchingBack() {
setNotificationSwitch(transition(WIFI, CELLULAR));
setNotificationType(LingerMonitor.NOTIFY_TYPE_NOTIFICATION);
verify(mNotifier, times(1)).clearNotification(100);
}
- @SmallTest
+ @Test
public void testUniqueToast() {
setNotificationSwitch(transition(WIFI, CELLULAR));
setNotificationType(LingerMonitor.NOTIFY_TYPE_TOAST);
verifyNoNotifications();
}
- @SmallTest
+ @Test
public void testMultipleNotifications() {
setNotificationSwitch(transition(WIFI, CELLULAR));
setNotificationType(LingerMonitor.NOTIFY_TYPE_NOTIFICATION);
verifyNotification(wifi2, cell);
}
- @SmallTest
+ @Test
public void testRateLimiting() throws InterruptedException {
mMonitor = new TestableLingerMonitor(mCtx, mNotifier, HIGH_DAILY_LIMIT, LOW_RATE_LIMIT);
verifyNoNotifications();
}
- @SmallTest
+ @Test
public void testDailyLimiting() throws InterruptedException {
mMonitor = new TestableLingerMonitor(mCtx, mNotifier, LOW_DAILY_LIMIT, HIGH_RATE_LIMIT);
verifyNoNotifications();
}
- @SmallTest
+ @Test
public void testUniqueNotification() {
setNotificationSwitch(transition(WIFI, CELLULAR));
setNotificationType(LingerMonitor.NOTIFY_TYPE_NOTIFICATION);
verifyNotification(from, to);
}
- @SmallTest
+ @Test
public void testIgnoreNeverValidatedNetworks() {
setNotificationType(LingerMonitor.NOTIFY_TYPE_TOAST);
setNotificationSwitch(transition(WIFI, CELLULAR));
verifyNoNotifications();
}
- @SmallTest
+ @Test
public void testIgnoreCurrentlyValidatedNetworks() {
setNotificationType(LingerMonitor.NOTIFY_TYPE_TOAST);
setNotificationSwitch(transition(WIFI, CELLULAR));
verifyNoNotifications();
}
- @SmallTest
+ @Test
public void testNoNotificationType() {
setNotificationType(LingerMonitor.NOTIFY_TYPE_TOAST);
setNotificationSwitch();
verifyNoNotifications();
}
- @SmallTest
+ @Test
public void testNoTransitionToNotify() {
setNotificationType(LingerMonitor.NOTIFY_TYPE_NONE);
setNotificationSwitch(transition(WIFI, CELLULAR));
verifyNoNotifications();
}
- @SmallTest
+ @Test
public void testDifferentTransitionToNotify() {
setNotificationType(LingerMonitor.NOTIFY_TYPE_TOAST);
setNotificationSwitch(transition(CELLULAR, WIFI));
import android.content.res.Resources;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.test.filters.SmallTest;
import android.telephony.TelephonyManager;
-import android.test.suitebuilder.annotation.SmallTest;
+
import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
+
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
-import junit.framework.TestCase;
+
+import org.junit.runner.RunWith;
+import org.junit.Before;
+import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-public class NetworkNotificationManagerTest extends TestCase {
+
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class NetworkNotificationManagerTest {
static final NetworkCapabilities CELL_CAPABILITIES = new NetworkCapabilities();
static final NetworkCapabilities WIFI_CAPABILITIES = new NetworkCapabilities();
NetworkNotificationManager mManager;
+ @Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mCaptor = ArgumentCaptor.forClass(Notification.class);
mManager = new NetworkNotificationManager(mCtx, mTelephonyManager, mNotificationManager);
}
- @SmallTest
+ @Test
public void testNotificationsShownAndCleared() {
final int NETWORK_ID_BASE = 100;
List<NotificationType> types = Arrays.asList(NotificationType.values());
}
}
- @SmallTest
+ @Test
public void testNoInternetNotificationsNotShownForCellular() {
mManager.showNotification(100, NO_INTERNET, mCellNai, mWifiNai, null, false);
mManager.showNotification(101, LOST_INTERNET, mCellNai, mWifiNai, null, false);
verify(mNotificationManager, times(1)).notifyAsUser(eq(tag), eq(eventId), any(), any());
}
- @SmallTest
+ @Test
public void testNotificationsNotShownIfNoInternetCapability() {
mWifiNai.networkCapabilities = new NetworkCapabilities();
mWifiNai.networkCapabilities .addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
verify(mNotificationManager, never()).notifyAsUser(any(), anyInt(), any(), any());
}
- @SmallTest
+ @Test
public void testDuplicatedNotificationsNoInternetThenSignIn() {
final int id = 101;
final String tag = NetworkNotificationManager.tagFor(id);
verify(mNotificationManager, times(1)).cancelAsUser(eq(tag), eq(SIGN_IN.eventId), any());
}
- @SmallTest
+ @Test
public void testDuplicatedNotificationsSignInThenNoInternet() {
final int id = 101;
final String tag = NetworkNotificationManager.tagFor(id);
import static android.content.pm.UserInfo.FLAG_MANAGED_PROFILE;
import static android.content.pm.UserInfo.FLAG_PRIMARY;
import static android.content.pm.UserInfo.FLAG_RESTRICTED;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import static org.mockito.AdditionalMatchers.*;
import static org.mockito.Mockito.*;
import android.os.Looper;
import android.os.UserHandle;
import android.os.UserManager;
-import android.test.AndroidTestCase;
-import android.test.suitebuilder.annotation.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.test.filters.SmallTest;
import android.util.ArrayMap;
import android.util.ArraySet;
import com.android.internal.R;
import com.android.internal.net.VpnConfig;
+import org.junit.runner.RunWith;
+import org.junit.Before;
+import org.junit.Test;
import org.mockito.Answers;
import org.mockito.InOrder;
import org.mockito.Mock;
import java.util.Map;
import java.util.Set;
+
/**
* Tests for {@link Vpn}.
*
* Build, install and run with:
- * runtest --path java/com/android/server/connectivity/VpnTest.java
+ * runtest frameworks-net -c com.android.server.connectivity.VpnTest
*/
-public class VpnTest extends AndroidTestCase {
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class VpnTest {
private static final String TAG = "VpnTest";
// Mock users
@Mock private NotificationManager mNotificationManager;
@Mock private Vpn.SystemServices mSystemServices;
- @Override
+ @Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
doNothing().when(mNetService).registerObserver(any());
}
- @SmallTest
+ @Test
public void testRestrictedProfilesAreAddedToVpn() {
setMockedUsers(primaryUser, secondaryUser, restrictedProfileA, restrictedProfileB);
})), ranges);
}
- @SmallTest
+ @Test
public void testManagedProfilesAreNotAddedToVpn() {
setMockedUsers(primaryUser, managedProfileA);
})), ranges);
}
- @SmallTest
+ @Test
public void testAddUserToVpnOnlyAddsOneUser() {
setMockedUsers(primaryUser, restrictedProfileA, managedProfileA);
})), ranges);
}
- @SmallTest
+ @Test
public void testUidWhiteAndBlacklist() throws Exception {
final Vpn vpn = createVpn(primaryUser.id);
final UidRange user = UidRange.createForUser(primaryUser.id);
})), disallow);
}
- @SmallTest
+ @Test
public void testLockdownChangingPackage() throws Exception {
final Vpn vpn = createVpn(primaryUser.id);
final UidRange user = UidRange.createForUser(primaryUser.id);
assertUnblocked(vpn, user.start + PKG_UIDS[3]);
}
- @SmallTest
+ @Test
public void testLockdownAddingAProfile() throws Exception {
final Vpn vpn = createVpn(primaryUser.id);
setMockedUsers(primaryUser);
}));
}
- @SmallTest
+ @Test
public void testLockdownRuleRepeatability() throws Exception {
final Vpn vpn = createVpn(primaryUser.id);
verify(mNetService, times(2)).setAllowOnlyVpnForUids(anyBoolean(), any(UidRange[].class));
}
- @SmallTest
+ @Test
public void testLockdownRuleReversibility() throws Exception {
final Vpn vpn = createVpn(primaryUser.id);
order.verify(mNetService).setAllowOnlyVpnForUids(eq(true), aryEq(entireUser));
}
- @SmallTest
+ @Test
public void testIsAlwaysOnPackageSupported() throws Exception {
final Vpn vpn = createVpn(primaryUser.id);
assertFalse(vpn.isAlwaysOnPackageSupported(PKGS[0]));
}
- @SmallTest
+ @Test
public void testNotificationShownForAlwaysOnApp() {
final UserHandle userHandle = UserHandle.of(primaryUser.id);
final Vpn vpn = createVpn(primaryUser.id);