Wrap ModulesService in new AppEngineServiceUtils

ModulesService does not provide a great API. Specifically, it doesn't have a
way to get the hostname for a specific service; you have to get the hostname for
a specific version as well. This is very rarely what we want, as we publish new
versions every week and don't expect old ones to hang around for very long, so
a task should execute against whatever the live version is, not whatever the
current version was back when the task was enqueued (especially because that
version might be deleted by now).

This new and improved wrapper API removes the confusion and plays better with
dependency injection to boot. We can also fold in other methods having to do
with App Engine services, whereas ModulesService was quite limited in scope.

This also has the side effect of fixing ResaveEntityAction, which is
currently broken because the tasks it's enqueuing to execute up to 30 days in
the future have the version hard-coded into the hostname, and we typically
delete old versions sooner than that.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=206173763
This commit is contained in:
mcilwain 2018-07-26 09:46:58 -07:00 committed by jianglai
parent c87fde605c
commit 6e74ba0587
27 changed files with 422 additions and 286 deletions

View file

@ -20,16 +20,15 @@ import static com.google.common.base.Strings.nullToEmpty;
import static com.google.common.collect.ImmutableList.toImmutableList;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.modules.ModulesService;
import com.google.appengine.api.modules.ModulesServiceFactory;
import com.google.appengine.api.taskqueue.TaskHandle;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Streams;
import google.registry.util.NonFinalForTesting;
import google.registry.util.AppEngineServiceUtils;
import java.util.NoSuchElementException;
import javax.inject.Inject;
/** An object providing methods for starting and querying Datastore backups. */
public class DatastoreBackupService {
@ -40,19 +39,11 @@ public class DatastoreBackupService {
/** The name of the app version used for hosting the Datastore Admin functionality. */
static final String DATASTORE_ADMIN_VERSION_NAME = "ah-builtin-python-bundle";
@NonFinalForTesting
private static ModulesService modulesService = ModulesServiceFactory.getModulesService();
private final AppEngineServiceUtils appEngineServiceUtils;
/**
* Returns an instance of this service.
*
* <p>This method exists to allow for making the service a singleton object if desired at some
* future point; the choice is meaningless right now because the service maintains no state.
* That means its client-facing methods could in theory be static methods, but they are not
* because that makes it difficult to mock this service in clients.
*/
public static DatastoreBackupService get() {
return new DatastoreBackupService();
@Inject
public DatastoreBackupService(AppEngineServiceUtils appEngineServiceUtils) {
this.appEngineServiceUtils = appEngineServiceUtils;
}
/**
@ -60,9 +51,10 @@ public class DatastoreBackupService {
*
* @see <a href="https://developers.google.com/appengine/articles/scheduled_backups">Scheduled Backups</a>
*/
private static TaskOptions makeTaskOptions(
private TaskOptions makeTaskOptions(
String queue, String name, String gcsBucket, ImmutableSet<String> kinds) {
String hostname = modulesService.getVersionHostname("default", DATASTORE_ADMIN_VERSION_NAME);
String hostname =
appEngineServiceUtils.getVersionHostname("default", DATASTORE_ADMIN_VERSION_NAME);
TaskOptions options = TaskOptions.Builder.withUrl("/_ah/datastore_admin/backup.create")
.header("Host", hostname)
.method(Method.GET)

View file

@ -103,9 +103,4 @@ public final class ExportRequestModule {
static String provideProjectId(HttpServletRequest req) {
return extractRequiredHeader(req, PROJECT_ID_HEADER);
}
@Provides
static DatastoreBackupService provideDatastoreBackupService() {
return DatastoreBackupService.get();
}
}

View file

@ -23,9 +23,6 @@ import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import com.google.appengine.api.modules.ModulesService;
import com.google.appengine.api.modules.ModulesServiceFactory;
import com.google.appengine.api.taskqueue.TaskHandle;
import com.google.appengine.api.taskqueue.TaskOptions.Method;
import com.google.common.flogger.FluentLogger;
import google.registry.config.RegistryConfig.Config;
@ -34,7 +31,6 @@ import google.registry.request.Parameter;
import google.registry.request.Response;
import google.registry.request.auth.Auth;
import google.registry.request.lock.LockHandler;
import google.registry.util.NonFinalForTesting;
import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.Callable;
@ -108,9 +104,6 @@ public class SyncRegistrarsSheetAction implements Runnable {
private static final String LOCK_NAME = "Synchronize registrars sheet";
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
@NonFinalForTesting
private static ModulesService modulesService = ModulesServiceFactory.getModulesService();
@Inject Response response;
@Inject SyncRegistrarsSheet syncRegistrarsSheet;
@Inject @Config("sheetLockTimeout") Duration timeout;
@ -152,9 +145,10 @@ public class SyncRegistrarsSheetAction implements Runnable {
}
}
/** Creates, enqueues, and returns a new backend task to sync registrar spreadsheets. */
public static TaskHandle enqueueBackendTask() {
String hostname = modulesService.getVersionHostname("backend", null);
return getQueue(QUEUE).add(withUrl(PATH).method(Method.GET).header("Host", hostname));
/**
* Enqueues a sync registrar sheet task targeting the App Engine service specified by hostname.
*/
public static void enqueueRegistrarSheetSync(String hostname) {
getQueue(QUEUE).add(withUrl(PATH).method(Method.GET).header("Host", hostname));
}
}

View file

@ -17,7 +17,6 @@ package google.registry.flows.async;
import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.util.DateTimeUtils.isBeforeOrAt;
import com.google.appengine.api.modules.ModulesService;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;
@ -32,6 +31,7 @@ import google.registry.model.EppResource;
import google.registry.model.ImmutableObject;
import google.registry.model.eppcommon.Trid;
import google.registry.model.host.HostResource;
import google.registry.util.AppEngineServiceUtils;
import google.registry.util.Retrier;
import javax.inject.Inject;
import javax.inject.Named;
@ -65,7 +65,7 @@ public final class AsyncFlowEnqueuer {
private final Queue asyncActionsPushQueue;
private final Queue asyncDeletePullQueue;
private final Queue asyncDnsRefreshPullQueue;
private final ModulesService modulesService;
private final AppEngineServiceUtils appEngineServiceUtils;
private final Retrier retrier;
@VisibleForTesting
@ -75,13 +75,13 @@ public final class AsyncFlowEnqueuer {
@Named(QUEUE_ASYNC_DELETE) Queue asyncDeletePullQueue,
@Named(QUEUE_ASYNC_HOST_RENAME) Queue asyncDnsRefreshPullQueue,
@Config("asyncDeleteFlowMapreduceDelay") Duration asyncDeleteDelay,
ModulesService modulesService,
AppEngineServiceUtils appEngineServiceUtils,
Retrier retrier) {
this.asyncActionsPushQueue = asyncActionsPushQueue;
this.asyncDeletePullQueue = asyncDeletePullQueue;
this.asyncDnsRefreshPullQueue = asyncDnsRefreshPullQueue;
this.asyncDeleteDelay = asyncDeleteDelay;
this.modulesService = modulesService;
this.appEngineServiceUtils = appEngineServiceUtils;
this.retrier = retrier;
}
@ -110,7 +110,7 @@ public final class AsyncFlowEnqueuer {
return;
}
logger.atInfo().log("Enqueuing async re-save of %s to run at %s.", entityKey, whenToResave);
String backendHostname = modulesService.getVersionHostname("backend", null);
String backendHostname = appEngineServiceUtils.getServiceHostname("backend");
TaskOptions task =
TaskOptions.Builder.withUrl(PATH_RESAVE_ENTITY)
.method(Method.POST)

View file

@ -34,13 +34,13 @@ import google.registry.request.Modules.AppIdentityCredentialModule;
import google.registry.request.Modules.DatastoreServiceModule;
import google.registry.request.Modules.GoogleCredentialModule;
import google.registry.request.Modules.Jackson2Module;
import google.registry.request.Modules.ModulesServiceModule;
import google.registry.request.Modules.NetHttpTransportModule;
import google.registry.request.Modules.URLFetchServiceModule;
import google.registry.request.Modules.UrlFetchTransportModule;
import google.registry.request.Modules.UseAppIdentityCredentialForGoogleApisModule;
import google.registry.request.Modules.UserServiceModule;
import google.registry.request.auth.AuthModule;
import google.registry.util.AppEngineServiceUtilsImpl.AppEngineServiceUtilsModule;
import google.registry.util.SystemClock.SystemClockModule;
import google.registry.util.SystemSleeper.SystemSleeperModule;
import javax.inject.Singleton;
@ -49,6 +49,7 @@ import javax.inject.Singleton;
@Singleton
@Component(
modules = {
AppEngineServiceUtilsModule.class,
AppIdentityCredentialModule.class,
AuthModule.class,
BackendRequestComponentModule.class,
@ -66,7 +67,6 @@ import javax.inject.Singleton;
Jackson2Module.class,
KeyModule.class,
KmsModule.class,
ModulesServiceModule.class,
NetHttpTransportModule.class,
SheetsServiceModule.class,
StackdriverModule.class,
@ -77,8 +77,7 @@ import javax.inject.Singleton;
UseAppIdentityCredentialForGoogleApisModule.class,
UserServiceModule.class,
google.registry.dns.writer.VoidDnsWriterModule.class,
}
)
})
interface BackendComponent {
BackendRequestHandler requestHandler();

View file

@ -27,13 +27,13 @@ import google.registry.monitoring.whitebox.StackdriverModule;
import google.registry.request.Modules.AppIdentityCredentialModule;
import google.registry.request.Modules.GoogleCredentialModule;
import google.registry.request.Modules.Jackson2Module;
import google.registry.request.Modules.ModulesServiceModule;
import google.registry.request.Modules.NetHttpTransportModule;
import google.registry.request.Modules.UrlFetchTransportModule;
import google.registry.request.Modules.UseAppIdentityCredentialForGoogleApisModule;
import google.registry.request.Modules.UserServiceModule;
import google.registry.request.auth.AuthModule;
import google.registry.ui.ConsoleDebug.ConsoleConfigModule;
import google.registry.util.AppEngineServiceUtilsImpl.AppEngineServiceUtilsModule;
import google.registry.util.SystemClock.SystemClockModule;
import google.registry.util.SystemSleeper.SystemSleeperModule;
import javax.inject.Singleton;
@ -42,6 +42,7 @@ import javax.inject.Singleton;
@Singleton
@Component(
modules = {
AppEngineServiceUtilsModule.class,
AppIdentityCredentialModule.class,
AuthModule.class,
ConfigModule.class,
@ -53,7 +54,6 @@ import javax.inject.Singleton;
Jackson2Module.class,
KeyModule.class,
KmsModule.class,
ModulesServiceModule.class,
NetHttpTransportModule.class,
ServerTridProviderModule.class,
StackdriverModule.class,
@ -62,8 +62,7 @@ import javax.inject.Singleton;
UrlFetchTransportModule.class,
UseAppIdentityCredentialForGoogleApisModule.class,
UserServiceModule.class,
}
)
})
interface FrontendComponent {
FrontendRequestHandler requestHandler();

View file

@ -27,12 +27,12 @@ import google.registry.monitoring.whitebox.StackdriverModule;
import google.registry.request.Modules.AppIdentityCredentialModule;
import google.registry.request.Modules.GoogleCredentialModule;
import google.registry.request.Modules.Jackson2Module;
import google.registry.request.Modules.ModulesServiceModule;
import google.registry.request.Modules.NetHttpTransportModule;
import google.registry.request.Modules.UrlFetchTransportModule;
import google.registry.request.Modules.UseAppIdentityCredentialForGoogleApisModule;
import google.registry.request.Modules.UserServiceModule;
import google.registry.request.auth.AuthModule;
import google.registry.util.AppEngineServiceUtilsImpl.AppEngineServiceUtilsModule;
import google.registry.util.SystemClock.SystemClockModule;
import google.registry.util.SystemSleeper.SystemSleeperModule;
import javax.inject.Singleton;
@ -41,6 +41,7 @@ import javax.inject.Singleton;
@Singleton
@Component(
modules = {
AppEngineServiceUtilsModule.class,
AppIdentityCredentialModule.class,
AuthModule.class,
ConfigModule.class,
@ -51,7 +52,6 @@ import javax.inject.Singleton;
Jackson2Module.class,
KeyModule.class,
KmsModule.class,
ModulesServiceModule.class,
NetHttpTransportModule.class,
ServerTridProviderModule.class,
StackdriverModule.class,
@ -60,8 +60,7 @@ import javax.inject.Singleton;
UrlFetchTransportModule.class,
UseAppIdentityCredentialForGoogleApisModule.class,
UserServiceModule.class,
}
)
})
interface PubApiComponent {
PubApiRequestHandler requestHandler();

View file

@ -30,12 +30,12 @@ import google.registry.request.Modules.AppIdentityCredentialModule;
import google.registry.request.Modules.DatastoreServiceModule;
import google.registry.request.Modules.GoogleCredentialModule;
import google.registry.request.Modules.Jackson2Module;
import google.registry.request.Modules.ModulesServiceModule;
import google.registry.request.Modules.NetHttpTransportModule;
import google.registry.request.Modules.UrlFetchTransportModule;
import google.registry.request.Modules.UseAppIdentityCredentialForGoogleApisModule;
import google.registry.request.Modules.UserServiceModule;
import google.registry.request.auth.AuthModule;
import google.registry.util.AppEngineServiceUtilsImpl.AppEngineServiceUtilsModule;
import google.registry.util.SystemClock.SystemClockModule;
import google.registry.util.SystemSleeper.SystemSleeperModule;
import javax.inject.Singleton;
@ -44,6 +44,7 @@ import javax.inject.Singleton;
@Singleton
@Component(
modules = {
AppEngineServiceUtilsModule.class,
AppIdentityCredentialModule.class,
AuthModule.class,
ConfigModule.class,
@ -59,7 +60,6 @@ import javax.inject.Singleton;
Jackson2Module.class,
KeyModule.class,
KmsModule.class,
ModulesServiceModule.class,
NetHttpTransportModule.class,
ServerTridProviderModule.class,
SystemClockModule.class,
@ -68,8 +68,7 @@ import javax.inject.Singleton;
UrlFetchTransportModule.class,
UseAppIdentityCredentialForGoogleApisModule.class,
UserServiceModule.class,
}
)
})
interface ToolsComponent {
ToolsRequestHandler requestHandler();
}

View file

@ -16,12 +16,12 @@ package google.registry.monitoring.whitebox;
import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl;
import com.google.appengine.api.modules.ModulesService;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TransientFailureException;
import com.google.common.base.Supplier;
import com.google.common.flogger.FluentLogger;
import google.registry.util.AppEngineServiceUtils;
import java.util.Map.Entry;
import javax.inject.Inject;
import javax.inject.Named;
@ -38,7 +38,7 @@ public class BigQueryMetricsEnqueuer {
public static final String QUEUE_BIGQUERY_STREAMING_METRICS = "bigquery-streaming-metrics";
@Inject ModulesService modulesService;
@Inject AppEngineServiceUtils appEngineServiceUtils;
@Inject @Named("insertIdGenerator") Supplier<String> idGenerator;
@Inject @Named(QUEUE_BIGQUERY_STREAMING_METRICS) Queue queue;
@ -46,7 +46,7 @@ public class BigQueryMetricsEnqueuer {
public void export(BigQueryMetric metric) {
try {
String hostname = modulesService.getVersionHostname("backend", null);
String hostname = appEngineServiceUtils.getCurrentVersionHostname("backend");
TaskOptions opts =
withUrl(MetricsExportAction.PATH)
.header("Host", hostname)

View file

@ -27,8 +27,6 @@ import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.modules.ModulesService;
import com.google.appengine.api.modules.ModulesServiceFactory;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
import com.google.appengine.api.users.UserService;
@ -61,17 +59,6 @@ public final class Modules {
}
}
/** Dagger module for {@link ModulesService}. */
@Module
public static final class ModulesServiceModule {
private static final ModulesService modulesService = ModulesServiceFactory.getModulesService();
@Provides
static ModulesService provideModulesService() {
return modulesService;
}
}
/** Dagger module for {@link URLFetchService}. */
@Module
public static final class URLFetchServiceModule {

View file

@ -17,9 +17,11 @@ package google.registry.tools;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.google.common.collect.Iterables;
import com.google.common.collect.Streams;
import google.registry.export.DatastoreBackupInfo;
import google.registry.export.DatastoreBackupService;
import google.registry.tools.Command.RemoteApiCommand;
import javax.inject.Inject;
/**
* Command to check the status of a Datastore backup, or "snapshot".
@ -33,16 +35,16 @@ public class CheckSnapshotCommand implements RemoteApiCommand {
required = true)
private String snapshotName;
@Inject DatastoreBackupService datastoreBackupService;
@Override
public void run() {
Iterable<DatastoreBackupInfo> backups =
DatastoreBackupService.get().findAllByNamePrefix(snapshotName);
datastoreBackupService.findAllByNamePrefix(snapshotName);
if (Iterables.isEmpty(backups)) {
System.err.println("No snapshot found with name: " + snapshotName);
return;
}
for (DatastoreBackupInfo backup : backups) {
System.out.println(backup.getInformation());
}
Streams.stream(backups).map(DatastoreBackupInfo::getInformation).forEach(System.out::println);
}
}

View file

@ -26,13 +26,13 @@ import static google.registry.request.RequestParameters.PARAM_TLDS;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.beust.jcommander.Parameters;
import com.google.appengine.api.modules.ModulesService;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.TaskOptions;
import google.registry.model.rde.RdeMode;
import google.registry.rde.RdeStagingAction;
import google.registry.tools.Command.RemoteApiCommand;
import google.registry.tools.params.DateTimeParameter;
import google.registry.util.AppEngineServiceUtils;
import java.util.List;
import java.util.stream.Collectors;
import javax.inject.Inject;
@ -75,7 +75,7 @@ final class GenerateEscrowDepositCommand implements RemoteApiCommand {
required = true)
private String outdir;
@Inject ModulesService modulesService;
@Inject AppEngineServiceUtils appEngineServiceUtils;
@Inject @Named("rde-report") Queue queue;
@Override
@ -102,7 +102,7 @@ final class GenerateEscrowDepositCommand implements RemoteApiCommand {
// Unlike many tool commands, this command is actually invoking an action on the backend module
// (because it's a mapreduce). So we invoke it in a different way.
String hostname = modulesService.getVersionHostname("backend", null);
String hostname = appEngineServiceUtils.getCurrentVersionHostname("backend");
TaskOptions opts =
withUrl(RdeStagingAction.PATH)
.header("Host", hostname)

View file

@ -26,11 +26,11 @@ import google.registry.request.Modules.AppIdentityCredentialModule;
import google.registry.request.Modules.DatastoreServiceModule;
import google.registry.request.Modules.GoogleCredentialModule;
import google.registry.request.Modules.Jackson2Module;
import google.registry.request.Modules.ModulesServiceModule;
import google.registry.request.Modules.URLFetchServiceModule;
import google.registry.request.Modules.UrlFetchTransportModule;
import google.registry.request.Modules.UseAppIdentityCredentialForGoogleApisModule;
import google.registry.request.Modules.UserServiceModule;
import google.registry.util.AppEngineServiceUtilsImpl.AppEngineServiceUtilsModule;
import google.registry.util.SystemClock.SystemClockModule;
import google.registry.util.SystemSleeper.SystemSleeperModule;
import google.registry.whois.WhoisModule;
@ -46,6 +46,7 @@ import javax.inject.Singleton;
@Component(
modules = {
AppEngineConnectionFlags.FlagsModule.class,
AppEngineServiceUtilsModule.class,
// TODO(b/36866706): Find a way to replace this with a command-line friendly version
AppIdentityCredentialModule.class,
AuthModule.class,
@ -60,7 +61,6 @@ import javax.inject.Singleton;
Jackson2Module.class,
KeyModule.class,
KmsModule.class,
ModulesServiceModule.class,
RdeModule.class,
RegistryToolModule.class,
SystemClockModule.class,
@ -72,9 +72,9 @@ import javax.inject.Singleton;
UserServiceModule.class,
VoidDnsWriterModule.class,
WhoisModule.class,
}
)
})
interface RegistryToolComponent {
void inject(CheckSnapshotCommand command);
void inject(CountDomainsCommand command);
void inject(CreateAnchorTenantCommand command);
void inject(CreateCdnsTld command);

View file

@ -16,6 +16,7 @@ package google.registry.ui.server.registrar;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Sets.difference;
import static google.registry.export.sheet.SyncRegistrarsSheetAction.enqueueRegistrarSheetSync;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.security.JsonResponseHelper.Status.ERROR;
import static google.registry.security.JsonResponseHelper.Status.SUCCESS;
@ -29,7 +30,6 @@ import com.google.common.collect.Multimap;
import com.google.common.collect.Streams;
import com.google.common.flogger.FluentLogger;
import google.registry.config.RegistryConfig.Config;
import google.registry.export.sheet.SyncRegistrarsSheetAction;
import google.registry.model.registrar.Registrar;
import google.registry.model.registrar.RegistrarContact;
import google.registry.model.registrar.RegistrarContact.Builder;
@ -43,6 +43,7 @@ import google.registry.security.JsonResponseHelper;
import google.registry.ui.forms.FormException;
import google.registry.ui.forms.FormFieldException;
import google.registry.ui.server.RegistrarFormFields;
import google.registry.util.AppEngineServiceUtils;
import google.registry.util.CollectionUtils;
import google.registry.util.DiffUtils;
import java.util.HashSet;
@ -76,6 +77,7 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA
@Inject HttpServletRequest request;
@Inject JsonActionRunner jsonActionRunner;
@Inject AppEngineServiceUtils appEngineServiceUtils;
@Inject AuthResult authResult;
@Inject SendEmailUtils sendEmailUtils;
@Inject SessionUtils sessionUtils;
@ -368,7 +370,7 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA
if (CollectionUtils.difference(changedKeys, "lastUpdateTime").isEmpty()) {
return;
}
SyncRegistrarsSheetAction.enqueueBackendTask();
enqueueRegistrarSheetSync(appEngineServiceUtils.getCurrentVersionHostname("backend"));
if (!registrarChangesNotificationEmailAddresses.isEmpty()) {
sendEmailUtils.sendEmail(
registrarChangesNotificationEmailAddresses,

View file

@ -0,0 +1,40 @@
// Copyright 2018 The Nomulus Authors. All Rights Reserved.
//
// 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 google.registry.util;
/**
* A wrapper for {@link com.google.appengine.api.modules.ModulesService} that provides a saner API.
*/
public interface AppEngineServiceUtils {
/**
* Returns a host name to use for the given service.
*
* <p>Note that this host name will not include a version, so it will always be whatever the live
* version is at the time that you hit the URL.
*/
String getServiceHostname(String service);
/**
* Returns a host name to use for the given service and current version.
*
* <p>Note that this host name will include the current version now at time of URL generation,
* which will not be the live version in the future.
*/
String getCurrentVersionHostname(String service);
/** Returns a host name to use for the given service and version. */
String getVersionHostname(String service, String version);
}

View file

@ -0,0 +1,70 @@
// Copyright 2018 The Nomulus Authors. All Rights Reserved.
//
// 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 google.registry.util;
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
import com.google.appengine.api.modules.ModulesService;
import com.google.appengine.api.modules.ModulesServiceFactory;
import dagger.Binds;
import dagger.Module;
import dagger.Provides;
import javax.inject.Inject;
/** A wrapper for {@link ModulesService} that provides a saner API. */
public class AppEngineServiceUtilsImpl implements AppEngineServiceUtils {
private final ModulesService modulesService;
@Inject
public AppEngineServiceUtilsImpl(ModulesService modulesService) {
this.modulesService = modulesService;
}
@Override
public String getServiceHostname(String service) {
// This will be in the format "version.service.projectid.appspot.com"
String hostnameWithVersion = modulesService.getVersionHostname(service, null);
// Strip off the version and return just "service.projectid.appspot.com"
return hostnameWithVersion.replaceFirst("^[^.]+\\.", "");
}
@Override
public String getCurrentVersionHostname(String service) {
return modulesService.getVersionHostname(service, null);
}
@Override
public String getVersionHostname(String service, String version) {
checkArgumentNotNull(version, "Must specify the version");
return modulesService.getVersionHostname(service, version);
}
/** Dagger module for AppEngineServiceUtils. */
@Module
public abstract static class AppEngineServiceUtilsModule {
private static final ModulesService modulesService = ModulesServiceFactory.getModulesService();
@Provides
static ModulesService provideModulesService() {
return modulesService;
}
@Binds
abstract AppEngineServiceUtils provideAppEngineServiceUtils(
AppEngineServiceUtilsImpl appEngineServiceUtilsImpl);
}
}

View file

@ -61,7 +61,6 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.google.appengine.api.modules.ModulesService;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;
import com.google.common.collect.ImmutableList;
@ -102,6 +101,7 @@ import google.registry.testing.InjectRule;
import google.registry.testing.MockitoJUnitRule;
import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.testing.mapreduce.MapreduceTestCase;
import google.registry.util.AppEngineServiceUtils;
import google.registry.util.RequestStatusChecker;
import google.registry.util.Retrier;
import google.registry.util.Sleeper;
@ -160,7 +160,7 @@ public class DeleteContactsAndHostsActionTest
getQueue(QUEUE_ASYNC_DELETE),
getQueue(QUEUE_ASYNC_HOST_RENAME),
Duration.ZERO,
mock(ModulesService.class),
mock(AppEngineServiceUtils.class),
new Retrier(new FakeSleeper(clock), 1));
AsyncFlowMetrics asyncFlowMetricsMock = mock(AsyncFlowMetrics.class);
action = new DeleteContactsAndHostsAction();

View file

@ -45,7 +45,6 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.google.appengine.api.modules.ModulesService;
import com.google.common.collect.ImmutableSet;
import com.googlecode.objectify.Key;
import google.registry.batch.RefreshDnsOnHostRenameAction.RefreshDnsOnHostRenameReducer;
@ -61,6 +60,7 @@ import google.registry.testing.InjectRule;
import google.registry.testing.MockitoJUnitRule;
import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.testing.mapreduce.MapreduceTestCase;
import google.registry.util.AppEngineServiceUtils;
import google.registry.util.RequestStatusChecker;
import google.registry.util.Retrier;
import google.registry.util.Sleeper;
@ -97,7 +97,7 @@ public class RefreshDnsOnHostRenameActionTest
getQueue(QUEUE_ASYNC_DELETE),
getQueue(QUEUE_ASYNC_HOST_RENAME),
Duration.ZERO,
mock(ModulesService.class),
mock(AppEngineServiceUtils.class),
new Retrier(new FakeSleeper(clock), 1));
AsyncFlowMetrics asyncFlowMetricsMock = mock(AsyncFlowMetrics.class);
action = new RefreshDnsOnHostRenameAction();

View file

@ -32,11 +32,9 @@ import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
import static org.joda.time.Duration.standardDays;
import static org.joda.time.Duration.standardSeconds;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.appengine.api.modules.ModulesService;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.googlecode.objectify.Key;
@ -55,6 +53,7 @@ import google.registry.testing.InjectRule;
import google.registry.testing.MockitoJUnitRule;
import google.registry.testing.ShardableTestCase;
import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.util.AppEngineServiceUtils;
import google.registry.util.Retrier;
import org.joda.time.DateTime;
import org.joda.time.Duration;
@ -76,7 +75,7 @@ public class ResaveEntityActionTest extends ShardableTestCase {
@Rule public final InjectRule inject = new InjectRule();
@Rule public final MockitoJUnitRule mocks = MockitoJUnitRule.create();
@Mock private ModulesService modulesService;
@Mock private AppEngineServiceUtils appEngineServiceUtils;
@Mock private Response response;
private final FakeClock clock = new FakeClock(DateTime.parse("2016-02-11T10:00:00Z"));
private AsyncFlowEnqueuer asyncFlowEnqueuer;
@ -84,15 +83,14 @@ public class ResaveEntityActionTest extends ShardableTestCase {
@Before
public void before() {
inject.setStaticField(Ofy.class, "clock", clock);
when(modulesService.getVersionHostname(any(String.class), any(String.class)))
.thenReturn("backend.hostname.fake");
when(appEngineServiceUtils.getServiceHostname("backend")).thenReturn("backend.hostname.fake");
asyncFlowEnqueuer =
new AsyncFlowEnqueuer(
getQueue(QUEUE_ASYNC_ACTIONS),
getQueue(QUEUE_ASYNC_DELETE),
getQueue(QUEUE_ASYNC_HOST_RENAME),
Duration.ZERO,
modulesService,
appEngineServiceUtils,
new Retrier(new FakeSleeper(clock), 1));
createTld("tld");
}

View file

@ -19,16 +19,15 @@ import static com.google.common.collect.Iterables.transform;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.modules.ModulesService;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import google.registry.testing.AppEngineRule;
import google.registry.testing.InjectRule;
import google.registry.testing.MockitoJUnitRule;
import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.util.AppEngineServiceUtils;
import java.util.Date;
import org.joda.time.DateTime;
import org.junit.Before;
@ -36,30 +35,28 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mock;
/** Unit tests for {@link DatastoreBackupService}. */
@RunWith(JUnit4.class)
public class DatastoreBackupServiceTest {
@Rule
public final InjectRule inject = new InjectRule();
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastore().withTaskQueue().build();
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore()
.withTaskQueue()
.build();
@Rule public final MockitoJUnitRule mocks = MockitoJUnitRule.create();
private final ModulesService modulesService = mock(ModulesService.class);
@Mock private AppEngineServiceUtils appEngineServiceUtils;
private static final DateTime START_TIME = DateTime.parse("2014-08-01T01:02:03Z");
private final DatastoreBackupService backupService = DatastoreBackupService.get();
private DatastoreBackupService backupService;
@Before
public void before() {
inject.setStaticField(DatastoreBackupService.class, "modulesService", modulesService);
when(modulesService.getVersionHostname("default", "ah-builtin-python-bundle"))
backupService = new DatastoreBackupService(appEngineServiceUtils);
when(appEngineServiceUtils.getVersionHostname("default", "ah-builtin-python-bundle"))
.thenReturn("ah-builtin-python-bundle.default.localhost");
persistBackupEntityWithName("backupA1");

View file

@ -18,11 +18,9 @@ import static com.google.appengine.api.taskqueue.QueueFactory.getQueue;
import static google.registry.flows.async.AsyncFlowEnqueuer.QUEUE_ASYNC_ACTIONS;
import static google.registry.flows.async.AsyncFlowEnqueuer.QUEUE_ASYNC_DELETE;
import static google.registry.flows.async.AsyncFlowEnqueuer.QUEUE_ASYNC_HOST_RENAME;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.appengine.api.modules.ModulesService;
import dagger.Component;
import dagger.Module;
import dagger.Provides;
@ -43,6 +41,7 @@ import google.registry.testing.FakeLockHandler;
import google.registry.testing.FakeSleeper;
import google.registry.tmch.TmchCertificateAuthority;
import google.registry.tmch.TmchXmlSignature;
import google.registry.util.AppEngineServiceUtils;
import google.registry.util.Clock;
import google.registry.util.Retrier;
import google.registry.util.Sleeper;
@ -71,7 +70,7 @@ interface EppTestComponent {
private EppMetric.Builder metricBuilder;
private FakeClock clock;
private FakeLockHandler lockHandler;
private ModulesService modulesService;
private AppEngineServiceUtils appEngineServiceUtils;
private Sleeper sleeper;
public static FakesAndMocksModule create() {
@ -91,23 +90,22 @@ interface EppTestComponent {
EppMetric.Builder eppMetricBuilder,
TmchXmlSignature tmchXmlSignature) {
FakesAndMocksModule instance = new FakesAndMocksModule();
ModulesService modulesService = mock(ModulesService.class);
when(modulesService.getVersionHostname(any(String.class), any(String.class)))
.thenReturn("backend.hostname.fake");
AppEngineServiceUtils appEngineServiceUtils = mock(AppEngineServiceUtils.class);
when(appEngineServiceUtils.getServiceHostname("backend")).thenReturn("backend.hostname.fake");
instance.asyncFlowEnqueuer =
new AsyncFlowEnqueuer(
getQueue(QUEUE_ASYNC_ACTIONS),
getQueue(QUEUE_ASYNC_DELETE),
getQueue(QUEUE_ASYNC_HOST_RENAME),
Duration.standardSeconds(90),
modulesService,
appEngineServiceUtils,
new Retrier(new FakeSleeper(clock), 1));
instance.clock = clock;
instance.domainFlowTmchUtils = new DomainFlowTmchUtils(tmchXmlSignature);
instance.sleeper = new FakeSleeper(clock);
instance.dnsQueue = DnsQueue.create();
instance.metricBuilder = eppMetricBuilder;
instance.modulesService = modulesService;
instance.appEngineServiceUtils = appEngineServiceUtils;
instance.metricsEnqueuer = mock(BigQueryMetricsEnqueuer.class);
instance.lockHandler = new FakeLockHandler(true);
return instance;
@ -154,8 +152,8 @@ interface EppTestComponent {
}
@Provides
ModulesService provideModulesService() {
return modulesService;
AppEngineServiceUtils provideAppEngineServiceUtils() {
return appEngineServiceUtils;
}
@Provides

View file

@ -29,10 +29,8 @@ import static google.registry.testing.TestLogHandlerUtils.assertLogMessage;
import static org.joda.time.Duration.standardDays;
import static org.joda.time.Duration.standardHours;
import static org.joda.time.Duration.standardSeconds;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;
import com.google.appengine.api.modules.ModulesService;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.flogger.LoggerConfig;
import com.googlecode.objectify.Key;
@ -44,6 +42,7 @@ import google.registry.testing.InjectRule;
import google.registry.testing.MockitoJUnitRule;
import google.registry.testing.ShardableTestCase;
import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.util.AppEngineServiceUtils;
import google.registry.util.CapturingLogHandler;
import google.registry.util.Retrier;
import java.util.logging.Level;
@ -67,7 +66,7 @@ public class AsyncFlowEnqueuerTest extends ShardableTestCase {
@Rule public final MockitoJUnitRule mocks = MockitoJUnitRule.create();
@Mock private ModulesService modulesService;
@Mock private AppEngineServiceUtils appEngineServiceUtils;
private AsyncFlowEnqueuer asyncFlowEnqueuer;
private final CapturingLogHandler logHandler = new CapturingLogHandler();
@ -76,15 +75,14 @@ public class AsyncFlowEnqueuerTest extends ShardableTestCase {
@Before
public void setUp() {
LoggerConfig.getConfig(AsyncFlowEnqueuer.class).addHandler(logHandler);
when(modulesService.getVersionHostname(any(String.class), any(String.class)))
.thenReturn("backend.hostname.fake");
when(appEngineServiceUtils.getServiceHostname("backend")).thenReturn("backend.hostname.fake");
asyncFlowEnqueuer =
new AsyncFlowEnqueuer(
getQueue(QUEUE_ASYNC_ACTIONS),
getQueue(QUEUE_ASYNC_DELETE),
getQueue(QUEUE_ASYNC_HOST_RENAME),
standardSeconds(90),
modulesService,
appEngineServiceUtils,
new Retrier(new FakeSleeper(clock), 1));
}

View file

@ -14,6 +14,7 @@ java_library(
"//java/google/registry/bigquery",
"//java/google/registry/model",
"//java/google/registry/monitoring/whitebox",
"//java/google/registry/util",
"//javatests/google/registry/testing",
"//third_party/objectify:objectify-v4_1",
"@com_google_apis_google_api_services_bigquery",

View file

@ -18,41 +18,36 @@ import static com.google.appengine.api.taskqueue.QueueFactory.getQueue;
import static google.registry.bigquery.BigqueryUtils.toBigqueryTimestamp;
import static google.registry.monitoring.whitebox.BigQueryMetricsEnqueuer.QUEUE_BIGQUERY_STREAMING_METRICS;
import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.api.services.bigquery.model.TableFieldSchema;
import com.google.appengine.api.modules.ModulesService;
import com.google.auto.value.AutoValue;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import google.registry.testing.AppEngineRule;
import google.registry.testing.InjectRule;
import google.registry.testing.MockitoJUnitRule;
import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.util.AppEngineServiceUtils;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Matchers;
import org.mockito.Mock;
/** Unit tests for {@link BigQueryMetricsEnqueuer}. */
@RunWith(JUnit4.class)
public class BigQueryMetricsEnqueuerTest {
@Rule
public final InjectRule inject = new InjectRule();
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastore().withLocalModules().withTaskQueue().build();
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore()
.withLocalModules()
.withTaskQueue()
.build();
@Rule public final MockitoJUnitRule mocks = MockitoJUnitRule.create();
private final ModulesService modulesService = mock(ModulesService.class);
@Mock private AppEngineServiceUtils appEngineServiceUtils;
private BigQueryMetricsEnqueuer enqueuer;
@ -60,10 +55,10 @@ public class BigQueryMetricsEnqueuerTest {
public void setUp() {
enqueuer = new BigQueryMetricsEnqueuer();
enqueuer.idGenerator = Suppliers.ofInstance("laffo");
enqueuer.modulesService = modulesService;
enqueuer.appEngineServiceUtils = appEngineServiceUtils;
enqueuer.queue = getQueue(QUEUE_BIGQUERY_STREAMING_METRICS);
when(modulesService.getVersionHostname(Matchers.anyString(), Matchers.anyString()))
.thenReturn("1.backend.test.localhost");
when(appEngineServiceUtils.getCurrentVersionHostname("backend"))
.thenReturn("backend.test.localhost");
}
@Test
@ -77,7 +72,7 @@ public class BigQueryMetricsEnqueuerTest {
assertTasksEnqueued("bigquery-streaming-metrics",
new TaskMatcher()
.url("/_dr/task/metrics")
.header("Host", "1.backend.test.localhost")
.header("Host", "backend.test.localhost")
.param("tableId", "test")
.param("startTime", "472176000.000000")
.param("endTime", "472176000.001000")

View file

@ -22,13 +22,12 @@ import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
import static org.mockito.Mockito.when;
import com.beust.jcommander.ParameterException;
import com.google.appengine.api.modules.ModulesService;
import google.registry.testing.InjectRule;
import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.util.AppEngineServiceUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mock;
/** Unit tests for {@link GenerateEscrowDepositCommand}. */
@ -38,17 +37,17 @@ public class GenerateEscrowDepositCommandTest
@Rule
public final InjectRule inject = new InjectRule();
@Mock ModulesService modulesService;
@Mock AppEngineServiceUtils appEngineServiceUtils;
@Before
public void before() {
createTld("tld");
createTld("anothertld");
command = new GenerateEscrowDepositCommand();
command.modulesService = modulesService;
command.appEngineServiceUtils = appEngineServiceUtils;
command.queue = getQueue("rde-report");
when(modulesService.getVersionHostname(Matchers.anyString(), Matchers.anyString()))
.thenReturn("1.backend.test.localhost");
when(appEngineServiceUtils.getCurrentVersionHostname("backend"))
.thenReturn("backend.test.localhost");
}
@Test
@ -191,7 +190,7 @@ public class GenerateEscrowDepositCommandTest
assertTasksEnqueued("rde-report",
new TaskMatcher()
.url("/_dr/task/rdeStaging")
.header("Host", "1.backend.test.localhost")
.header("Host", "backend.test.localhost")
.param("mode", "THIN")
.param("watermarks", "2017-01-01T00:00:00.000Z")
.param("tlds", "tld")
@ -207,7 +206,7 @@ public class GenerateEscrowDepositCommandTest
assertTasksEnqueued("rde-report",
new TaskMatcher()
.url("/_dr/task/rdeStaging")
.header("Host", "1.backend.test.localhost")
.header("Host", "backend.test.localhost")
.param("mode", "THIN")
.param("watermarks", "2017-01-01T00:00:00.000Z")
.param("tlds", "tld")
@ -222,7 +221,7 @@ public class GenerateEscrowDepositCommandTest
assertTasksEnqueued("rde-report",
new TaskMatcher()
.url("/_dr/task/rdeStaging")
.header("Host", "1.backend.test.localhost")
.header("Host", "backend.test.localhost")
.param("mode", "FULL")
.param("watermarks", "2017-01-01T00:00:00.000Z")
.param("tlds", "tld")
@ -243,7 +242,7 @@ public class GenerateEscrowDepositCommandTest
assertTasksEnqueued("rde-report",
new TaskMatcher()
.url("/_dr/task/rdeStaging")
.header("Host", "1.backend.test.localhost")
.header("Host", "backend.test.localhost")
.param("mode", "THIN")
.param("watermarks", "2017-01-01T00:00:00.000Z,2017-01-02T00:00:00.000Z")
.param("tlds", "tld,anothertld")

View file

@ -17,17 +17,12 @@ package google.registry.ui.server.registrar;
import static google.registry.config.RegistryConfig.getGSuiteOutgoingEmailAddress;
import static google.registry.config.RegistryConfig.getGSuiteOutgoingEmailDisplayName;
import static google.registry.security.JsonHttpTestUtils.createJsonPayload;
import static google.registry.security.JsonHttpTestUtils.createJsonResponseSupplier;
import static google.registry.testing.DatastoreHelper.loadRegistrar;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.appengine.api.modules.ModulesService;
import com.google.appengine.api.users.User;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import google.registry.export.sheet.SyncRegistrarsSheetAction;
import google.registry.model.ofy.Ofy;
import google.registry.request.JsonActionRunner;
import google.registry.request.JsonResponse;
@ -38,10 +33,11 @@ import google.registry.request.auth.UserAuthInfo;
import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock;
import google.registry.testing.InjectRule;
import google.registry.testing.MockitoJUnitRule;
import google.registry.util.AppEngineServiceUtils;
import google.registry.util.SendEmailService;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
@ -53,6 +49,7 @@ import org.junit.Before;
import org.junit.Rule;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mock;
/** Base class for tests using {@link RegistrarSettingsAction}. */
@RunWith(JUnit4.class)
@ -61,32 +58,31 @@ public class RegistrarSettingsActionTestCase {
static final String CLIENT_ID = "TheRegistrar";
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore()
.withTaskQueue()
.build();
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastore().withTaskQueue().build();
@Rule
public final InjectRule inject = new InjectRule();
@Rule public final InjectRule inject = new InjectRule();
@Rule public final MockitoJUnitRule mocks = MockitoJUnitRule.create();
final HttpServletRequest req = mock(HttpServletRequest.class);
final HttpServletResponse rsp = mock(HttpServletResponse.class);
final SendEmailService emailService = mock(SendEmailService.class);
final ModulesService modulesService = mock(ModulesService.class);
final SessionUtils sessionUtils = mock(SessionUtils.class);
@Mock AppEngineServiceUtils appEngineServiceUtils;
@Mock HttpServletRequest req;
@Mock HttpServletResponse rsp;
@Mock SendEmailService emailService;
@Mock SessionUtils sessionUtils;
final User user = new User("user", "gmail.com");
Message message;
final RegistrarSettingsAction action = new RegistrarSettingsAction();
final StringWriter writer = new StringWriter();
final Supplier<Map<String, Object>> json = createJsonResponseSupplier(writer);
final FakeClock clock = new FakeClock(DateTime.parse("2014-01-01T00:00:00Z"));
@Before
public void setUp() throws Exception {
action.request = req;
action.sessionUtils = sessionUtils;
action.appEngineServiceUtils = appEngineServiceUtils;
when(appEngineServiceUtils.getCurrentVersionHostname("backend")).thenReturn("backend.hostname");
action.authResult = AuthResult.create(AuthLevel.USER, UserAuthInfo.create(user, false));
action.jsonActionRunner = new JsonActionRunner(
ImmutableMap.of(), new JsonResponse(new ResponseImpl(rsp)));
@ -96,7 +92,6 @@ public class RegistrarSettingsActionTestCase {
new SendEmailUtils(getGSuiteOutgoingEmailAddress(), getGSuiteOutgoingEmailDisplayName());
inject.setStaticField(Ofy.class, "clock", clock);
inject.setStaticField(SendEmailUtils.class, "emailService", emailService);
inject.setStaticField(SyncRegistrarsSheetAction.class, "modulesService", modulesService);
message = new MimeMessage(Session.getDefaultInstance(new Properties(), null));
when(emailService.createMessage()).thenReturn(message);
when(req.getMethod()).thenReturn("POST");
@ -109,6 +104,5 @@ public class RegistrarSettingsActionTestCase {
// would still return the old value)
when(sessionUtils.getRegistrarForAuthResult(req, action.authResult))
.thenAnswer(x -> loadRegistrar(CLIENT_ID));
when(modulesService.getVersionHostname("backend", null)).thenReturn("backend.hostname");
}
}

View file

@ -0,0 +1,78 @@
// Copyright 2018 The Nomulus Authors. All Rights Reserved.
//
// 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 google.registry.util;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.assertThrows;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.when;
import com.google.appengine.api.modules.ModulesService;
import google.registry.testing.MockitoJUnitRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mock;
/** Unit tests for {@link AppEngineServiceUtilsImpl}. */
@RunWith(JUnit4.class)
public class AppEngineServiceUtilsImplTest {
@Rule public final MockitoJUnitRule mocks = MockitoJUnitRule.create();
@Mock private ModulesService modulesService;
private AppEngineServiceUtils appEngineServiceUtils;
@Before
public void before() {
appEngineServiceUtils = new AppEngineServiceUtilsImpl(modulesService);
when(modulesService.getVersionHostname(anyString(), isNull(String.class)))
.thenReturn("1234.servicename.projectid.appspot.fake");
when(modulesService.getVersionHostname(anyString(), eq("2345")))
.thenReturn("2345.servicename.projectid.appspot.fake");
}
@Test
public void test_getServiceHostname_doesntIncludeVersionId() {
assertThat(appEngineServiceUtils.getServiceHostname("servicename"))
.isEqualTo("servicename.projectid.appspot.fake");
}
@Test
public void test_getVersionHostname_doesIncludeVersionId() {
assertThat(appEngineServiceUtils.getCurrentVersionHostname("servicename"))
.isEqualTo("1234.servicename.projectid.appspot.fake");
}
@Test
public void test_getVersionHostname_worksWithVersionId() {
assertThat(appEngineServiceUtils.getVersionHostname("servicename", "2345"))
.isEqualTo("2345.servicename.projectid.appspot.fake");
}
@Test
public void test_getVersionHostname_throwsWhenVersionIdIsNull() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
() -> appEngineServiceUtils.getVersionHostname("servicename", null));
assertThat(thrown).hasMessageThat().isEqualTo("Must specify the version");
}
}