aboutsummaryrefslogtreecommitdiff
path: root/tools/tradefed-host/src/com/android/afwtest/tradefed/targetprep/AfwTestEnvDumper.java
blob: 0c3a2e6fc76df8dad90ca89495812b4b6a4a5309 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
/*
 * Copyright (C) 2016 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.afwtest.tradefed.targetprep;

import com.google.common.base.Joiner;

import com.android.afwtest.tradefed.utils.TimeUtil;
import com.android.tradefed.build.IBuildInfo;
import com.android.tradefed.config.Option;
import com.android.tradefed.config.OptionClass;
import com.android.tradefed.device.DeviceNotAvailableException;
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.device.PackageInfo;
import com.android.tradefed.log.LogUtil.CLog;
import com.android.tradefed.targetprep.ITargetCleaner;
import com.android.tradefed.targetprep.TargetSetupError;
import com.android.tradefed.util.StreamUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * A target preparer that dumps testing environment info to a text file.
 *
 * <p>
 * The file is saved at:
 *   ${CTS_ROOT}/android-cts/repository/logs/{given-prefix}_EnvDump_{TimeStamp}.txt.
 * Generally {given-prefix} should be the test apk file name.
 * </p>
 */
@OptionClass(alias = "afw-test-env-dumper")
public class AfwTestEnvDumper extends AfwTestTargetPreparer implements ITargetCleaner {

    private static final String DUMP_FILE_NAME_SUFFIX = "EnvDump";

    @Option(name = "file-name-prefix",
            description = "Dump file name prefix, suggested to be test apk file name",
            mandatory = true)
    private String mFileNamePrefix = null;

    /**
     * {@inheritDoc}
     */
    @Override
    public void setUp(ITestDevice device, IBuildInfo buildInfo)
            throws TargetSetupError,
                    DeviceNotAvailableException {
        // Do nothing, dump after the test only
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void tearDown(ITestDevice device, IBuildInfo buildInfo, Throwable e)
            throws DeviceNotAvailableException {

        try {
            String str = getEnv(device);

            // Creates the dump file
            File dumpFile = getDumpFile(buildInfo);

            OutputStream os = new FileOutputStream(dumpFile);
            os.write(str.getBytes());
            StreamUtil.flushAndCloseStream(os);

            CLog.i(String.format("Dumped file: %s", dumpFile.getAbsolutePath()));
        } catch (IOException exception) {
            CLog.e("Failed to dump app versions to file", e);
        }
    }

    /**
     * Gets environment configurations as string.
     *
     * @param device testing device
     * @return environment configuration as string
     */
    protected String getEnv(ITestDevice device) throws DeviceNotAvailableException {
        return getAppVersions(device);
    }

    /**
     * Gets a {@link File} to dump environment info.
     *
     * @param buildInfo reference to {@link IBuildInfo}
     * @return {@link File} object of a unique file
     */
    private File getDumpFile(IBuildInfo buildInfo) throws FileNotFoundException {
        return new File(getCtsBuildHelper(buildInfo).getLogsDir(),
                String.format("%s_%s_%s.txt",
                        mFileNamePrefix,
                        DUMP_FILE_NAME_SUFFIX,
                        TimeUtil.getResultTimestamp()));
    }

    /**
     * Gets versions of all {@link App} as a string.
     *
     * @param device reference to {@link ITestDevice}
     * @return versions of all {@link App} as string
     */
    private String getAppVersions(ITestDevice device) throws DeviceNotAvailableException {
        Set<String> installPkgs = device.getInstalledPackageNames();

        List<String> appVersions = new ArrayList<String>();

        for (Map.Entry<String, String> pkg: getPackagesToDump().entrySet()) {
            String pkgName = pkg.getKey();
            String appName = pkg.getValue();
            // Gets versions of install app only
            if (installPkgs.contains(pkgName)) {
                PackageInfo pkgInfo = device.getAppPackageInfo(pkgName);
                String appVer = String.format("%s: Ver %s", appName, pkgInfo.getVersionName());

                // Log it to tradefed console for debugging purpose
                CLog.i(appVer);

                appVersions.add(appVer);
            }
        }

        return Joiner.on("\n").join(appVersions.iterator());
    }


    /**
     * Gets set of packages whose info should be dumped.
     *
     * @return a {@link Map} with key=full package name and value=app representation name
     */
    protected Map<String, String> getPackagesToDump() {
        Map<String, String> pkgs = new HashMap<String, String>();

        pkgs.put("com.google.android.gms", "Google Mobile Service");
        pkgs.put("com.android.managedprovisioning", "Managed Provisioning");
        pkgs.put("com.afwsamples.testdpc", "TestDPC");

        return pkgs;
    }
}