diff options
36 files changed, 588 insertions, 3798 deletions
diff --git a/cmds/dumpstate/Android.mk b/cmds/dumpstate/Android.mk index 27891ecf6fd1..431a55658b48 100644 --- a/cmds/dumpstate/Android.mk +++ b/cmds/dumpstate/Android.mk @@ -15,15 +15,4 @@ LOCAL_SHARED_LIBRARIES := libcutils include $(BUILD_EXECUTABLE) -COMMANDS = dumpcrash -SYMLINKS := $(addprefix $(TARGET_OUT_EXECUTABLES)/,$(COMMANDS)) -$(SYMLINKS): DUMPSTATE_BINARY := dumpstate -$(SYMLINKS): $(LOCAL_INSTALLED_MODULE) $(LOCAL_PATH)/Android.mk - @echo "Symlink: $@ -> $(DUMPSTATE_BINARY)" - @mkdir -p $(dir $@) - @rm -rf $@ - $(hide) ln -sf $(DUMPSTATE_BINARY) $@ - -ALL_DEFAULT_INSTALLED_MODULES += $(SYMLINKS) - endif diff --git a/cmds/dumpstate/dumpstate.c b/cmds/dumpstate/dumpstate.c index a2b5d8df9f2c..9300915fa458 100644 --- a/cmds/dumpstate/dumpstate.c +++ b/cmds/dumpstate/dumpstate.c @@ -14,361 +14,254 @@ * limitations under the License. */ +#include <errno.h> +#include <fcntl.h> +#include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> -#include <unistd.h> +#include <sys/resource.h> #include <sys/stat.h> -#include <limits.h> -#include <errno.h> -#include <fcntl.h> #include <sys/time.h> -#include <sys/resource.h> +#include <unistd.h> -#include <cutils/sockets.h> -#include "private/android_filesystem_config.h" +#include <cutils/properties.h> +#include "private/android_filesystem_config.h" #define LOG_TAG "dumpstate" #include <utils/Log.h> #include "dumpstate.h" -static char* const gzip_args[] = { "gzip", "-6", 0 }; -static int start_pattern[] = { 150, 0 }; -static int end_pattern[] = { 75, 50, 75, 50, 75, 0 }; - -static struct tm now; - -static void dump_kernel_log(const char *path, const char *title) ; +/* read before root is shed */ +static char cmdline_buf[16384] = "(unknown)"; +static const char *dump_traces_path = NULL; /* dumps the current system state to stdout */ -static void dumpstate(int full) { - if (full) { - PRINT("========================================================"); - PRINT("== dumpstate"); - PRINT("========================================================"); - PRINT("------ MEMORY INFO ------"); - DUMP("/proc/meminfo"); - PRINT("------ CPU INFO ------"); - EXEC7("top", "-n", "1", "-d", "1", "-m", "30", "-t"); - PRINT("------ PROCRANK ------"); - EXEC_XBIN("procrank"); - PRINT("------ VIRTUAL MEMORY STATS ------"); - DUMP("/proc/vmstat"); - PRINT("------ VMALLOC INFO ------"); - DUMP("/proc/vmallocinfo"); - PRINT("------ SLAB INFO ------"); - DUMP("/proc/slabinfo"); - PRINT("------ ZONEINFO ------"); - DUMP("/proc/zoneinfo"); - PRINT("------ SYSTEM LOG ------"); - EXEC4("logcat", "-v", "time", "-d", "*:v"); - PRINT("------ VM TRACES ------"); - DUMP("/data/anr/traces.txt"); - PRINT("------ EVENT LOG TAGS ------"); - DUMP("/etc/event-log-tags"); - PRINT("------ EVENT LOG ------"); - EXEC6("logcat", "-b", "events", "-v", "time", "-d", "*:v"); - PRINT("------ RADIO LOG ------"); - EXEC6("logcat", "-b", "radio", "-v", "time", "-d", "*:v"); - PRINT("------ NETWORK STATE ------"); - PRINT("Interfaces:"); - EXEC("netcfg"); - PRINT(""); - PRINT("Routes:"); - DUMP("/proc/net/route"); -#ifdef FWDUMP_bcm4329 - PRINT("Dump wlan FW log"); - EXEC_XBIN6("su", "root","dhdutil","-i","eth0","upload","/data/local/tmp/wlan_crash.dump"); -#endif - PRINT("------ SYSTEM PROPERTIES ------"); - print_properties(); - PRINT("------ KERNEL LOG ------"); - EXEC("dmesg"); - PRINT("------ KERNEL WAKELOCKS ------"); - DUMP("/proc/wakelocks"); - PRINT("------ KERNEL CPUFREQ ------"); - DUMP("/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state"); - PRINT(""); - PRINT("------ PROCESSES ------"); - EXEC1("ps", "-P"); - PRINT("------ PROCESSES AND THREADS ------"); - EXEC3("ps", "-t", "-p", "-P"); - PRINT("------ LIBRANK ------"); - EXEC_XBIN("librank"); - PRINT("------ BINDER FAILED TRANSACTION LOG ------"); - DUMP("/proc/binder/failed_transaction_log"); - PRINT(""); - PRINT("------ BINDER TRANSACTION LOG ------"); - DUMP("/proc/binder/transaction_log"); - PRINT(""); - PRINT("------ BINDER TRANSACTIONS ------"); - DUMP("/proc/binder/transactions"); - PRINT(""); - PRINT("------ BINDER STATS ------"); - DUMP("/proc/binder/stats"); - PRINT(""); - PRINT("------ BINDER PROCESS STATE: $i ------"); - DUMP_FILES("/proc/binder/proc"); - PRINT("------ FILESYSTEMS ------"); - EXEC("df"); - PRINT("------ PACKAGE SETTINGS ------"); - DUMP("/data/system/packages.xml"); - PRINT("------ PACKAGE UID ERRORS ------"); - DUMP("/data/system/uiderrors.txt"); - - dump_kernel_log("/proc/last_kmsg", "LAST KMSG"); - - PRINT("------ LAST RADIO LOG ------"); - EXEC1("parse_radio_log", "/proc/last_radio_log"); - - dump_kernel_log("/data/dontpanic/apanic_console", - "PANIC CONSOLE"); - dump_kernel_log("/data/dontpanic/apanic_threads", - "PANIC THREADS"); - - PRINT("------ BACKLIGHTS ------"); - DUMP_PROMPT("LCD brightness=", "/sys/class/leds/lcd-backlight/brightness"); - DUMP_PROMPT("Button brightness=", "/sys/class/leds/button-backlight/brightness"); - DUMP_PROMPT("Keyboard brightness=", "/sys/class/leds/keyboard-backlight/brightness"); - DUMP_PROMPT("ALS mode=", "/sys/class/leds/lcd-backlight/als"); - DUMP_PROMPT("LCD driver registers:\n", "/sys/class/leds/lcd-backlight/registers"); +static void dumpstate() { + time_t now = time(NULL); + char build[PROPERTY_VALUE_MAX], fingerprint[PROPERTY_VALUE_MAX]; + char radio[PROPERTY_VALUE_MAX], bootloader[PROPERTY_VALUE_MAX]; + char network[PROPERTY_VALUE_MAX], date[80]; + + property_get("ro.build.display.id", build, "(unknown)"); + property_get("ro.build.fingerprint", fingerprint, "(unknown)"); + property_get("ro.baseband", radio, "(unknown)"); + property_get("ro.bootloader", bootloader, "(unknown)"); + property_get("gsm.operator.alpha", network, "(unknown)"); + strftime(date, sizeof(date), "%Y-%m-%d %H:%M:%S", localtime(&now)); + + printf("========================================================\n"); + printf("== dumpstate: %s\n", date); + printf("========================================================\n"); + + printf("\n"); + printf("Build: %s\n", build); + printf("Bootloader: %s\n", bootloader); + printf("Radio: %s\n", radio); + printf("Network: %s\n", network); + + printf("Kernel: "); + dump_file(NULL, "/proc/version"); + printf("Command line: %s\n", strtok(cmdline_buf, "\n")); + printf("\n"); + + dump_file("MEMORY INFO", "/proc/meminfo"); + run_command("CPU INFO", 10, "top", "-n", "1", "-d", "1", "-m", "30", "-t", NULL); + run_command("PROCRANK", 20, "procrank", NULL); + dump_file("VIRTUAL MEMORY STATS", "/proc/vmstat"); + dump_file("VMALLOC INFO", "/proc/vmallocinfo"); + dump_file("SLAB INFO", "/proc/slabinfo"); + dump_file("ZONEINFO", "/proc/zoneinfo"); + + run_command("SYSTEM LOG", 20, "logcat", "-v", "time", "-d", "*:v", NULL); + + /* show the traces we collected in main(), if that was done */ + if (dump_traces_path != NULL) { + dump_file("VM TRACES JUST NOW", dump_traces_path); } - PRINT("========================================================"); - PRINT("== build.prop"); - PRINT("========================================================"); - - /* the crash server parses key-value pairs between the VERSION INFO and - * END lines so we can aggregate crash reports based on this data. - */ - PRINT("------ VERSION INFO ------"); - print_date("currenttime=", &now); - DUMP_PROMPT("kernel.version=", "/proc/version"); - DUMP_PROMPT("kernel.cmdline=", "/proc/cmdline"); - DUMP("/system/build.prop"); - PROPERTY("gsm.version.ril-impl"); - PROPERTY("gsm.version.baseband"); - PROPERTY("gsm.imei"); - PROPERTY("gsm.sim.operator.numeric"); - PROPERTY("gsm.operator.alpha"); - PRINT("------ END ------"); - - if (full) { - PRINT("========================================================"); - PRINT("== dumpsys"); - PRINT("========================================================"); - /* the full dumpsys is starting to take a long time, so we need - to increase its timeout. we really need to do the timeouts in - dumpsys itself... */ - EXEC_TIMEOUT("dumpsys", 60); + + /* only show ANR traces if they're less than 15 minutes old */ + struct stat st; + char anr_traces_path[PATH_MAX]; + property_get("dalvik.vm.stack-trace-file", anr_traces_path, ""); + if (anr_traces_path[0] && !stat(anr_traces_path, &st) && time(NULL) - st.st_mtime < 15 * 60) { + dump_file("VM TRACES AT LAST ANR", anr_traces_path); } -} -/* used to check the file name passed via argv[0] */ -static int check_command_name(const char* name, const char* test) { - int name_length, test_length; + // dump_file("EVENT LOG TAGS", "/etc/event-log-tags"); + run_command("EVENT LOG", 20, "logcat", "-b", "events", "-v", "time", "-d", "*:v", NULL); + run_command("RADIO LOG", 20, "logcat", "-b", "radio", "-v", "time", "-d", "*:v", NULL); - if (!strcmp(name, test)) - return 1; + run_command("NETWORK INTERFACES", 10, "netcfg", NULL); + dump_file("NETWORK ROUTES", "/proc/net/route"); - name_length = strlen(name); - test_length = strlen(test); +#ifdef FWDUMP_bcm4329 + run_command("DUMP WIFI FIRMWARE LOG", 60, + "dhdutil", "-i", "eth0", "upload", "/data/local/tmp/wlan_crash.dump", NULL); +#endif - if (name_length > test_length + 2) { - name += (name_length - test_length); - if (name[-1] != '/') - return 0; - if (!strcmp(name, test)) - return 1; - } + print_properties(); + + run_command("KERNEL LOG", 20, "dmesg", NULL); + + dump_file("KERNEL WAKELOCKS", "/proc/wakelocks"); + dump_file("KERNEL CPUFREQ", "/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state"); + + run_command("PROCESSES", 10, "ps", "-P", NULL); + run_command("PROCESSES AND THREADS", 10, "ps", "-t", "-p", "-P", NULL); + run_command("LIBRANK", 10, "librank", NULL); + + dump_file("BINDER FAILED TRANSACTION LOG", "/proc/binder/failed_transaction_log"); + dump_file("BINDER TRANSACTION LOG", "/proc/binder/transaction_log"); + dump_file("BINDER TRANSACTIONS", "/proc/binder/transactions"); + dump_file("BINDER STATS", "/proc/binder/stats"); + run_command("BINDER PROCESS STATE", 10, "sh", "-c", "cat /proc/binder/proc/*"); + + run_command("FILESYSTEMS & FREE SPACE", 10, "df", NULL); + + dump_file("PACKAGE SETTINGS", "/data/system/packages.xml"); + dump_file("PACKAGE UID ERRORS", "/data/system/uiderrors.txt"); + + dump_file("LAST KMSG", "/proc/last_kmsg"); + run_command("LAST RADIO LOG", 10, "parse_radio_log", "/proc/last_radio_log", NULL); + dump_file("LAST PANIC CONSOLE", "/data/dontpanic/apanic_console"); + dump_file("LAST PANIC THREADS", "/data/dontpanic/apanic_threads"); + + printf("----- BACKLIGHTS -----\n"); + printf("LCD brightness="); + dump_file(NULL, "/sys/class/leds/lcd-backlight/brightness"); + printf("Button brightness="); + dump_file(NULL, "/sys/class/leds/button-backlight/brightness"); + printf("Keyboard brightness="); + dump_file(NULL, "/sys/class/leds/keyboard-backlight/brightness"); + printf("ALS mode="); + dump_file(NULL, "/sys/class/leds/lcd-backlight/als"); + printf("LCD driver registers:\n"); + dump_file(NULL, "/sys/class/leds/lcd-backlight/registers"); + printf("\n"); + + printf("========================================================\n"); + printf("== Android Framework Services\n"); + printf("========================================================\n"); + + /* the full dumpsys is starting to take a long time, so we need + to increase its timeout. we really need to do the timeouts in + dumpsys itself... */ + run_command("DUMPSYS", 60, "dumpsys", NULL); +} - return 0; + +static void usage() { + fprintf(stderr, "usage: dumpstate [-d] [-o file] [-s] [-z]\n" + " -d: append date to filename (requires -o)\n" + " -o: write to file (instead of stdout)\n" + " -s: write output to control socket (for init)\n" + " -z: gzip output (requires -o)\n"); } int main(int argc, char *argv[]) { - int dumpcrash = check_command_name(argv[0], "dumpcrash"); - int add_date = 0; - char* outfile = 0; - int vibrate = 0; - int compress = 0; - int socket = 0; - int c, fd, vibrate_fd, fds[2]; - char path[PATH_MAX]; - pid_t pid; - gid_t groups[] = { AID_LOG, AID_SDCARD_RW }; + int do_add_date = 0; + int do_compress = 0; + char* use_outfile = 0; + int use_socket = 0; LOGI("begin\n"); /* set as high priority, and protect from OOM killer */ setpriority(PRIO_PROCESS, 0, -20); - protect_from_oom_killer(); + FILE *oom_adj = fopen("/proc/self/oom_adj", "w"); + if (oom_adj) { + fputs("-17", oom_adj); + fclose(oom_adj); + } - get_time(&now); + /* very first thing, collect VM traces from Dalvik (needs root) */ + dump_traces_path = dump_vm_traces(); - do { - c = getopt(argc, argv, "do:svz"); - if (c == EOF) - break; + int c; + while ((c = getopt(argc, argv, "dho:svz")) != -1) { switch (c) { - case 'd': - add_date = 1; - break; - case 'o': - outfile = optarg; - break; - case 'v': - vibrate = 1; - break; - case 'z': - compress = 1; - break; - case 's': - socket = 1; - break; - case '?': - fprintf(stderr, "%s: invalid option -%c\n", - argv[0], optopt); + case 'd': do_add_date = 1; break; + case 'o': use_outfile = optarg; break; + case 's': use_socket = 1; break; + case 'v': break; // compatibility no-op + case 'z': do_compress = 6; break; + case '?': printf("\n"); + case 'h': + usage(); exit(1); } - } while (1); + } - /* open vibrator before switching user */ - if (vibrate) { - vibrate_fd = open("/sys/class/timed_output/vibrator/enable", O_WRONLY); - if (vibrate_fd > 0) - fcntl(vibrate_fd, F_SETFD, FD_CLOEXEC); - } else - vibrate_fd = -1; + /* open the vibrator before dropping root */ + FILE *vibrator = fopen("/sys/class/timed_output/vibrator/enable", "w"); + if (vibrator) fcntl(fileno(vibrator), F_SETFD, FD_CLOEXEC); + + /* read /proc/cmdline before dropping root */ + FILE *cmdline = fopen("/proc/cmdline", "r"); + if (cmdline != NULL) { + fgets(cmdline_buf, sizeof(cmdline_buf), cmdline); + fclose(cmdline); + } /* switch to non-root user and group */ + gid_t groups[] = { AID_LOG, AID_SDCARD_RW }; setgroups(sizeof(groups)/sizeof(groups[0]), groups); setuid(AID_SHELL); - /* make it safe to use both printf and STDOUT_FILENO */ - setvbuf(stdout, 0, _IONBF, 0); - - if (socket) { - struct sockaddr addr; - socklen_t alen; - - int s = android_get_control_socket("dumpstate"); - if (s < 0) { - fprintf(stderr, "could not open dumpstate socket\n"); - exit(1); - } - if (listen(s, 4) < 0) { - fprintf(stderr, "could not listen on dumpstate socket\n"); - exit(1); + char path[PATH_MAX], tmp_path[PATH_MAX]; + pid_t gzip_pid = -1; + + if (use_socket) { + redirect_to_socket(stdout, "dumpstate"); + } else if (use_outfile) { + strlcpy(path, use_outfile, sizeof(path)); + if (do_add_date) { + char date[80]; + time_t now = time(NULL); + strftime(date, sizeof(date), "-%Y-%m-%d-%H-%M-%S", localtime(&now)); + strlcat(path, date, sizeof(path)); } + strlcat(path, ".txt", sizeof(path)); + if (do_compress) strlcat(path, ".gz", sizeof(path)); + strlcpy(tmp_path, path, sizeof(tmp_path)); + strlcat(tmp_path, ".tmp", sizeof(tmp_path)); + gzip_pid = redirect_to_file(stdout, tmp_path, do_compress); + } - alen = sizeof(addr); - fd = accept(s, &addr, &alen); - if (fd < 0) { - fprintf(stderr, "could not accept dumpstate socket\n"); - exit(1); - } + /* bzzzzzz */ + if (vibrator) { + fputs("150", vibrator); + fflush(vibrator); + } - /* redirect stdout to the socket */ - dup2(fd, STDOUT_FILENO); - close(fd); - } else if (outfile) { - if (strlen(outfile) > sizeof(path) - 100) - exit(1); - - strcpy(path, outfile); - if (add_date) { - char date[260]; - strftime(date, sizeof(date), - "-%Y-%m-%d-%H-%M-%S", - &now); - strcat(path, date); - } - if (compress) - strcat(path, ".gz"); - else - strcat(path, ".txt"); - - /* ensure that all directories in the path exist */ - create_directories(path); - fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); - if (fd < 0) - return fd; - - if (compress) { - pipe(fds); - - /* redirect our stdout to the pipe */ - dup2(fds[1], STDOUT_FILENO); - close(fds[1]); - - if ((pid = fork()) < 0) - { - fprintf(stderr, "fork error\n"); - exit(1); - } - - if (pid) { - /* parent case */ - - /* close our copy of the input to gzip */ - close(fds[0]); - /* close our copy of the output file */ - close(fd); - } else { - /* child case */ - - /* redirect our input pipe to stdin */ - dup2(fds[0], STDIN_FILENO); - close(fds[0]); - - /* redirect stdout to the output file */ - dup2(fd, STDOUT_FILENO); - close(fd); - - /* run gzip to postprocess our output */ - execv("/system/bin/gzip", gzip_args); - fprintf(stderr, "execv returned\n"); - } - } else { - /* redirect stdout to the output file */ - dup2(fd, STDOUT_FILENO); - close(fd); + dumpstate(); + + /* bzzz bzzz bzzz */ + if (vibrator) { + int i; + for (i = 0; i < 3; i++) { + fputs("75\n", vibrator); + fflush(vibrator); + usleep((75 + 50) * 1000); } + fclose(vibrator); } - /* else everything will print to stdout */ - if (vibrate) { - vibrate_pattern(vibrate_fd, start_pattern); - } - dumpstate(!dumpcrash); - if (vibrate) { - vibrate_pattern(vibrate_fd, end_pattern); - close(vibrate_fd); + /* wait for gzip to finish, otherwise it might get killed when we exit */ + if (gzip_pid > 0) { + fclose(stdout); + waitpid(gzip_pid, NULL, 0); } - /* so gzip will terminate */ - close(STDOUT_FILENO); + /* rename the (now complete) .tmp file to its final location */ + if (use_outfile && rename(tmp_path, path)) { + fprintf(stderr, "rename(%s, %s): %s\n", tmp_path, path, strerror(errno)); + } LOGI("done\n"); return 0; } - -static void dump_kernel_log(const char *path, const char *title) - -{ - printf("------ KERNEL %s LOG ------\n", title); - if (access(path, R_OK) < 0) - printf("%s: %s\n", path, strerror(errno)); - else { - struct stat sbuf; - - if (stat(path, &sbuf) < 0) - printf("%s: stat failed (%s)\n", path, strerror(errno)); - else - printf("Harvested %s", ctime(&sbuf.st_mtime)); - - DUMP(path); - } -} diff --git a/cmds/dumpstate/dumpstate.h b/cmds/dumpstate/dumpstate.h index ed1f005659cb..6d48a859e15f 100644 --- a/cmds/dumpstate/dumpstate.h +++ b/cmds/dumpstate/dumpstate.h @@ -18,157 +18,24 @@ #define _DUMPSTATE_H_ #include <time.h> - -// Commands time out after 60 seconds -#define TIMEOUT 60 - -#define PRINT(s) printf("%s\n", s) - -#define DUMP(file) dump_file(file) - -#define DUMP_FILES(path) dump_files(path) - -#define DUMP_PROMPT(prompt, file) \ -{ \ - printf(prompt); \ - dump_file(file); \ -} - -#define EXEC(cmd) \ -{ \ - static struct Command c = { \ - "/system/bin/" cmd, \ - { cmd, 0 } \ - }; \ - run_command(&c, TIMEOUT); \ -} - -#define EXEC_TIMEOUT(cmd, tmout)\ -{ \ - static struct Command c = { \ - "/system/bin/" cmd, \ - { cmd, 0 } \ - }; \ - run_command(&c, tmout); \ -} - -#define EXEC_XBIN(cmd) \ -{ \ - static struct Command c = { \ - "/system/xbin/" cmd, \ - { cmd, 0 } \ - }; \ - run_command(&c, TIMEOUT); \ -} - -#define EXEC1(cmd, a1) \ -{ \ - static struct Command c = { \ - "/system/bin/" cmd, \ - { cmd, a1, 0 } \ - }; \ - run_command(&c, TIMEOUT); \ -} - -#define EXEC2(cmd, a1, a2) \ -{ \ - static struct Command c = { \ - "/system/bin/" cmd, \ - { cmd, a1, a2, 0 } \ - }; \ - run_command(&c, TIMEOUT); \ -} - -#define EXEC3(cmd, a1, a2, a3) \ -{ \ - static struct Command c = { \ - "/system/bin/" cmd, \ - { cmd, a1, a2, a3, 0 } \ - }; \ - run_command(&c, TIMEOUT); \ -} - -#define EXEC4(cmd, a1, a2, a3, a4) \ -{ \ - static struct Command c = { \ - "/system/bin/" cmd, \ - { cmd, a1, a2, a3, a4, 0 } \ - }; \ - run_command(&c, TIMEOUT); \ -} - -#define EXEC6(cmd, a1, a2, a3, a4, a5, a6) \ -{ \ - static struct Command c = { \ - "/system/bin/" cmd, \ - { cmd, a1, a2, a3, a4, a5, a6, 0 } \ - }; \ - run_command(&c, TIMEOUT); \ -} - -#define EXEC7(cmd, a1, a2, a3, a4, a5, a6, a7) \ -{ \ - static struct Command c = { \ - "/system/bin/" cmd, \ - { cmd, a1, a2, a3, a4, a5, a6, a7, 0 } \ - }; \ - run_command(&c, TIMEOUT); \ -} - -#define EXEC8(cmd, a1, a2, a3, a4, a5, a6, a7, a8) \ -{ \ - static struct Command c = { \ - "/system/bin/" cmd, \ - { cmd, a1, a2, a3, a4, a5, a6, a7, a8, 0 } \ - }; \ - run_command(&c, TIMEOUT); \ -} - -#define EXEC_XBIN6(cmd, a1, a2, a3, a4, a5, a6) \ -{ \ - static struct Command c = { \ - "/system/xbin/" cmd, \ - { cmd, a1, a2, a3, a4, a5, a6, 0 } \ - }; \ - run_command(&c, TIMEOUT); \ -} - -#define PROPERTY(name) print_property(name) - -struct Command { - const char* path; - char* const args[]; -}; -typedef struct Command Command; +#include <unistd.h> /* prints the contents of a file */ -int dump_file(const char* path); - -/* prints the contents of all files in a directory */ -void dump_files(const char* path); - -/* forks a command and waits for it to finish */ -int run_command(struct Command* cmd, int timeout); - -/* reads the current time into tm */ -void get_time(struct tm *tm); - -/* prints the date in tm */ -void print_date(const char* prompt, struct tm *tm); +int dump_file(const char *title, const char* path); -/* prints the name and value of a system property */ -int print_property(const char* name); +/* forks a command and waits for it to finish -- terminate args with NULL */ +int run_command(const char *title, int timeout_seconds, const char *command, ...); /* prints all the system properties */ void print_properties(); -/* creates directories as needed for the given path */ -void create_directories(char *path); +/* redirect output to a service control socket */ +void redirect_to_socket(FILE *redirect, const char *service); -/* runs the vibrator using the given pattern */ -void vibrate_pattern(int fd, int* pattern); +/* redirect output to a file, optionally gzipping; returns gzip pid */ +pid_t redirect_to_file(FILE *redirect, char *path, int gzip_level); -/* prevents the OOM killer from killing us */ -void protect_from_oom_killer(); +/* dump Dalvik stack traces, return the trace file location (NULL if none) */ +const char *dump_vm_traces(); #endif /* _DUMPSTATE_H_ */ diff --git a/cmds/dumpstate/utils.c b/cmds/dumpstate/utils.c index 60d845f61bf3..fda618cc4c52 100644 --- a/cmds/dumpstate/utils.c +++ b/cmds/dumpstate/utils.c @@ -14,217 +14,337 @@ * limitations under the License. */ +#include <dirent.h> +#include <errno.h> +#include <fcntl.h> +#include <limits.h> +#include <poll.h> +#include <signal.h> +#include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> -#include <time.h> -#include <unistd.h> +#include <sys/inotify.h> #include <sys/stat.h> -#include <dirent.h> -#include <limits.h> -#include <fcntl.h> -#include <signal.h> #include <sys/time.h> #include <sys/wait.h> +#include <time.h> +#include <unistd.h> #include <cutils/properties.h> -#include <sys/system_properties.h> +#include <cutils/sockets.h> #include "dumpstate.h" /* prints the contents of a file */ -int dump_file(const char* path) { - char buffer[32768]; - int fd, amount_read; - int ret = 0; - - fd = open(path, O_RDONLY); - if (fd < 0) - return fd; - - do { - ret = read(fd, buffer, sizeof(buffer)); - if (ret > 0) - ret = write(STDOUT_FILENO, buffer, ret); - } while (ret > 0); - - buffer[0] = '\n'; - write(STDOUT_FILENO, buffer, 1); - - close(fd); - return ret; -} +int dump_file(const char *title, const char* path) { + char buffer[32768]; + int fd = open(path, O_RDONLY); + if (fd < 0) { + int err = errno; + if (title) printf("----- %s (%s) -----\n", title, path); + printf("*** %s: %s\n", path, strerror(err)); + if (title) printf("\n"); + return -1; + } -/* prints the contents of all files in a directory */ -void dump_files(const char* path) { - DIR* dir; - struct dirent* entry; - char buffer[PATH_MAX]; + if (title) printf("----- %s (%s", title, path); - dir = opendir(path); - if (!dir) { - fprintf(stderr, "could not open directory %s\n", path); - return; + if (title) { + struct stat st; + if (memcmp(path, "/proc/", 6) && memcmp(path, "/sys/", 5) && !fstat(fd, &st)) { + char stamp[80]; + time_t mtime = st.st_mtime; + strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime)); + printf(": %s", stamp); + } + printf(") -----\n"); } - while ((entry = readdir(dir))) { - if (entry->d_type == DT_REG) { - snprintf(buffer, sizeof(buffer), "%s/%s", path, entry->d_name); - dump_file(path); - printf("\n"); + int newline = 0; + for (;;) { + int ret = read(fd, buffer, sizeof(buffer)); + if (ret > 0) { + newline = (buffer[ret - 1] == '\n'); + ret = fwrite(buffer, ret, 1, stdout); } + if (ret <= 0) break; } - closedir(dir); -} - -/* prints the name and value of a system property */ -int print_property(const char* name) { - char value[PROP_VALUE_MAX]; - - __system_property_get(name, value); - printf("%s=%s\n", name, value); + close(fd); + if (!newline) printf("\n"); + if (title) printf("\n"); return 0; } -static pid_t alarm_pid = 0; -static int timed_out = 0; -static void sig_alarm(int sig) -{ - if (alarm_pid) { - kill(alarm_pid, SIGKILL); - timed_out = 1; - alarm_pid = 0; - } -} - /* forks a command and waits for it to finish */ -int run_command(struct Command* cmd, int timeout) { - struct sigaction sa; - pid_t pid; - int status; +int run_command(const char *title, int timeout_seconds, const char *command, ...) { + fflush(stdout); + clock_t start = clock(); + pid_t pid = fork(); - pid = fork(); /* handle error case */ - if (pid < 0) + if (pid < 0) { + printf("*** fork: %s\n", strerror(errno)); return pid; + } /* handle child case */ if (pid == 0) { - int ret = execv(cmd->path, cmd->args); - if (ret) - fprintf(stderr, "execv %s returned %d\n", cmd->path, ret); - exit(ret); + const char *args[1024] = {command}; + size_t arg; + + va_list ap; + va_start(ap, command); + if (title) printf("----- %s (%s", title, command); + for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) { + args[arg] = va_arg(ap, const char *); + if (args[arg] == NULL) break; + if (title) printf(" %s", args[arg]); + } + if (title) printf(") -----\n"); + fflush(stdout); + + execvp(command, (char**) args); + printf("*** exec(%s): %s\n", command, strerror(errno)); + _exit(-1); } /* handle parent case */ - timed_out = 0; - if (timeout) { - memset(&sa, 0, sizeof(sa)); - sa.sa_flags = SA_RESETHAND; - sa.sa_handler = sig_alarm; - sigaction(SIGALRM, &sa, NULL); + for (;;) { + int status; + pid_t p = waitpid(pid, &status, WNOHANG); + float elapsed = (float) (clock() - start) / CLOCKS_PER_SEC; + if (p == pid) { + if (WIFSIGNALED(status)) { + printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status)); + } else if (WEXITSTATUS(status) > 0) { + printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status)); + } + if (title) printf("[%s: %.1fs elapsed]\n\n", command, elapsed); + return status; + } - /* set an alarm so we don't hang forever */ - alarm_pid = pid; - alarm(timeout); - } + if (timeout_seconds && elapsed > timeout_seconds) { + printf("*** %s: Timed out after %.1fs (killing pid %d)\n", command, elapsed, pid); + kill(pid, SIGTERM); + return -1; + } - waitpid(pid, &status, 0); + usleep(100000); // poll every 0.1 sec + } +} - if (timed_out) - printf("ERROR: command %s timed out\n", cmd->path); +size_t num_props = 0; +static char* props[2000]; - return status; +static void print_prop(const char *key, const char *name, void *user) { + (void) user; + if (num_props < sizeof(props) / sizeof(props[0])) { + char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10]; + snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name); + props[num_props++] = strdup(buf); + } } -/* reads the current time into tm */ -void get_time(struct tm *tm) { - time_t t; - - tzset(); - time(&t); - localtime_r(&t, tm); +static int compare_prop(const void *a, const void *b) { + return strcmp(*(char * const *) a, *(char * const *) b); } -/* prints the date in tm */ -void print_date(const char* prompt, struct tm *tm) { - char strbuf[260]; +/* prints all the system properties */ +void print_properties() { + size_t i; + num_props = 0; + property_list(print_prop, NULL); + qsort(&props, num_props, sizeof(props[0]), compare_prop); - strftime(strbuf, sizeof(strbuf), - "%a %b %e %H:%M:%S %Z %Y", - tm); - printf("%s%s\n", prompt, strbuf); + printf("----- SYSTEM PROPERTIES -----\n"); + for (i = 0; i < num_props; ++i) { + fputs(props[i], stdout); + free(props[i]); + } + printf("\n"); } +/* redirect output to a service control socket */ +void redirect_to_socket(FILE *redirect, const char *service) { + int s = android_get_control_socket(service); + if (s < 0) { + fprintf(stderr, "android_get_control_socket(%s): %s\n", service, strerror(errno)); + exit(1); + } + if (listen(s, 4) < 0) { + fprintf(stderr, "listen(control socket): %s\n", strerror(errno)); + exit(1); + } -static void print_prop(const char *key, const char *name, - void *user __attribute__((unused))) -{ - printf("[%s]: [%s]\n", key, name); -} + struct sockaddr addr; + socklen_t alen = sizeof(addr); + int fd = accept(s, &addr, &alen); + if (fd < 0) { + fprintf(stderr, "accept(control socket): %s\n", strerror(errno)); + exit(1); + } -/* prints all the system properties */ -void print_properties() { - property_list(print_prop, NULL); + fflush(redirect); + dup2(fd, fileno(redirect)); + close(fd); } -/* creates directories as needed for the given path */ -void create_directories(char *path) -{ +/* redirect output to a file, optionally gzipping; returns gzip pid (or -1) */ +pid_t redirect_to_file(FILE *redirect, char *path, int gzip_level) { char *chp = path; /* skip initial slash */ if (chp[0] == '/') chp++; + /* create leading directories, if necessary */ while (chp && chp[0]) { chp = strchr(chp, '/'); if (chp) { *chp = 0; - mkdir(path, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); - *chp = '/'; - chp++; + mkdir(path, 0775); /* drwxrwxr-x */ + *chp++ = '/'; } } -} -/* runs the vibrator using the given pattern */ -void vibrate_pattern(int fd, int* pattern) -{ - struct timespec tm; - char buffer[10]; - - while (*pattern) { - /* read vibrate on time */ - int on_time = *pattern++; - snprintf(buffer, sizeof(buffer), "%d", on_time); - write(fd, buffer, strlen(buffer)); - - /* read vibrate off time */ - int delay = *pattern++; - if (delay) { - delay += on_time; - - tm.tv_sec = delay / 1000; - tm.tv_nsec = (delay % 1000) * 1000000; - nanosleep(&tm, NULL); - } else - break; + int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); + if (fd < 0) { + fprintf(stderr, "%s: %s\n", path, strerror(errno)); + exit(1); + } + + pid_t gzip_pid = -1; + if (gzip_level > 0) { + int fds[2]; + if (pipe(fds)) { + fprintf(stderr, "pipe: %s\n", strerror(errno)); + exit(1); + } + + fflush(redirect); + fflush(stdout); + + gzip_pid = fork(); + if (gzip_pid < 0) { + fprintf(stderr, "fork: %s\n", strerror(errno)); + exit(1); + } + + if (gzip_pid == 0) { + dup2(fds[0], STDIN_FILENO); + dup2(fd, STDOUT_FILENO); + + close(fd); + close(fds[0]); + close(fds[1]); + + char level[10]; + snprintf(level, sizeof(level), "-%d", gzip_level); + execlp("gzip", "gzip", level, NULL); + fprintf(stderr, "exec(gzip): %s\n", strerror(errno)); + _exit(-1); + } + + close(fd); + close(fds[0]); + fd = fds[1]; } + + dup2(fd, fileno(redirect)); + close(fd); + return gzip_pid; } -/* prevents the OOM killer from killing us */ -void protect_from_oom_killer() -{ - int fd; +/* dump Dalvik stack traces, return the trace file location (NULL if none) */ +const char *dump_vm_traces() { + char traces_path[PROPERTY_VALUE_MAX] = ""; + property_get("dalvik.vm.stack-trace-file", traces_path, ""); + if (!traces_path[0]) return NULL; + + /* move the old traces.txt (if any) out of the way temporarily */ + char anr_traces_path[PATH_MAX]; + strlcpy(anr_traces_path, traces_path, sizeof(anr_traces_path)); + strlcat(anr_traces_path, ".anr", sizeof(anr_traces_path)); + rename(traces_path, anr_traces_path); + + /* create a new, empty traces.txt file to receive stack dumps */ + int fd = open(traces_path, O_CREAT | O_WRONLY | O_TRUNC, 0666); /* -rw-rw-rw- */ + if (fd < 0) { + fprintf(stderr, "%s: %s\n", traces_path, strerror(errno)); + return NULL; + } + close(fd); + + /* walk /proc and kill -QUIT all Dalvik processes */ + DIR *proc = opendir("/proc"); + if (proc == NULL) { + fprintf(stderr, "/proc: %s\n", strerror(errno)); + return NULL; + } + + /* use inotify to find when processes are done dumping */ + int ifd = inotify_init(); + if (ifd < 0) { + fprintf(stderr, "inotify_init: %s\n", strerror(errno)); + return NULL; + } + + int wfd = inotify_add_watch(ifd, traces_path, IN_CLOSE_WRITE); + if (wfd < 0) { + fprintf(stderr, "inotify_add_watch(%s): %s\n", traces_path, strerror(errno)); + return NULL; + } - fd = open("/proc/self/oom_adj", O_WRONLY); - if (fd >= 0) { - // -17 should make us immune to OOM - const char* text = "-17"; - write(fd, text, strlen(text)); + struct dirent *d; + while ((d = readdir(proc))) { + int pid = atoi(d->d_name); + if (pid <= 0) continue; + + /* identify Dalvik: /proc/(pid)/exe = /system/bin/app_process */ + char path[PATH_MAX], data[PATH_MAX]; + snprintf(path, sizeof(path), "/proc/%d/exe", pid); + size_t len = readlink(path, data, sizeof(data) - 1); + if (len <= 0 || memcmp(data, "/system/bin/app_process", 23)) continue; + + /* skip zygote -- it won't dump its stack anyway */ + snprintf(path, sizeof(path), "/proc/%d/cmdline", pid); + int fd = open(path, O_RDONLY); + len = read(fd, data, sizeof(data) - 1); close(fd); + if (len <= 0 || !memcmp(data, "zygote", 6)) continue; + + if (kill(pid, SIGQUIT)) { + fprintf(stderr, "kill(%d, SIGQUIT): %s\n", pid, strerror(errno)); + continue; + } + + /* wait for the writable-close notification from inotify */ + struct pollfd pfd = { ifd, POLLIN, 0 }; + int ret = poll(&pfd, 1, 200); /* 200 msec timeout */ + if (ret < 0) { + fprintf(stderr, "poll: %s\n", strerror(errno)); + } else if (ret == 0) { + fprintf(stderr, "warning: timed out dumping pid %d\n", pid); + } else { + struct inotify_event ie; + read(ifd, &ie, sizeof(ie)); + } } + + close(ifd); + + static char dump_traces_path[PATH_MAX]; + strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path)); + strlcat(dump_traces_path, ".bugreport", sizeof(dump_traces_path)); + if (rename(traces_path, dump_traces_path)) { + fprintf(stderr, "rename(%s, %s): %s\n", traces_path, dump_traces_path, strerror(errno)); + return NULL; + } + + /* replace the saved [ANR] traces.txt file */ + rename(anr_traces_path, traces_path); + return dump_traces_path; } diff --git a/core/java/android/app/SearchManager.java b/core/java/android/app/SearchManager.java index a75e8dc8c0ff..9112be46a183 100644 --- a/core/java/android/app/SearchManager.java +++ b/core/java/android/app/SearchManager.java @@ -1332,7 +1332,7 @@ public class SearchManager public final static String EXTRA_DATA_KEY = "intent_extra_data_key"; /** - * String extra data key for {@link Intent#ACTION_GLOBAL_SEARCH} intents. Contains the initial + * String extra data key for {@link #INTENT_ACTION_GLOBAL_SEARCH} intents. Contains the initial * query to show in the global search activity. * * @hide Pending API council approval @@ -1340,7 +1340,7 @@ public class SearchManager public final static String INITIAL_QUERY = "initial_query"; /** - * Boolean extra data key for {@link Intent#ACTION_GLOBAL_SEARCH} intents. If {@code true}, + * Boolean extra data key for {@link Intent#INTENT_ACTION_GLOBAL_SEARCH} intents. If {@code true}, * the initial query should be selected. * * @hide Pending API council approval @@ -1816,7 +1816,7 @@ public class SearchManager Log.w(TAG, "No global search activity found."); return; } - Intent intent = new Intent(Intent.ACTION_GLOBAL_SEARCH); + Intent intent = new Intent(INTENT_ACTION_GLOBAL_SEARCH); intent.setComponent(globalSearchActivity); // TODO: Always pass name of calling package as an extra? if (appSearchData != null) { @@ -1847,7 +1847,7 @@ public class SearchManager * we have settled on the right mechanism for finding the global search activity. */ private ComponentName getGlobalSearchActivity() { - Intent intent = new Intent(Intent.ACTION_GLOBAL_SEARCH); + Intent intent = new Intent(INTENT_ACTION_GLOBAL_SEARCH); PackageManager pm = mContext.getPackageManager(); List<ResolveInfo> activities = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java index bf37b624672c..bbd359bea989 100644 --- a/core/java/android/content/Intent.java +++ b/core/java/android/content/Intent.java @@ -1102,16 +1102,6 @@ public class Intent implements Parcelable, Cloneable { public static final String ACTION_SEARCH_LONG_PRESS = "android.intent.action.SEARCH_LONG_PRESS"; /** - * Activity Action: Start the global search activity. - * <p>Input: Nothing. - * <p>Output: Nothing. - * - * @hide Pending API council approval - */ - @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) - public static final String ACTION_GLOBAL_SEARCH = "android.intent.action.GLOBAL_SEARCH"; - - /** * Activity Action: The user pressed the "Report" button in the crash/ANR dialog. * This intent is delivered to the package which installed the application, usually * the Market. diff --git a/core/java/android/net/ConnectivityManager.java b/core/java/android/net/ConnectivityManager.java index a70866de4306..30799ec9f3b8 100644 --- a/core/java/android/net/ConnectivityManager.java +++ b/core/java/android/net/ConnectivityManager.java @@ -129,14 +129,14 @@ public class ConnectivityManager public static final int TYPE_WIFI = 1; /** * An MMS-specific Mobile data connection. This connection may be the - * same as {@link #TYPEMOBILE} but it may be different. This is used + * same as {@link #TYPE_MOBILE} but it may be different. This is used * by applications needing to talk to the carrier's Multimedia Messaging * Service servers. It may coexist with default data connections. */ public static final int TYPE_MOBILE_MMS = 2; /** * A SUPL-specific Mobile data connection. This connection may be the - * same as {@link #TYPEMOBILE} but it may be different. This is used + * same as {@link #TYPE_MOBILE} but it may be different. This is used * by applications needing to talk to the carrier's Secure User Plane * Location servers for help locating the device. It may coexist with * default data connections. @@ -144,7 +144,7 @@ public class ConnectivityManager public static final int TYPE_MOBILE_SUPL = 3; /** * A DUN-specific Mobile data connection. This connection may be the - * same as {@link #TYPEMOBILE} but it may be different. This is used + * same as {@link #TYPE_MOBILE} but it may be different. This is used * by applicaitons performing a Dial Up Networking bridge so that * the carrier is aware of DUN traffic. It may coexist with default data * connections. @@ -152,7 +152,7 @@ public class ConnectivityManager public static final int TYPE_MOBILE_DUN = 4; /** * A High Priority Mobile data connection. This connection is typically - * the same as {@link #TYPEMOBILE} but the routing setup is different. + * the same as {@link #TYPE_MOBILE} but the routing setup is different. * Only requesting processes will have access to the Mobile DNS servers * and only IP's explicitly requested via {@link #requestRouteToHost} * will route over this interface if a default route exists. diff --git a/core/java/android/webkit/MimeTypeMap.java b/core/java/android/webkit/MimeTypeMap.java index 84a8a3cd359c..a9d6ff6305d0 100644 --- a/core/java/android/webkit/MimeTypeMap.java +++ b/core/java/android/webkit/MimeTypeMap.java @@ -124,6 +124,11 @@ public class MimeTypeMap { return null; } + // Static method called by jni. + private static String mimeTypeFromExtension(String extension) { + return getSingleton().getMimeTypeFromExtension(extension); + } + /** * Return true if the given extension has a registered MIME type. * @param extension A file extension without the leading '.' @@ -344,6 +349,7 @@ public class MimeTypeMap { sMimeTypeMap.loadEntry("application/x-pkcs7-crl", "crl"); sMimeTypeMap.loadEntry("application/x-quicktimeplayer", "qtl"); sMimeTypeMap.loadEntry("application/x-shar", "shar"); + sMimeTypeMap.loadEntry("application/x-shockwave-flash", "swf"); sMimeTypeMap.loadEntry("application/x-stuffit", "sit"); sMimeTypeMap.loadEntry("application/x-sv4cpio", "sv4cpio"); sMimeTypeMap.loadEntry("application/x-sv4crc", "sv4crc"); diff --git a/core/res/res/values/arrays.xml b/core/res/res/values/arrays.xml index 66f0e820cb38..53bb5864fd87 100644 --- a/core/res/res/values/arrays.xml +++ b/core/res/res/values/arrays.xml @@ -131,6 +131,7 @@ the first component from this list which is found to be installed is set as the preferred activity. --> <string-array name="default_web_search_providers"> + <item>com.android.quicksearchbox/com.android.googlesearch.GoogleSearch</item> <item>com.google.android.providers.enhancedgooglesearch/.Launcher</item> <item>com.android.googlesearch/.GoogleSearch</item> <item>com.android.websearch/.Search.1</item> diff --git a/libs/rs/rsProgram.cpp b/libs/rs/rsProgram.cpp index b528c4656226..656a3c339529 100644 --- a/libs/rs/rsProgram.cpp +++ b/libs/rs/rsProgram.cpp @@ -110,7 +110,6 @@ Program::~Program() void Program::bindAllocation(Allocation *alloc, uint32_t slot) { - LOGE("bind alloc %p %i", alloc, slot); if (mConstants[slot].get() == alloc) { return; } diff --git a/libs/rs/rsProgramVertex.cpp b/libs/rs/rsProgramVertex.cpp index 8849bda0eb63..cf6d7fcf5f5b 100644 --- a/libs/rs/rsProgramVertex.cpp +++ b/libs/rs/rsProgramVertex.cpp @@ -124,7 +124,6 @@ void ProgramVertex::createShader() mShader.append(mUniformNames[0]); mShader.append(";\n"); - LOGE("constant %i ", mConstantCount); for (uint32_t ct=0; ct < mConstantCount; ct++) { const Element *e = mConstantTypes[ct]->getElement(); for (uint32_t field=0; field < e->getFieldCount(); field++) { @@ -337,7 +336,7 @@ void ProgramVertex::init(Context *rsc) mUniformCount = 1; mUniformNames[0].setTo("UNI_MVP"); - for (uint32_t ct=0; ct < mInputCount; ct++) { + for (uint32_t ct=0; ct < mConstantCount; ct++) { initAddUserElement(mConstantTypes[ct]->getElement(), mUniformNames, &mUniformCount, "UNI_"); } } else { diff --git a/telephony/java/com/android/internal/telephony/Call.java b/telephony/java/com/android/internal/telephony/Call.java index b95dd11046dd..4967ab81e5fc 100644 --- a/telephony/java/com/android/internal/telephony/Call.java +++ b/telephony/java/com/android/internal/telephony/Call.java @@ -18,6 +18,8 @@ package com.android.internal.telephony; import java.util.List; +import android.util.Log; + /** * {@hide} */ @@ -54,6 +56,8 @@ public abstract class Call { // merged, etc. protected boolean isGeneric = false; + protected final String LOG_TAG = "Call"; + /* Instance Methods */ /** Do not modify the List result!!! This list is not yours to keep @@ -235,4 +239,17 @@ public abstract class Call { public void setGeneric(boolean generic) { isGeneric = generic; } + + /** + * Hangup call if it is alive + */ + public void hangupIfAlive() { + if (getState().isAlive()) { + try { + hangup(); + } catch (CallStateException ex) { + Log.w(LOG_TAG, " hangupIfActive: caught " + ex); + } + } + } } diff --git a/telephony/java/com/android/internal/telephony/ServiceStateTracker.java b/telephony/java/com/android/internal/telephony/ServiceStateTracker.java index 6892998479f8..73836497dc4e 100644 --- a/telephony/java/com/android/internal/telephony/ServiceStateTracker.java +++ b/telephony/java/com/android/internal/telephony/ServiceStateTracker.java @@ -271,6 +271,13 @@ public abstract class ServiceStateTracker extends Handler { protected abstract void updateSpnDisplay(); protected abstract void setPowerStateToDesired(); + /** + * Clean up existing voice and data connection then turn off radio power. + * + * Hang up the existing voice calls to decrease call drop rate. + */ + protected abstract void powerOffRadioSafely(); + /** Cancel a pending (if any) pollState() operation */ protected void cancelPollState() { // This will effectively cancel the rest of the poll requests. diff --git a/telephony/java/com/android/internal/telephony/cdma/CdmaServiceStateTracker.java b/telephony/java/com/android/internal/telephony/cdma/CdmaServiceStateTracker.java index af3cbd5eb7e9..42feaa904b10 100644 --- a/telephony/java/com/android/internal/telephony/cdma/CdmaServiceStateTracker.java +++ b/telephony/java/com/android/internal/telephony/cdma/CdmaServiceStateTracker.java @@ -514,7 +514,7 @@ final class CdmaServiceStateTracker extends ServiceStateTracker { synchronized(this) { if (mPendingRadioPowerOffAfterDataOff) { if (DBG) log("EVENT_SET_RADIO_OFF, turn radio off now."); - cm.setRadioPower(false, null); + hangupAndPowerOff(); mPendingRadioPowerOffAfterDataOff = false; } } @@ -541,32 +541,42 @@ final class CdmaServiceStateTracker extends ServiceStateTracker { dcTracker.getStateInString(), dcTracker.getAnyDataEnabled() ? 1 : 0); } - Message msg = dcTracker.obtainMessage(DataConnectionTracker.EVENT_CLEAN_UP_CONNECTION); - msg.arg1 = 1; // tearDown is true - msg.obj = CDMAPhone.REASON_RADIO_TURNED_OFF; - dcTracker.sendMessage(msg); - synchronized(this) { - if (!mPendingRadioPowerOffAfterDataOff) { - DataConnectionTracker.State currentState = dcTracker.getState(); - if (currentState != DataConnectionTracker.State.CONNECTED - && currentState != DataConnectionTracker.State.DISCONNECTING - && currentState != DataConnectionTracker.State.INITING) { - if (DBG) log("Data disconnected, turn off radio right away."); - cm.setRadioPower(false, null); - } - else if (sendEmptyMessageDelayed(EVENT_SET_RADIO_POWER_OFF, 30000)) { - if (DBG) { - log("Wait up to 30 sec for data to disconnect, then turn off radio."); - } - mPendingRadioPowerOffAfterDataOff = true; - } else { - Log.w(LOG_TAG, "Cannot send delayed Msg, turn off radio right away."); - cm.setRadioPower(false, null); + // If it's on and available and we want it off gracefully + powerOffRadioSafely(); + } // Otherwise, we're in the desired state + } + + @Override + protected void powerOffRadioSafely(){ + // clean data connection + DataConnectionTracker dcTracker = phone.mDataConnection; + + Message msg = dcTracker.obtainMessage(DataConnectionTracker.EVENT_CLEAN_UP_CONNECTION); + msg.arg1 = 1; // tearDown is true + msg.obj = CDMAPhone.REASON_RADIO_TURNED_OFF; + dcTracker.sendMessage(msg); + + synchronized(this) { + if (!mPendingRadioPowerOffAfterDataOff) { + DataConnectionTracker.State currentState = dcTracker.getState(); + if (currentState != DataConnectionTracker.State.CONNECTED + && currentState != DataConnectionTracker.State.DISCONNECTING + && currentState != DataConnectionTracker.State.INITING) { + if (DBG) log("Data disconnected, turn off radio right away."); + hangupAndPowerOff(); + } + else if (sendEmptyMessageDelayed(EVENT_SET_RADIO_POWER_OFF, 30000)) { + if (DBG) { + log("Wait up to 30 sec for data to disconnect, then turn off radio."); } + mPendingRadioPowerOffAfterDataOff = true; + } else { + Log.w(LOG_TAG, "Cannot send delayed Msg, turn off radio right away."); + hangupAndPowerOff(); } } - } // Otherwise, we're in the desired state + } } @Override @@ -1644,11 +1654,19 @@ final class CdmaServiceStateTracker extends ServiceStateTracker { if (mPendingRadioPowerOffAfterDataOff) { if (DBG) log("Process pending request to turn radio off."); removeMessages(EVENT_SET_RADIO_POWER_OFF); - cm.setRadioPower(false, null); + hangupAndPowerOff(); mPendingRadioPowerOffAfterDataOff = false; return true; } return false; } } + + private void hangupAndPowerOff() { + // hang up all active voice calls + phone.mCT.ringingCall.hangupIfAlive(); + phone.mCT.backgroundCall.hangupIfAlive(); + phone.mCT.foregroundCall.hangupIfAlive(); + cm.setRadioPower(false, null); + } } diff --git a/telephony/java/com/android/internal/telephony/gsm/GsmDataConnectionTracker.java b/telephony/java/com/android/internal/telephony/gsm/GsmDataConnectionTracker.java index 3f52eff59e67..6695ccbff2d9 100644 --- a/telephony/java/com/android/internal/telephony/gsm/GsmDataConnectionTracker.java +++ b/telephony/java/com/android/internal/telephony/gsm/GsmDataConnectionTracker.java @@ -808,7 +808,7 @@ public final class GsmDataConnectionTracker extends DataConnectionTracker { protected void restartRadio() { Log.d(LOG_TAG, "************TURN OFF RADIO**************"); cleanUpConnection(true, Phone.REASON_RADIO_TURNED_OFF); - phone.mCM.setRadioPower(false, null); + mGsmPhone.mSST.powerOffRadioSafely(); /* Note: no need to call setRadioPower(true). Assuming the desired * radio power state is still ON (as tracked by ServiceStateTracker), * ServiceStateTracker will call setRadioPower when it receives the diff --git a/telephony/java/com/android/internal/telephony/gsm/GsmServiceStateTracker.java b/telephony/java/com/android/internal/telephony/gsm/GsmServiceStateTracker.java index c2c89c016449..48e5c97b1131 100644 --- a/telephony/java/com/android/internal/telephony/gsm/GsmServiceStateTracker.java +++ b/telephony/java/com/android/internal/telephony/gsm/GsmServiceStateTracker.java @@ -518,26 +518,41 @@ final class GsmServiceStateTracker extends ServiceStateTracker { EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_DATA_STATE_RADIO_OFF, dcTracker.getStateInString(), dcTracker.getAnyDataEnabled() ? 1 : 0); } - Message msg = dcTracker.obtainMessage(DataConnectionTracker.EVENT_CLEAN_UP_CONNECTION); - msg.arg1 = 1; // tearDown is true - msg.obj = GSMPhone.REASON_RADIO_TURNED_OFF; - dcTracker.sendMessage(msg); - - // poll data state up to 15 times, with a 100ms delay - // totaling 1.5 sec. Normal data disable action will finish in 100ms. - for (int i = 0; i < MAX_NUM_DATA_STATE_READS; i++) { - if (dcTracker.getState() != DataConnectionTracker.State.CONNECTED - && dcTracker.getState() != DataConnectionTracker.State.DISCONNECTING) { - Log.d(LOG_TAG, "Data shutdown complete."); - break; - } - SystemClock.sleep(DATA_STATE_POLL_SLEEP_MS); - } - // If it's on and available and we want it off.. - cm.setRadioPower(false, null); + // If it's on and available and we want it off gracefully + powerOffRadioSafely(); } // Otherwise, we're in the desired state } + @Override + protected void powerOffRadioSafely() { + // clean data connection + DataConnectionTracker dcTracker = phone.mDataConnection; + Message msg = dcTracker.obtainMessage(DataConnectionTracker.EVENT_CLEAN_UP_CONNECTION); + msg.arg1 = 1; // tearDown is true + msg.obj = GSMPhone.REASON_RADIO_TURNED_OFF; + dcTracker.sendMessage(msg); + + // poll data state up to 15 times, with a 100ms delay + // totaling 1.5 sec. Normal data disable action will finish in 100ms. + for (int i = 0; i < MAX_NUM_DATA_STATE_READS; i++) { + if (dcTracker.getState() != DataConnectionTracker.State.CONNECTED + && dcTracker.getState() != DataConnectionTracker.State.DISCONNECTING) { + Log.d(LOG_TAG, "Data shutdown complete."); + break; + } + SystemClock.sleep(DATA_STATE_POLL_SLEEP_MS); + } + + // hang up all active voice calls + if (phone.isInCall()) { + phone.mCT.ringingCall.hangupIfAlive(); + phone.mCT.backgroundCall.hangupIfAlive(); + phone.mCT.foregroundCall.hangupIfAlive(); + } + + cm.setRadioPower(false, null); + } + protected void updateSpnDisplay() { int rule = phone.mSIMRecords.getDisplayRule(ss.getOperatorNumeric()); String spn = phone.mSIMRecords.getServiceProviderName(); diff --git a/tests/AndroidTests/src/com/android/unit_tests/AndroidTests.java b/tests/AndroidTests/src/com/android/unit_tests/AndroidTests.java deleted file mode 100644 index 4b86add1c7d0..000000000000 --- a/tests/AndroidTests/src/com/android/unit_tests/AndroidTests.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2005 The Android Open Source Project - * - * 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.android.unit_tests; - -import android.test.FrameworkTests; -import android.test.suitebuilder.TestSuiteBuilder; - -import junit.framework.TestSuite; - -public class AndroidTests extends TestSuite { - - public static TestSuite suite() { - TestSuiteBuilder suiteBuilder = new TestSuiteBuilder(AndroidTests.class); - TestSuite suite = suiteBuilder.includeAllPackagesUnderHere().build(); - - return suite; - } -} diff --git a/tests/AndroidTests/src/com/android/unit_tests/DatabaseCursorTest.java b/tests/AndroidTests/src/com/android/unit_tests/DatabaseCursorTest.java deleted file mode 100644 index 5df499d1604d..000000000000 --- a/tests/AndroidTests/src/com/android/unit_tests/DatabaseCursorTest.java +++ /dev/null @@ -1,626 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * 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.android.unit_tests; - -import android.content.ContentValues; -import android.database.Cursor; -import android.database.CursorIndexOutOfBoundsException; -import android.database.DataSetObserver; -import android.database.DatabaseUtils; -import android.database.sqlite.SQLiteCursor; -import android.database.sqlite.SQLiteCursorDriver; -import android.database.sqlite.SQLiteDatabase; -import android.database.sqlite.SQLiteQuery; -import android.database.sqlite.SQLiteStatement; -import android.os.Looper; -import android.test.PerformanceTestCase; -import android.test.suitebuilder.annotation.LargeTest; -import android.test.suitebuilder.annotation.MediumTest; -import android.test.suitebuilder.annotation.SmallTest; -import android.test.suitebuilder.annotation.Suppress; -import android.util.Log; - -import java.io.File; -import java.util.Arrays; -import java.util.Random; - -import junit.framework.TestCase; - -public class DatabaseCursorTest extends TestCase implements PerformanceTestCase { - - private static final String sString1 = "this is a test"; - private static final String sString2 = "and yet another test"; - private static final String sString3 = "this string is a little longer, but still a test"; - - private static final int CURRENT_DATABASE_VERSION = 42; - private SQLiteDatabase mDatabase; - private File mDatabaseFile; - - @Override - protected void setUp() throws Exception { - super.setUp(); - mDatabaseFile = new File("/sqlite_stmt_journals", "database_test.db"); - if (mDatabaseFile.exists()) { - mDatabaseFile.delete(); - } - mDatabase = SQLiteDatabase.openOrCreateDatabase(mDatabaseFile.getPath(), null); - assertNotNull(mDatabase); - mDatabase.setVersion(CURRENT_DATABASE_VERSION); - } - - @Override - protected void tearDown() throws Exception { - mDatabase.close(); - mDatabaseFile.delete(); - super.tearDown(); - } - - public boolean isPerformanceOnly() { - return false; - } - - // These test can only be run once. - public int startPerformance(Intermediates intermediates) { - return 1; - } - - private void populateDefaultTable() { - mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, data TEXT);"); - - mDatabase.execSQL("INSERT INTO test (data) VALUES ('" + sString1 + "');"); - mDatabase.execSQL("INSERT INTO test (data) VALUES ('" + sString2 + "');"); - mDatabase.execSQL("INSERT INTO test (data) VALUES ('" + sString3 + "');"); - } - - @MediumTest - public void testCursorUpdate() { - mDatabase.execSQL( - "CREATE TABLE test (_id INTEGER PRIMARY KEY, d INTEGER, s INTEGER);"); - for(int i = 0; i < 20; i++) { - mDatabase.execSQL("INSERT INTO test (d, s) VALUES (" + i + - "," + i%2 + ");"); - } - - Cursor c = mDatabase.query("test", null, "s = 0", null, null, null, null); - int dCol = c.getColumnIndexOrThrow("d"); - int sCol = c.getColumnIndexOrThrow("s"); - - int count = 0; - while (c.moveToNext()) { - assertTrue(c.updateInt(dCol, 3)); - count++; - } - assertEquals(10, count); - - assertTrue(c.commitUpdates()); - - assertTrue(c.requery()); - - count = 0; - while (c.moveToNext()) { - assertEquals(3, c.getInt(dCol)); - count++; - } - - assertEquals(10, count); - assertTrue(c.moveToFirst()); - assertTrue(c.deleteRow()); - assertEquals(9, c.getCount()); - c.close(); - } - - @MediumTest - public void testBlob() throws Exception { - // create table - mDatabase.execSQL( - "CREATE TABLE test (_id INTEGER PRIMARY KEY, s TEXT, d REAL, l INTEGER, b BLOB);"); - // insert blob - Object[] args = new Object[4]; - - byte[] blob = new byte[1000]; - byte value = 99; - Arrays.fill(blob, value); - args[3] = blob; - - String s = new String("text"); - args[0] = s; - Double d = 99.9; - args[1] = d; - Long l = (long)1000; - args[2] = l; - - String sql = "INSERT INTO test (s, d, l, b) VALUES (?,?,?,?)"; - mDatabase.execSQL(sql, args); - // use cursor to access blob - Cursor c = mDatabase.query("test", null, null, null, null, null, null); - c.moveToNext(); - ContentValues cv = new ContentValues(); - DatabaseUtils.cursorRowToContentValues(c, cv); - - int bCol = c.getColumnIndexOrThrow("b"); - int sCol = c.getColumnIndexOrThrow("s"); - int dCol = c.getColumnIndexOrThrow("d"); - int lCol = c.getColumnIndexOrThrow("l"); - byte[] cBlob = c.getBlob(bCol); - assertTrue(Arrays.equals(blob, cBlob)); - assertEquals(s, c.getString(sCol)); - assertEquals((double)d, c.getDouble(dCol)); - assertEquals((long)l, c.getLong(lCol)); - - // new byte[] - byte[] newblob = new byte[1000]; - value = 98; - Arrays.fill(blob, value); - - c.updateBlob(bCol, newblob); - cBlob = c.getBlob(bCol); - assertTrue(Arrays.equals(newblob, cBlob)); - - // commit - assertTrue(c.commitUpdates()); - assertTrue(c.requery()); - c.moveToNext(); - cBlob = c.getBlob(bCol); - assertTrue(Arrays.equals(newblob, cBlob)); - c.close(); - } - - @MediumTest - public void testRealColumns() throws Exception { - mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, data REAL);"); - ContentValues values = new ContentValues(); - values.put("data", 42.11); - long id = mDatabase.insert("test", "data", values); - assertTrue(id > 0); - Cursor c = mDatabase.rawQuery("SELECT data FROM test", null); - assertNotNull(c); - assertTrue(c.moveToFirst()); - assertEquals(42.11, c.getDouble(0)); - c.close(); - } - - @MediumTest - public void testCursor1() throws Exception { - populateDefaultTable(); - - Cursor c = mDatabase.query("test", null, null, null, null, null, null); - - int dataColumn = c.getColumnIndexOrThrow("data"); - - // The cursor should ignore text before the last period when looking for a column. (This - // is a temporary hack in all implementations of getColumnIndex.) - int dataColumn2 = c.getColumnIndexOrThrow("junk.data"); - assertEquals(dataColumn, dataColumn2); - - assertSame(3, c.getCount()); - - assertTrue(c.isBeforeFirst()); - - try { - c.getInt(0); - fail("CursorIndexOutOfBoundsException expected"); - } catch (CursorIndexOutOfBoundsException ex) { - // expected - } - - c.moveToNext(); - assertEquals(1, c.getInt(0)); - - String s = c.getString(dataColumn); - assertEquals(sString1, s); - - c.moveToNext(); - s = c.getString(dataColumn); - assertEquals(sString2, s); - - c.moveToNext(); - s = c.getString(dataColumn); - assertEquals(sString3, s); - - c.moveToPosition(-1); - c.moveToNext(); - s = c.getString(dataColumn); - assertEquals(sString1, s); - - c.moveToPosition(2); - s = c.getString(dataColumn); - assertEquals(sString3, s); - - int i; - - for (c.moveToFirst(), i = 0; !c.isAfterLast(); c.moveToNext(), i++) { - c.getInt(0); - } - - assertEquals(3, i); - - try { - c.getInt(0); - fail("CursorIndexOutOfBoundsException expected"); - } catch (CursorIndexOutOfBoundsException ex) { - // expected - } - c.close(); - } - - @MediumTest - public void testCursor2() throws Exception { - populateDefaultTable(); - - Cursor c = mDatabase.query("test", null, "_id > 1000", null, null, null, null); - assertEquals(0, c.getCount()); - assertTrue(c.isBeforeFirst()); - - try { - c.getInt(0); - fail("CursorIndexOutOfBoundsException expected"); - } catch (CursorIndexOutOfBoundsException ex) { - // expected - } - - int i; - for (c.moveToFirst(), i = 0; !c.isAfterLast(); c.moveToNext(), i++) { - c.getInt(0); - } - assertEquals(0, i); - try { - c.getInt(0); - fail("CursorIndexOutOfBoundsException expected"); - } catch (CursorIndexOutOfBoundsException ex) { - // expected - } - c.close(); - } - - @MediumTest - public void testLargeField() throws Exception { - mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, data TEXT);"); - - StringBuilder sql = new StringBuilder(2100); - sql.append("INSERT INTO test (data) VALUES ('"); - Random random = new Random(System.currentTimeMillis()); - StringBuilder randomString = new StringBuilder(1979); - for (int i = 0; i < 1979; i++) { - randomString.append((random.nextInt() & 0xf) % 10); - } - sql.append(randomString); - sql.append("');"); - mDatabase.execSQL(sql.toString()); - - Cursor c = mDatabase.query("test", null, null, null, null, null, null); - assertNotNull(c); - assertEquals(1, c.getCount()); - - assertTrue(c.moveToFirst()); - assertEquals(0, c.getPosition()); - String largeString = c.getString(c.getColumnIndexOrThrow("data")); - assertNotNull(largeString); - assertEquals(randomString.toString(), largeString); - c.close(); - } - - class TestObserver extends DataSetObserver { - int total; - SQLiteCursor c; - boolean quit = false; - public TestObserver(int total_, SQLiteCursor cursor) { - c = cursor; - total = total_; - } - - @Override - public void onChanged() { - int count = c.getCount(); - if (total == count) { - int i = 0; - while (c.moveToNext()) { - assertEquals(i, c.getInt(1)); - i++; - } - assertEquals(count, i); - quit = true; - Looper.myLooper().quit(); - } - } - - @Override - public void onInvalidated() { - } - } - - //@Large - @Suppress - public void testLoadingThreadDelayRegisterData() throws Exception { - mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, data INT);"); - - final int count = 505; - String sql = "INSERT INTO test (data) VALUES (?);"; - SQLiteStatement s = mDatabase.compileStatement(sql); - for (int i = 0; i < count; i++) { - s.bindLong(1, i); - s.execute(); - } - - int maxRead = 500; - int initialRead = 5; - SQLiteCursor c = (SQLiteCursor)mDatabase.rawQuery("select * from test;", - null, initialRead, maxRead); - - TestObserver observer = new TestObserver(count, c); - c.getCount(); - c.registerDataSetObserver(observer); - if (!observer.quit) { - Looper.loop(); - } - c.close(); - } - - @LargeTest - public void testLoadingThread() throws Exception { - mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, data INT);"); - - final int count = 50000; - String sql = "INSERT INTO test (data) VALUES (?);"; - SQLiteStatement s = mDatabase.compileStatement(sql); - for (int i = 0; i < count; i++) { - s.bindLong(1, i); - s.execute(); - } - - int maxRead = 1000; - int initialRead = 5; - SQLiteCursor c = (SQLiteCursor)mDatabase.rawQuery("select * from test;", - null, initialRead, maxRead); - - TestObserver observer = new TestObserver(count, c); - c.registerDataSetObserver(observer); - c.getCount(); - - Looper.loop(); - c.close(); - } - - @LargeTest - public void testLoadingThreadClose() throws Exception { - mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, data INT);"); - - final int count = 1000; - String sql = "INSERT INTO test (data) VALUES (?);"; - SQLiteStatement s = mDatabase.compileStatement(sql); - for (int i = 0; i < count; i++) { - s.bindLong(1, i); - s.execute(); - } - - int maxRead = 11; - int initialRead = 5; - SQLiteCursor c = (SQLiteCursor)mDatabase.rawQuery("select * from test;", - null, initialRead, maxRead); - - TestObserver observer = new TestObserver(count, c); - c.registerDataSetObserver(observer); - c.getCount(); - c.close(); - } - - @LargeTest - public void testLoadingThreadDeactivate() throws Exception { - mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, data INT);"); - - final int count = 1000; - String sql = "INSERT INTO test (data) VALUES (?);"; - SQLiteStatement s = mDatabase.compileStatement(sql); - for (int i = 0; i < count; i++) { - s.bindLong(1, i); - s.execute(); - } - - int maxRead = 11; - int initialRead = 5; - SQLiteCursor c = (SQLiteCursor)mDatabase.rawQuery("select * from test;", - null, initialRead, maxRead); - - TestObserver observer = new TestObserver(count, c); - c.registerDataSetObserver(observer); - c.getCount(); - c.deactivate(); - c.close(); - } - - @LargeTest - public void testManyRowsLong() throws Exception { - mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, data INT);"); - - final int count = 36799; - for (int i = 0; i < count; i++) { - mDatabase.execSQL("INSERT INTO test (data) VALUES (" + i + ");"); - } - - Cursor c = mDatabase.query("test", new String[]{"data"}, null, null, null, null, null); - assertNotNull(c); - - int i = 0; - while (c.moveToNext()) { - assertEquals(i, c.getInt(0)); - i++; - } - assertEquals(count, i); - assertEquals(count, c.getCount()); - - Log.d("testManyRows", "count " + Integer.toString(i)); - c.close(); - } - - @LargeTest - public void testManyRowsTxt() throws Exception { - mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, data TEXT);"); - StringBuilder sql = new StringBuilder(2100); - sql.append("INSERT INTO test (data) VALUES ('"); - Random random = new Random(System.currentTimeMillis()); - StringBuilder randomString = new StringBuilder(1979); - for (int i = 0; i < 1979; i++) { - randomString.append((random.nextInt() & 0xf) % 10); - } - sql.append(randomString); - sql.append("');"); - - // if cursor window size changed, adjust this value too - final int count = 600; // more than two fillWindow needed - for (int i = 0; i < count; i++) { - mDatabase.execSQL(sql.toString()); - } - - Cursor c = mDatabase.query("test", new String[]{"data"}, null, null, null, null, null); - assertNotNull(c); - - int i = 0; - while (c.moveToNext()) { - assertEquals(randomString.toString(), c.getString(0)); - i++; - } - assertEquals(count, i); - assertEquals(count, c.getCount()); - c.close(); - } - - @LargeTest - public void testManyRowsTxtLong() throws Exception { - mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, txt TEXT, data INT);"); - - Random random = new Random(System.currentTimeMillis()); - StringBuilder randomString = new StringBuilder(1979); - for (int i = 0; i < 1979; i++) { - randomString.append((random.nextInt() & 0xf) % 10); - } - - // if cursor window size changed, adjust this value too - final int count = 600; - for (int i = 0; i < count; i++) { - StringBuilder sql = new StringBuilder(2100); - sql.append("INSERT INTO test (txt, data) VALUES ('"); - sql.append(randomString); - sql.append("','"); - sql.append(i); - sql.append("');"); - mDatabase.execSQL(sql.toString()); - } - - Cursor c = mDatabase.query("test", new String[]{"txt", "data"}, null, null, null, null, null); - assertNotNull(c); - - int i = 0; - while (c.moveToNext()) { - assertEquals(randomString.toString(), c.getString(0)); - assertEquals(i, c.getInt(1)); - i++; - } - assertEquals(count, i); - assertEquals(count, c.getCount()); - c.close(); - } - - @MediumTest - public void testRequery() throws Exception { - populateDefaultTable(); - - Cursor c = mDatabase.rawQuery("SELECT * FROM test", null); - assertNotNull(c); - assertEquals(3, c.getCount()); - c.deactivate(); - c.requery(); - assertEquals(3, c.getCount()); - c.close(); - } - - @MediumTest - public void testRequeryWithSelection() throws Exception { - populateDefaultTable(); - - Cursor c = mDatabase.rawQuery("SELECT data FROM test WHERE data = '" + sString1 + "'", - null); - assertNotNull(c); - assertEquals(1, c.getCount()); - assertTrue(c.moveToFirst()); - assertEquals(sString1, c.getString(0)); - c.deactivate(); - c.requery(); - assertEquals(1, c.getCount()); - assertTrue(c.moveToFirst()); - assertEquals(sString1, c.getString(0)); - c.close(); - } - - @MediumTest - public void testRequeryWithSelectionArgs() throws Exception { - populateDefaultTable(); - - Cursor c = mDatabase.rawQuery("SELECT data FROM test WHERE data = ?", - new String[]{sString1}); - assertNotNull(c); - assertEquals(1, c.getCount()); - assertTrue(c.moveToFirst()); - assertEquals(sString1, c.getString(0)); - c.deactivate(); - c.requery(); - assertEquals(1, c.getCount()); - assertTrue(c.moveToFirst()); - assertEquals(sString1, c.getString(0)); - c.close(); - } - - @MediumTest - public void testRequeryWithAlteredSelectionArgs() throws Exception { - /** - * Test the ability of a subclass of SQLiteCursor to change its query arguments. - */ - populateDefaultTable(); - - SQLiteDatabase.CursorFactory factory = new SQLiteDatabase.CursorFactory() { - public Cursor newCursor( - SQLiteDatabase db, SQLiteCursorDriver masterQuery, String editTable, - SQLiteQuery query) { - return new SQLiteCursor(db, masterQuery, editTable, query) { - @Override - public boolean requery() { - setSelectionArguments(new String[]{"2"}); - return super.requery(); - } - }; - } - }; - Cursor c = mDatabase.rawQueryWithFactory( - factory, "SELECT data FROM test WHERE _id <= ?", new String[]{"1"}, - null); - assertNotNull(c); - assertEquals(1, c.getCount()); - assertTrue(c.moveToFirst()); - assertEquals(sString1, c.getString(0)); - - // Our hacked requery() changes the query arguments in the cursor. - c.requery(); - - assertEquals(2, c.getCount()); - assertTrue(c.moveToFirst()); - assertEquals(sString1, c.getString(0)); - assertTrue(c.moveToNext()); - assertEquals(sString2, c.getString(0)); - - // Test that setting query args on a deactivated cursor also works. - c.deactivate(); - c.requery(); - } -} diff --git a/tests/AndroidTests/src/com/android/unit_tests/DatabaseStatementTest.java b/tests/AndroidTests/src/com/android/unit_tests/DatabaseStatementTest.java deleted file mode 100644 index 16ca59f51b83..000000000000 --- a/tests/AndroidTests/src/com/android/unit_tests/DatabaseStatementTest.java +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * 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.android.unit_tests; - -import android.database.Cursor; -import android.database.sqlite.SQLiteConstraintException; -import android.database.sqlite.SQLiteDatabase; -import android.database.sqlite.SQLiteDoneException; -import android.database.sqlite.SQLiteStatement; -import android.test.PerformanceTestCase; -import android.test.suitebuilder.annotation.MediumTest; -import android.test.suitebuilder.annotation.SmallTest; -import junit.framework.TestCase; - -import java.io.File; - -public class DatabaseStatementTest extends TestCase implements PerformanceTestCase { - - private static final String sString1 = "this is a test"; - private static final String sString2 = "and yet another test"; - private static final String sString3 = "this string is a little longer, but still a test"; - - private static final int CURRENT_DATABASE_VERSION = 42; - private SQLiteDatabase mDatabase; - private File mDatabaseFile; - - @Override - protected void setUp() throws Exception { - super.setUp(); - mDatabaseFile = new File("/sqlite_stmt_journals", "database_test.db"); - if (mDatabaseFile.exists()) { - mDatabaseFile.delete(); - } - mDatabase = SQLiteDatabase.openOrCreateDatabase(mDatabaseFile.getPath(), null); - assertNotNull(mDatabase); - mDatabase.setVersion(CURRENT_DATABASE_VERSION); - } - - @Override - protected void tearDown() throws Exception { - mDatabase.close(); - mDatabaseFile.delete(); - super.tearDown(); - } - - public boolean isPerformanceOnly() { - return false; - } - - // These test can only be run once. - public int startPerformance(Intermediates intermediates) { - return 1; - } - - private void populateDefaultTable() { - mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, data TEXT);"); - - mDatabase.execSQL("INSERT INTO test (data) VALUES ('" + sString1 + "');"); - mDatabase.execSQL("INSERT INTO test (data) VALUES ('" + sString2 + "');"); - mDatabase.execSQL("INSERT INTO test (data) VALUES ('" + sString3 + "');"); - } - - @MediumTest - public void testExecuteStatement() throws Exception { - populateDefaultTable(); - SQLiteStatement statement = mDatabase.compileStatement("DELETE FROM test"); - statement.execute(); - - Cursor c = mDatabase.query("test", null, null, null, null, null, null); - assertEquals(0, c.getCount()); - c.deactivate(); - statement.close(); - } - - @MediumTest - public void testSimpleQuery() throws Exception { - mDatabase.execSQL("CREATE TABLE test (num INTEGER NOT NULL, str TEXT NOT NULL);"); - mDatabase.execSQL("INSERT INTO test VALUES (1234, 'hello');"); - SQLiteStatement statement1 = - mDatabase.compileStatement("SELECT num FROM test WHERE str = ?"); - SQLiteStatement statement2 = - mDatabase.compileStatement("SELECT str FROM test WHERE num = ?"); - - try { - statement1.bindString(1, "hello"); - long value = statement1.simpleQueryForLong(); - assertEquals(1234, value); - - statement1.bindString(1, "world"); - statement1.simpleQueryForLong(); - fail("shouldn't get here"); - } catch (SQLiteDoneException e) { - // expected - } - - try { - statement2.bindLong(1, 1234); - String value = statement1.simpleQueryForString(); - assertEquals("hello", value); - - statement2.bindLong(1, 5678); - statement1.simpleQueryForString(); - fail("shouldn't get here"); - } catch (SQLiteDoneException e) { - // expected - } - - statement1.close(); - statement2.close(); - } - - @MediumTest - public void testStatementLongBinding() throws Exception { - mDatabase.execSQL("CREATE TABLE test (num INTEGER);"); - SQLiteStatement statement = mDatabase.compileStatement("INSERT INTO test (num) VALUES (?)"); - - for (int i = 0; i < 10; i++) { - statement.bindLong(1, i); - statement.execute(); - } - statement.close(); - - Cursor c = mDatabase.query("test", null, null, null, null, null, null); - int numCol = c.getColumnIndexOrThrow("num"); - c.moveToFirst(); - for (long i = 0; i < 10; i++) { - long num = c.getLong(numCol); - assertEquals(i, num); - c.moveToNext(); - } - c.close(); - } - - @MediumTest - public void testStatementStringBinding() throws Exception { - mDatabase.execSQL("CREATE TABLE test (num TEXT);"); - SQLiteStatement statement = mDatabase.compileStatement("INSERT INTO test (num) VALUES (?)"); - - for (long i = 0; i < 10; i++) { - statement.bindString(1, Long.toHexString(i)); - statement.execute(); - } - statement.close(); - - Cursor c = mDatabase.query("test", null, null, null, null, null, null); - int numCol = c.getColumnIndexOrThrow("num"); - c.moveToFirst(); - for (long i = 0; i < 10; i++) { - String num = c.getString(numCol); - assertEquals(Long.toHexString(i), num); - c.moveToNext(); - } - c.close(); - } - - @MediumTest - public void testStatementClearBindings() throws Exception { - mDatabase.execSQL("CREATE TABLE test (num INTEGER);"); - SQLiteStatement statement = mDatabase.compileStatement("INSERT INTO test (num) VALUES (?)"); - - for (long i = 0; i < 10; i++) { - statement.bindLong(1, i); - statement.clearBindings(); - statement.execute(); - } - statement.close(); - - Cursor c = mDatabase.query("test", null, null, null, null, null, "ROWID"); - int numCol = c.getColumnIndexOrThrow("num"); - assertTrue(c.moveToFirst()); - for (long i = 0; i < 10; i++) { - assertTrue(c.isNull(numCol)); - c.moveToNext(); - } - c.close(); - } - - @MediumTest - public void testSimpleStringBinding() throws Exception { - mDatabase.execSQL("CREATE TABLE test (num TEXT, value TEXT);"); - String statement = "INSERT INTO test (num, value) VALUES (?,?)"; - - String[] args = new String[2]; - for (int i = 0; i < 2; i++) { - args[i] = Integer.toHexString(i); - } - - mDatabase.execSQL(statement, args); - - Cursor c = mDatabase.query("test", null, null, null, null, null, null); - int numCol = c.getColumnIndexOrThrow("num"); - int valCol = c.getColumnIndexOrThrow("value"); - c.moveToFirst(); - String num = c.getString(numCol); - assertEquals(Integer.toHexString(0), num); - - String val = c.getString(valCol); - assertEquals(Integer.toHexString(1), val); - c.close(); - } - - @MediumTest - public void testStatementMultipleBindings() throws Exception { - mDatabase.execSQL("CREATE TABLE test (num INTEGER, str TEXT);"); - SQLiteStatement statement = - mDatabase.compileStatement("INSERT INTO test (num, str) VALUES (?, ?)"); - - for (long i = 0; i < 10; i++) { - statement.bindLong(1, i); - statement.bindString(2, Long.toHexString(i)); - statement.execute(); - } - statement.close(); - - Cursor c = mDatabase.query("test", null, null, null, null, null, "ROWID"); - int numCol = c.getColumnIndexOrThrow("num"); - int strCol = c.getColumnIndexOrThrow("str"); - assertTrue(c.moveToFirst()); - for (long i = 0; i < 10; i++) { - long num = c.getLong(numCol); - String str = c.getString(strCol); - assertEquals(i, num); - assertEquals(Long.toHexString(i), str); - c.moveToNext(); - } - c.close(); - } - - private static class StatementTestThread extends Thread { - private SQLiteDatabase mDatabase; - private SQLiteStatement mStatement; - - public StatementTestThread(SQLiteDatabase db, SQLiteStatement statement) { - super(); - mDatabase = db; - mStatement = statement; - } - - @Override - public void run() { - mDatabase.beginTransaction(); - for (long i = 0; i < 10; i++) { - mStatement.bindLong(1, i); - mStatement.bindString(2, Long.toHexString(i)); - mStatement.execute(); - } - mDatabase.setTransactionSuccessful(); - mDatabase.endTransaction(); - - Cursor c = mDatabase.query("test", null, null, null, null, null, "ROWID"); - int numCol = c.getColumnIndexOrThrow("num"); - int strCol = c.getColumnIndexOrThrow("str"); - assertTrue(c.moveToFirst()); - for (long i = 0; i < 10; i++) { - long num = c.getLong(numCol); - String str = c.getString(strCol); - assertEquals(i, num); - assertEquals(Long.toHexString(i), str); - c.moveToNext(); - } - c.close(); - } - } - - @MediumTest - public void testStatementMultiThreaded() throws Exception { - mDatabase.execSQL("CREATE TABLE test (num INTEGER, str TEXT);"); - SQLiteStatement statement = - mDatabase.compileStatement("INSERT INTO test (num, str) VALUES (?, ?)"); - - StatementTestThread thread = new StatementTestThread(mDatabase, statement); - thread.start(); - try { - thread.join(); - } finally { - statement.close(); - } - } - - @MediumTest - public void testStatementConstraint() throws Exception { - mDatabase.execSQL("CREATE TABLE test (num INTEGER NOT NULL);"); - SQLiteStatement statement = mDatabase.compileStatement("INSERT INTO test (num) VALUES (?)"); - - // Try to insert NULL, which violates the constraint - try { - statement.clearBindings(); - statement.execute(); - fail("expected exception not thrown"); - } catch (SQLiteConstraintException e) { - // expected - } - - // Make sure the statement can still be used - statement.bindLong(1, 1); - statement.execute(); - statement.close(); - - Cursor c = mDatabase.query("test", null, null, null, null, null, null); - int numCol = c.getColumnIndexOrThrow("num"); - c.moveToFirst(); - long num = c.getLong(numCol); - assertEquals(1, num); - c.close(); - } -} diff --git a/tests/AndroidTests/src/com/android/unit_tests/DatabaseTests.java b/tests/AndroidTests/src/com/android/unit_tests/DatabaseTests.java index a7a1400341dc..a288c73facdd 100644 --- a/tests/AndroidTests/src/com/android/unit_tests/DatabaseTests.java +++ b/tests/AndroidTests/src/com/android/unit_tests/DatabaseTests.java @@ -23,8 +23,6 @@ public class DatabaseTests { TestSuite suite = new TestSuite(DatabaseTests.class.getName()); suite.addTestSuite(DatabaseGeneralTest.class); - suite.addTestSuite(DatabaseCursorTest.class); - suite.addTestSuite(DatabaseStatementTest.class); suite.addTestSuite(DatabaseLocaleTest.class); suite.addTestSuite(CursorWindowTest.class); suite.addTestSuite(DatabaseLockTest.class); diff --git a/tests/AndroidTests/src/com/android/unit_tests/NeighboringCellInfoTest.java b/tests/AndroidTests/src/com/android/unit_tests/NeighboringCellInfoTest.java deleted file mode 100644 index 7252aa95fabf..000000000000 --- a/tests/AndroidTests/src/com/android/unit_tests/NeighboringCellInfoTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2009 The Android Open Source Project - * - * 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.android.unit_tests; - -import android.os.Parcel; -import android.test.AndroidTestCase; -import android.telephony.NeighboringCellInfo; -import android.test. suitebuilder.annotation.SmallTest; - -import static android.telephony.TelephonyManager.NETWORK_TYPE_UNKNOWN; -import static android.telephony.TelephonyManager.NETWORK_TYPE_EDGE; -import static android.telephony.TelephonyManager.NETWORK_TYPE_GPRS; -import static android.telephony.TelephonyManager.NETWORK_TYPE_UMTS; - -public class NeighboringCellInfoTest extends AndroidTestCase { - @SmallTest - public void testConstructor() { - int rssi = 31; - NeighboringCellInfo nc; - - nc = new NeighboringCellInfo(rssi, "FFFFFFF", NETWORK_TYPE_EDGE); - assertEquals(NETWORK_TYPE_EDGE, nc.getNetworkType()); - assertEquals(rssi, nc.getRssi()); - assertEquals(0xfff, nc.getLac()); - assertEquals(0xffff, nc.getCid()); - assertEquals(NeighboringCellInfo.UNKNOWN_CID, nc.getPsc()); - - nc = new NeighboringCellInfo(rssi, "1FF", NETWORK_TYPE_UMTS); - assertEquals(NETWORK_TYPE_UMTS, nc.getNetworkType()); - assertEquals(rssi, nc.getRssi()); - assertEquals(NeighboringCellInfo.UNKNOWN_CID, nc.getCid()); - assertEquals(NeighboringCellInfo.UNKNOWN_CID, nc.getLac()); - assertEquals(0x1ff, nc.getPsc()); - - nc = new NeighboringCellInfo(rssi, "1FF", NETWORK_TYPE_UNKNOWN); - assertEquals(NETWORK_TYPE_UNKNOWN, nc.getNetworkType()); - assertEquals(rssi, nc.getRssi()); - assertEquals(NeighboringCellInfo.UNKNOWN_CID, nc.getCid()); - assertEquals(NeighboringCellInfo.UNKNOWN_CID, nc.getLac()); - assertEquals(NeighboringCellInfo.UNKNOWN_CID, nc.getPsc()); - } - - @SmallTest - public void testParcel() { - int rssi = 20; - - NeighboringCellInfo nc = new NeighboringCellInfo(rssi, "12345678", NETWORK_TYPE_GPRS); - assertEquals(NETWORK_TYPE_GPRS, nc.getNetworkType()); - assertEquals(rssi, nc.getRssi()); - assertEquals(0x1234, nc.getLac()); - assertEquals(0x5678, nc.getCid()); - assertEquals(NeighboringCellInfo.UNKNOWN_CID, nc.getPsc()); - - Parcel p = Parcel.obtain(); - p.setDataPosition(0); - nc.writeToParcel(p, 0); - - p.setDataPosition(0); - NeighboringCellInfo nw = new NeighboringCellInfo(p); - assertEquals(NETWORK_TYPE_GPRS, nw.getNetworkType()); - assertEquals(rssi, nw.getRssi()); - assertEquals(0x1234, nw.getLac()); - assertEquals(0x5678, nw.getCid()); - assertEquals(NeighboringCellInfo.UNKNOWN_CID, nw.getPsc()); - } -} diff --git a/tests/AndroidTests/src/com/android/unit_tests/content/ArrayTest.java b/tests/AndroidTests/src/com/android/unit_tests/content/ArrayTest.java deleted file mode 100644 index 4d5b5e778041..000000000000 --- a/tests/AndroidTests/src/com/android/unit_tests/content/ArrayTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * 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.android.unit_tests.content; - -import android.content.res.Resources; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; -import android.util.TypedValue; -import com.android.unit_tests.R; - -public class ArrayTest extends AndroidTestCase { - private Resources mResources; - - @Override - protected void setUp() throws Exception { - super.setUp(); - mResources = mContext.getResources(); - } - - private void checkEntry(int resid, int index, Object res, Object expected) { - assertEquals("in resource 0x" + Integer.toHexString(resid) - + " at index " + index, expected, res); - } - - private void checkStringArray(int resid, String[] expected) { - String[] res = mResources.getStringArray(resid); - assertEquals(res.length, expected.length); - for (int i=0; i<expected.length; i++) { - checkEntry(resid, i, res[i], expected[i]); - } - } - - private void checkTextArray(int resid, String[] expected) { - CharSequence[] res = mResources.getTextArray(resid); - assertEquals(res.length, expected.length); - for (int i=0; i<expected.length; i++) { - checkEntry(resid, i, res[i], expected[i]); - } - } - - private void checkIntArray(int resid, int[] expected) { - int[] res = mResources.getIntArray(resid); - assertEquals(res.length, expected.length); - for (int i=0; i<expected.length; i++) { - assertEquals("in resource 0x" + Integer.toHexString(resid) - + " at index " + i, expected[i], res[i]); - } - } - - @SmallTest - public void testStrings() throws Exception { - checkStringArray(R.array.strings, new String[] {"zero", "1", "here"}); - checkTextArray(R.array.strings, new String[] {"zero", "1", "here"}); - checkStringArray(R.array.integers, new String[] {null, null, null}); - checkTextArray(R.array.integers, new String[] {null, null, null}); - } - - @SmallTest - public void testIntegers() throws Exception { - checkIntArray(R.array.strings, new int[] {0, 0, 0}); - checkIntArray(R.array.integers, new int[] {0, 1, 101}); - } -} diff --git a/tests/AndroidTests/src/com/android/unit_tests/content/ConfigTest.java b/tests/AndroidTests/src/com/android/unit_tests/content/ConfigTest.java deleted file mode 100644 index a065d7016af0..000000000000 --- a/tests/AndroidTests/src/com/android/unit_tests/content/ConfigTest.java +++ /dev/null @@ -1,540 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * 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.android.unit_tests.content; - -import android.content.Context; -import android.content.res.AssetManager; -import android.content.res.Configuration; -import android.content.res.Resources; -import android.content.res.TypedArray; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.MediumTest; -import android.test.suitebuilder.annotation.SmallTest; -import android.util.DisplayMetrics; -import android.view.Display; -import android.view.WindowManager; -import com.android.unit_tests.R; - -import java.util.Locale; - -public class ConfigTest extends AndroidTestCase { - enum properties { - LANGUAGE, - COUNTRY, - MCC, - MNC, - TOUCHSCREEN, - KEYBOARD, - KEYBOARDHIDDEN, - NAVIGATION, - ORIENTATION, - WIDTH, - HEIGHT, - DENSITY - } - - private static void checkValue(Resources res, int resId, String expectedValue) { - try { - String actual = res.getString(resId); - assertNotNull("Returned wrong configuration-based simple value: expected <nothing>, got '" - + actual + "' from resource 0x" - + Integer.toHexString(resId), - expectedValue); - assertEquals("Returned wrong configuration-based simple value: expected '" - + expectedValue + "', got '" + actual + "' from resource 0x" - + Integer.toHexString(resId), - expectedValue, actual); - } catch (Resources.NotFoundException e) { - assertNull("Resource not found for configuration-based simple value: expecting \"" - + expectedValue + "\"", - expectedValue); - } - } - - private static void checkValue(Resources res, int resId, - int[] styleable, String[] expectedValues) { - Resources.Theme theme = res.newTheme(); - TypedArray sa = theme.obtainStyledAttributes(resId, styleable); - for (int i = 0; i < styleable.length; i++) { - String actual = sa.getString(i); - assertEquals("Returned wrong configuration-based style value: expected '" - + expectedValues[i] + "', got '" + actual + "' from attr " - + i + " of resource 0x" + Integer.toHexString(resId), - actual, expectedValues[i]); - } - sa.recycle(); - } - - class TotalConfig { - Configuration mConfig; - DisplayMetrics mMetrics; - - TotalConfig() { - mConfig = new Configuration(); - // don't rely on build settings - they may change - mConfig.locale = new Locale("en", "US"); - mConfig.mcc = 310; - mConfig.mnc = 001; // unused - mConfig.touchscreen = Configuration.TOUCHSCREEN_FINGER; - mConfig.keyboard = Configuration.KEYBOARD_QWERTY; - mConfig.keyboardHidden = Configuration.KEYBOARDHIDDEN_YES; - mConfig.navigation = Configuration.NAVIGATION_TRACKBALL; - mConfig.orientation = Configuration.ORIENTATION_PORTRAIT; - - mMetrics = new DisplayMetrics(); - mMetrics.widthPixels = 200; - mMetrics.heightPixels = 320; - mMetrics.density = 1; - } - - void setProperty(properties p, int value) { - switch(p) { - case MCC: - mConfig.mcc = value; - break; - case MNC: - mConfig.mnc = value; - break; - case TOUCHSCREEN: - mConfig.touchscreen = value; - break; - case KEYBOARD: - mConfig.keyboard = value; - break; - case KEYBOARDHIDDEN: - mConfig.keyboardHidden = value; - break; - case NAVIGATION: - mConfig.navigation = value; - break; - case ORIENTATION: - mConfig.orientation = value; - break; - case WIDTH: - mMetrics.widthPixels = value; - break; - case HEIGHT: - mMetrics.heightPixels = value; - break; - case DENSITY: - // this is the ratio from the standard - - mMetrics.density = (((float)value)/((float)DisplayMetrics.DENSITY_DEFAULT)); - break; - default: - assert(false); - break; - } - } - - public void setProperty(properties p, String value) { - switch(p) { - case LANGUAGE: - String oldCountry = mConfig.locale.getCountry(); - mConfig.locale = new Locale(value, oldCountry); - break; - case COUNTRY: - String oldLanguage = mConfig.locale.getLanguage(); - mConfig.locale = new Locale(oldLanguage, value); - break; - default: - assert(false); - break; - } - } - - public Resources getResources() { - AssetManager assmgr = new AssetManager(); - assmgr.addAssetPath(mContext.getPackageResourcePath()); - return new Resources(assmgr, mMetrics, mConfig); - } - } - - private static void checkPair(Resources res, int[] notResIds, - int simpleRes, String simpleString, - int bagRes, String bagString) { - boolean willHave = true; - if (notResIds != null) { - for (int i : notResIds) { - if (i == simpleRes) { - willHave = false; - break; - } - } - } - checkValue(res, simpleRes, willHave ? simpleString : null); - checkValue(res, bagRes, R.styleable.TestConfig, - new String[]{willHave ? bagString : null}); - } - - @SmallTest - public void testAllConfigs() throws Exception { - /** - * Test a resource that contains a value for each possible single - * configuration value. - */ - TotalConfig config = new TotalConfig(); - Resources res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple default"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag default"}); - - config = new TotalConfig(); - config.setProperty(properties.LANGUAGE, "xx"); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple xx"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag xx"}); - - config = new TotalConfig(); - config.setProperty(properties.LANGUAGE, "xx"); - config.setProperty(properties.COUNTRY, "YY"); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple xx-rYY"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag xx-rYY"}); - - config = new TotalConfig(); - config.setProperty(properties.MCC, 111); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple mcc111"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag mcc111"}); - - config = new TotalConfig(); - config.setProperty(properties.MNC, 222); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple mnc222"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag mnc222"}); - - config = new TotalConfig(); - config.setProperty(properties.TOUCHSCREEN, Configuration.TOUCHSCREEN_NOTOUCH); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple notouch"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag notouch"}); - - config = new TotalConfig(); - config.setProperty(properties.TOUCHSCREEN, Configuration.TOUCHSCREEN_STYLUS); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple stylus"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag stylus"}); - - config = new TotalConfig(); - config.setProperty(properties.KEYBOARD, Configuration.KEYBOARD_NOKEYS); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple nokeys"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag nokeys"}); - - config = new TotalConfig(); - config.setProperty(properties.KEYBOARD, Configuration.KEYBOARD_12KEY); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple 12key"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag 12key"}); - - config = new TotalConfig(); - config.setProperty(properties.KEYBOARDHIDDEN, Configuration.KEYBOARDHIDDEN_NO); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple keysexposed"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag keysexposed"}); - - config = new TotalConfig(); - config.setProperty(properties.NAVIGATION, Configuration.NAVIGATION_NONAV); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple nonav"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag nonav"}); - - config = new TotalConfig(); - config.setProperty(properties.NAVIGATION, Configuration.NAVIGATION_DPAD); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple dpad"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag dpad"}); - - config = new TotalConfig(); - config.setProperty(properties.NAVIGATION, Configuration.NAVIGATION_WHEEL); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple wheel"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag wheel"}); - - config = new TotalConfig(); - config.setProperty(properties.HEIGHT, 480); - config.setProperty(properties.WIDTH, 320); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple 480x320"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag 480x320"}); - - config = new TotalConfig(); - config.setProperty(properties.DENSITY, 240); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple 240dpi"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag 240dpi"}); - - config = new TotalConfig(); - config.setProperty(properties.ORIENTATION, Configuration.ORIENTATION_LANDSCAPE); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple landscape"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag landscape"}); - - config = new TotalConfig(); - config.setProperty(properties.ORIENTATION, Configuration.ORIENTATION_SQUARE); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple square"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag square"}); - } - - @MediumTest - public void testDensity() throws Exception { - // have 32, 240 and the default 160 content. - // rule is that closest wins, with down scaling (larger content) - // being twice as nice as upscaling. - // transition at H/2 * (-1 +/- sqrt(1+8L/H)) - // SO, X < 49 goes to 32 - // 49 >= X < 182 goes to 160 - // X >= 182 goes to 240 - TotalConfig config = new TotalConfig(); - config.setProperty(properties.DENSITY, 2); - Resources res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple 32dpi"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag 32dpi"}); - - config = new TotalConfig(); - config.setProperty(properties.DENSITY, 32); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple 32dpi"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag 32dpi"}); - - config = new TotalConfig(); - config.setProperty(properties.DENSITY, 48); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple 32dpi"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag 32dpi"}); - - config = new TotalConfig(); - config.setProperty(properties.DENSITY, 49); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple default"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag default"}); - - config = new TotalConfig(); - config.setProperty(properties.DENSITY, 150); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple default"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag default"}); - - config = new TotalConfig(); - config.setProperty(properties.DENSITY, 181); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple default"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag default"}); - - config = new TotalConfig(); - config.setProperty(properties.DENSITY, 182); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple 240dpi"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag 240dpi"}); - - config = new TotalConfig(); - config.setProperty(properties.DENSITY, 239); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple 240dpi"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag 240dpi"}); - - config = new TotalConfig(); - config.setProperty(properties.DENSITY, 490); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple 240dpi"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag 240dpi"}); - } - -// TODO - add tests for special cases - ie, other key params seem ignored if -// nokeys is set - - @MediumTest - public void testCombinations() throws Exception { - /** - * Verify that proper strings are found for multiple-selectivity case - * (ie, a string set for locale and mcc is found only when both are - * true). - */ - TotalConfig config = new TotalConfig(); - config.setProperty(properties.LANGUAGE, "xx"); - config.setProperty(properties.COUNTRY, "YY"); - config.setProperty(properties.MCC, 111); - Resources res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple mcc111 xx-rYY"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag mcc111 xx-rYY"}); - - config = new TotalConfig(); - config.setProperty(properties.LANGUAGE, "xx"); - config.setProperty(properties.COUNTRY, "YY"); - config.setProperty(properties.MCC, 333); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple xx-rYY"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag xx-rYY"}); - - config = new TotalConfig(); - config.setProperty(properties.MNC, 333); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple default"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag default"}); - } - - @MediumTest - public void testPrecidence() throws Exception { - /** - * Verify that in cases of ties, the specific ordering is followed - */ - - /** - * Precidence order: mcc, mnc, locale, orientation, density, - * touchscreen, hidden, keyboard, navigation, width-height - */ - - /** - * verify mcc trumps mnc. Have 110-xx, 220-xx but no 110-220 - * so with is selected? Should be mcc110-xx. - */ - TotalConfig config = new TotalConfig(); - config.setProperty(properties.MCC, 110); - config.setProperty(properties.MNC, 220); - config.setProperty(properties.LANGUAGE, "xx"); - Resources res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple mcc110 xx"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag mcc110 xx"}); - - /* full A + B + C doesn't exist. Do we get A + C or B + C? - */ - config = new TotalConfig(); - config.setProperty(properties.MCC, 111); - config.setProperty(properties.MNC, 222); - config.setProperty(properties.LANGUAGE, "xx"); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple mcc111 mnc222"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag mcc111 mnc222"}); - - config = new TotalConfig(); - config.setProperty(properties.MNC, 222); - config.setProperty(properties.LANGUAGE, "xx"); - config.setProperty(properties.ORIENTATION, - Configuration.ORIENTATION_SQUARE); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple mnc222 xx"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag mnc222 xx"}); - - config = new TotalConfig(); - config.setProperty(properties.LANGUAGE, "xx"); - config.setProperty(properties.ORIENTATION, - Configuration.ORIENTATION_SQUARE); - config.setProperty(properties.DENSITY, 32); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple xx square"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag xx square"}); - - config = new TotalConfig(); - config.setProperty(properties.ORIENTATION, - Configuration.ORIENTATION_SQUARE); - config.setProperty(properties.DENSITY, 32); - config.setProperty(properties.TOUCHSCREEN, - Configuration.TOUCHSCREEN_STYLUS); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple square 32dpi"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag square 32dpi"}); - - config = new TotalConfig(); - config.setProperty(properties.DENSITY, 32); - config.setProperty(properties.TOUCHSCREEN, - Configuration.TOUCHSCREEN_STYLUS); - config.setProperty(properties.KEYBOARDHIDDEN, - Configuration.KEYBOARDHIDDEN_NO); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple 32dpi stylus"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag 32dpi stylus"}); - - config = new TotalConfig(); - config.setProperty(properties.TOUCHSCREEN, - Configuration.TOUCHSCREEN_STYLUS); - config.setProperty(properties.KEYBOARDHIDDEN, - Configuration.KEYBOARDHIDDEN_NO); - config.setProperty(properties.KEYBOARD, Configuration.KEYBOARD_12KEY); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple stylus keysexposed"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag stylus keysexposed"}); - - config = new TotalConfig(); - config.setProperty(properties.KEYBOARDHIDDEN, - Configuration.KEYBOARDHIDDEN_NO); - config.setProperty(properties.KEYBOARD, Configuration.KEYBOARD_12KEY); - config.setProperty(properties.NAVIGATION, - Configuration.NAVIGATION_DPAD); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple keysexposed 12key"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag keysexposed 12key"}); - - config = new TotalConfig(); - config.setProperty(properties.KEYBOARD, Configuration.KEYBOARD_12KEY); - config.setProperty(properties.NAVIGATION, - Configuration.NAVIGATION_DPAD); - config.setProperty(properties.HEIGHT, 63); - config.setProperty(properties.WIDTH, 57); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple 12key dpad"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag 12key dpad"}); - - config = new TotalConfig(); - config.setProperty(properties.NAVIGATION, - Configuration.NAVIGATION_DPAD); - config.setProperty(properties.HEIGHT, 640); - config.setProperty(properties.WIDTH, 400); - res = config.getResources(); - checkValue(res, R.configVarying.simple, "simple dpad"); - checkValue(res, R.configVarying.bag, - R.styleable.TestConfig, new String[]{"bag dpad"}); - } -} diff --git a/tests/AndroidTests/src/com/android/unit_tests/content/ContentTests.java b/tests/AndroidTests/src/com/android/unit_tests/content/ContentTests.java index 80318dcc6772..636660f8d48e 100644 --- a/tests/AndroidTests/src/com/android/unit_tests/content/ContentTests.java +++ b/tests/AndroidTests/src/com/android/unit_tests/content/ContentTests.java @@ -23,10 +23,6 @@ public class ContentTests { TestSuite suite = new TestSuite(ContentTests.class.getName()); suite.addTestSuite(AssetTest.class); - suite.addTestSuite(IntentFilterTest.class); - suite.addTest(ResourceTests.suite()); - suite.addTestSuite(PluralResourcesTest.class); - suite.addTestSuite(ConfigTest.class); return suite; } } diff --git a/tests/AndroidTests/src/com/android/unit_tests/content/FractionTest.java b/tests/AndroidTests/src/com/android/unit_tests/content/FractionTest.java deleted file mode 100644 index 74a6b8de3d5b..000000000000 --- a/tests/AndroidTests/src/com/android/unit_tests/content/FractionTest.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * 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.android.unit_tests.content; - -import android.content.res.Resources; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; -import android.util.TypedValue; -import com.android.unit_tests.R; - -public class FractionTest extends AndroidTestCase { - - private Resources mResources; - private final TypedValue mValue = new TypedValue(); - - @Override - protected void setUp() throws Exception { - super.setUp(); - mResources = mContext.getResources(); - } - - @SmallTest - public void testFractions() throws Exception { - tryFraction(R.dimen.frac100perc, 1, 1, 1); - tryFraction(R.dimen.frac1perc, 1, 1, .01f); - tryFraction(R.dimen.fracp1perc, 1, 1, .001f); - tryFraction(R.dimen.fracp01perc, 1, 1, .0001f); - tryFraction(R.dimen.frac0perc, 1, 1, 0); - tryFraction(R.dimen.frac1p1perc, 1, 1, .011f); - tryFraction(R.dimen.frac100p1perc, 1, 1, 1.001f); - tryFraction(R.dimen.frac25510perc, 1, 1, 255.1f); - tryFraction(R.dimen.frac25610perc, 1, 1, 256.1f); - tryFraction(R.dimen.frac6553510perc, 1, 1, 65535.1f); - tryFraction(R.dimen.frac6553610perc, 1, 1, 65536.1f); - - tryFraction(R.dimen.frac100perc, 100, 1, 100); - tryFraction(R.dimen.frac1perc, 100, 1, .01f * 100); - tryFraction(R.dimen.fracp1perc, 100, 1, .001f * 100); - tryFraction(R.dimen.fracp01perc, 100, 1, .0001f * 100); - tryFraction(R.dimen.frac0perc, 100, 1, 0); - tryFraction(R.dimen.frac1p1perc, 100, 1, .011f * 100); - tryFraction(R.dimen.frac100p1perc, 100, 1, 1.001f * 100); - tryFraction(R.dimen.frac25510perc, 100, 1, 255.1f * 100); - tryFraction(R.dimen.frac25610perc, 100, 1, 256.1f * 100); - tryFraction(R.dimen.frac6553510perc, 100, 1, 65535.1f * 100); - tryFraction(R.dimen.frac6553610perc, 100, 1, 65536.1f * 100); - - tryFraction(R.dimen.frac100pperc, 100, 2, 2); - tryFraction(R.dimen.frac1pperc, 100, 2, .01f * 2); - tryFraction(R.dimen.fracp1pperc, 100, 2, .001f * 2); - tryFraction(R.dimen.fracp01pperc, 100, 2, .0001f * 2); - tryFraction(R.dimen.frac0pperc, 100, 2, 0); - tryFraction(R.dimen.frac1p1pperc, 100, 2, .011f * 2); - tryFraction(R.dimen.frac100p1pperc, 100, 2, 1.001f * 2); - tryFraction(R.dimen.frac25510pperc, 100, 2, 255.1f * 2); - tryFraction(R.dimen.frac25610pperc, 100, 2, 256.1f * 2); - tryFraction(R.dimen.frac6553510pperc, 100, 2, 65535.1f * 2); - tryFraction(R.dimen.frac6553610pperc, 100, 2, 65536.1f * 2); - } - - private void tryFraction(int resid, float base, float pbase, float expected) { - mResources.getValue(resid, mValue, true); - float res = mValue.getFraction(base, pbase); - float diff = Math.abs(expected - res); - float prec = expected * 1e-4f; - if (prec < 1e-5f) { - prec = 1e-5f; - } - //System.out.println( - // "Res 0x" + Integer.toHexString(resid) + ": got=" + res - // + ", expected=" + expected + ", diff=" + diff); - assertFalse("Expecting value " + expected + " got " + res - + ": in resource 0x" + Integer.toHexString(resid) - + " " + mValue, - diff > prec); - } -} - diff --git a/tests/AndroidTests/src/com/android/unit_tests/content/IntentFilterTest.java b/tests/AndroidTests/src/com/android/unit_tests/content/IntentFilterTest.java deleted file mode 100644 index 0335b9d38798..000000000000 --- a/tests/AndroidTests/src/com/android/unit_tests/content/IntentFilterTest.java +++ /dev/null @@ -1,570 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * 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.android.unit_tests.content; - -import android.content.IntentFilter; -import android.test.suitebuilder.annotation.SmallTest; -import static android.os.PatternMatcher.PATTERN_LITERAL; -import static android.os.PatternMatcher.PATTERN_PREFIX; -import static android.os.PatternMatcher.PATTERN_SIMPLE_GLOB; -import android.net.Uri; -import android.util.StringBuilderPrinter; -import junit.framework.TestCase; - -import java.util.HashSet; - -public class IntentFilterTest extends TestCase { - - public static class Match extends IntentFilter { - Match(String[] actions, String[] categories, String[] mimeTypes, - String[] schemes, String[] authorities, String[] ports) { - if (actions != null) { - for (int i = 0; i < actions.length; i++) { - addAction(actions[i]); - } - } - if (categories != null) { - for (int i = 0; i < categories.length; i++) { - addCategory(categories[i]); - } - } - if (mimeTypes != null) { - for (int i = 0; i < mimeTypes.length; i++) { - try { - addDataType(mimeTypes[i]); - } catch (IntentFilter.MalformedMimeTypeException e) { - throw new RuntimeException("Bad mime type", e); - } - } - } - if (schemes != null) { - for (int i = 0; i < schemes.length; i++) { - addDataScheme(schemes[i]); - } - } - if (authorities != null) { - for (int i = 0; i < authorities.length; i++) { - addDataAuthority(authorities[i], - ports != null ? ports[i] : null); - } - } - } - - Match(String[] actions, String[] categories, String[] mimeTypes, - String[] schemes, String[] authorities, String[] ports, - String[] paths, int[] pathTypes) { - this(actions, categories, mimeTypes, schemes, authorities, ports); - if (paths != null) { - for (int i = 0; i < paths.length; i++) { - addDataPath(paths[i], pathTypes[i]); - } - } - } - } - - public static class MatchCondition { - public final int result; - public final String action; - public final String mimeType; - public final Uri data; - public final String[] categories; - - public MatchCondition(int _result, String _action, String[] _categories, - String _mimeType, String _data) { - result = _result; - action = _action; - mimeType = _mimeType; - data = _data != null ? Uri.parse(_data) : null; - categories = _categories; - } - } - - public static void checkMatches(IntentFilter filter, - MatchCondition[] results) { - for (int i = 0; i < results.length; i++) { - MatchCondition mc = results[i]; - HashSet<String> categories = null; - if (mc.categories != null) { - for (int j = 0; j < mc.categories.length; j++) { - if (categories == null) { - categories = new HashSet<String>(); - } - categories.add(mc.categories[j]); - } - } - int result = filter.match(mc.action, mc.mimeType, - mc.data != null ? mc.data.getScheme() : null, mc.data, - categories, "test"); - if ( (result & IntentFilter.MATCH_CATEGORY_MASK) - != (mc.result & IntentFilter.MATCH_CATEGORY_MASK) ) { - StringBuilder msg = new StringBuilder(); - msg.append("Error matching against IntentFilter:\n"); - filter.dump(new StringBuilderPrinter(msg), " "); - msg.append("Match action: "); - msg.append(mc.action); - msg.append("\nMatch mimeType: "); - msg.append(mc.mimeType); - msg.append("\nMatch data: "); - msg.append(mc.data); - msg.append("\nMatch categories: "); - if (mc.categories != null) { - for (int j = 0; j < mc.categories.length; j++) { - if (j > 0) msg.append(", "); - msg.append(mc.categories[j]); - } - } - msg.append("\nExpected result: 0x"); - msg.append(Integer.toHexString(mc.result)); - msg.append(", got result: 0x"); - msg.append(Integer.toHexString(result)); - throw new RuntimeException(msg.toString()); - } - } - } - - @SmallTest - public void testActions() throws Exception { - IntentFilter filter = new Match( - new String[]{"action1"}, null, null, null, null, null); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.MATCH_CATEGORY_EMPTY, null, - null, null, null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_EMPTY, "action1", - null, null, null), - new MatchCondition(IntentFilter.NO_MATCH_ACTION, "action2", - null, null, null), - }); - - filter = new Match( - new String[]{"action1", "action2"}, - null, null, null, null, null); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.MATCH_CATEGORY_EMPTY, null, - null, null, null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_EMPTY, "action1", - null, null, null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_EMPTY, "action2", - null, null, null), - new MatchCondition(IntentFilter.NO_MATCH_ACTION, "action3", - null, null, null), - }); - } - - @SmallTest - public void testCategories() throws Exception { - IntentFilter filter = new Match( - null, new String[]{"category1"}, null, null, null, null); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.MATCH_CATEGORY_EMPTY, null, - null, null, null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_EMPTY, null, - new String[]{"category1"}, null, null), - new MatchCondition(IntentFilter.NO_MATCH_CATEGORY, null, - new String[]{"category2"}, null, null), - new MatchCondition(IntentFilter.NO_MATCH_CATEGORY, null, - new String[]{"category1", "category2"}, null, null), - }); - - filter = new Match( - null, new String[]{"category1", "category2"}, null, null, - null, null); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.MATCH_CATEGORY_EMPTY, null, - null, null, null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_EMPTY, null, - new String[]{"category1"}, null, null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_EMPTY, null, - new String[]{"category2"}, null, null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_EMPTY, null, - new String[]{"category1", "category2"}, null, null), - new MatchCondition(IntentFilter.NO_MATCH_CATEGORY, null, - new String[]{"category3"}, null, null), - new MatchCondition(IntentFilter.NO_MATCH_CATEGORY, null, - new String[]{"category1", "category2", "category3"}, - null, null), - }); - } - - @SmallTest - public void testMimeTypes() throws Exception { - IntentFilter filter = new Match( - null, null, new String[]{"which1/what1"}, null, null, null); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.NO_MATCH_TYPE, null, - null, null, null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_TYPE, null, null, - "which1/what1", null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_TYPE, null, null, - "which1/*", null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_TYPE, null, null, - "*/*", null), - new MatchCondition(IntentFilter.NO_MATCH_TYPE, null, null, - "which2/what2", null), - new MatchCondition(IntentFilter.NO_MATCH_TYPE, null, null, - "which2/*", null), - new MatchCondition(IntentFilter.NO_MATCH_TYPE, null, null, - "which1/what2", null), - }); - - filter = new Match(null, null, - new String[]{"which1/what1", "which2/what2"}, null, null, - null); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.NO_MATCH_TYPE, null, - null, null, null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_TYPE, null, null, - "which1/what1", null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_TYPE, null, null, - "which1/*", null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_TYPE, null, null, - "*/*", null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_TYPE, null, null, - "which2/what2", null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_TYPE, null, null, - "which2/*", null), - new MatchCondition(IntentFilter.NO_MATCH_TYPE, null, null, - "which1/what2", null), - new MatchCondition(IntentFilter.NO_MATCH_TYPE, null, null, - "which3/what3", null), - }); - - filter = new Match(null, null, - new String[]{"which1/*"}, null, null, null); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.NO_MATCH_TYPE, null, - null, null, null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_TYPE, null, null, - "which1/what1", null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_TYPE, null, null, - "which1/*", null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_TYPE, null, null, - "*/*", null), - new MatchCondition(IntentFilter.NO_MATCH_TYPE, null, null, - "which2/what2", null), - new MatchCondition(IntentFilter.NO_MATCH_TYPE, null, null, - "which2/*", null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_TYPE, null, null, - "which1/what2", null), - new MatchCondition(IntentFilter.NO_MATCH_TYPE, null, null, - "which3/what3", null), - }); - - filter = new Match(null, null, - new String[]{"*/*"}, null, null, null); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.NO_MATCH_TYPE, null, - null, null, null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_TYPE, null, null, - "which1/what1", null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_TYPE, null, null, - "which1/*", null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_TYPE, null, null, - "*/*", null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_TYPE, null, null, - "which2/what2", null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_TYPE, null, null, - "which2/*", null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_TYPE, null, null, - "which1/what2", null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_TYPE, null, null, - "which3/what3", null), - }); - } - - @SmallTest - public void testSchemes() throws Exception { - IntentFilter filter = new Match(null, null, null, - new String[]{"scheme1"}, null, null); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_SCHEME, null, - null, null, "scheme1:foo"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme2:foo"), - }); - - filter = new Match(null, null, null, - new String[]{"scheme1", "scheme2"}, null, null); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_SCHEME, null, - null, null, "scheme1:foo"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_SCHEME, null, - null, null, "scheme2:foo"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme3:foo"), - }); - } - - @SmallTest - public void testAuthorities() throws Exception { - IntentFilter filter = new Match(null, null, null, - new String[]{"scheme1"}, - new String[]{"authority1"}, new String[]{null}); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, null), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme1:foo"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_HOST, null, - null, null, "scheme1://authority1/"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme1://authority2/"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_HOST, null, - null, null, "scheme1://authority1:100/"), - }); - - filter = new Match(null, null, null, new String[]{"scheme1"}, - new String[]{"authority1"}, new String[]{"100"}); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, null), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme1:foo"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme1://authority1/"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme1://authority2/"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PORT, null, - null, null, "scheme1://authority1:100/"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme1://authority1:200/"), - }); - - filter = new Match(null, null, null, new String[]{"scheme1"}, - new String[]{"authority1", "authority2"}, - new String[]{"100", null}); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, null), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme1:foo"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme1://authority1/"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_HOST, null, - null, null, "scheme1://authority2/"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PORT, null, - null, null, "scheme1://authority1:100/"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme1://authority1:200/"), - }); - } - - @SmallTest - public void testPaths() throws Exception { - IntentFilter filter = new Match(null, null, null, - new String[]{"scheme"}, new String[]{"authority"}, null, - new String[]{"/literal1", "/2literal"}, - new int[]{PATTERN_LITERAL, PATTERN_LITERAL}); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/literal1"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/2literal"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme://authority/literal"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme://authority/literal12"), - }); - filter = new Match(null, null, null, - new String[]{"scheme"}, new String[]{"authority"}, null, - new String[]{"/literal1", "/2literal"}, - new int[]{PATTERN_PREFIX, PATTERN_PREFIX}); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/literal1"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/2literal"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme://authority/literal"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/literal12"), - }); - filter = new Match(null, null, null, - new String[]{"scheme"}, new String[]{"authority"}, null, - new String[]{"/.*"}, - new int[]{PATTERN_SIMPLE_GLOB}); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/literal1"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme://authority"), - }); - filter = new Match(null, null, null, - new String[]{"scheme"}, new String[]{"authority"}, null, - new String[]{".*"}, - new int[]{PATTERN_SIMPLE_GLOB}); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/literal1"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority"), - }); - filter = new Match(null, null, null, - new String[]{"scheme"}, new String[]{"authority"}, null, - new String[]{"/a1*b"}, - new int[]{PATTERN_SIMPLE_GLOB}); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/ab"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/a1b"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/a11b"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme://authority/a2b"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme://authority/a1bc"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme://authority/"), - }); - filter = new Match(null, null, null, - new String[]{"scheme"}, new String[]{"authority"}, null, - new String[]{"/a1*"}, - new int[]{PATTERN_SIMPLE_GLOB}); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/a1"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme://authority/ab"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/a11"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme://authority/a1b"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/a11"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme://authority/a2"), - }); - filter = new Match(null, null, null, - new String[]{"scheme"}, new String[]{"authority"}, null, - new String[]{"/a\\.*b"}, - new int[]{PATTERN_SIMPLE_GLOB}); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/ab"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/a.b"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/a..b"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme://authority/a2b"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme://authority/a.bc"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme://authority/"), - }); - filter = new Match(null, null, null, - new String[]{"scheme"}, new String[]{"authority"}, null, - new String[]{"/a.*b"}, - new int[]{PATTERN_SIMPLE_GLOB}); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/ab"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/a.b"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/a.1b"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/a2b"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme://authority/a.bc"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme://authority/"), - }); - filter = new Match(null, null, null, - new String[]{"scheme"}, new String[]{"authority"}, null, - new String[]{"/a.*"}, - new int[]{PATTERN_SIMPLE_GLOB}); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, null), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/ab"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/a.b"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/a.1b"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/a2b"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/a.bc"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme://authority/"), - }); - filter = new Match(null, null, null, - new String[]{"scheme"}, new String[]{"authority"}, null, - new String[]{"/a.\\*b"}, - new int[]{PATTERN_SIMPLE_GLOB}); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, null), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme://authority/ab"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/a.*b"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/a1*b"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme://authority/a2b"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme://authority/a.bc"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme://authority/"), - }); - filter = new Match(null, null, null, - new String[]{"scheme"}, new String[]{"authority"}, null, - new String[]{"/a.\\*"}, - new int[]{PATTERN_SIMPLE_GLOB}); - checkMatches(filter, new MatchCondition[]{ - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, null), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme://authority/ab"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/a.*"), - new MatchCondition(IntentFilter.MATCH_CATEGORY_PATH, null, - null, null, "scheme://authority/a1*"), - new MatchCondition(IntentFilter.NO_MATCH_DATA, null, - null, null, "scheme://authority/a1b"), - }); - } - -} - diff --git a/tests/AndroidTests/src/com/android/unit_tests/content/PluralResourcesTest.java b/tests/AndroidTests/src/com/android/unit_tests/content/PluralResourcesTest.java deleted file mode 100644 index c3d1478e8f63..000000000000 --- a/tests/AndroidTests/src/com/android/unit_tests/content/PluralResourcesTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * 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.android.unit_tests.content; - -import android.content.res.AssetManager; -import android.content.res.Configuration; -import android.content.res.Resources; -import android.content.res.TypedArray; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; -import android.util.TypedValue; -import android.util.Log; -import com.android.unit_tests.R; - -import junit.framework.Assert; - -import java.util.Locale; - -public class PluralResourcesTest extends AndroidTestCase { - private static final String TAG = "PluralResourcesTest"; - - private Resources mResources; - - @Override - protected void setUp() throws Exception { - super.setUp(); - mResources = mContext.getResources(); - } - - Resources resourcesForLanguage(String lang) { - Configuration config = new Configuration(); - config.updateFrom(mResources.getConfiguration()); - config.locale = new Locale(lang); - return new Resources(mResources.getAssets(), mResources.getDisplayMetrics(), config); - } - - @SmallTest - public void testPlurals() throws Exception { - CharSequence cs; - Resources res = resourcesForLanguage("en"); - - cs = res.getQuantityText(R.plurals.plurals_test, 0); - Log.d(TAG, "english 0 cs=" + cs); - Assert.assertEquals(cs.toString(), "Some dogs"); - - cs = res.getQuantityText(R.plurals.plurals_test, 1); - Log.d(TAG, "english 1 cs=" + cs); - Assert.assertEquals(cs.toString(), "A dog"); - - cs = res.getQuantityText(R.plurals.plurals_test, 2); - Assert.assertEquals(cs.toString(), "Some dogs"); - - cs = res.getQuantityText(R.plurals.plurals_test, 5); - Assert.assertEquals(cs.toString(), "Some dogs"); - - cs = res.getQuantityText(R.plurals.plurals_test, 500); - Assert.assertEquals(cs.toString(), "Some dogs"); - } - - @SmallTest - public void testCzech() throws Exception { - CharSequence cs; - Resources res = resourcesForLanguage("cs"); - - cs = res.getQuantityText(R.plurals.plurals_test, 0); - Log.d(TAG, "czech 0 cs=" + cs); - Assert.assertEquals(cs.toString(), "Some Czech dogs"); - - cs = res.getQuantityText(R.plurals.plurals_test, 1); - Log.d(TAG, "czech 1 cs=" + cs); - Assert.assertEquals(cs.toString(), "A Czech dog"); - - cs = res.getQuantityText(R.plurals.plurals_test, 2); - Log.d(TAG, "czech 2 cs=" + cs); - Assert.assertEquals(cs.toString(), "Few Czech dogs"); - - cs = res.getQuantityText(R.plurals.plurals_test, 5); - Assert.assertEquals(cs.toString(), "Some Czech dogs"); - - cs = res.getQuantityText(R.plurals.plurals_test, 500); - Assert.assertEquals(cs.toString(), "Some Czech dogs"); - } -} diff --git a/tests/AndroidTests/src/com/android/unit_tests/content/PrimitiveTest.java b/tests/AndroidTests/src/com/android/unit_tests/content/PrimitiveTest.java deleted file mode 100644 index 44098cc5edcb..000000000000 --- a/tests/AndroidTests/src/com/android/unit_tests/content/PrimitiveTest.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * 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.android.unit_tests.content; - -import android.content.res.Resources; -import android.content.res.TypedArray; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; -import android.util.TypedValue; -import com.android.unit_tests.R; - -public class PrimitiveTest extends AndroidTestCase { - private Resources mResources; - - @Override - protected void setUp() throws Exception { - super.setUp(); - mResources = mContext.getResources(); - } - - private void tryEnum(int resid, int expected) { - TypedArray sa = - mContext.obtainStyledAttributes(resid, R.styleable.EnumStyle); - int value = sa.getInt(R.styleable.EnumStyle_testEnum, -1); - sa.recycle(); - - assertEquals("Expecting value " + expected + " got " + value - + ": in resource 0x" + Integer.toHexString(resid), - expected, value); - } - - @SmallTest - public void testEnum() throws Exception { - tryEnum(R.style.TestEnum1, 1); - tryEnum(R.style.TestEnum2, 2); - tryEnum(R.style.TestEnum10, 10); - tryEnum(R.style.TestEnum1_EmptyInherit, 1); - } - - private void tryFlag(int resid, int expected) { - TypedArray sa = - mContext.obtainStyledAttributes(resid, R.styleable.FlagStyle); - int value = sa.getInt(R.styleable.FlagStyle_testFlags, -1); - sa.recycle(); - - assertEquals("Expecting value " + expected + " got " + value - + ": in resource 0x" + Integer.toHexString(resid), - expected, value); - } - - @SmallTest - public void testFlags() throws Exception { - tryFlag(R.style.TestFlag1, 0x1); - tryFlag(R.style.TestFlag2, 0x2); - tryFlag(R.style.TestFlag31, 0x40000000); - tryFlag(R.style.TestFlag1And2, 0x3); - tryFlag(R.style.TestFlag1And2And31, 0x40000003); - } - - private void tryBoolean(int resid, boolean expected) { - TypedValue v = new TypedValue(); - mContext.getResources().getValue(resid, v, true); - assertEquals(TypedValue.TYPE_INT_BOOLEAN, v.type); - assertEquals("Expecting boolean value " + expected + " got " + v - + " from TypedValue: in resource 0x" + Integer.toHexString(resid), - expected, v.data != 0); - assertEquals("Expecting boolean value " + expected + " got " + v - + " from getBoolean(): in resource 0x" + Integer.toHexString(resid), - expected, mContext.getResources().getBoolean(resid)); - } - - @SmallTest - public void testBoolean() throws Exception { - tryBoolean(R.bool.trueRes, true); - tryBoolean(R.bool.falseRes, false); - } - - private void tryString(int resid, String expected) { - TypedValue v = new TypedValue(); - mContext.getResources().getValue(resid, v, true); - assertEquals(TypedValue.TYPE_STRING, v.type); - assertEquals("Expecting string value " + expected + " got " + v - + ": in resource 0x" + Integer.toHexString(resid), - expected, v.string); - } - - @SmallTest - public void testStringCoerce() throws Exception { - tryString(R.string.coerceIntegerToString, "100"); - tryString(R.string.coerceBooleanToString, "true"); - tryString(R.string.coerceColorToString, "#fff"); - tryString(R.string.coerceFloatToString, "100.0"); - tryString(R.string.coerceDimensionToString, "100px"); - tryString(R.string.coerceFractionToString, "100%"); - } - - private static void checkString(int resid, String actual, String expected) { - assertEquals("Expecting string value \"" + expected + "\" got \"" - + actual + "\" in resources 0x" + Integer.toHexString(resid), - expected, actual); - } - - @SmallTest - public void testFormattedString() throws Exception { - // Make sure the regular one doesn't format anything - checkString(R.string.formattedStringNone, - mResources.getString(R.string.formattedStringNone), - "Format[]"); - checkString(R.string.formattedStringOne, - mResources.getString(R.string.formattedStringOne), - "Format[%d]"); - checkString(R.string.formattedStringTwo, - mResources.getString(R.string.formattedStringTwo), - "Format[%3$d,%2$s]"); - // Make sure the formatted one works - checkString(R.string.formattedStringNone, - mResources.getString(R.string.formattedStringNone), - "Format[]"); - checkString(R.string.formattedStringOne, - mResources.getString(R.string.formattedStringOne, 42), - "Format[42]"); - checkString(R.string.formattedStringTwo, - mResources.getString(R.string.formattedStringTwo, "unused", "hi", 43), - "Format[43,hi]"); - } -} - diff --git a/tests/AndroidTests/src/com/android/unit_tests/content/RawResourceTest.java b/tests/AndroidTests/src/com/android/unit_tests/content/RawResourceTest.java deleted file mode 100644 index 1786dc46b89f..000000000000 --- a/tests/AndroidTests/src/com/android/unit_tests/content/RawResourceTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2008 The Android Open Source Project - * - * 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.android.unit_tests.content; - -import android.content.res.Resources; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; -import com.android.unit_tests.R; - -import java.io.InputStream; - -public class RawResourceTest extends AndroidTestCase { - private Resources mResources; - - @Override - protected void setUp() throws Exception { - super.setUp(); - mResources = mContext.getResources(); - } - - @SmallTest - public void testReadToEnd() throws Exception { - InputStream is = mResources.openRawResource(R.raw.text); - AssetTest.verifyTextAsset(is); - } -} diff --git a/tests/AndroidTests/src/com/android/unit_tests/content/ResourceNameTest.java b/tests/AndroidTests/src/com/android/unit_tests/content/ResourceNameTest.java deleted file mode 100644 index 2a56243cfb0e..000000000000 --- a/tests/AndroidTests/src/com/android/unit_tests/content/ResourceNameTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * 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.android.unit_tests.content; - -import android.content.res.Resources; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; - -import com.android.unit_tests.R; - -public class ResourceNameTest extends AndroidTestCase { - - @SmallTest - public void testGetResourceName() { - Resources res = mContext.getResources(); - - String fullName = res.getResourceName(R.configVarying.simple); - assertEquals("com.android.unit_tests:configVarying/simple", fullName); - - String packageName = res.getResourcePackageName(R.configVarying.simple); - assertEquals("com.android.unit_tests", packageName); - - String typeName = res.getResourceTypeName(R.configVarying.simple); - assertEquals("configVarying", typeName); - - String entryName = res.getResourceEntryName(R.configVarying.simple); - assertEquals("simple", entryName); - } - - @SmallTest - public void testGetResourceIdentifier() { - Resources res = mContext.getResources(); - int resid = res.getIdentifier( - "com.android.unit_tests:configVarying/simple", - null, null); - assertEquals(R.configVarying.simple, resid); - - resid = res.getIdentifier("configVarying/simple", null, - "com.android.unit_tests"); - assertEquals(R.configVarying.simple, resid); - - resid = res.getIdentifier("simple", "configVarying", - "com.android.unit_tests"); - assertEquals(R.configVarying.simple, resid); - } -} - diff --git a/tests/AndroidTests/src/com/android/unit_tests/content/ResourceTests.java b/tests/AndroidTests/src/com/android/unit_tests/content/ResourceTests.java deleted file mode 100644 index 943941e517a4..000000000000 --- a/tests/AndroidTests/src/com/android/unit_tests/content/ResourceTests.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * 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.android.unit_tests.content; - -import junit.framework.TestSuite; - -public class ResourceTests { - public static TestSuite suite() { - TestSuite suite = new TestSuite(ResourceTests.class.getName()); - - suite.addTestSuite(FractionTest.class); - suite.addTestSuite(PrimitiveTest.class); - suite.addTestSuite(ArrayTest.class); - suite.addTestSuite(ConfigTest.class); - suite.addTestSuite(RawResourceTest.class); - suite.addTestSuite(ResourceNameTest.class); - return suite; - } -} diff --git a/tests/AndroidTests/src/com/android/unit_tests/vcard/VCardTestSuite.java b/tests/AndroidTests/src/com/android/unit_tests/vcard/VCardTestSuite.java deleted file mode 100644 index f3d1c5eebe72..000000000000 --- a/tests/AndroidTests/src/com/android/unit_tests/vcard/VCardTestSuite.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2009 The Android Open Source Project - * - * 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.android.unit_tests.vcard; - -import com.android.unit_tests.AndroidTests; - -import android.test.suitebuilder.TestSuiteBuilder; - -import junit.framework.TestSuite; - -public class VCardTestSuite extends TestSuite { - public static TestSuite suite() { - TestSuiteBuilder suiteBuilder = new TestSuiteBuilder(AndroidTests.class); - suiteBuilder.includeAllPackagesUnderHere(); - return suiteBuilder.build(); - } -}
\ No newline at end of file diff --git a/tests/CoreTests/android/core/CoreTests.java b/tests/CoreTests/android/core/CoreTests.java index e4f835c05737..442fe0f943ad 100644 --- a/tests/CoreTests/android/core/CoreTests.java +++ b/tests/CoreTests/android/core/CoreTests.java @@ -59,7 +59,6 @@ public class CoreTests extends TestSuite { suite.addTestSuite(LocationManagerProximityTest.class); suite.addTestSuite(AndroidTestRunnerTest.class); suite.addTestSuite(InstrumentationTestRunnerTest.class); - suite.addTestSuite(CookieTest.class); return suite; } diff --git a/tests/CoreTests/android/webkit/CookieTest.java b/tests/CoreTests/android/webkit/CookieTest.java deleted file mode 100644 index 5c5a6a825658..000000000000 --- a/tests/CoreTests/android/webkit/CookieTest.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright (C) 2008 The Android Open Source Project - * - * 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 android.webkit; - -import android.content.Context; -import android.test.AndroidTestCase; -import android.util.Log; -import android.webkit.CookieManager; -import android.webkit.CookieSyncManager; - -public class CookieTest extends AndroidTestCase { - - /** - * To run these tests: $ mmm frameworks/base/tests/CoreTests/android && adb - * remount && adb sync $ adb shell am instrument -w \ -e class - * android.webkit.CookieTest \ - * android.core/android.test.InstrumentationTestRunner - */ - - private CookieManager mCookieManager; - - @Override - public void setContext(Context context) { - assertTrue(mContext == null); - super.setContext(context); - CookieSyncManager.createInstance(context); - mCookieManager = CookieManager.getInstance(); - mCookieManager.removeAllCookie(); - } - - public void testParse() { - mCookieManager.removeAllCookie(); - String url = "http://www.foo.com"; - - // basic - mCookieManager.setCookie(url, "a=b"); - String cookie = mCookieManager.getCookie(url); - assertTrue(cookie.equals("a=b")); - - // quoted - mCookieManager.setCookie(url, "c=\"d;\""); - cookie = mCookieManager.getCookie(url); - assertTrue(cookie.equals("a=b; c=\"d;\"")); - - // empty - mCookieManager.setCookie(url, "; path=/"); - cookie = mCookieManager.getCookie(url); - assertTrue(cookie.equals("a=b; c=\"d;\"")); - } - - public void testDomain() { - mCookieManager.removeAllCookie(); - String url = "http://www.foo.com"; - - // basic - mCookieManager.setCookie(url, "a=b"); - String cookie = mCookieManager.getCookie(url); - assertTrue(cookie.equals("a=b")); - - // no cross domain cookie - cookie = mCookieManager.getCookie("http://bar.com"); - assertTrue(cookie == null); - - // more than one cookie - mCookieManager.setCookie(url, "c=d; domain=.foo.com"); - cookie = mCookieManager.getCookie(url); - assertTrue(cookie.equals("a=b; c=d")); - - // host cookie should not be accessible from a sub-domain. - cookie = mCookieManager.getCookie("http://bar.www.foo.com"); - assertTrue(cookie.equals("c=d")); - - // test setting a domain= that doesn't start w/ a dot, should - // treat it as a domain cookie, as if there was a pre-pended dot. - mCookieManager.setCookie(url, "e=f; domain=www.foo.com"); - cookie = mCookieManager.getCookie(url); - assertTrue(cookie.equals("a=b; c=d; e=f")); - cookie = mCookieManager.getCookie("http://sub.www.foo.com"); - assertTrue(cookie.equals("c=d; e=f")); - cookie = mCookieManager.getCookie("http://foo.com"); - assertTrue(cookie.equals("c=d")); - } - - public void testSubDomain() { - mCookieManager.removeAllCookie(); - String url_abcd = "http://a.b.c.d.com"; - String url_bcd = "http://b.c.d.com"; - String url_cd = "http://c.d.com"; - String url_d = "http://d.com"; - - mCookieManager.setCookie(url_abcd, "a=1; domain=.a.b.c.d.com"); - mCookieManager.setCookie(url_abcd, "b=2; domain=.b.c.d.com"); - mCookieManager.setCookie(url_abcd, "c=3; domain=.c.d.com"); - mCookieManager.setCookie(url_abcd, "d=4; domain=.d.com"); - - String cookie = mCookieManager.getCookie(url_abcd); - assertTrue(cookie.equals("a=1; b=2; c=3; d=4")); - cookie = mCookieManager.getCookie(url_bcd); - assertTrue(cookie.equals("b=2; c=3; d=4")); - cookie = mCookieManager.getCookie(url_cd); - assertTrue(cookie.equals("c=3; d=4")); - cookie = mCookieManager.getCookie(url_d); - assertTrue(cookie.equals("d=4")); - - // check that the same cookie can exist on different sub-domains. - mCookieManager.setCookie(url_bcd, "x=bcd; domain=.b.c.d.com"); - mCookieManager.setCookie(url_bcd, "x=cd; domain=.c.d.com"); - cookie = mCookieManager.getCookie(url_bcd); - assertTrue(cookie.equals("b=2; c=3; d=4; x=bcd; x=cd")); - cookie = mCookieManager.getCookie(url_cd); - assertTrue(cookie.equals("c=3; d=4; x=cd")); - } - - public void testInvalidDomain() { - mCookieManager.removeAllCookie(); - String url = "http://foo.bar.com"; - - mCookieManager.setCookie(url, "a=1; domain=.yo.foo.bar.com"); - String cookie = mCookieManager.getCookie(url); - assertTrue(cookie == null); - - mCookieManager.setCookie(url, "b=2; domain=.foo.com"); - cookie = mCookieManager.getCookie(url); - assertTrue(cookie == null); - - mCookieManager.setCookie(url, "c=3; domain=.bar.foo.com"); - cookie = mCookieManager.getCookie(url); - assertTrue(cookie == null); - - mCookieManager.setCookie(url, "d=4; domain=.foo.bar.com.net"); - cookie = mCookieManager.getCookie(url); - assertTrue(cookie == null); - - mCookieManager.setCookie(url, "e=5; domain=.ar.com"); - cookie = mCookieManager.getCookie(url); - assertTrue(cookie == null); - - mCookieManager.setCookie(url, "f=6; domain=.com"); - cookie = mCookieManager.getCookie(url); - assertTrue(cookie == null); - - mCookieManager.setCookie(url, "g=7; domain=.co.uk"); - cookie = mCookieManager.getCookie(url); - assertTrue(cookie == null); - - mCookieManager.setCookie(url, "h=8; domain=.foo.bar.com.com"); - cookie = mCookieManager.getCookie(url); - assertTrue(cookie == null); - } - - public void testPath() { - mCookieManager.removeAllCookie(); - String url = "http://www.foo.com"; - - mCookieManager.setCookie(url, "a=b; path=/wee"); - String cookie = mCookieManager.getCookie(url + "/wee"); - assertTrue(cookie.equals("a=b")); - cookie = mCookieManager.getCookie(url + "/wee/"); - assertTrue(cookie.equals("a=b")); - cookie = mCookieManager.getCookie(url + "/wee/hee"); - assertTrue(cookie.equals("a=b")); - cookie = mCookieManager.getCookie(url + "/wee/hee/more"); - assertTrue(cookie.equals("a=b")); - cookie = mCookieManager.getCookie(url + "/weehee"); - assertTrue(cookie == null); - cookie = mCookieManager.getCookie(url); - assertTrue(cookie == null); - - mCookieManager.setCookie(url, "a=c; path="); - cookie = mCookieManager.getCookie(url + "/wee"); - assertTrue(cookie.equals("a=b; a=c")); - cookie = mCookieManager.getCookie(url); - assertTrue(cookie.equals("a=c")); - - mCookieManager.setCookie(url, "a=d"); - cookie = mCookieManager.getCookie(url + "/wee"); - assertTrue(cookie.equals("a=b; a=d")); - } -} diff --git a/tests/FrameworkTest/tests/src/com/android/frameworktest/expandablelistview/ExpandableListWithHeadersTest.java b/tests/FrameworkTest/tests/src/com/android/frameworktest/expandablelistview/ExpandableListWithHeadersTest.java deleted file mode 100644 index 49b5106cf7a5..000000000000 --- a/tests/FrameworkTest/tests/src/com/android/frameworktest/expandablelistview/ExpandableListWithHeadersTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * 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.android.frameworktest.expandablelistview; - -import android.test.ActivityInstrumentationTestCase; -import android.test.suitebuilder.annotation.LargeTest; -import android.test.suitebuilder.annotation.MediumTest; -import android.view.KeyEvent; -import android.widget.ExpandableListView; - -import com.android.frameworktest.expandablelistview.ExpandableListWithHeaders; -import com.android.frameworktest.util.ListUtil; - -public class ExpandableListWithHeadersTest extends ActivityInstrumentationTestCase<ExpandableListWithHeaders> { - private ExpandableListView mExpandableListView; - private ListUtil mListUtil; - - public ExpandableListWithHeadersTest() { - super("com.android.frameworktest", - ExpandableListWithHeaders.class); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - - mExpandableListView = getActivity().getExpandableListView(); - mListUtil = new ListUtil(mExpandableListView, getInstrumentation()); - } - - @MediumTest - public void testPreconditions() { - assertNotNull(mExpandableListView); - } - - @MediumTest - public void testExpandOnFirstPosition() { - // Should be a header, and hence the first group should NOT have expanded - mListUtil.arrowScrollToSelectedPosition(0); - sendKeys(KeyEvent.KEYCODE_DPAD_CENTER); - getInstrumentation().waitForIdleSync(); - assertFalse(mExpandableListView.isGroupExpanded(0)); - } - - @LargeTest - public void testExpandOnFirstGroup() { - mListUtil.arrowScrollToSelectedPosition(getActivity().getNumOfHeadersAndFooters()); - sendKeys(KeyEvent.KEYCODE_DPAD_CENTER); - getInstrumentation().waitForIdleSync(); - assertTrue(mExpandableListView.isGroupExpanded(0)); - } -} diff --git a/tests/FrameworkTest/tests/src/com/android/frameworktest/view/RemoteViewsActivityTest.java b/tests/FrameworkTest/tests/src/com/android/frameworktest/view/RemoteViewsActivityTest.java deleted file mode 100644 index 3dcb2525500e..000000000000 --- a/tests/FrameworkTest/tests/src/com/android/frameworktest/view/RemoteViewsActivityTest.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (C) 2008 The Android Open Source Project - * - * 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.android.frameworktest.view; - -import android.os.Parcel; -import android.test.ActivityInstrumentationTestCase; -import android.test.suitebuilder.annotation.MediumTest; -import android.view.InflateException; -import android.view.View; -import android.view.ViewGroup; -import android.widget.RemoteViews; - -import com.android.frameworktest.R; -import com.android.frameworktest.view.RemoteViewsActivity; - -public class RemoteViewsActivityTest extends ActivityInstrumentationTestCase<RemoteViewsActivity> { - public RemoteViewsActivityTest() { - super("com.android.frameworktest", RemoteViewsActivity.class); - } - - @Override - public void setUp() throws Exception { - super.setUp(); - } - - @MediumTest - public void testGood() throws Exception { - final RemoteViewsActivity activity = getActivity(); - - RemoteViews orig = new RemoteViews("com.android.frameworktest", - R.layout.remote_view_test_good); - Parcel p = Parcel.obtain(); - orig.writeToParcel(p, 0); - p.setDataPosition(0); - - RemoteViews r = RemoteViews.CREATOR.createFromParcel(p); - - ViewGroup parent = (ViewGroup) activity.findViewById(R.id.parent); - - View result = r.apply(activity, parent); - - p.recycle(); - - assertTrue("LinearLayout not inflated", result.findViewById(R.id.linear) != null); - assertTrue("TextView not inflated", result.findViewById(R.id.text) != null); - assertTrue("ImageView not inflated", result.findViewById(R.id.image) != null); - assertTrue("FrameLayout not inflated", result.findViewById(R.id.frame) != null); - assertTrue("RelateiveLayout not inflated", result.findViewById(R.id.relative) != null); - assertTrue("AbsoluteLayout not inflated", result.findViewById(R.id.absolute) != null); - assertTrue("ProgressBar not inflated", result.findViewById(R.id.progress) != null); - assertTrue("ImageButton not inflated", result.findViewById(R.id.image_button) != null); - assertTrue("Button not inflated", result.findViewById(R.id.button) != null); - } - - @MediumTest - public void testDerivedClass() throws Exception { - final RemoteViewsActivity activity = getActivity(); - - RemoteViews orig = new RemoteViews("com.android.frameworktest", - R.layout.remote_view_test_bad_1); - Parcel p = Parcel.obtain(); - orig.writeToParcel(p, 0); - p.setDataPosition(0); - - RemoteViews r = RemoteViews.CREATOR.createFromParcel(p); - - ViewGroup parent = (ViewGroup) activity.findViewById(R.id.parent); - - boolean exceptionThrown = false; - View result = null; - - try { - result = r.apply(activity, parent); - } catch (InflateException e) { - exceptionThrown = true; - } - - p.recycle(); - - assertTrue("Derived class (EditText) allowed to be inflated", exceptionThrown); - assertNull("Derived class (EditText) allowed to be inflated", result); - } - - @MediumTest - public void testWebView() throws Exception { - final RemoteViewsActivity activity = getActivity(); - - RemoteViews orig = new RemoteViews("com.android.frameworktest", - R.layout.remote_view_test_bad_2); - Parcel p = Parcel.obtain(); - orig.writeToParcel(p, 0); - p.setDataPosition(0); - - RemoteViews r = RemoteViews.CREATOR.createFromParcel(p); - - ViewGroup parent = (ViewGroup) activity.findViewById(R.id.parent); - - boolean exceptionThrown = false; - View result = null; - - try { - result = r.apply(activity, parent); - } catch (InflateException e) { - exceptionThrown = true; - } - - p.recycle(); - - assertTrue("WebView allowed to be inflated", exceptionThrown); - assertNull("WebView allowed to be inflated", result); - } -} |