aboutsummaryrefslogtreecommitdiff
path: root/tests/instrumented/src/main/java/com/google/android/enterprise/connectedapps/instrumented/utils/InstrumentedTestUtilities.java
blob: be1db8e096da9b5a4300a7caf54f922d56e5cd76 (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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/*
 * Copyright 2021 Google LLC
 *
 * 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
 *
 *   https://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.google.android.enterprise.connectedapps.instrumented.utils;

import static java.nio.charset.StandardCharsets.UTF_8;

import android.content.Context;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.ParcelFileDescriptor;
import android.os.UserHandle;
import androidx.test.platform.app.InstrumentationRegistry;
import com.google.android.enterprise.connectedapps.ProfileConnector;
import com.google.android.enterprise.connectedapps.SharedTestUtilities;
import com.google.android.enterprise.connectedapps.instrumented.utils.ServiceCall.Parameter;
import com.google.android.enterprise.connectedapps.testing.ProfileAvailabilityPoll;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Wrapper around {@link
 * com.google.android.enterprise.connectedapps.testing.InstrumentedTestUtilities} which adds
 * features needed only by the SDK.
 */
public class InstrumentedTestUtilities {

  private final ProfileConnector connector;
  private final Context context;
  private final com.google.android.enterprise.connectedapps.testing.InstrumentedTestUtilities
          instrumentedTestUtilities;

  private static final int S_REQUEST_QUIET_MODE_ENABLED_ID = 73;
  private static final int R_REQUEST_QUIET_MODE_ENABLED_ID = 72;
  private static final int REQUEST_QUIET_MODE_ENABLED_ID = 58;

  private static final String USER_ID_KEY = "USER_ID";
  private static final Parameter USER_ID_PARAMETER = new Parameter(USER_ID_KEY);

  private static final ServiceCall S_TURN_OFF_WORK_PROFILE_COMMAND =
          new ServiceCall("user", S_REQUEST_QUIET_MODE_ENABLED_ID)
                  .setUser(1000) // user 1000 has packageName "android"
                  .addStringParam("android") // callingPackage
                  .addBooleanParam(true) // enableQuietMode
                  .addIntParam(USER_ID_PARAMETER) // userId
                  .addIntParam(0) // target
                  .addIntParam(0); // flags

  private static final ServiceCall R_TURN_OFF_WORK_PROFILE_COMMAND =
          new ServiceCall("user", R_REQUEST_QUIET_MODE_ENABLED_ID)
                  .setUser(1000) // user 1000 has packageName "android"
                  .addStringParam("android") // callingPackage
                  .addBooleanParam(true) // enableQuietMode
                  .addIntParam(USER_ID_PARAMETER) // userId
                  .addIntParam(0) // target
                  .addIntParam(0); // flags

  private static final ServiceCall TURN_OFF_WORK_PROFILE_COMMAND =
          new ServiceCall("user", REQUEST_QUIET_MODE_ENABLED_ID)
                  .setUser(1000) // user 1000 has packageName "android"
                  .addStringParam("android") // callingPackage
                  .addBooleanParam(true) // enableQuietMode
                  .addIntParam(USER_ID_PARAMETER) // userId
                  .addIntParam(0); // target

  private static final ServiceCall S_TURN_ON_WORK_PROFILE_COMMAND =
          new ServiceCall("user", S_REQUEST_QUIET_MODE_ENABLED_ID)
                  .setUser(1000) // user 1000 has packageName "android"
                  .addStringParam("android") // callingPackage
                  .addBooleanParam(false) // enableQuietMode
                  .addIntParam(USER_ID_PARAMETER) // userId
                  .addIntParam(0) // target
                  .addIntParam(0); // flags

  private static final ServiceCall R_TURN_ON_WORK_PROFILE_COMMAND =
          new ServiceCall("user", R_REQUEST_QUIET_MODE_ENABLED_ID)
                  .setUser(1000) // user 1000 has packageName "android"
                  .addStringParam("android") // callingPackage
                  .addBooleanParam(false) // enableQuietMode
                  .addIntParam(USER_ID_PARAMETER) // userId
                  .addIntParam(0) // target
                  .addIntParam(0); // flags

  private static final ServiceCall TURN_ON_WORK_PROFILE_COMMAND =
          new ServiceCall("user", REQUEST_QUIET_MODE_ENABLED_ID)
                  .setUser(1000) // user 1000 has packageName "android"
                  .addStringParam("android") // callingPackage
                  .addBooleanParam(false) // enableQuietMode
                  .addIntParam(USER_ID_PARAMETER) // userId
                  .addIntParam(0); // target

  public InstrumentedTestUtilities(Context context, ProfileConnector connector) {
    this.context = context;
    this.connector = connector;
    this.instrumentedTestUtilities =
            new com.google.android.enterprise.connectedapps.testing.InstrumentedTestUtilities(
                    context, connector);
  }

  /**
   * See {@link
   * com.google.android.enterprise.connectedapps.testing.InstrumentedTestUtilities#hasWorkProfile()}.
   */
  public boolean hasWorkProfile() {
    return instrumentedTestUtilities.hasWorkProfile();
  }

  /**
   * See {@link
   * com.google.android.enterprise.connectedapps.testing.InstrumentedTestUtilities#getWorkProfileUserId()}.
   */
  public int getWorkProfileUserId() {
    return instrumentedTestUtilities.getWorkProfileUserId();
  }

  private UserHandle getWorkProfileUserHandle() {
    return SharedTestUtilities.getUserHandleForUserId(getWorkProfileUserId());
  }

  /**
   * See {@link
   * com.google.android.enterprise.connectedapps.testing.InstrumentedTestUtilities#ensureReadyForCrossProfileCalls()}.
   */
  public void ensureReadyForCrossProfileCalls() {
    instrumentedTestUtilities.ensureReadyForCrossProfileCalls();
    ensureWorkProfileTurnedOn();
  }

  /**
   * See {@link
   * com.google.android.enterprise.connectedapps.testing.InstrumentedTestUtilities#ensureNoWorkProfile()}.
   */
  public void ensureNoWorkProfile() {
    instrumentedTestUtilities.ensureNoWorkProfile();
  }

  public void removeUser(int userId) {
    runCommandWithOutput("pm remove-user " + userId);
  }

  public void installInUser(int userId) {
    runCommandWithOutput(
            "cmd package install-existing --user " + userId + " " + context.getPackageName());
  }

  /**
   * Grant the {@code INTERACT_ACROSS_USERS} permission if this app declares it.
   *
   * <p>This is required before cross-profile interaction will work.
   */
  public void grantInteractAcrossUsers() {
    // TODO(scottjonathan): Support INTERACT_ACROSS_PROFILES in these tests.
    runCommandWithOutput(
            "pm grant " + context.getPackageName() + " android.permission.INTERACT_ACROSS_USERS");
  }

  /**
   * See {@link
   * com.google.android.enterprise.connectedapps.testing.InstrumentedTestUtilities#ensureWorkProfileExists()}
   */
  public void ensureWorkProfileExists() {
    instrumentedTestUtilities.ensureWorkProfileExists();
  }

  /**
   * Create a work profile but do not install the test app.
   *
   * <p>This means that, as there is no profile owner, it will not be recognised as a work profile
   * by the SDK when running on that profile.
   */
  public void ensureWorkProfileExistsWithoutTestApp() {
    if (hasWorkProfile()) {
      if (!userHasPackageInstalled(getWorkProfileUserId(), context.getPackageName())) {
        return;
      }


      runCommandWithOutput("pm remove-user " + getWorkProfileUserId());

      // TODO(162219825): Try to remove the package

//      throw new IllegalStateException(
//              "There is already a work profile on the device with user id "
//                      + getWorkProfileUserId()
//                      + ".");
    }
    runCommandWithOutput("pm create-user --profileOf 0 --managed TestProfile123");
    int workProfileUserId = getWorkProfileUserId();
    startUser(workProfileUserId);
  }

  private static boolean userHasPackageInstalled(int userId, String packageName) {
    String expectedPackageLine = "package:" + packageName;
    String[] installedPackages =
            runCommandWithOutput("pm list packages --user " + userId).split("\n");
    for (String installedPackage : installedPackages) {
      if (installedPackage.equals(expectedPackageLine)) {
        return true;
      }
    }
    return false;
  }

  /** Ensure that the work profile is running. */
  public void ensureWorkProfileTurnedOn() {
    turnOnWorkProfileAndWait();
  }

  /** Ensure that the work profile is not running. */
  public void ensureWorkProfileTurnedOff() {
    turnOffWorkProfileAndWait();
  }

  /**
   * Turn off the work profile and block until it has been turned off.
   *
   * <p>This uses {@link ServiceCall} and so is only guaranteed to work correctly on AOSP.
   *
   * @see #turnOffWorkProfile()
   */
  public void turnOffWorkProfileAndWait() {
    turnOffWorkProfile();

    ProfileAvailabilityPoll.blockUntilProfileNotAvailable(context, getWorkProfileUserHandle());
  }

  // TODO(160147511): Remove use of service calls for versions after R
  /**
   * Turn off the work profile
   *
   * <p>This uses {@link ServiceCall} and so is only guaranteed to work correctly on AOSP.
   *
   * @see #turnOffWorkProfileAndWait()
   */
  public void turnOffWorkProfile() {
    if (VERSION.CODENAME.equals("S")) {
      runCommandWithOutput(
              S_TURN_OFF_WORK_PROFILE_COMMAND
                      .prepare()
                      .setInt(USER_ID_KEY, getWorkProfileUserId())
                      .getCommand());
    } else if (VERSION.SDK_INT == VERSION_CODES.R) {
      runCommandWithOutput(
              R_TURN_OFF_WORK_PROFILE_COMMAND
                      .prepare()
                      .setInt(USER_ID_KEY, getWorkProfileUserId())
                      .getCommand());
    } else if (VERSION.SDK_INT == VERSION_CODES.Q || VERSION.SDK_INT == VERSION_CODES.P) {
      runCommandWithOutput(
              TURN_OFF_WORK_PROFILE_COMMAND
                      .prepare()
                      .setInt(USER_ID_KEY, getWorkProfileUserId())
                      .getCommand());
    } else {
      throw new IllegalStateException("Cannot turn off work on this version of android");
    }
  }

  /**
   * Turn on the work profile and block until it has been turned on.
   *
   * <p>This uses {@link ServiceCall} and so is only guaranteed to work correctly on AOSP.
   *
   * @see #turnOnWorkProfile()
   */
  public void turnOnWorkProfileAndWait() {
    if (connector.isAvailable()) {
      return; // Already on
    }

    turnOnWorkProfile();

    ProfileAvailabilityPoll.blockUntilProfileRunningAndUnlocked(
            context, getWorkProfileUserHandle());
  }

  // TODO(160147511): Remove use of service calls for versions after R
  /**
   * Turn on the work profile and block until it has been turned on.
   *
   * <p>This uses {@link ServiceCall} and so is only guaranteed to work correctly on AOSP.
   *
   * @see #turnOnWorkProfileAndWait()
   */
  public void turnOnWorkProfile() {
    if (VERSION.CODENAME.equals("S")) {
      runCommandWithOutput(
              S_TURN_ON_WORK_PROFILE_COMMAND
                      .prepare()
                      .setInt(USER_ID_KEY, getWorkProfileUserId())
                      .getCommand());
    } else if (VERSION.SDK_INT == VERSION_CODES.R) {
      runCommandWithOutput(
              R_TURN_ON_WORK_PROFILE_COMMAND
                      .prepare()
                      .setInt(USER_ID_KEY, getWorkProfileUserId())
                      .getCommand());
    } else if (VERSION.SDK_INT == VERSION_CODES.Q || VERSION.SDK_INT == VERSION_CODES.P) {
      runCommandWithOutput(
              TURN_ON_WORK_PROFILE_COMMAND
                      .prepare()
                      .setInt(USER_ID_KEY, getWorkProfileUserId())
                      .getCommand());
    } else {
      throw new IllegalStateException("Cannot turn on work on this version of android");
    }
  }

  /**
   * See {@link
   * com.google.android.enterprise.connectedapps.testing.InstrumentedTestUtilities#waitForDisconnected()}.
   */
  public void waitForDisconnected() {
    instrumentedTestUtilities.waitForDisconnected();
  }

  /**
   * See {@link
   * com.google.android.enterprise.connectedapps.testing.InstrumentedTestUtilities#waitForConnected()}.
   */
  public void waitForConnected() {
    instrumentedTestUtilities.waitForConnected();
  }

  /**
   * Manually call {@link ProfileConnector#startConnecting()} and wait for connection to be
   * complete.
   */
  public void manuallyConnectAndWait() {
    connector.startConnecting();
    waitForConnected();
  }

  private static final Pattern CREATE_USER_PATTERN =
          Pattern.compile("Success: created user id (\\d+)");

  public int createUser(String username) {
    String output = runCommandWithOutput("pm create-user " + username);

    Matcher userMatcher = CREATE_USER_PATTERN.matcher(output);
    if (userMatcher.find()) {
      return Integer.parseInt(userMatcher.group(1));
    }

    throw new IllegalStateException("Could not create user. Output: " + output);
  }

  public void startUser(int userId) {
    UserHandle userHandle = SharedTestUtilities.getUserHandleForUserId(userId);
    InstrumentedTestUtilities.runCommandWithOutput("am start-user " + userId);
    ProfileAvailabilityPoll.blockUntilProfileRunningAndUnlocked(context, userHandle);
  }

  private static String runCommandWithOutput(String command) {
    // TODO: Log output so we can see why it's failing
    ParcelFileDescriptor p = runCommand(command);

    InputStream inputStream = new FileInputStream(p.getFileDescriptor());

    try (Scanner scanner = new Scanner(inputStream, UTF_8.name())) {
      return scanner.useDelimiter("\\A").next();
    } catch (NoSuchElementException e) {
      return "";
    }
  }

  private static ParcelFileDescriptor runCommand(String command) {
    return InstrumentationRegistry.getInstrumentation()
            .getUiAutomation()
            .executeShellCommand(command);
  }
}