LoadTestsAutoTest.java revision 5794f2302209981c64425ea2b661b17f00b8f808
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.dumprendertree;
18
19import android.app.Instrumentation;
20import android.content.Context;
21import android.content.Intent;
22import android.os.Bundle;
23import android.os.Debug;
24import android.os.Environment;
25import android.os.Process;
26import android.test.ActivityInstrumentationTestCase2;
27import android.util.Log;
28
29import java.io.File;
30import java.io.FileOutputStream;
31import java.io.IOException;
32import java.io.InputStream;
33import java.io.OutputStream;
34import java.io.PrintStream;
35import java.util.concurrent.CountDownLatch;
36import java.util.concurrent.TimeUnit;
37
38public class LoadTestsAutoTest extends ActivityInstrumentationTestCase2<TestShellActivity> {
39
40    private final static String LOGTAG = "LoadTest";
41    private final static String LOAD_TEST_RESULT =
42        Environment.getExternalStorageDirectory() + "/load_test_result.txt";
43    private final static int MAX_GC_WAIT_SEC = 10;
44    private boolean mFinished;
45    static final String LOAD_TEST_RUNNER_FILES[] = {
46        "run_page_cycler.py"
47    };
48
49    public LoadTestsAutoTest() {
50        super("com.android.dumprendertree", TestShellActivity.class);
51    }
52
53    // This function writes the result of the layout test to
54    // Am status so that it can be picked up from a script.
55    public void passOrFailCallback(String file, boolean result) {
56        Instrumentation inst = getInstrumentation();
57        Bundle bundle = new Bundle();
58        bundle.putBoolean(file, result);
59        inst.sendStatus(0, bundle);
60    }
61
62    // Invokes running of layout tests
63    // and waits till it has finished running.
64    public void runPageCyclerTest() {
65        LayoutTestsAutoRunner runner = (LayoutTestsAutoRunner) getInstrumentation();
66
67        if (runner.mTestPath == null) {
68            Log.e(LOGTAG, "No test specified");
69            return;
70        }
71
72        TestShellActivity activity = (TestShellActivity) getActivity();
73
74        Log.v(LOGTAG, "About to run tests, calling gc first...");
75        freeMem();
76
77        // Run tests
78        runTestAndWaitUntilDone(activity, runner.mTestPath, runner.mTimeoutInMillis,
79                runner.mGetDrawTime, runner.mSaveImagePath);
80
81        activity.clearCache();
82        try {
83            Thread.sleep(5000);
84        } catch (InterruptedException e) {
85        }
86        dumpMemoryInfo();
87
88        // Kill activity
89        activity.finish();
90    }
91
92    private void freeMem() {
93        Log.v(LOGTAG, "freeMem: calling gc...");
94        final CountDownLatch latch = new CountDownLatch(1);
95        Object dummy = new Object() {
96            @Override
97            protected void finalize() throws Throwable {
98                latch.countDown();
99                super.finalize();
100            }
101        };
102        dummy = null;
103        System.gc();
104        try {
105            if (!latch.await(MAX_GC_WAIT_SEC, TimeUnit.SECONDS)) {
106                Log.w(LOGTAG, "gc did not happen in 10s");
107            }
108        } catch (InterruptedException e) {
109            //ignore
110        }
111    }
112
113    private void printRow(PrintStream ps, String format, Object...objs) {
114        ps.println(String.format(format, objs));
115    }
116
117    private void dumpMemoryInfo() {
118        try {
119            freeMem();
120            Log.v(LOGTAG, "Dumping memory information.");
121
122            FileOutputStream out = new FileOutputStream(LOAD_TEST_RESULT, true);
123            PrintStream ps = new PrintStream(out);
124
125            ps.print("\n\n\n");
126            ps.println("** MEMINFO in pid " + Process.myPid()
127                    + " [com.android.dumprendertree] **");
128            String formatString = "%17s %8s %8s %8s %8s";
129
130            long nativeMax = Debug.getNativeHeapSize() / 1024;
131            long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
132            long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
133            Runtime runtime = Runtime.getRuntime();
134            long dalvikMax = runtime.totalMemory() / 1024;
135            long dalvikFree = runtime.freeMemory() / 1024;
136            long dalvikAllocated = dalvikMax - dalvikFree;
137
138
139            Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
140            Debug.getMemoryInfo(memInfo);
141
142            final int nativeShared = memInfo.nativeSharedDirty;
143            final int dalvikShared = memInfo.dalvikSharedDirty;
144            final int otherShared = memInfo.otherSharedDirty;
145
146            final int nativePrivate = memInfo.nativePrivateDirty;
147            final int dalvikPrivate = memInfo.dalvikPrivateDirty;
148            final int otherPrivate = memInfo.otherPrivateDirty;
149
150            printRow(ps, formatString, "", "native", "dalvik", "other", "total");
151            printRow(ps, formatString, "size:", nativeMax, dalvikMax, "N/A", nativeMax + dalvikMax);
152            printRow(ps, formatString, "allocated:", nativeAllocated, dalvikAllocated, "N/A",
153                    nativeAllocated + dalvikAllocated);
154            printRow(ps, formatString, "free:", nativeFree, dalvikFree, "N/A",
155                    nativeFree + dalvikFree);
156
157            printRow(ps, formatString, "(Pss):", memInfo.nativePss, memInfo.dalvikPss,
158                    memInfo.otherPss, memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss);
159
160            printRow(ps, formatString, "(shared dirty):", nativeShared, dalvikShared, otherShared,
161                    nativeShared + dalvikShared + otherShared);
162            printRow(ps, formatString, "(priv dirty):", nativePrivate, dalvikPrivate, otherPrivate,
163                    nativePrivate + dalvikPrivate + otherPrivate);
164            ps.print("\n\n\n");
165            ps.flush();
166            ps.close();
167            out.flush();
168            out.close();
169        } catch (IOException e) {
170            Log.e(LOGTAG, e.getMessage());
171        }
172    }
173
174    // A convenient method to be called by another activity.
175    private void runTestAndWaitUntilDone(TestShellActivity activity, String url, int timeout,
176            boolean getDrawTime, String saveImagePath) {
177        activity.setCallback(new TestShellCallback() {
178            public void finished() {
179                synchronized (LoadTestsAutoTest.this) {
180                    mFinished = true;
181                    LoadTestsAutoTest.this.notifyAll();
182                }
183            }
184
185            public void timedOut(String url) {
186            }
187        });
188
189        mFinished = false;
190        Intent intent = new Intent(Intent.ACTION_VIEW);
191        intent.setClass(activity, TestShellActivity.class);
192        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
193        intent.putExtra(TestShellActivity.TEST_URL, url);
194        intent.putExtra(TestShellActivity.TIMEOUT_IN_MILLIS, timeout);
195        intent.putExtra(TestShellActivity.RESULT_FILE, LOAD_TEST_RESULT);
196        intent.putExtra(TestShellActivity.GET_DRAW_TIME, getDrawTime);
197        if (saveImagePath != null)
198            intent.putExtra(TestShellActivity.SAVE_IMAGE, saveImagePath);
199        activity.startActivity(intent);
200
201        // Wait until done.
202        synchronized (this) {
203            while(!mFinished) {
204                try {
205                    this.wait();
206                } catch (InterruptedException e) { }
207            }
208        }
209    }
210
211    public void copyRunnerAssetsToCache() {
212        try {
213            Context targetContext = getInstrumentation().getTargetContext();
214            File cacheDir = targetContext.getCacheDir();
215
216            for( int i=0; i< LOAD_TEST_RUNNER_FILES.length; i++) {
217                InputStream in = targetContext.getAssets().open(
218                        LOAD_TEST_RUNNER_FILES[i]);
219                OutputStream out = new FileOutputStream(
220                        new File(cacheDir, LOAD_TEST_RUNNER_FILES[i]));
221
222                byte[] buf = new byte[2048];
223                int len;
224
225                while ((len = in.read(buf)) >= 0 ) {
226                    out.write(buf, 0, len);
227                }
228                out.close();
229                in.close();
230            }
231        }catch (IOException e) {
232          e.printStackTrace();
233        }
234
235    }
236
237}
238