1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you
5  * may not use this file except in compliance with the License. You may
6  * 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
13  * implied. See the License for the specific language governing
14  * permissions and limitations under the License.
15  */
16 
17 package com.android.vts.util;
18 
19 import com.google.cloud.datastore.testing.LocalDatastoreHelper;
20 import lombok.RequiredArgsConstructor;
21 import lombok.extern.slf4j.Slf4j;
22 import org.junit.jupiter.api.extension.BeforeAllCallback;
23 import org.junit.jupiter.api.extension.BeforeEachCallback;
24 import org.junit.jupiter.api.extension.ExtensionContext;
25 import org.junit.jupiter.api.extension.ExtensionContext.Namespace;
26 
27 /** Sets up and tears down the Local Datastore emulator, defaults to strong consistency */
28 @RequiredArgsConstructor
29 @Slf4j
30 public class LocalDatastoreExtension implements BeforeAllCallback, BeforeEachCallback {
31 
32     private final double consistency;
33 
LocalDatastoreExtension()34     public LocalDatastoreExtension() {
35         this(1.0);
36     }
37 
38     @Override
beforeAll(final ExtensionContext context)39     public void beforeAll(final ExtensionContext context) throws Exception {
40         if (getHelper(context) == null) {
41             log.info("Creating new LocalDatastoreHelper");
42 
43             final LocalDatastoreHelper helper = LocalDatastoreHelper.create(consistency);
44             context.getRoot().getStore(Namespace.GLOBAL).put(LocalDatastoreHelper.class, helper);
45             helper.start();
46         }
47     }
48 
49     @Override
beforeEach(final ExtensionContext context)50     public void beforeEach(final ExtensionContext context) throws Exception {
51         final LocalDatastoreHelper helper = getHelper(context);
52         helper.reset();
53     }
54 
55     /** Get the helper created in beforeAll; it should be global so there will one per test run */
getHelper(final ExtensionContext context)56     public static LocalDatastoreHelper getHelper(final ExtensionContext context) {
57         return context.getRoot()
58                 .getStore(Namespace.GLOBAL)
59                 .get(LocalDatastoreHelper.class, LocalDatastoreHelper.class);
60     }
61 }
62