1 /*
2  * Copyright (C) 2017 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 package com.android.server.cts.device.batterystats;
17 
18 import static org.junit.Assert.assertTrue;
19 import static org.junit.Assert.fail;
20 
21 import android.app.job.JobInfo;
22 import android.app.job.JobScheduler;
23 import android.content.ComponentName;
24 import android.util.Log;
25 
26 import androidx.test.runner.AndroidJUnit4;
27 
28 import org.junit.Test;
29 import org.junit.runner.RunWith;
30 
31 import java.util.concurrent.CountDownLatch;
32 import java.util.concurrent.TimeUnit;
33 
34 /**
35  * Used by BatteryStatsValidationTest.
36  */
37 @RunWith(AndroidJUnit4.class)
38 public class BatteryStatsJobDurationTests extends BatteryStatsDeviceTestBase {
39 
40     private static final ComponentName JOB_COMPONENT_NAME =
41             new ComponentName("com.android.server.cts.device.batterystats",
42                     SimpleJobService.class.getName());
43     // Keep a buffer because job execution can take longer on resource constrained devices
44     // like Android Wear.
45     private static final long JOB_TIMEOUT_MS = SimpleJobService.JOB_EXECUTION_MS + 30000L;
46 
47     public static final String TAG = "BatteryStatsJobDurTests";
48 
createJobInfo(int id)49     private JobInfo createJobInfo(int id) {
50         JobInfo.Builder builder = new JobInfo.Builder(id, JOB_COMPONENT_NAME);
51         builder.setOverrideDeadline(0);
52         return builder.build();
53     }
54 
55     @Test
testJobDuration()56     public void testJobDuration() throws Exception {
57         JobScheduler js = mContext.getSystemService(JobScheduler.class);
58         assertTrue("JobScheduler service not available", js != null);
59         final JobInfo job = createJobInfo(1);
60         for (int i = 0; i < 3; i++) {
61             CountDownLatch latch = SimpleJobService.resetCountDownLatch();
62             Log.i(TAG, "Scheduling job");
63             js.schedule(job);
64             Log.i(TAG, "Waiting for job to finish");
65             if (!latch.await(JOB_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
66                 Log.e(TAG, String.format("Job didn't finish in %d ms", JOB_TIMEOUT_MS));
67                 fail(String.format("Job didn't finish in %d ms", JOB_TIMEOUT_MS));
68             }
69         }
70     }
71 }
72