1 /*
2  * Copyright 2018 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 
17 package androidx.work;
18 
19 import androidx.test.core.app.ApplicationProvider;
20 import androidx.work.impl.WorkDatabase;
21 import androidx.work.impl.model.WorkName;
22 import androidx.work.impl.model.WorkTag;
23 
24 import com.google.common.truth.Truth;
25 
26 import org.junit.After;
27 import org.junit.Before;
28 
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.Executors;
31 import java.util.concurrent.TimeUnit;
32 
33 /**
34  * An abstract class for getting an in-memory instance of the {@link WorkDatabase}.
35  */
36 public abstract class DatabaseTest extends WorkManagerTest {
37     protected WorkDatabase mDatabase;
38     private final ExecutorService mQueryExecutor = Executors.newCachedThreadPool();
39 
40     @Before
initializeDb()41     public void initializeDb() {
42         mDatabase = WorkDatabase.create(
43                 ApplicationProvider.getApplicationContext(),
44                 mQueryExecutor,
45                 new SystemClock(), // only used for the pruning task
46                 true);
47     }
48 
49     @After
closeDb()50     public void closeDb() throws InterruptedException {
51         mQueryExecutor.shutdown();
52         Truth.assertThat(mQueryExecutor.awaitTermination(3, TimeUnit.SECONDS)).isTrue();
53         mDatabase.close();
54     }
55 
insertWork(OneTimeWorkRequest work)56     protected void insertWork(OneTimeWorkRequest work) {
57         mDatabase.workSpecDao().insertWorkSpec(work.getWorkSpec());
58     }
59 
insertTags(OneTimeWorkRequest work)60     protected void insertTags(OneTimeWorkRequest work) {
61         for (String tag : work.getTags()) {
62             WorkTag workTag = new WorkTag(tag, work.getStringId());
63             mDatabase.workTagDao().insert(workTag);
64         }
65     }
66 
insertName(String name, OneTimeWorkRequest work)67     protected void insertName(String name, OneTimeWorkRequest work) {
68         WorkName workName = new WorkName(name, work.getStringId());
69         mDatabase.workNameDao().insert(workName);
70     }
71 
insertWork(PeriodicWorkRequest periodicWork)72     protected void insertWork(PeriodicWorkRequest periodicWork) {
73         mDatabase.workSpecDao().insertWorkSpec(periodicWork.getWorkSpec());
74     }
75 }
76