Compare commits

...
Author SHA1 Message Date
gbrodmanandGitHub 9b7f6ce500 Fix some SQL credential issues identified when deploying Beam pipelines (#706)
* Fix some SQL credential issues identified when deploying Beam pipelines

There are two issues fixed here.
1. Without calling `FileSystems.setDefaultPipelineOptions(PipelineOptionsFactory.create()), the Nomulus tool doesn't know how to handle gs:// scheme files. Thus, if you try to deploy (for instance) the Spec11 pipeline using a GCS credential file, it fails.
2. There was a misunderstanding before about what the credential file
actually refers to -- there is a credential file in JSON format that is
used for gcloud authorization, and there is a space-delimited SQL access
info file that has the instance name, username, and password. These are
separate options and should have separate command-line params.

* Actually we don't need this for remote deployment
2020-07-22 16:52:31 -04:00
Ben McIlwainandGitHub cd23748fe8 Upgrade rest of tools test classes to JUnit 5 (#705) 2020-07-22 11:09:21 -04:00
Ben McIlwainandGitHub cf41f5d354 Upgrade all remaining flows tests to JUnit 5 (#704) 2020-07-21 19:52:33 -04:00
Ben McIlwainandGitHub 9a5ba249db Upgrade converters/TMCH/RDAP to JUnit 5 (#703)
Also renames some existing Rules to Extensions (and removes JUnit 4 features
from them entirely if no longer being used).
2020-07-21 18:48:41 -04:00
Shicong HuangandGitHub f5186f8476 Merge two PremiumList entities (#690) 2020-07-21 18:18:52 -04:00
Lai JiangandGitHub 4e0ca19d2e Remove IDN elements from BRDA (#670)
Also added unit tests for RdeStagingReducer.
2020-07-21 15:29:32 -04:00
Ben McIlwainandGitHub c812807ab3 Upgrade mapreduce and DNS tests from JUnit 4 to JUnit 5 (#701)
* Upgrade mapreduce and DNS tests from JUnit 4 to JUnit 5

* Merge branch 'master' into junit5-batch-and-dns
2020-07-20 21:33:24 -04:00
Ben McIlwainandGitHub 9edb43f3e4 Upgrade command test classes from JUnit 4 to JUnit 5 (#700)
* Convert first batch of command tests to JUnit 5

* Upgrade rest of command tests to JUnit 5

* Migrate the last few test classes
2020-07-20 20:45:52 -04:00
gbrodmanandGitHub b721533759 Create an ImmutableObjectSubject for comparing SQL objects (#695)
* Create an ImmutableObjectSubject for comparing SQL objects

Many times, when comparing objects that are loaded in from / saved to
SQL in tests, there are some fields we don't care about. Specifically,
we might not care about the last update time, revision ID, or other
things like that that are autoassigned by the DB. If we use this, we can
ignore those fields while still comparing the other ones.

* Create an ImmutableObject Correspondence for more flexible usage
2020-07-20 13:14:09 -04:00
gbrodmanandGitHub ce35f6bc93 Include the user's registry lock email in the lock/unlock modal (#696)
* Include the user's registry lock email in the lock/unlock modal
2020-07-20 12:01:34 -04:00
gbrodmanandGitHub f7a67b7676 Add a 'Host' parameter to the relock action enqueuer (#699)
* Add a 'Host' parameter to the relock action enqueuer

I believe this is why we are seeing 404s currently -- we should be
specifying the backend host as the target like we do for the
resave-entity async action.
2020-07-17 15:35:44 -04:00
gbrodmanandGitHub 4438944900 Validate potentially-invalid domain names when (un)locking domains (#698)
* Validate potentially-invalid domain names when (un)locking domains
2020-07-17 12:05:19 -04:00
320 changed files with 4986 additions and 4979 deletions
@@ -169,10 +169,12 @@ public final class AsyncTaskEnqueuer {
lock.getRelockDuration().isPresent(),
"Lock with ID %s not configured for relock",
lock.getRevisionId());
String backendHostname = appEngineServiceUtils.getServiceHostname("backend");
addTaskToQueueWithRetry(
asyncActionsPushQueue,
TaskOptions.Builder.withUrl(RelockDomainAction.PATH)
.method(Method.POST)
.header("Host", backendHostname)
.param(
RelockDomainAction.OLD_UNLOCK_REVISION_ID_PARAM,
String.valueOf(lock.getRevisionId()))
@@ -48,6 +48,10 @@ public final class RdeRevision extends ImmutableObject {
*/
int revision;
public int getRevision() {
return revision;
}
/**
* Returns next revision ID to use when staging a new deposit file for the given triplet.
*
@@ -14,7 +14,9 @@
package google.registry.model.registry.label;
import static com.google.common.base.Charsets.US_ASCII;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.hash.Funnels.stringFunnel;
import static com.google.common.hash.Funnels.unencodedCharsFunnel;
import static google.registry.config.RegistryConfig.getDomainLabelListCacheDuration;
import static google.registry.config.RegistryConfig.getSingletonCachePersistDuration;
@@ -32,43 +34,82 @@ import com.google.common.cache.CacheLoader;
import com.google.common.cache.CacheLoader.InvalidCacheLoadException;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.hash.BloomFilter;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Ignore;
import com.googlecode.objectify.annotation.Parent;
import google.registry.model.Buildable;
import google.registry.model.ImmutableObject;
import google.registry.model.annotations.ReportedOn;
import google.registry.model.registry.Registry;
import google.registry.schema.replay.DatastoreAndSqlEntity;
import google.registry.schema.replay.DatastoreEntity;
import google.registry.schema.replay.SqlEntity;
import google.registry.schema.tld.PremiumListDao;
import google.registry.util.NonFinalForTesting;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import javax.annotation.Nullable;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Index;
import javax.persistence.JoinColumn;
import javax.persistence.MapKeyColumn;
import javax.persistence.PostLoad;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.LazyInitializationException;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.joda.time.Duration;
/** A premium list entity, persisted to Datastore, that is used to check domain label prices. */
/**
* A premium list entity that is used to check domain label prices.
*
* <p>Note that the primary key of this entity is {@link #revisionId}, which is auto-generated by
* the database. So, if a retry of insertion happens after the previous attempt unexpectedly
* succeeds, we will end up with having two exact same premium lists that differ only by revisionId.
* This is fine though, because we only use the list with the highest revisionId.
*/
@ReportedOn
@Entity
@javax.persistence.Entity
@Table(indexes = {@Index(columnList = "name", name = "premiumlist_name_idx")})
public final class PremiumList extends BaseDomainLabelList<Money, PremiumList.PremiumListEntry>
implements DatastoreEntity {
implements DatastoreAndSqlEntity {
/** Stores the revision key for the set of currently used premium list entry entities. */
Key<PremiumListRevision> revisionKey;
@Transient Key<PremiumListRevision> revisionKey;
@Override
public ImmutableList<SqlEntity> toSqlEntities() {
return ImmutableList.of(); // PremiumList is dual-written
}
@Ignore
@Column(nullable = false)
CurrencyUnit currency;
@Ignore
@ElementCollection
@CollectionTable(
name = "PremiumEntry",
joinColumns = @JoinColumn(name = "revisionId", referencedColumnName = "revisionId"))
@MapKeyColumn(name = "domainLabel")
@Column(name = "price", nullable = false)
Map<String, BigDecimal> labelsToPrices;
@Ignore
@Column(nullable = false)
BloomFilter<String> bloomFilter;
/** Virtual parent entity for premium list entry entities associated with a single revision. */
@ReportedOn
@@ -247,6 +288,35 @@ public final class PremiumList extends BaseDomainLabelList<Money, PremiumList.Pr
return Optional.ofNullable(loadPremiumList(name));
}
/** Returns the {@link CurrencyUnit} used for this list. */
public CurrencyUnit getCurrency() {
return currency;
}
/**
* Returns a {@link Map} of domain labels to prices.
*
* <p>Note that this is lazily loaded and thus will throw a {@link LazyInitializationException} if
* used outside the transaction in which the given entity was loaded. You generally should not be
* using this anyway as it's inefficient to load all of the PremiumEntry rows if you don't need
* them. To check prices, use {@link PremiumListDao#getPremiumPrice} instead.
*/
@Nullable
public ImmutableMap<String, BigDecimal> getLabelsToPrices() {
return labelsToPrices == null ? null : ImmutableMap.copyOf(labelsToPrices);
}
/**
* Returns a Bloom filter to determine whether a label might be premium, or is definitely not.
*
* <p>If the domain label might be premium, then the next step is to check for the existence of a
* corresponding row in the PremiumListEntry table. Otherwise, we know for sure it's not premium,
* and no DB load is required.
*/
public BloomFilter<String> getBloomFilter() {
return bloomFilter;
}
/**
* A premium list entry entity, persisted to Datastore. Each instance represents the price of a
* single label on a given TLD.
@@ -339,9 +409,39 @@ public final class PremiumList extends BaseDomainLabelList<Money, PremiumList.Pr
return this;
}
public Builder setCurrency(CurrencyUnit currency) {
getInstance().currency = currency;
return this;
}
public Builder setLabelsToPrices(Map<String, BigDecimal> labelsToPrices) {
getInstance().labelsToPrices = ImmutableMap.copyOf(labelsToPrices);
return this;
}
@Override
public PremiumList build() {
if (getInstance().labelsToPrices != null) {
// ASCII is used for the charset because all premium list domain labels are stored
// punycoded.
getInstance().bloomFilter =
BloomFilter.create(stringFunnel(US_ASCII), getInstance().labelsToPrices.size());
getInstance()
.labelsToPrices
.keySet()
.forEach(label -> getInstance().bloomFilter.put(label));
}
return super.build();
}
}
@PrePersist
void prePersist() {
lastUpdateTime = creationTime;
}
@PostLoad
void postLoad() {
creationTime = lastUpdateTime;
}
}
@@ -29,7 +29,7 @@ public enum RdeResourceType {
DOMAIN("urn:ietf:params:xml:ns:rdeDomain-1.0", EnumSet.of(FULL, THIN)),
HOST("urn:ietf:params:xml:ns:rdeHost-1.0", EnumSet.of(FULL)),
REGISTRAR("urn:ietf:params:xml:ns:rdeRegistrar-1.0", EnumSet.of(FULL, THIN)),
IDN("urn:ietf:params:xml:ns:rdeIDN-1.0", EnumSet.of(FULL, THIN)),
IDN("urn:ietf:params:xml:ns:rdeIDN-1.0", EnumSet.of(FULL)),
HEADER("urn:ietf:params:xml:ns:rdeHeader-1.0", EnumSet.of(FULL, THIN));
private final String uri;
@@ -77,7 +77,7 @@ public final class RdeStagingReducer extends Reducer<PendingDeposit, DepositFrag
private final byte[] stagingKeyBytes;
private final RdeMarshaller marshaller;
private RdeStagingReducer(
RdeStagingReducer(
TaskQueueUtils taskQueueUtils,
LockHandler lockHandler,
int gcsBufferSize,
@@ -125,7 +125,7 @@ public final class RdeStagingReducer extends Reducer<PendingDeposit, DepositFrag
final DateTime watermark = key.watermark();
final int revision =
Optional.ofNullable(key.revision())
.orElse(RdeRevision.getNextRevision(tld, watermark, mode));
.orElseGet(() -> RdeRevision.getNextRevision(tld, watermark, mode));
String id = RdeUtil.timestampToId(watermark);
String prefix = RdeNamingUtils.makeRydeFilename(tld, watermark, mode, 1, revision);
if (key.manual()) {
@@ -168,9 +168,13 @@ public final class RdeStagingReducer extends Reducer<PendingDeposit, DepositFrag
logger.atSevere().log("Fragment error: %s", fragment.error());
}
}
for (IdnTableEnum idn : IdnTableEnum.values()) {
output.write(marshaller.marshalIdn(idn.getTable()));
counter.increment(RdeResourceType.IDN);
// Don't write the IDN elements for BRDA.
if (mode == RdeMode.FULL) {
for (IdnTableEnum idn : IdnTableEnum.values()) {
output.write(marshaller.marshalIdn(idn.getTable()));
counter.increment(RdeResourceType.IDN);
}
}
// Output XML that says how many resources were emitted.
@@ -16,6 +16,7 @@ package google.registry.schema.tld;
import com.google.common.collect.ImmutableList;
import google.registry.model.ImmutableObject;
import google.registry.model.registry.label.PremiumList;
import google.registry.schema.replay.DatastoreEntity;
import google.registry.schema.replay.SqlEntity;
import java.io.Serializable;
@@ -1,151 +0,0 @@
// Copyright 2019 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.schema.tld;
import static com.google.common.base.Charsets.US_ASCII;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.hash.Funnels.stringFunnel;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.hash.BloomFilter;
import google.registry.model.CreateAutoTimestamp;
import google.registry.schema.replay.DatastoreEntity;
import google.registry.schema.replay.SqlEntity;
import java.math.BigDecimal;
import java.util.Map;
import javax.annotation.Nullable;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.JoinColumn;
import javax.persistence.MapKeyColumn;
import javax.persistence.Table;
import org.hibernate.LazyInitializationException;
import org.joda.money.CurrencyUnit;
import org.joda.time.DateTime;
/**
* A list of premium prices for domain names.
*
* <p>Note that the primary key of this entity is {@link #revisionId}, which is auto-generated by
* the database. So, if a retry of insertion happens after the previous attempt unexpectedly
* succeeds, we will end up with having two exact same premium lists that differ only by revisionId.
* This is fine though, because we only use the list with the highest revisionId.
*/
@Entity
@Table(indexes = {@Index(columnList = "name", name = "premiumlist_name_idx")})
public class PremiumList implements SqlEntity {
@Column(nullable = false)
private String name;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false)
private Long revisionId;
@Column(nullable = false)
private CreateAutoTimestamp creationTimestamp = CreateAutoTimestamp.create(null);
@Column(nullable = false)
private CurrencyUnit currency;
@ElementCollection
@CollectionTable(
name = "PremiumEntry",
joinColumns = @JoinColumn(name = "revisionId", referencedColumnName = "revisionId"))
@MapKeyColumn(name = "domainLabel")
@Column(name = "price", nullable = false)
private Map<String, BigDecimal> labelsToPrices;
@Column(nullable = false)
private BloomFilter<String> bloomFilter;
private PremiumList(String name, CurrencyUnit currency, Map<String, BigDecimal> labelsToPrices) {
this.name = name;
this.currency = currency;
this.labelsToPrices = labelsToPrices;
// ASCII is used for the charset because all premium list domain labels are stored punycoded.
this.bloomFilter = BloomFilter.create(stringFunnel(US_ASCII), labelsToPrices.size());
labelsToPrices.keySet().forEach(this.bloomFilter::put);
}
// Hibernate requires this default constructor.
private PremiumList() {}
/** Constructs a {@link PremiumList} object. */
public static PremiumList create(
String name, CurrencyUnit currency, Map<String, BigDecimal> labelsToPrices) {
return new PremiumList(name, currency, labelsToPrices);
}
/** Returns the name of the premium list, which is usually also a TLD string. */
public String getName() {
return name;
}
/** Returns the {@link CurrencyUnit} used for this list. */
public CurrencyUnit getCurrency() {
return currency;
}
/** Returns the ID of this revision, or throws if null. */
public Long getRevisionId() {
checkState(
revisionId != null,
"revisionId is null because this object has not yet been persisted to the DB");
return revisionId;
}
/** Returns the creation time of this revision of the premium list. */
public DateTime getCreationTimestamp() {
return creationTimestamp.getTimestamp();
}
/**
* Returns a {@link Map} of domain labels to prices.
*
* <p>Note that this is lazily loaded and thus will throw a {@link LazyInitializationException} if
* used outside the transaction in which the given entity was loaded. You generally should not be
* using this anyway as it's inefficient to load all of the PremiumEntry rows if you don't need
* them. To check prices, use {@link PremiumListDao#getPremiumPrice} instead.
*/
@Nullable
public ImmutableMap<String, BigDecimal> getLabelsToPrices() {
return labelsToPrices == null ? null : ImmutableMap.copyOf(labelsToPrices);
}
/**
* Returns a Bloom filter to determine whether a label might be premium, or is definitely not.
*
* <p>If the domain label might be premium, then the next step is to check for the existence of a
* corresponding row in the PremiumListEntry table. Otherwise, we know for sure it's not premium,
* and no DB load is required.
*/
public BloomFilter<String> getBloomFilter() {
return bloomFilter;
}
@Override
public ImmutableList<DatastoreEntity> toDatastoreEntities() {
return ImmutableList.of(); // PremiumList is dual-written
}
}
@@ -25,6 +25,7 @@ import com.google.common.annotations.VisibleForTesting;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import google.registry.model.registry.label.PremiumList;
import google.registry.util.NonFinalForTesting;
import java.math.BigDecimal;
import java.util.Optional;
@@ -20,6 +20,7 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import com.google.common.cache.CacheLoader.InvalidCacheLoadException;
import com.google.common.util.concurrent.UncheckedExecutionException;
import google.registry.model.registry.Registry;
import google.registry.model.registry.label.PremiumList;
import google.registry.schema.tld.PremiumListCache.RevisionIdAndLabel;
import java.math.BigDecimal;
import java.util.Optional;
@@ -16,6 +16,7 @@ package google.registry.schema.tld;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static org.joda.time.DateTimeZone.UTC;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
@@ -23,11 +24,13 @@ import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import google.registry.model.registry.label.PremiumList;
import google.registry.model.registry.label.PremiumList.PremiumListEntry;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import org.joda.money.CurrencyUnit;
import org.joda.time.DateTime;
/** Static utility methods for {@link PremiumList}. */
public class PremiumListUtils {
@@ -37,10 +40,7 @@ public class PremiumListUtils {
Splitter.on('\n').omitEmptyStrings().splitToList(inputData);
ImmutableMap<String, PremiumListEntry> prices =
new google.registry.model.registry.label.PremiumList.Builder()
.setName(name)
.build()
.parse(inputDataPreProcessed);
new PremiumList.Builder().setName(name).build().parse(inputDataPreProcessed);
ImmutableSet<CurrencyUnit> currencies =
prices.values().stream()
.map(e -> e.getValue().getCurrencyUnit())
@@ -54,7 +54,12 @@ public class PremiumListUtils {
Map<String, BigDecimal> priceAmounts =
Maps.transformValues(prices, ple -> ple.getValue().getAmount());
return PremiumList.create(name, currency, priceAmounts);
return new PremiumList.Builder()
.setName(name)
.setCurrency(currency)
.setLabelsToPrices(priceAmounts)
.setCreationTime(DateTime.now(UTC))
.build();
}
private PremiumListUtils() {}
@@ -66,6 +66,12 @@ final class RegistryCli implements AutoCloseable, CommandRunner {
+ "If not set, credentials saved by running `nomulus login' will be used.")
private String credentialJson = null;
@Parameter(
names = {"--sql_access_info"},
description = "Name of a file containing space-separated SQL access info used when deploying "
+ "Beam pipelines")
private String sqlAccessInfoFile = null;
// Do not make this final - compile-time constant inlining may interfere with JCommander.
@ParametersDelegate
private LoggingParameters loggingParams = new LoggingParameters();
@@ -161,7 +167,7 @@ final class RegistryCli implements AutoCloseable, CommandRunner {
component =
DaggerRegistryToolComponent.builder()
.credentialFilePath(credentialJson)
.beamJpaModule(new BeamJpaModule(credentialJson))
.beamJpaModule(new BeamJpaModule(sqlAccessInfoFile))
.build();
// JCommander stores sub-commands as nested JCommander objects containing a list of user objects
@@ -82,7 +82,7 @@ public class CreatePremiumListAction extends CreateOrUpdatePremiumListAction {
logger.atInfo().log("Saving premium list to Cloud SQL for TLD %s", name);
// TODO(mcilwain): Call logInputData() here once Datastore persistence is removed.
google.registry.schema.tld.PremiumList premiumList = parseToPremiumList(name, inputData);
PremiumList premiumList = parseToPremiumList(name, inputData);
PremiumListDao.saveNew(premiumList);
String message =
@@ -74,7 +74,7 @@ public class UpdatePremiumListAction extends CreateOrUpdatePremiumListAction {
protected void saveToCloudSql() {
logger.atInfo().log("Updating premium list '%s' in Cloud SQL.", name);
// TODO(mcilwain): Add logInputData() call here once DB migration is complete.
google.registry.schema.tld.PremiumList premiumList = parseToPremiumList(name, inputData);
PremiumList premiumList = parseToPremiumList(name, inputData);
PremiumListDao.update(premiumList);
String message =
String.format(
@@ -30,6 +30,7 @@ import com.google.common.collect.ImmutableList;
import com.google.common.flogger.FluentLogger;
import com.google.gson.Gson;
import google.registry.config.RegistryConfig.Config;
import google.registry.flows.domain.DomainFlowUtils;
import google.registry.model.registrar.Registrar;
import google.registry.model.registrar.RegistrarContact;
import google.registry.request.Action;
@@ -118,6 +119,7 @@ public class RegistryLockPostAction implements Runnable, JsonActionRunner.JsonAc
String registrarId = postInput.registrarId;
checkArgument(!Strings.isNullOrEmpty(registrarId), "Missing key for registrarId");
checkArgument(!Strings.isNullOrEmpty(postInput.domainName), "Missing key for domainName");
DomainFlowUtils.validateDomainName(postInput.domainName);
checkNotNull(postInput.isLock, "Missing key for isLock");
UserAuthInfo userAuthInfo =
authResult
@@ -92,6 +92,7 @@ registry.registrar.RegistryLock.prototype.fillLocksPage_ = function(e) {
lockEnabledForContact: locksDetails.lockEnabledForContact});
if (locksDetails.lockEnabledForContact) {
this.registryLockEmailAddress = locksDetails.email;
// Listen to the lock-domain 'submit' button click
var lockButton = goog.dom.getRequiredElement('button-lock-domain');
goog.events.listen(lockButton, goog.events.EventType.CLICK, this.onLockDomain_, false, this);
@@ -116,7 +117,10 @@ registry.registrar.RegistryLock.prototype.showModal_ = function(targetElement, d
// attach the modal to the parent element so focus remains correct if the user closes the modal
var modalElement = goog.soy.renderAsElement(
registry.soy.registrar.registrylock.confirmModal,
{domain: domain, isLock: isLock, isAdmin: this.isAdmin});
{domain: domain,
isLock: isLock,
isAdmin: this.isAdmin,
emailAddress: this.registryLockEmailAddress});
parentElement.prepend(modalElement);
if (domain == null) {
goog.dom.getRequiredElement('domain-lock-input-value').focus();
@@ -29,12 +29,12 @@
<class>google.registry.model.host.HostResource</class>
<class>google.registry.model.registrar.Registrar</class>
<class>google.registry.model.registrar.RegistrarContact</class>
<class>google.registry.model.registry.label.PremiumList</class>
<class>google.registry.model.reporting.Spec11ThreatMatch</class>
<class>google.registry.schema.domain.RegistryLock</class>
<class>google.registry.schema.tmch.ClaimsList</class>
<class>google.registry.schema.cursor.Cursor</class>
<class>google.registry.schema.server.Lock</class>
<class>google.registry.schema.tld.PremiumList</class>
<class>google.registry.schema.tld.PremiumEntry</class>
<class>google.registry.model.domain.secdns.DelegationSignerData</class>
<class>google.registry.model.domain.GracePeriod</class>
@@ -115,12 +115,12 @@
{template .confirmModal}
{@param isLock: bool}
{@param isAdmin: bool}
{@param emailAddress: string}
{@param? domain: string|null}
<div id="lock-confirm-modal" class="{css('lock-confirm-modal')}">
<div class="modal-content">
<p>Are you sure you want to {if $isLock}lock a domain{else}unlock the domain {$domain}{/if}?
We will send an email to the email address on file to confirm the {if not $isLock}un{/if}
lock.</p>
We will send an email to {$emailAddress} to confirm the {if not $isLock}un{/if}lock.</p>
<label for="domain-to-lock">Domain: </label>
<input id="domain-lock-input-value"
{if isNonnull($domain)}
@@ -33,29 +33,26 @@ import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.util.Retrier;
import google.registry.util.TaskQueueUtils;
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.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link CommitLogCheckpointAction}. */
@RunWith(JUnit4.class)
public class CommitLogCheckpointActionTest {
private static final String QUEUE_NAME = "export-commits";
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
CommitLogCheckpointStrategy strategy = mock(CommitLogCheckpointStrategy.class);
private CommitLogCheckpointStrategy strategy = mock(CommitLogCheckpointStrategy.class);
DateTime now = DateTime.now(UTC);
CommitLogCheckpointAction task = new CommitLogCheckpointAction();
private DateTime now = DateTime.now(UTC);
private CommitLogCheckpointAction task = new CommitLogCheckpointAction();
@Before
public void before() {
@BeforeEach
void beforeEach() {
task.clock = new FakeClock(now);
task.strategy = strategy;
task.taskQueueUtils = new TaskQueueUtils(new Retrier(null, 1));
@@ -66,7 +63,7 @@ public class CommitLogCheckpointActionTest {
}
@Test
public void testRun_noCheckpointEverWritten_writesCheckpointAndEnqueuesTask() {
void testRun_noCheckpointEverWritten_writesCheckpointAndEnqueuesTask() {
task.run();
assertTasksEnqueued(
QUEUE_NAME,
@@ -78,7 +75,7 @@ public class CommitLogCheckpointActionTest {
}
@Test
public void testRun_checkpointWrittenBeforeNow_writesCheckpointAndEnqueuesTask() {
void testRun_checkpointWrittenBeforeNow_writesCheckpointAndEnqueuesTask() {
DateTime oneMinuteAgo = now.minusMinutes(1);
persistResource(CommitLogCheckpointRoot.create(oneMinuteAgo));
task.run();
@@ -92,7 +89,7 @@ public class CommitLogCheckpointActionTest {
}
@Test
public void testRun_checkpointWrittenAfterNow_doesntOverwrite_orEnqueueTask() {
void testRun_checkpointWrittenAfterNow_doesntOverwrite_orEnqueueTask() {
DateTime oneMinuteFromNow = now.plusMinutes(1);
persistResource(CommitLogCheckpointRoot.create(oneMinuteFromNow));
task.run();
@@ -36,27 +36,22 @@ import google.registry.testing.FakeClock;
import google.registry.testing.InjectRule;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link CommitLogCheckpointStrategy}. */
@RunWith(JUnit4.class)
public class CommitLogCheckpointStrategyTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Rule
public final InjectRule inject = new InjectRule();
@RegisterExtension public final InjectRule inject = new InjectRule();
final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01TZ"));
final Ofy ofy = new Ofy(clock);
final TransactionManager tm = new DatastoreTransactionManager(ofy);
final CommitLogCheckpointStrategy strategy = new CommitLogCheckpointStrategy();
private final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01TZ"));
private final Ofy ofy = new Ofy(clock);
private final TransactionManager tm = new DatastoreTransactionManager(ofy);
private final CommitLogCheckpointStrategy strategy = new CommitLogCheckpointStrategy();
/**
* Supplier to inject into CommitLogBucket for doling out predictable bucket IDs.
@@ -64,7 +59,7 @@ public class CommitLogCheckpointStrategyTest {
* <p>If not overridden, the supplier returns 1 so that other saves won't hit an NPE (since even
* if they use saveWithoutBackup() the transaction still selects a bucket key early).
*/
final FakeSupplier<Integer> fakeBucketIdSupplier = new FakeSupplier<>(1);
private final FakeSupplier<Integer> fakeBucketIdSupplier = new FakeSupplier<>(1);
/** Gross but necessary supplier that can be modified to return the desired value. */
private static class FakeSupplier<T> implements Supplier<T> {
@@ -74,7 +69,7 @@ public class CommitLogCheckpointStrategyTest {
/** Set this value field to make the supplier return this value. */
T value = null;
public FakeSupplier(T defaultValue) {
FakeSupplier(T defaultValue) {
this.defaultValue = defaultValue;
}
@@ -84,8 +79,8 @@ public class CommitLogCheckpointStrategyTest {
}
}
@Before
public void before() {
@BeforeEach
void beforeEach() {
strategy.clock = clock;
strategy.ofy = ofy;
@@ -102,13 +97,13 @@ public class CommitLogCheckpointStrategyTest {
}
@Test
public void test_readBucketTimestamps_noCommitLogs() {
void test_readBucketTimestamps_noCommitLogs() {
assertThat(strategy.readBucketTimestamps())
.containsExactly(1, START_OF_TIME, 2, START_OF_TIME, 3, START_OF_TIME);
}
@Test
public void test_readBucketTimestamps_withSomeCommitLogs() {
void test_readBucketTimestamps_withSomeCommitLogs() {
DateTime startTime = clock.nowUtc();
writeCommitLogToBucket(1);
clock.advanceOneMilli();
@@ -118,7 +113,7 @@ public class CommitLogCheckpointStrategyTest {
}
@Test
public void test_readBucketTimestamps_againAfterUpdate_reflectsUpdate() {
void test_readBucketTimestamps_againAfterUpdate_reflectsUpdate() {
DateTime firstTime = clock.nowUtc();
writeCommitLogToBucket(1);
writeCommitLogToBucket(2);
@@ -133,14 +128,14 @@ public class CommitLogCheckpointStrategyTest {
}
@Test
public void test_readNewCommitLogsAndFindThreshold_noCommitsAtAll_returnsEndOfTime() {
void test_readNewCommitLogsAndFindThreshold_noCommitsAtAll_returnsEndOfTime() {
ImmutableMap<Integer, DateTime> bucketTimes =
ImmutableMap.of(1, START_OF_TIME, 2, START_OF_TIME, 3, START_OF_TIME);
assertThat(strategy.readNewCommitLogsAndFindThreshold(bucketTimes)).isEqualTo(END_OF_TIME);
}
@Test
public void test_readNewCommitLogsAndFindThreshold_noNewCommits_returnsEndOfTime() {
void test_readNewCommitLogsAndFindThreshold_noNewCommits_returnsEndOfTime() {
DateTime now = clock.nowUtc();
writeCommitLogToBucket(1);
clock.advanceOneMilli();
@@ -153,7 +148,7 @@ public class CommitLogCheckpointStrategyTest {
}
@Test
public void test_readNewCommitLogsAndFindThreshold_tiedNewCommits_returnsCommitTimeMinusOne() {
void test_readNewCommitLogsAndFindThreshold_tiedNewCommits_returnsCommitTimeMinusOne() {
DateTime now = clock.nowUtc();
writeCommitLogToBucket(1);
writeCommitLogToBucket(2);
@@ -164,7 +159,7 @@ public class CommitLogCheckpointStrategyTest {
}
@Test
public void test_readNewCommitLogsAndFindThreshold_someNewCommits_returnsEarliestTimeMinusOne() {
void test_readNewCommitLogsAndFindThreshold_someNewCommits_returnsEarliestTimeMinusOne() {
DateTime now = clock.nowUtc();
writeCommitLogToBucket(1); // 1A
writeCommitLogToBucket(2); // 2A
@@ -191,7 +186,7 @@ public class CommitLogCheckpointStrategyTest {
}
@Test
public void test_readNewCommitLogsAndFindThreshold_commitsAtBucketTimes() {
void test_readNewCommitLogsAndFindThreshold_commitsAtBucketTimes() {
DateTime now = clock.nowUtc();
ImmutableMap<Integer, DateTime> bucketTimes =
ImmutableMap.of(1, now.minusMillis(1), 2, now, 3, now.plusMillis(1));
@@ -199,7 +194,7 @@ public class CommitLogCheckpointStrategyTest {
}
@Test
public void test_computeBucketCheckpointTimes_earlyThreshold_setsEverythingToThreshold() {
void test_computeBucketCheckpointTimes_earlyThreshold_setsEverythingToThreshold() {
DateTime now = clock.nowUtc();
ImmutableMap<Integer, DateTime> bucketTimes =
ImmutableMap.of(1, now.minusMillis(1), 2, now, 3, now.plusMillis(1));
@@ -208,7 +203,7 @@ public class CommitLogCheckpointStrategyTest {
}
@Test
public void test_computeBucketCheckpointTimes_middleThreshold_clampsToThreshold() {
void test_computeBucketCheckpointTimes_middleThreshold_clampsToThreshold() {
DateTime now = clock.nowUtc();
ImmutableMap<Integer, DateTime> bucketTimes =
ImmutableMap.of(1, now.minusMillis(1), 2, now, 3, now.plusMillis(1));
@@ -217,7 +212,7 @@ public class CommitLogCheckpointStrategyTest {
}
@Test
public void test_computeBucketCheckpointTimes_lateThreshold_leavesBucketTimesAsIs() {
void test_computeBucketCheckpointTimes_lateThreshold_leavesBucketTimesAsIs() {
DateTime now = clock.nowUtc();
ImmutableMap<Integer, DateTime> bucketTimes =
ImmutableMap.of(1, now.minusMillis(1), 2, now, 3, now.plusMillis(1));
@@ -226,7 +221,7 @@ public class CommitLogCheckpointStrategyTest {
}
@Test
public void test_computeCheckpoint_noCommitsAtAll_bucketCheckpointTimesAreStartOfTime() {
void test_computeCheckpoint_noCommitsAtAll_bucketCheckpointTimesAreStartOfTime() {
assertThat(strategy.computeCheckpoint())
.isEqualTo(CommitLogCheckpoint.create(
clock.nowUtc(),
@@ -234,7 +229,7 @@ public class CommitLogCheckpointStrategyTest {
}
@Test
public void test_computeCheckpoint_noNewCommitLogs_bucketCheckpointTimesAreBucketTimes() {
void test_computeCheckpoint_noNewCommitLogs_bucketCheckpointTimesAreBucketTimes() {
DateTime now = clock.nowUtc();
writeCommitLogToBucket(1);
clock.advanceOneMilli();
@@ -250,7 +245,7 @@ public class CommitLogCheckpointStrategyTest {
}
@Test
public void test_computeCheckpoint_someNewCommits_bucketCheckpointTimesAreClampedToThreshold() {
void test_computeCheckpoint_someNewCommits_bucketCheckpointTimesAreClampedToThreshold() {
DateTime now = clock.nowUtc();
writeCommitLogToBucket(1); // 1A
writeCommitLogToBucket(2); // 2A
@@ -29,14 +29,11 @@ import google.registry.testing.InjectRule;
import google.registry.testing.mapreduce.MapreduceTestCase;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link DeleteOldCommitLogsAction}. */
@RunWith(JUnit4.class)
public class DeleteOldCommitLogsActionTest
extends MapreduceTestCase<DeleteOldCommitLogsAction> {
@@ -44,11 +41,10 @@ public class DeleteOldCommitLogsActionTest
private final FakeResponse response = new FakeResponse();
private ContactResource contact;
@Rule
public final InjectRule inject = new InjectRule();
@RegisterExtension public final InjectRule inject = new InjectRule();
@Before
public void setup() {
@BeforeEach
void beforeEach() {
inject.setStaticField(Ofy.class, "clock", clock);
action = new DeleteOldCommitLogsAction();
action.mrRunner = makeDefaultRunner();
@@ -107,11 +103,9 @@ public class DeleteOldCommitLogsActionTest
return ImmutableList.copyOf(ofy().load().type(clazz).iterable());
}
/**
* Check that with very short maxAge, only the referenced elements remain.
*/
/** Check that with very short maxAge, only the referenced elements remain. */
@Test
public void test_shortMaxAge() throws Exception {
void test_shortMaxAge() throws Exception {
runMapreduce(Duration.millis(1));
assertThat(ImmutableList.copyOf(ofy().load().type(CommitLogManifest.class).keys().iterable()))
@@ -121,11 +115,9 @@ public class DeleteOldCommitLogsActionTest
assertThat(ofyLoadType(CommitLogMutation.class)).hasSize(contact.getRevisions().size() * 3);
}
/**
* Check that with very long maxAge, all the elements remain.
*/
/** Check that with very long maxAge, all the elements remain. */
@Test
public void test_longMaxAge() throws Exception {
void test_longMaxAge() throws Exception {
ImmutableList<CommitLogManifest> initialManifests = ofyLoadType(CommitLogManifest.class);
ImmutableList<CommitLogMutation> initialMutations = ofyLoadType(CommitLogMutation.class);
@@ -39,17 +39,14 @@ import google.registry.testing.GcsTestingUtils;
import google.registry.testing.TestObject;
import java.util.List;
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.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link ExportCommitLogDiffAction}. */
@RunWith(JUnit4.class)
public class ExportCommitLogDiffActionTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder()
.withDatastoreAndCloudSql()
@@ -64,15 +61,15 @@ public class ExportCommitLogDiffActionTest {
private final ExportCommitLogDiffAction task = new ExportCommitLogDiffAction();
@Before
public void before() {
@BeforeEach
void beforeEach() {
task.gcsService = gcsService;
task.gcsBucket = "gcs bucket";
task.batchSize = 5;
}
@Test
public void testRun_noCommitHistory_onlyUpperCheckpointExported() throws Exception {
void testRun_noCommitHistory_onlyUpperCheckpointExported() throws Exception {
task.lowerCheckpointTime = oneMinuteAgo;
task.upperCheckpointTime = now;
@@ -104,7 +101,7 @@ public class ExportCommitLogDiffActionTest {
}
@Test
public void testRun_regularCommitHistory_exportsCorrectCheckpointDiff() throws Exception {
void testRun_regularCommitHistory_exportsCorrectCheckpointDiff() throws Exception {
task.lowerCheckpointTime = oneMinuteAgo;
task.upperCheckpointTime = now;
@@ -175,7 +172,7 @@ public class ExportCommitLogDiffActionTest {
}
@Test
public void testRun_simultaneousTransactions_bothExported() throws Exception {
void testRun_simultaneousTransactions_bothExported() throws Exception {
task.lowerCheckpointTime = oneMinuteAgo;
task.upperCheckpointTime = now;
@@ -227,7 +224,7 @@ public class ExportCommitLogDiffActionTest {
}
@Test
public void testRun_exportsAcrossMultipleBatches() throws Exception {
void testRun_exportsAcrossMultipleBatches() throws Exception {
task.batchSize = 2;
task.lowerCheckpointTime = oneMinuteAgo;
task.upperCheckpointTime = now;
@@ -288,7 +285,7 @@ public class ExportCommitLogDiffActionTest {
}
@Test
public void testRun_checkpointDiffWithNeverTouchedBuckets_exportsCorrectly() throws Exception {
void testRun_checkpointDiffWithNeverTouchedBuckets_exportsCorrectly() throws Exception {
task.lowerCheckpointTime = oneMinuteAgo;
task.upperCheckpointTime = now;
@@ -322,8 +319,7 @@ public class ExportCommitLogDiffActionTest {
}
@Test
public void testRun_checkpointDiffWithNonExistentBucketTimestamps_exportsCorrectly()
throws Exception {
void testRun_checkpointDiffWithNonExistentBucketTimestamps_exportsCorrectly() throws Exception {
// Non-existent bucket timestamps can exist when the commit log bucket count was increased
// recently.
@@ -404,7 +400,7 @@ public class ExportCommitLogDiffActionTest {
}
@Test
public void testRun_exportingFromStartOfTime_exportsAllCommits() throws Exception {
void testRun_exportingFromStartOfTime_exportsAllCommits() throws Exception {
task.lowerCheckpointTime = START_OF_TIME;
task.upperCheckpointTime = now;
@@ -44,28 +44,25 @@ import java.util.List;
import java.util.concurrent.Callable;
import java.util.logging.LogRecord;
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.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link GcsDiffFileLister}. */
@RunWith(JUnit4.class)
public class GcsDiffFileListerTest {
static final String GCS_BUCKET = "gcs bucket";
private static final String GCS_BUCKET = "gcs bucket";
final DateTime now = DateTime.now(UTC);
final GcsDiffFileLister diffLister = new GcsDiffFileLister();
final GcsService gcsService = GcsServiceFactory.createGcsService();
private final DateTime now = DateTime.now(UTC);
private final GcsDiffFileLister diffLister = new GcsDiffFileLister();
private final GcsService gcsService = GcsServiceFactory.createGcsService();
private final TestLogHandler logHandler = new TestLogHandler();
@Rule
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Before
public void before() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
diffLister.gcsService = gcsService;
diffLister.gcsBucket = GCS_BUCKET;
diffLister.executor = newDirectExecutorService();
@@ -111,13 +108,13 @@ public class GcsDiffFileListerTest {
}
@Test
public void testList_noFilesFound() {
void testList_noFilesFound() {
DateTime fromTime = now.plusMillis(1);
assertThat(listDiffFiles(fromTime, null)).isEmpty();
}
@Test
public void testList_patchesHoles() {
void testList_patchesHoles() {
// Fake out the GCS list() method to return only the first and last file.
// We can't use Mockito.spy() because GcsService's impl is final.
diffLister.gcsService = (GcsService) newProxyInstance(
@@ -162,7 +159,7 @@ public class GcsDiffFileListerTest {
}
@Test
public void testList_failsOnFork() throws Exception {
void testList_failsOnFork() throws Exception {
// We currently have files for now-4m ... now, construct the following sequence:
// now-8m <- now-7m <- now-6m now-5m <- now-4m ... now
// ^___________________________|
@@ -179,7 +176,7 @@ public class GcsDiffFileListerTest {
}
@Test
public void testList_boundaries() {
void testList_boundaries() {
assertThat(listDiffFiles(now.minusMinutes(4), now))
.containsExactly(
now.minusMinutes(4),
@@ -192,7 +189,7 @@ public class GcsDiffFileListerTest {
}
@Test
public void testList_failsOnGaps() throws Exception {
void testList_failsOnGaps() throws Exception {
// We currently have files for now-4m ... now, construct the following sequence:
// now-8m <- now-7m <- now-6m {missing} <- now-4m ... now
for (int i = 6; i < 9; ++i) {
@@ -228,7 +225,7 @@ public class GcsDiffFileListerTest {
}
@Test
public void testList_toTimeSpecified() {
void testList_toTimeSpecified() {
assertThat(listDiffFiles(
now.minusMinutes(4).minusSeconds(1), now.minusMinutes(2).plusSeconds(1)))
.containsExactly(
@@ -54,31 +54,28 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
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.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link RestoreCommitLogsAction}. */
@RunWith(JUnit4.class)
public class RestoreCommitLogsActionTest {
static final String GCS_BUCKET = "gcs bucket";
private static final String GCS_BUCKET = "gcs bucket";
final DateTime now = DateTime.now(UTC);
final RestoreCommitLogsAction action = new RestoreCommitLogsAction();
final GcsService gcsService = createGcsService();
private final DateTime now = DateTime.now(UTC);
private final RestoreCommitLogsAction action = new RestoreCommitLogsAction();
private final GcsService gcsService = createGcsService();
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder()
.withDatastoreAndCloudSql()
.withOfyTestEntities(TestObject.class)
.build();
@Before
public void init() {
@BeforeEach
void beforeEach() {
action.gcsService = gcsService;
action.dryRun = false;
action.datastoreService = DatastoreServiceFactory.getDatastoreService();
@@ -91,7 +88,7 @@ public class RestoreCommitLogsActionTest {
}
@Test
public void testRestore_multipleDiffFiles() throws Exception {
void testRestore_multipleDiffFiles() throws Exception {
ofy().saveWithoutBackup().entities(
TestObject.create("previous to keep"),
TestObject.create("previous to delete")).now();
@@ -141,7 +138,7 @@ public class RestoreCommitLogsActionTest {
}
@Test
public void testRestore_noManifests() throws Exception {
void testRestore_noManifests() throws Exception {
ofy().saveWithoutBackup().entity(
TestObject.create("previous to keep")).now();
saveDiffFileNotToRestore(now.minusMinutes(1));
@@ -155,7 +152,7 @@ public class RestoreCommitLogsActionTest {
}
@Test
public void testRestore_manifestWithNoDeletions() throws Exception {
void testRestore_manifestWithNoDeletions() throws Exception {
ofy().saveWithoutBackup().entity(TestObject.create("previous to keep")).now();
Key<CommitLogBucket> bucketKey = getBucketKey(1);
Key<CommitLogManifest> manifestKey = CommitLogManifest.createKey(bucketKey, now);
@@ -174,7 +171,7 @@ public class RestoreCommitLogsActionTest {
}
@Test
public void testRestore_manifestWithNoMutations() throws Exception {
void testRestore_manifestWithNoMutations() throws Exception {
ofy().saveWithoutBackup().entities(
TestObject.create("previous to keep"),
TestObject.create("previous to delete")).now();
@@ -195,7 +192,7 @@ public class RestoreCommitLogsActionTest {
// This is a pathological case that shouldn't be possible, but we should be robust to it.
@Test
public void testRestore_manifestWithNoMutationsOrDeletions() throws Exception {
void testRestore_manifestWithNoMutationsOrDeletions() throws Exception {
ofy().saveWithoutBackup().entities(
TestObject.create("previous to keep")).now();
saveDiffFileNotToRestore(now.minusMinutes(1));
@@ -211,7 +208,7 @@ public class RestoreCommitLogsActionTest {
}
@Test
public void testRestore_mutateExistingEntity() throws Exception {
void testRestore_mutateExistingEntity() throws Exception {
ofy().saveWithoutBackup().entity(TestObject.create("existing", "a")).now();
Key<CommitLogManifest> manifestKey = CommitLogManifest.createKey(getBucketKey(1), now);
saveDiffFileNotToRestore(now.minusMinutes(1));
@@ -229,7 +226,7 @@ public class RestoreCommitLogsActionTest {
// This should be harmless; deletes are idempotent.
@Test
public void testRestore_deleteMissingEntity() throws Exception {
void testRestore_deleteMissingEntity() throws Exception {
ofy().saveWithoutBackup().entity(TestObject.create("previous to keep", "a")).now();
saveDiffFileNotToRestore(now.minusMinutes(1));
Iterable<ImmutableObject> commitLogs = saveDiffFile(
@@ -50,26 +50,24 @@ import google.registry.util.Retrier;
import java.util.logging.Level;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
/** Unit tests for {@link AsyncTaskEnqueuer}. */
@RunWith(JUnit4.class)
@ExtendWith(MockitoExtension.class)
public class AsyncTaskEnqueuerTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@Rule public final InjectRule inject = new InjectRule();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@RegisterExtension public final InjectRule inject = new InjectRule();
@Mock private AppEngineServiceUtils appEngineServiceUtils;
@@ -77,8 +75,8 @@ public class AsyncTaskEnqueuerTest {
private final CapturingLogHandler logHandler = new CapturingLogHandler();
private final FakeClock clock = new FakeClock(DateTime.parse("2015-05-18T12:34:56Z"));
@Before
public void setUp() {
@BeforeEach
void beforeEach() {
LoggerConfig.getConfig(AsyncTaskEnqueuer.class).addHandler(logHandler);
when(appEngineServiceUtils.getServiceHostname("backend")).thenReturn("backend.hostname.fake");
asyncTaskEnqueuer = createForTesting(appEngineServiceUtils, clock, standardSeconds(90));
@@ -96,7 +94,7 @@ public class AsyncTaskEnqueuerTest {
}
@Test
public void test_enqueueAsyncResave_success() {
void test_enqueueAsyncResave_success() {
ContactResource contact = persistActiveContact("jd23456");
asyncTaskEnqueuer.enqueueAsyncResave(contact, clock.nowUtc(), clock.nowUtc().plusDays(5));
assertTasksEnqueued(
@@ -114,7 +112,7 @@ public class AsyncTaskEnqueuerTest {
}
@Test
public void test_enqueueAsyncResave_multipleResaves() {
void test_enqueueAsyncResave_multipleResaves() {
ContactResource contact = persistActiveContact("jd23456");
DateTime now = clock.nowUtc();
asyncTaskEnqueuer.enqueueAsyncResave(
@@ -130,16 +128,15 @@ public class AsyncTaskEnqueuerTest {
.header("content-type", "application/x-www-form-urlencoded")
.param(PARAM_RESOURCE_KEY, Key.create(contact).getString())
.param(PARAM_REQUESTED_TIME, now.toString())
.param(
PARAM_RESAVE_TIMES,
"2015-05-20T14:34:56.000Z,2015-05-21T15:34:56.000Z")
.param(PARAM_RESAVE_TIMES, "2015-05-20T14:34:56.000Z,2015-05-21T15:34:56.000Z")
.etaDelta(
standardHours(24).minus(standardSeconds(30)),
standardHours(24).plus(standardSeconds(30))));
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void test_enqueueAsyncResave_ignoresTasksTooFarIntoFuture() throws Exception {
void test_enqueueAsyncResave_ignoresTasksTooFarIntoFuture() throws Exception {
ContactResource contact = persistActiveContact("jd23456");
asyncTaskEnqueuer.enqueueAsyncResave(contact, clock.nowUtc(), clock.nowUtc().plusDays(31));
assertNoTasksEnqueued(QUEUE_ASYNC_ACTIONS);
@@ -147,7 +144,7 @@ public class AsyncTaskEnqueuerTest {
}
@Test
public void testEnqueueRelock() {
void testEnqueueRelock() {
RegistryLock lock =
saveRegistryLock(
new RegistryLock.Builder()
@@ -168,6 +165,7 @@ public class AsyncTaskEnqueuerTest {
new TaskMatcher()
.url(RelockDomainAction.PATH)
.method("POST")
.header("Host", "backend.hostname.fake")
.param(
RelockDomainAction.OLD_UNLOCK_REVISION_ID_PARAM,
String.valueOf(lock.getRevisionId()))
@@ -176,8 +174,9 @@ public class AsyncTaskEnqueuerTest {
standardHours(6).plus(standardSeconds(30))));
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testFailure_enqueueRelock_noDuration() {
void testFailure_enqueueRelock_noDuration() {
RegistryLock lockWithoutDuration =
saveRegistryLock(
new RegistryLock.Builder()
@@ -21,19 +21,16 @@ import static google.registry.batch.AsyncTaskMetrics.OperationType.CONTACT_AND_H
import com.google.common.collect.ImmutableSet;
import google.registry.testing.FakeClock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link AsyncTaskMetrics}. */
@RunWith(JUnit4.class)
public class AsyncTaskMetricsTest {
class AsyncTaskMetricsTest {
private final FakeClock clock = new FakeClock();
private final AsyncTaskMetrics asyncTaskMetrics = new AsyncTaskMetrics(clock);
@Test
public void testRecordAsyncFlowResult_calculatesDurationMillisCorrectly() {
void testRecordAsyncFlowResult_calculatesDurationMillisCorrectly() {
asyncTaskMetrics.recordAsyncFlowResult(
CONTACT_AND_HOST_DELETE,
SUCCESS,
@@ -105,19 +105,16 @@ import google.registry.util.SystemSleeper;
import java.util.Optional;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.Mock;
/** Unit tests for {@link DeleteContactsAndHostsAction}. */
@RunWith(JUnit4.class)
public class DeleteContactsAndHostsActionTest
extends MapreduceTestCase<DeleteContactsAndHostsAction> {
@Rule public final InjectRule inject = new InjectRule();
@RegisterExtension public final InjectRule inject = new InjectRule();
private AsyncTaskEnqueuer enqueuer;
private final FakeClock clock = new FakeClock(DateTime.parse("2015-01-15T11:22:33Z"));
@@ -146,8 +143,8 @@ public class DeleteContactsAndHostsActionTest
ofy().clearSessionCache();
}
@Before
public void setup() {
@BeforeEach
void beforeEach() {
inject.setStaticField(Ofy.class, "clock", clock);
enqueuer =
AsyncTaskEnqueuerTest.createForTesting(
@@ -171,7 +168,7 @@ public class DeleteContactsAndHostsActionTest
}
@Test
public void testSuccess_contact_referencedByActiveDomain_doesNotGetDeleted() throws Exception {
void testSuccess_contact_referencedByActiveDomain_doesNotGetDeleted() throws Exception {
ContactResource contact = persistContactPendingDelete("blah8221");
persistResource(newDomainBase("example.tld", contact));
DateTime timeEnqueued = clock.nowUtc();
@@ -211,17 +208,17 @@ public class DeleteContactsAndHostsActionTest
}
@Test
public void testSuccess_contact_notReferenced_getsDeleted_andPiiWipedOut() throws Exception {
void testSuccess_contact_notReferenced_getsDeleted_andPiiWipedOut() throws Exception {
runSuccessfulContactDeletionTest(Optional.of("fakeClientTrid"));
}
@Test
public void testSuccess_contact_andNoClientTrid_deletesSuccessfully() throws Exception {
void testSuccess_contact_andNoClientTrid_deletesSuccessfully() throws Exception {
runSuccessfulContactDeletionTest(Optional.empty());
}
@Test
public void test_cannotAcquireLock() {
void test_cannotAcquireLock() {
// Make lock acquisition fail.
acquireLock();
enqueueMapreduceOnly();
@@ -229,7 +226,7 @@ public class DeleteContactsAndHostsActionTest
}
@Test
public void test_mapreduceHasWorkToDo_lockIsAcquired() {
void test_mapreduceHasWorkToDo_lockIsAcquired() {
ContactResource contact = persistContactPendingDelete("blah8221");
persistResource(newDomainBase("example.tld", contact));
DateTime timeEnqueued = clock.nowUtc();
@@ -244,7 +241,7 @@ public class DeleteContactsAndHostsActionTest
}
@Test
public void test_noTasksToLease_releasesLockImmediately() {
void test_noTasksToLease_releasesLockImmediately() {
enqueueMapreduceOnly();
// If the Lock was correctly released, then we can acquire it now.
assertThat(acquireLock()).isPresent();
@@ -293,8 +290,7 @@ public class DeleteContactsAndHostsActionTest
}
@Test
public void testSuccess_contactWithoutPendingTransfer_isDeletedAndHasNoTransferData()
throws Exception {
void testSuccess_contactWithoutPendingTransfer_isDeletedAndHasNoTransferData() throws Exception {
ContactResource contact = persistContactPendingDelete("blah8221");
enqueuer.enqueueAsyncDelete(
contact,
@@ -308,7 +304,7 @@ public class DeleteContactsAndHostsActionTest
}
@Test
public void testSuccess_contactWithPendingTransfer_getsDeleted() throws Exception {
void testSuccess_contactWithPendingTransfer_getsDeleted() throws Exception {
DateTime transferRequestTime = clock.nowUtc().minusDays(3);
ContactResource contact =
persistContactWithPendingTransfer(
@@ -371,7 +367,7 @@ public class DeleteContactsAndHostsActionTest
}
@Test
public void testSuccess_contact_referencedByDeletedDomain_getsDeleted() throws Exception {
void testSuccess_contact_referencedByDeletedDomain_getsDeleted() throws Exception {
ContactResource contactUsed = persistContactPendingDelete("blah1234");
persistResource(
newDomainBase("example.tld", contactUsed)
@@ -410,7 +406,7 @@ public class DeleteContactsAndHostsActionTest
}
@Test
public void testSuccess_contact_notRequestedByOwner_doesNotGetDeleted() throws Exception {
void testSuccess_contact_notRequestedByOwner_doesNotGetDeleted() throws Exception {
ContactResource contact = persistContactPendingDelete("jane0991");
enqueuer.enqueueAsyncDelete(
contact,
@@ -438,7 +434,7 @@ public class DeleteContactsAndHostsActionTest
}
@Test
public void testSuccess_contact_notRequestedByOwner_isSuperuser_getsDeleted() throws Exception {
void testSuccess_contact_notRequestedByOwner_isSuperuser_getsDeleted() throws Exception {
ContactResource contact = persistContactWithPii("nate007");
enqueuer.enqueueAsyncDelete(
contact,
@@ -480,7 +476,7 @@ public class DeleteContactsAndHostsActionTest
}
@Test
public void testSuccess_targetResourcesDontExist_areDelayedForADay() throws Exception {
void testSuccess_targetResourcesDontExist_areDelayedForADay() throws Exception {
ContactResource contactNotSaved = newContactResource("somecontact");
HostResource hostNotSaved = newHostResource("a11.blah.foo");
DateTime timeBeforeRun = clock.nowUtc();
@@ -519,7 +515,7 @@ public class DeleteContactsAndHostsActionTest
}
@Test
public void testSuccess_unparseableTasks_areDelayedForADay() throws Exception {
void testSuccess_unparseableTasks_areDelayedForADay() throws Exception {
TaskOptions task =
TaskOptions.Builder.withMethod(Method.PULL).param("gobbledygook", "kljhadfgsd9f7gsdfh");
getQueue(QUEUE_ASYNC_DELETE).add(task);
@@ -535,7 +531,7 @@ public class DeleteContactsAndHostsActionTest
}
@Test
public void testSuccess_resourcesNotInPendingDelete_areSkipped() throws Exception {
void testSuccess_resourcesNotInPendingDelete_areSkipped() throws Exception {
ContactResource contact = persistActiveContact("blah2222");
HostResource host = persistActiveHost("rustles.your.jimmies");
DateTime timeEnqueued = clock.nowUtc();
@@ -567,7 +563,7 @@ public class DeleteContactsAndHostsActionTest
}
@Test
public void testSuccess_alreadyDeletedResources_areSkipped() throws Exception {
void testSuccess_alreadyDeletedResources_areSkipped() throws Exception {
ContactResource contactDeleted = persistDeletedContact("blah1236", clock.nowUtc().minusDays(2));
HostResource hostDeleted = persistDeletedHost("a.lim.lop", clock.nowUtc().minusDays(3));
enqueuer.enqueueAsyncDelete(
@@ -590,7 +586,7 @@ public class DeleteContactsAndHostsActionTest
}
@Test
public void testSuccess_host_referencedByActiveDomain_doesNotGetDeleted() throws Exception {
void testSuccess_host_referencedByActiveDomain_doesNotGetDeleted() throws Exception {
HostResource host = persistHostPendingDelete("ns1.example.tld");
persistUsedDomain("example.tld", persistActiveContact("abc456"), host);
DateTime timeEnqueued = clock.nowUtc();
@@ -627,12 +623,12 @@ public class DeleteContactsAndHostsActionTest
}
@Test
public void testSuccess_host_notReferenced_getsDeleted() throws Exception {
void testSuccess_host_notReferenced_getsDeleted() throws Exception {
runSuccessfulHostDeletionTest(Optional.of("fakeClientTrid"));
}
@Test
public void testSuccess_host_andNoClientTrid_deletesSuccessfully() throws Exception {
void testSuccess_host_andNoClientTrid_deletesSuccessfully() throws Exception {
runSuccessfulHostDeletionTest(Optional.empty());
}
@@ -675,7 +671,7 @@ public class DeleteContactsAndHostsActionTest
}
@Test
public void testSuccess_host_referencedByDeletedDomain_getsDeleted() throws Exception {
void testSuccess_host_referencedByDeletedDomain_getsDeleted() throws Exception {
HostResource host = persistHostPendingDelete("ns1.example.tld");
persistResource(
newDomainBase("example.tld")
@@ -715,7 +711,7 @@ public class DeleteContactsAndHostsActionTest
}
@Test
public void testSuccess_subordinateHost_getsDeleted() throws Exception {
void testSuccess_subordinateHost_getsDeleted() throws Exception {
DomainBase domain =
persistResource(
newDomainBase("example.tld")
@@ -766,7 +762,7 @@ public class DeleteContactsAndHostsActionTest
}
@Test
public void testSuccess_host_notRequestedByOwner_doesNotGetDeleted() throws Exception {
void testSuccess_host_notRequestedByOwner_doesNotGetDeleted() throws Exception {
HostResource host = persistHostPendingDelete("ns2.example.tld");
enqueuer.enqueueAsyncDelete(
host,
@@ -794,7 +790,7 @@ public class DeleteContactsAndHostsActionTest
}
@Test
public void testSuccess_host_notRequestedByOwner_isSuperuser_getsDeleted() throws Exception {
void testSuccess_host_notRequestedByOwner_isSuperuser_getsDeleted() throws Exception {
HostResource host = persistHostPendingDelete("ns66.example.tld");
enqueuer.enqueueAsyncDelete(
host,
@@ -828,7 +824,7 @@ public class DeleteContactsAndHostsActionTest
}
@Test
public void testSuccess_deleteABunchOfContactsAndHosts_butNotSome() throws Exception {
void testSuccess_deleteABunchOfContactsAndHosts_butNotSome() throws Exception {
ContactResource c1 = persistContactPendingDelete("nsaid54");
ContactResource c2 = persistContactPendingDelete("nsaid55");
ContactResource c3 = persistContactPendingDelete("nsaid57");
@@ -46,29 +46,26 @@ import google.registry.model.registry.Registry;
import google.registry.model.registry.Registry.TldType;
import google.registry.model.reporting.HistoryEntry;
import google.registry.testing.FakeResponse;
import google.registry.testing.SystemPropertyRule;
import google.registry.testing.SystemPropertyExtension;
import google.registry.testing.mapreduce.MapreduceTestCase;
import java.util.Optional;
import java.util.Set;
import org.joda.money.Money;
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.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link DeleteProberDataAction}. */
@RunWith(JUnit4.class)
public class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDataAction> {
class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDataAction> {
private static final DateTime DELETION_TIME = DateTime.parse("2010-01-01T00:00:00.000Z");
@Rule
public final SystemPropertyRule systemPropertyRule = new SystemPropertyRule();
@RegisterExtension
final SystemPropertyExtension systemPropertyExtension = new SystemPropertyExtension();
@Before
public void init() {
@BeforeEach
void beforeEach() {
// Entities in these two should not be touched.
createTld("tld", "TLD");
// Since "example" doesn't end with .test, its entities won't be deleted even though it is of
@@ -96,7 +93,7 @@ public class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDa
action.isDryRun = false;
action.tlds = ImmutableSet.of();
action.registryAdminClientId = "TheRegistrar";
RegistryEnvironment.SANDBOX.setup(systemPropertyRule);
RegistryEnvironment.SANDBOX.setup(systemPropertyExtension);
}
private void runMapreduce() throws Exception {
@@ -105,7 +102,7 @@ public class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDa
}
@Test
public void test_deletesAllAndOnlyProberData() throws Exception {
void test_deletesAllAndOnlyProberData() throws Exception {
Set<ImmutableObject> tldEntities = persistLotsOfDomains("tld");
Set<ImmutableObject> exampleEntities = persistLotsOfDomains("example");
Set<ImmutableObject> notTestEntities = persistLotsOfDomains("not-test.test");
@@ -120,7 +117,7 @@ public class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDa
}
@Test
public void testSuccess_deletesAllAndOnlyGivenTlds() throws Exception {
void testSuccess_deletesAllAndOnlyGivenTlds() throws Exception {
Set<ImmutableObject> tldEntities = persistLotsOfDomains("tld");
Set<ImmutableObject> exampleEntities = persistLotsOfDomains("example");
Set<ImmutableObject> notTestEntities = persistLotsOfDomains("not-test.test");
@@ -136,7 +133,7 @@ public class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDa
}
@Test
public void testFail_givenNonTestTld() {
void testFail_givenNonTestTld() {
action.tlds = ImmutableSet.of("not-test.test");
IllegalArgumentException thrown =
assertThrows(IllegalArgumentException.class, this::runMapreduce);
@@ -146,7 +143,7 @@ public class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDa
}
@Test
public void testFail_givenNonExistentTld() {
void testFail_givenNonExistentTld() {
action.tlds = ImmutableSet.of("non-existent.test");
IllegalArgumentException thrown =
assertThrows(IllegalArgumentException.class, this::runMapreduce);
@@ -156,9 +153,9 @@ public class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDa
}
@Test
public void testFail_givenNonDotTestTldOnProd() {
void testFail_givenNonDotTestTldOnProd() {
action.tlds = ImmutableSet.of("example");
RegistryEnvironment.PRODUCTION.setup(systemPropertyRule);
RegistryEnvironment.PRODUCTION.setup(systemPropertyExtension);
IllegalArgumentException thrown =
assertThrows(IllegalArgumentException.class, this::runMapreduce);
assertThat(thrown)
@@ -167,7 +164,7 @@ public class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDa
}
@Test
public void testSuccess_doesntDeleteNicDomainForProbers() throws Exception {
void testSuccess_doesntDeleteNicDomainForProbers() throws Exception {
DomainBase nic = persistActiveDomain("nic.ib-any.test");
ForeignKeyIndex<DomainBase> fkiNic =
ForeignKeyIndex.load(DomainBase.class, "nic.ib-any.test", START_OF_TIME);
@@ -178,7 +175,7 @@ public class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDa
}
@Test
public void testDryRun_doesntDeleteData() throws Exception {
void testDryRun_doesntDeleteData() throws Exception {
Set<ImmutableObject> tldEntities = persistLotsOfDomains("tld");
Set<ImmutableObject> oaEntities = persistLotsOfDomains("oa-canary.test");
action.isDryRun = true;
@@ -188,7 +185,7 @@ public class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDa
}
@Test
public void testSuccess_activeDomain_isSoftDeleted() throws Exception {
void testSuccess_activeDomain_isSoftDeleted() throws Exception {
DomainBase domain = persistResource(
newDomainBase("blah.ib-any.test")
.asBuilder()
@@ -203,7 +200,7 @@ public class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDa
}
@Test
public void testSuccess_activeDomain_doubleMapSoftDeletes() throws Exception {
void testSuccess_activeDomain_doubleMapSoftDeletes() throws Exception {
DomainBase domain = persistResource(
newDomainBase("blah.ib-any.test")
.asBuilder()
@@ -220,7 +217,7 @@ public class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDa
}
@Test
public void test_recentlyCreatedDomain_isntDeletedYet() throws Exception {
void test_recentlyCreatedDomain_isntDeletedYet() throws Exception {
persistResource(
newDomainBase("blah.ib-any.test")
.asBuilder()
@@ -234,7 +231,7 @@ public class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDa
}
@Test
public void testDryRun_doesntSoftDeleteData() throws Exception {
void testDryRun_doesntSoftDeleteData() throws Exception {
DomainBase domain = persistResource(
newDomainBase("blah.ib-any.test")
.asBuilder()
@@ -246,7 +243,7 @@ public class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDa
}
@Test
public void test_domainWithSubordinateHosts_isSkipped() throws Exception {
void test_domainWithSubordinateHosts_isSkipped() throws Exception {
persistActiveHost("ns1.blah.ib-any.test");
DomainBase nakedDomain =
persistDeletedDomain("todelete.ib-any.test", DateTime.now(UTC).minusYears(1));
@@ -263,7 +260,7 @@ public class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDa
}
@Test
public void testFailure_registryAdminClientId_isRequiredForSoftDeletion() {
void testFailure_registryAdminClientId_isRequiredForSoftDeletion() {
persistResource(
newDomainBase("blah.ib-any.test")
.asBuilder()
@@ -59,28 +59,25 @@ import java.util.List;
import java.util.Optional;
import org.joda.money.Money;
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.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link ExpandRecurringBillingEventsAction}. */
@RunWith(JUnit4.class)
public class ExpandRecurringBillingEventsActionTest
extends MapreduceTestCase<ExpandRecurringBillingEventsAction> {
@Rule
public final InjectRule inject = new InjectRule();
@RegisterExtension public final InjectRule inject = new InjectRule();
private final DateTime beginningOfTest = DateTime.parse("2000-10-02T00:00:00Z");
private final FakeClock clock = new FakeClock(beginningOfTest);
DomainBase domain;
HistoryEntry historyEntry;
BillingEvent.Recurring recurring;
private DomainBase domain;
private HistoryEntry historyEntry;
private BillingEvent.Recurring recurring;
@Before
public void init() {
@BeforeEach
void beforeEach() {
inject.setStaticField(Ofy.class, "clock", clock);
action = new ExpandRecurringBillingEventsAction();
action.mrRunner = makeDefaultRunner();
@@ -161,7 +158,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_expandSingleEvent() throws Exception {
void testSuccess_expandSingleEvent() throws Exception {
persistResource(recurring);
action.cursorTimeParam = Optional.of(START_OF_TIME);
runMapreduce();
@@ -176,7 +173,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_expandSingleEvent_deletedDomain() throws Exception {
void testSuccess_expandSingleEvent_deletedDomain() throws Exception {
DateTime deletionTime = DateTime.parse("2000-08-01T00:00:00Z");
DomainBase deletedDomain = persistDeletedDomain("deleted.tld", deletionTime);
historyEntry = persistResource(new HistoryEntry.Builder().setParent(deletedDomain).build());
@@ -208,7 +205,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_expandSingleEvent_idempotentForDuplicateRuns() throws Exception {
void testSuccess_expandSingleEvent_idempotentForDuplicateRuns() throws Exception {
persistResource(recurring);
action.cursorTimeParam = Optional.of(START_OF_TIME);
runMapreduce();
@@ -225,7 +222,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_expandSingleEvent_idempotentForExistingOneTime() throws Exception {
void testSuccess_expandSingleEvent_idempotentForExistingOneTime() throws Exception {
persistResource(recurring);
BillingEvent.OneTime persisted = persistResource(defaultOneTimeBuilder()
.setParent(historyEntry)
@@ -240,8 +237,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_expandSingleEvent_notIdempotentForDifferentBillingTime()
throws Exception {
void testSuccess_expandSingleEvent_notIdempotentForDifferentBillingTime() throws Exception {
persistResource(recurring);
action.cursorTimeParam = Optional.of(START_OF_TIME);
runMapreduce();
@@ -259,8 +255,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_expandSingleEvent_notIdempotentForDifferentRecurring()
throws Exception {
void testSuccess_expandSingleEvent_notIdempotentForDifferentRecurring() throws Exception {
persistResource(recurring);
BillingEvent.Recurring recurring2 = persistResource(recurring.asBuilder()
.setId(3L)
@@ -289,7 +284,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_ignoreRecurringBeforeWindow() throws Exception {
void testSuccess_ignoreRecurringBeforeWindow() throws Exception {
recurring = persistResource(recurring.asBuilder()
.setEventTime(DateTime.parse("1997-01-05T00:00:00Z"))
.setRecurrenceEndTime(DateTime.parse("1999-10-05T00:00:00Z"))
@@ -303,7 +298,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_ignoreRecurringAfterWindow() throws Exception {
void testSuccess_ignoreRecurringAfterWindow() throws Exception {
recurring = persistResource(recurring.asBuilder()
.setEventTime(clock.nowUtc().plusYears(2))
.build());
@@ -315,7 +310,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_expandSingleEvent_billingTimeAtCursorTime() throws Exception {
void testSuccess_expandSingleEvent_billingTimeAtCursorTime() throws Exception {
persistResource(recurring);
action.cursorTimeParam = Optional.of(DateTime.parse("2000-02-19T00:00:00Z"));
runMapreduce();
@@ -328,8 +323,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_expandSingleEvent_cursorTimeBetweenEventAndBillingTime()
throws Exception {
void testSuccess_expandSingleEvent_cursorTimeBetweenEventAndBillingTime() throws Exception {
persistResource(recurring);
action.cursorTimeParam = Optional.of(DateTime.parse("2000-01-12T00:00:00Z"));
runMapreduce();
@@ -342,7 +336,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_expandSingleEvent_billingTimeAtExecutionTime() throws Exception {
void testSuccess_expandSingleEvent_billingTimeAtExecutionTime() throws Exception {
DateTime testTime = DateTime.parse("2000-02-19T00:00:00Z").minusMillis(1);
persistResource(recurring);
action.cursorTimeParam = Optional.of(START_OF_TIME);
@@ -359,7 +353,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_expandSingleEvent_multipleYearCreate() throws Exception {
void testSuccess_expandSingleEvent_multipleYearCreate() throws Exception {
DateTime testTime = beginningOfTest.plusYears(2);
action.cursorTimeParam = Optional.of(recurring.getEventTime());
recurring =
@@ -381,7 +375,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_expandSingleEvent_withCursor() throws Exception {
void testSuccess_expandSingleEvent_withCursor() throws Exception {
persistResource(recurring);
saveCursor(START_OF_TIME);
runMapreduce();
@@ -394,7 +388,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_expandSingleEvent_withCursorPastExpected() throws Exception {
void testSuccess_expandSingleEvent_withCursorPastExpected() throws Exception {
persistResource(recurring);
// Simulate a quick second run of the mapreduce (this should be a no-op).
saveCursor(clock.nowUtc().minusSeconds(1));
@@ -406,7 +400,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_expandSingleEvent_recurrenceEndBeforeEvent() throws Exception {
void testSuccess_expandSingleEvent_recurrenceEndBeforeEvent() throws Exception {
// This can occur when a domain is transferred or deleted before a domain comes up for renewal.
recurring = persistResource(recurring.asBuilder()
.setRecurrenceEndTime(recurring.getEventTime().minusDays(5))
@@ -420,7 +414,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_expandSingleEvent_dryRun() throws Exception {
void testSuccess_expandSingleEvent_dryRun() throws Exception {
persistResource(recurring);
action.isDryRun = true;
saveCursor(START_OF_TIME); // Need a saved cursor to verify that it didn't move.
@@ -432,7 +426,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_expandSingleEvent_multipleYears() throws Exception {
void testSuccess_expandSingleEvent_multipleYears() throws Exception {
DateTime testTime = clock.nowUtc().plusYears(5);
clock.setTo(testTime);
List<BillingEvent> expectedEvents = new ArrayList<>();
@@ -463,7 +457,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_expandSingleEvent_multipleYears_cursorInBetweenYears() throws Exception {
void testSuccess_expandSingleEvent_multipleYears_cursorInBetweenYears() throws Exception {
DateTime testTime = clock.nowUtc().plusYears(5);
clock.setTo(testTime);
List<BillingEvent> expectedEvents = new ArrayList<>();
@@ -492,7 +486,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_singleEvent_beforeRenewal() throws Exception {
void testSuccess_singleEvent_beforeRenewal() throws Exception {
DateTime testTime = DateTime.parse("2000-01-04T00:00:00Z");
clock.setTo(testTime);
persistResource(recurring);
@@ -505,7 +499,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_singleEvent_afterRecurrenceEnd_inAutorenewGracePeriod() throws Exception {
void testSuccess_singleEvent_afterRecurrenceEnd_inAutorenewGracePeriod() throws Exception {
// The domain creation date is 1999-01-05, and the first renewal date is thus 2000-01-05.
DateTime testTime = DateTime.parse("2001-02-06T00:00:00Z");
clock.setTo(testTime);
@@ -530,8 +524,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_singleEvent_afterRecurrenceEnd_outsideAutorenewGracePeriod()
throws Exception {
void testSuccess_singleEvent_afterRecurrenceEnd_outsideAutorenewGracePeriod() throws Exception {
// The domain creation date is 1999-01-05, and the first renewal date is thus 2000-01-05.
DateTime testTime = DateTime.parse("2001-02-06T00:00:00Z");
clock.setTo(testTime);
@@ -556,7 +549,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_expandSingleEvent_billingTimeOnLeapYear() throws Exception {
void testSuccess_expandSingleEvent_billingTimeOnLeapYear() throws Exception {
recurring =
persistResource(
recurring.asBuilder().setEventTime(DateTime.parse("2000-01-15T00:00:00Z")).build());
@@ -575,7 +568,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_expandSingleEvent_billingTimeNotOnLeapYear() throws Exception {
void testSuccess_expandSingleEvent_billingTimeNotOnLeapYear() throws Exception {
DateTime testTime = DateTime.parse("2001-12-01T00:00:00Z");
recurring =
persistResource(
@@ -597,7 +590,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_expandMultipleEvents() throws Exception {
void testSuccess_expandMultipleEvents() throws Exception {
persistResource(recurring);
BillingEvent.Recurring recurring2 = persistResource(recurring.asBuilder()
.setEventTime(recurring.getEventTime().plusMonths(3))
@@ -630,7 +623,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_premiumDomain() throws Exception {
void testSuccess_premiumDomain() throws Exception {
persistResource(
Registry.get("tld")
.asBuilder()
@@ -651,7 +644,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testSuccess_varyingRenewPrices() throws Exception {
void testSuccess_varyingRenewPrices() throws Exception {
DateTime testTime = beginningOfTest.plusYears(1);
persistResource(
Registry.get("tld")
@@ -691,7 +684,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testFailure_cursorAfterExecutionTime() {
void testFailure_cursorAfterExecutionTime() {
action.cursorTimeParam = Optional.of(clock.nowUtc().plusYears(1));
IllegalArgumentException thrown =
assertThrows(IllegalArgumentException.class, this::runMapreduce);
@@ -701,7 +694,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testFailure_cursorAtExecutionTime() {
void testFailure_cursorAtExecutionTime() {
// The clock advances one milli on runMapreduce.
action.cursorTimeParam = Optional.of(clock.nowUtc().plusMillis(1));
IllegalArgumentException thrown =
@@ -712,7 +705,7 @@ public class ExpandRecurringBillingEventsActionTest
}
@Test
public void testFailure_mapperException_doesNotMoveCursor() throws Exception {
void testFailure_mapperException_doesNotMoveCursor() throws Exception {
saveCursor(START_OF_TIME); // Need a saved cursor to verify that it didn't move.
// Set target to a TLD that doesn't exist.
recurring = persistResource(recurring.asBuilder().setTargetId("domain.junk").build());
@@ -61,27 +61,24 @@ import google.registry.util.SystemSleeper;
import java.util.Optional;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.Mock;
/** Unit tests for {@link RefreshDnsOnHostRenameAction}. */
@RunWith(JUnit4.class)
public class RefreshDnsOnHostRenameActionTest
extends MapreduceTestCase<RefreshDnsOnHostRenameAction> {
@Rule public final InjectRule inject = new InjectRule();
@RegisterExtension public final InjectRule inject = new InjectRule();
private AsyncTaskEnqueuer enqueuer;
private final FakeClock clock = new FakeClock(DateTime.parse("2015-01-15T11:22:33Z"));
private final FakeResponse fakeResponse = new FakeResponse();
@Mock private RequestStatusChecker requestStatusChecker;
@Before
public void setup() {
@BeforeEach
void beforeEach() {
createTld("tld");
enqueuer =
AsyncTaskEnqueuerTest.createForTesting(
@@ -124,7 +121,7 @@ public class RefreshDnsOnHostRenameActionTest
}
@Test
public void testSuccess_dnsUpdateEnqueued() throws Exception {
void testSuccess_dnsUpdateEnqueued() throws Exception {
HostResource host = persistActiveHost("ns1.example.tld");
persistResource(newDomainBase("example.tld", host));
persistResource(newDomainBase("otherexample.tld", host));
@@ -141,7 +138,7 @@ public class RefreshDnsOnHostRenameActionTest
}
@Test
public void testSuccess_multipleHostsProcessedInBatch() throws Exception {
void testSuccess_multipleHostsProcessedInBatch() throws Exception {
HostResource host1 = persistActiveHost("ns1.example.tld");
HostResource host2 = persistActiveHost("ns2.example.tld");
HostResource host3 = persistActiveHost("ns3.example.tld");
@@ -165,7 +162,7 @@ public class RefreshDnsOnHostRenameActionTest
}
@Test
public void testSuccess_deletedHost_doesntTriggerDnsRefresh() throws Exception {
void testSuccess_deletedHost_doesntTriggerDnsRefresh() throws Exception {
HostResource host = persistDeletedHost("ns11.fakesss.tld", clock.nowUtc().minusDays(4));
persistResource(newDomainBase("example1.tld", host));
DateTime timeEnqueued = clock.nowUtc();
@@ -180,7 +177,7 @@ public class RefreshDnsOnHostRenameActionTest
}
@Test
public void testSuccess_noDnsTasksForDeletedDomain() throws Exception {
void testSuccess_noDnsTasksForDeletedDomain() throws Exception {
HostResource renamedHost = persistActiveHost("ns1.example.tld");
persistResource(
newDomainBase("example.tld", renamedHost)
@@ -194,7 +191,7 @@ public class RefreshDnsOnHostRenameActionTest
}
@Test
public void testRun_hostDoesntExist_delaysTask() throws Exception {
void testRun_hostDoesntExist_delaysTask() throws Exception {
HostResource host = newHostResource("ns1.example.tld");
enqueuer.enqueueAsyncDnsRefresh(host, clock.nowUtc());
enqueueMapreduceOnly();
@@ -208,7 +205,7 @@ public class RefreshDnsOnHostRenameActionTest
}
@Test
public void test_cannotAcquireLock() {
void test_cannotAcquireLock() {
// Make lock acquisition fail.
acquireLock();
enqueueMapreduceOnly();
@@ -217,7 +214,7 @@ public class RefreshDnsOnHostRenameActionTest
}
@Test
public void test_mapreduceHasWorkToDo_lockIsAcquired() {
void test_mapreduceHasWorkToDo_lockIsAcquired() {
HostResource host = persistActiveHost("ns1.example.tld");
enqueuer.enqueueAsyncDnsRefresh(host, clock.nowUtc());
enqueueMapreduceOnly();
@@ -225,7 +222,7 @@ public class RefreshDnsOnHostRenameActionTest
}
@Test
public void test_noTasksToLease_releasesLockImmediately() throws Exception {
void test_noTasksToLease_releasesLockImmediately() throws Exception {
enqueueMapreduceOnly();
assertNoDnsTasksEnqueued();
assertNoTasksEnqueued(QUEUE_ASYNC_HOST_RENAME);
@@ -44,14 +44,11 @@ import google.registry.util.AppEngineServiceUtils;
import google.registry.util.StringGenerator.Alphabets;
import java.util.Optional;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link RelockDomainAction}. */
@RunWith(JUnit4.class)
public class RelockDomainActionTest {
private static final String DOMAIN_NAME = "example.tld";
@@ -67,7 +64,7 @@ public class RelockDomainActionTest {
AsyncTaskEnqueuerTest.createForTesting(
mock(AppEngineServiceUtils.class), clock, Duration.ZERO));
@Rule
@RegisterExtension
public final AppEngineRule appEngineRule =
AppEngineRule.builder()
.withDatastoreAndCloudSql()
@@ -78,8 +75,8 @@ public class RelockDomainActionTest {
private RegistryLock oldLock;
private RelockDomainAction action;
@Before
public void setup() {
@BeforeEach
void beforeEach() {
createTlds("tld", "net");
HostResource host = persistActiveHost("ns1.example.net");
domain = persistResource(newDomainBase(DOMAIN_NAME, host));
@@ -95,7 +92,7 @@ public class RelockDomainActionTest {
}
@Test
public void testLock() {
void testLock() {
action.run();
assertThat(reloadDomain(domain).getStatusValues())
.containsAtLeastElementsIn(REGISTRY_LOCK_STATUSES);
@@ -107,7 +104,7 @@ public class RelockDomainActionTest {
}
@Test
public void testFailure_unknownCode() {
void testFailure_unknownCode() {
action = createAction(12128675309L);
action.run();
assertThat(response.getStatus()).isEqualTo(SC_NO_CONTENT);
@@ -115,7 +112,7 @@ public class RelockDomainActionTest {
}
@Test
public void testFailure_pendingDelete() {
void testFailure_pendingDelete() {
persistResource(domain.asBuilder().setStatusValues(ImmutableSet.of(PENDING_DELETE)).build());
action.run();
assertThat(response.getStatus()).isEqualTo(SC_NO_CONTENT);
@@ -124,7 +121,7 @@ public class RelockDomainActionTest {
}
@Test
public void testFailure_pendingTransfer() {
void testFailure_pendingTransfer() {
persistResource(domain.asBuilder().setStatusValues(ImmutableSet.of(PENDING_TRANSFER)).build());
action.run();
assertThat(response.getStatus()).isEqualTo(SC_NO_CONTENT);
@@ -133,7 +130,7 @@ public class RelockDomainActionTest {
}
@Test
public void testFailure_domainAlreadyLocked() {
void testFailure_domainAlreadyLocked() {
domainLockUtils.administrativelyApplyLock(DOMAIN_NAME, CLIENT_ID, null, true);
action.run();
assertThat(response.getStatus()).isEqualTo(SC_NO_CONTENT);
@@ -142,7 +139,7 @@ public class RelockDomainActionTest {
}
@Test
public void testFailure_domainDeleted() {
void testFailure_domainDeleted() {
persistDomainAsDeleted(domain, clock.nowUtc());
action.run();
assertThat(response.getStatus()).isEqualTo(SC_NO_CONTENT);
@@ -151,7 +148,7 @@ public class RelockDomainActionTest {
}
@Test
public void testFailure_domainTransferred() {
void testFailure_domainTransferred() {
persistResource(domain.asBuilder().setPersistedCurrentSponsorClientId("NewRegistrar").build());
action.run();
assertThat(response.getStatus()).isEqualTo(SC_NO_CONTENT);
@@ -164,7 +161,7 @@ public class RelockDomainActionTest {
}
@Test
public void testFailure_relockAlreadySet() {
void testFailure_relockAlreadySet() {
RegistryLock newLock =
domainLockUtils.administrativelyApplyLock(DOMAIN_NAME, CLIENT_ID, null, true);
saveRegistryLock(oldLock.asBuilder().setRelock(newLock).build());
@@ -25,18 +25,14 @@ import google.registry.model.transfer.TransferStatus;
import google.registry.testing.FakeResponse;
import google.registry.testing.mapreduce.MapreduceTestCase;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link ResaveAllEppResourcesAction}. */
@RunWith(JUnit4.class)
public class ResaveAllEppResourcesActionTest
extends MapreduceTestCase<ResaveAllEppResourcesAction> {
class ResaveAllEppResourcesActionTest extends MapreduceTestCase<ResaveAllEppResourcesAction> {
@Before
public void init() {
@BeforeEach
void beforeEach() {
action = new ResaveAllEppResourcesAction();
action.mrRunner = makeDefaultRunner();
action.response = new FakeResponse();
@@ -48,7 +44,7 @@ public class ResaveAllEppResourcesActionTest
}
@Test
public void test_mapreduceSuccessfullyResavesEntity() throws Exception {
void test_mapreduceSuccessfullyResavesEntity() throws Exception {
ContactResource contact = persistActiveContact("test123");
DateTime creationTime = contact.getUpdateTimestamp().getTimestamp();
assertThat(ofy().load().entity(contact).now().getUpdateTimestamp().getTimestamp())
@@ -60,7 +56,7 @@ public class ResaveAllEppResourcesActionTest
}
@Test
public void test_mapreduceResolvesPendingTransfer() throws Exception {
void test_mapreduceResolvesPendingTransfer() throws Exception {
DateTime now = DateTime.now(UTC);
// Set up a contact with a transfer that implicitly completed five days ago.
ContactResource contact =
@@ -49,33 +49,32 @@ import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.util.AppEngineServiceUtils;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
/** Unit tests for {@link ResaveEntityAction}. */
@RunWith(JUnit4.class)
@ExtendWith(MockitoExtension.class)
public class ResaveEntityActionTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@Rule public final InjectRule inject = new InjectRule();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@RegisterExtension public final InjectRule inject = new InjectRule();
@Mock private AppEngineServiceUtils appEngineServiceUtils;
@Mock private Response response;
private final FakeClock clock = new FakeClock(DateTime.parse("2016-02-11T10:00:00Z"));
private AsyncTaskEnqueuer asyncTaskEnqueuer;
@Before
public void before() {
@BeforeEach
void beforeEach() {
inject.setStaticField(Ofy.class, "clock", clock);
when(appEngineServiceUtils.getServiceHostname("backend")).thenReturn("backend.hostname.fake");
asyncTaskEnqueuer =
@@ -93,8 +92,9 @@ public class ResaveEntityActionTest {
action.run();
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void test_domainPendingTransfer_isResavedAndTransferCompleted() {
void test_domainPendingTransfer_isResavedAndTransferCompleted() {
DomainBase domain =
persistDomainWithPendingTransfer(
persistDomainWithDependentResources(
@@ -116,7 +116,7 @@ public class ResaveEntityActionTest {
}
@Test
public void test_domainPendingDeletion_isResavedAndReenqueued() {
void test_domainPendingDeletion_isResavedAndReenqueued() {
DomainBase domain =
persistResource(
newDomainBase("domain.tld")
@@ -44,12 +44,10 @@ import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.RuleChain;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit test for {@link Transforms#writeToSql}. */
@RunWith(JUnit4.class)
public class WriteToSqlTest implements Serializable {
private static final DateTime START_TIME = DateTime.parse("2000-01-01T00:00:00.0Z");
private final FakeClock fakeClock = new FakeClock(START_TIME);
@@ -35,22 +35,18 @@ import java.io.StringWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for Dagger injection of the DNS package. */
@RunWith(JUnit4.class)
public final class DnsInjectionTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@Rule
public final InjectRule inject = new InjectRule();
@RegisterExtension public final InjectRule inject = new InjectRule();
private final HttpServletRequest req = mock(HttpServletRequest.class);
private final HttpServletResponse rsp = mock(HttpServletResponse.class);
@@ -59,8 +55,8 @@ public final class DnsInjectionTest {
private DnsTestComponent component;
private DnsQueue dnsQueue;
@Before
public void setUp() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
inject.setStaticField(Ofy.class, "clock", clock);
when(rsp.getWriter()).thenReturn(new PrintWriter(httpOutput));
component = DaggerDnsTestComponent.builder()
@@ -71,7 +67,7 @@ public final class DnsInjectionTest {
}
@Test
public void testReadDnsQueueAction_injectsAndWorks() {
void testReadDnsQueueAction_injectsAndWorks() {
persistActiveSubordinateHost("ns1.example.lol", persistActiveDomain("example.lol"));
clock.advanceOneMilli();
dnsQueue.addDomainRefreshTask("example.lol");
@@ -81,7 +77,7 @@ public final class DnsInjectionTest {
}
@Test
public void testRefreshDns_domain_injectsAndWorks() {
void testRefreshDns_domain_injectsAndWorks() {
persistActiveDomain("example.lol");
when(req.getParameter("type")).thenReturn("domain");
when(req.getParameter("name")).thenReturn("example.lol");
@@ -90,7 +86,7 @@ public final class DnsInjectionTest {
}
@Test
public void testRefreshDns_missingDomain_throwsNotFound() {
void testRefreshDns_missingDomain_throwsNotFound() {
when(req.getParameter("type")).thenReturn("domain");
when(req.getParameter("name")).thenReturn("example.lol");
NotFoundException thrown =
@@ -99,7 +95,7 @@ public final class DnsInjectionTest {
}
@Test
public void testRefreshDns_host_injectsAndWorks() {
void testRefreshDns_host_injectsAndWorks() {
persistActiveSubordinateHost("ns1.example.lol", persistActiveDomain("example.lol"));
when(req.getParameter("type")).thenReturn("host");
when(req.getParameter("name")).thenReturn("ns1.example.lol");
@@ -108,7 +104,7 @@ public final class DnsInjectionTest {
}
@Test
public void testRefreshDns_missingHost_throwsNotFound() {
void testRefreshDns_missingHost_throwsNotFound() {
when(req.getParameter("type")).thenReturn("host");
when(req.getParameter("name")).thenReturn("ns1.example.lol");
NotFoundException thrown =
@@ -24,31 +24,28 @@ import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock;
import google.registry.testing.TaskQueueHelper.TaskMatcher;
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.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link DnsQueue}. */
@RunWith(JUnit4.class)
public class DnsQueueTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
private DnsQueue dnsQueue;
private final FakeClock clock = new FakeClock(DateTime.parse("2010-01-01T10:00:00Z"));
@Before
public void init() {
@BeforeEach
void beforeEach() {
dnsQueue = DnsQueue.createForTesting(clock);
dnsQueue.leaseTasksBatchSize = 10;
}
@Test
public void test_addHostRefreshTask_success() {
void test_addHostRefreshTask_success() {
createTld("tld");
dnsQueue.addHostRefreshTask("octopus.tld");
assertTasksEnqueued(
@@ -61,7 +58,7 @@ public class DnsQueueTest {
}
@Test
public void test_addHostRefreshTask_failsOnUnknownTld() {
void test_addHostRefreshTask_failsOnUnknownTld() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -78,7 +75,7 @@ public class DnsQueueTest {
}
@Test
public void test_addDomainRefreshTask_success() {
void test_addDomainRefreshTask_success() {
createTld("tld");
dnsQueue.addDomainRefreshTask("octopus.tld");
assertTasksEnqueued(
@@ -91,7 +88,7 @@ public class DnsQueueTest {
}
@Test
public void test_addDomainRefreshTask_failsOnUnknownTld() {
void test_addDomainRefreshTask_failsOnUnknownTld() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -44,22 +44,18 @@ import google.registry.testing.FakeLockHandler;
import google.registry.testing.InjectRule;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link PublishDnsUpdatesAction}. */
@RunWith(JUnit4.class)
public class PublishDnsUpdatesActionTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@Rule
public final InjectRule inject = new InjectRule();
@RegisterExtension public final InjectRule inject = new InjectRule();
private final FakeClock clock = new FakeClock(DateTime.parse("1971-01-01TZ"));
private final FakeLockHandler lockHandler = new FakeLockHandler(true);
private final DnsWriter dnsWriter = mock(DnsWriter.class);
@@ -67,8 +63,8 @@ public class PublishDnsUpdatesActionTest {
private final DnsQueue dnsQueue = mock(DnsQueue.class);
private PublishDnsUpdatesAction action;
@Before
public void setUp() {
@BeforeEach
void beforeEach() {
inject.setStaticField(Ofy.class, "clock", clock);
createTld("xn--q9jyb4c");
persistResource(
@@ -104,7 +100,7 @@ public class PublishDnsUpdatesActionTest {
}
@Test
public void testHost_published() {
void testHost_published() {
action = createAction("xn--q9jyb4c");
action.hosts = ImmutableSet.of("ns1.example.xn--q9jyb4c");
@@ -132,7 +128,7 @@ public class PublishDnsUpdatesActionTest {
}
@Test
public void testDomain_published() {
void testDomain_published() {
action = createAction("xn--q9jyb4c");
action.domains = ImmutableSet.of("example.xn--q9jyb4c");
@@ -160,7 +156,7 @@ public class PublishDnsUpdatesActionTest {
}
@Test
public void testAction_acquiresCorrectLock() {
void testAction_acquiresCorrectLock() {
persistResource(Registry.get("xn--q9jyb4c").asBuilder().setNumDnsPublishLocks(4).build());
action = createAction("xn--q9jyb4c");
action.lockIndex = 2;
@@ -178,7 +174,7 @@ public class PublishDnsUpdatesActionTest {
}
@Test
public void testPublish_commitFails() {
void testPublish_commitFails() {
action = createAction("xn--q9jyb4c");
action.domains = ImmutableSet.of("example.xn--q9jyb4c", "example2.xn--q9jyb4c");
action.hosts =
@@ -207,11 +203,12 @@ public class PublishDnsUpdatesActionTest {
}
@Test
public void testHostAndDomain_published() {
void testHostAndDomain_published() {
action = createAction("xn--q9jyb4c");
action.domains = ImmutableSet.of("example.xn--q9jyb4c", "example2.xn--q9jyb4c");
action.hosts = ImmutableSet.of(
"ns1.example.xn--q9jyb4c", "ns2.example.xn--q9jyb4c", "ns1.example2.xn--q9jyb4c");
action.hosts =
ImmutableSet.of(
"ns1.example.xn--q9jyb4c", "ns2.example.xn--q9jyb4c", "ns1.example2.xn--q9jyb4c");
action.run();
@@ -241,7 +238,7 @@ public class PublishDnsUpdatesActionTest {
}
@Test
public void testWrongTld_notPublished() {
void testWrongTld_notPublished() {
action = createAction("xn--q9jyb4c");
action.domains = ImmutableSet.of("example.com", "example2.com");
action.hosts = ImmutableSet.of("ns1.example.com", "ns2.example.com", "ns1.example2.com");
@@ -269,7 +266,7 @@ public class PublishDnsUpdatesActionTest {
}
@Test
public void testLockIsntAvailable() {
void testLockIsntAvailable() {
action = createAction("xn--q9jyb4c");
action.domains = ImmutableSet.of("example.com", "example2.com");
action.hosts = ImmutableSet.of("ns1.example.com", "ns2.example.com", "ns1.example2.com");
@@ -293,7 +290,7 @@ public class PublishDnsUpdatesActionTest {
}
@Test
public void testParam_invalidLockIndex() {
void testParam_invalidLockIndex() {
persistResource(Registry.get("xn--q9jyb4c").asBuilder().setNumDnsPublishLocks(4).build());
action = createAction("xn--q9jyb4c");
action.domains = ImmutableSet.of("example.com");
@@ -319,7 +316,7 @@ public class PublishDnsUpdatesActionTest {
}
@Test
public void testRegistryParam_mismatchedMaxLocks() {
void testRegistryParam_mismatchedMaxLocks() {
persistResource(Registry.get("xn--q9jyb4c").asBuilder().setNumDnsPublishLocks(4).build());
action = createAction("xn--q9jyb4c");
action.domains = ImmutableSet.of("example.com");
@@ -345,7 +342,7 @@ public class PublishDnsUpdatesActionTest {
}
@Test
public void testWrongDnsWriter() {
void testWrongDnsWriter() {
action = createAction("xn--q9jyb4c");
action.domains = ImmutableSet.of("example.com", "example2.com");
action.hosts = ImmutableSet.of("ns1.example.com", "ns2.example.com", "ns1.example2.com");
@@ -56,14 +56,11 @@ import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link ReadDnsQueueAction}. */
@RunWith(JUnit4.class)
public class ReadDnsQueueActionTest {
private static final int TEST_TLD_UPDATE_BATCH_SIZE = 100;
@@ -72,7 +69,7 @@ public class ReadDnsQueueActionTest {
// test in the future. Set to year 3000 so it'll remain in the future for a very long time.
private FakeClock clock = new FakeClock(DateTime.parse("3000-01-01TZ"));
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder()
.withDatastoreAndCloudSql()
@@ -93,8 +90,8 @@ public class ReadDnsQueueActionTest {
.withClock(clock)
.build();
@Before
public void before() {
@BeforeEach
void beforeEach() {
// Because of b/73372999 - the FakeClock can't be in the past, or the TaskQueues stop working.
// To make sure it's never in the past, we set the date far-far into the future
clock.setTo(DateTime.parse("3000-01-01TZ"));
@@ -171,7 +168,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_methodPostIsDefault() {
void testSuccess_methodPostIsDefault() {
dnsQueue.addDomainRefreshTask("domain.com");
dnsQueue.addDomainRefreshTask("domain.net");
dnsQueue.addDomainRefreshTask("domain.example");
@@ -187,7 +184,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_allSingleLockTlds() {
void testSuccess_allSingleLockTlds() {
dnsQueue.addDomainRefreshTask("domain.com");
dnsQueue.addDomainRefreshTask("domain.net");
dnsQueue.addDomainRefreshTask("domain.example");
@@ -200,7 +197,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_moreUpdatesThanQueueBatchSize() {
void testSuccess_moreUpdatesThanQueueBatchSize() {
// The task queue has a batch size of 1000 (that's the maximum number of items you can lease at
// once).
ImmutableList<String> domains =
@@ -219,15 +216,14 @@ public class ReadDnsQueueActionTest {
assertThat(queuedParams).hasSize(15);
// Check all the expected domains are indeed enqueued
assertThat(
queuedParams
.stream()
queuedParams.stream()
.map(params -> params.get("domains").stream().collect(onlyElement()))
.flatMap(values -> Splitter.on(',').splitToList(values).stream()))
.containsExactlyElementsIn(domains);
}
@Test
public void testSuccess_twoDnsWriters() {
void testSuccess_twoDnsWriters() {
persistResource(
Registry.get("com")
.asBuilder()
@@ -242,7 +238,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_differentUpdateTimes_usesMinimum() {
void testSuccess_differentUpdateTimes_usesMinimum() {
clock.setTo(DateTime.parse("3000-02-03TZ"));
dnsQueue.addDomainRefreshTask("domain1.com");
clock.setTo(DateTime.parse("3000-02-04TZ"));
@@ -256,18 +252,18 @@ public class ReadDnsQueueActionTest {
assertThat(getQueuedParams(DNS_PUBLISH_PUSH_QUEUE_NAME)).hasSize(1);
assertThat(getQueuedParams(DNS_PUBLISH_PUSH_QUEUE_NAME).get(0))
.containsExactly(
"enqueued", "3000-02-05T01:00:00.000Z",
"itemsCreated", "3000-02-03T00:00:00.000Z",
"tld", "com",
"dnsWriter", "comWriter",
"domains", "domain1.com,domain2.com,domain3.com",
"hosts", "",
"lockIndex", "1",
"numPublishLocks", "1");
"enqueued", "3000-02-05T01:00:00.000Z",
"itemsCreated", "3000-02-03T00:00:00.000Z",
"tld", "com",
"dnsWriter", "comWriter",
"domains", "domain1.com,domain2.com,domain3.com",
"hosts", "",
"lockIndex", "1",
"numPublishLocks", "1");
}
@Test
public void testSuccess_oneTldPaused_returnedToQueue() {
void testSuccess_oneTldPaused_returnedToQueue() {
persistResource(Registry.get("net").asBuilder().setDnsPaused(true).build());
dnsQueue.addDomainRefreshTask("domain.com");
dnsQueue.addDomainRefreshTask("domain.net");
@@ -281,7 +277,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_oneTldUnknown_returnedToQueue() {
void testSuccess_oneTldUnknown_returnedToQueue() {
dnsQueue.addDomainRefreshTask("domain.com");
dnsQueue.addDomainRefreshTask("domain.example");
QueueFactory.getQueue(DNS_PULL_QUEUE_NAME)
@@ -301,7 +297,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_corruptTaskTldMismatch_published() {
void testSuccess_corruptTaskTldMismatch_published() {
// TODO(mcilwain): what's the correct action to take in this case?
dnsQueue.addDomainRefreshTask("domain.com");
dnsQueue.addDomainRefreshTask("domain.example");
@@ -322,7 +318,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_corruptTaskNoTld_discarded() {
void testSuccess_corruptTaskNoTld_discarded() {
dnsQueue.addDomainRefreshTask("domain.com");
dnsQueue.addDomainRefreshTask("domain.example");
QueueFactory.getQueue(DNS_PULL_QUEUE_NAME)
@@ -341,7 +337,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_corruptTaskNoName_discarded() {
void testSuccess_corruptTaskNoName_discarded() {
dnsQueue.addDomainRefreshTask("domain.com");
dnsQueue.addDomainRefreshTask("domain.example");
QueueFactory.getQueue(DNS_PULL_QUEUE_NAME)
@@ -360,7 +356,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_corruptTaskNoType_discarded() {
void testSuccess_corruptTaskNoType_discarded() {
dnsQueue.addDomainRefreshTask("domain.com");
dnsQueue.addDomainRefreshTask("domain.example");
QueueFactory.getQueue(DNS_PULL_QUEUE_NAME)
@@ -379,7 +375,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_corruptTaskWrongType_discarded() {
void testSuccess_corruptTaskWrongType_discarded() {
dnsQueue.addDomainRefreshTask("domain.com");
dnsQueue.addDomainRefreshTask("domain.example");
QueueFactory.getQueue(DNS_PULL_QUEUE_NAME)
@@ -399,7 +395,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_zone_getsIgnored() {
void testSuccess_zone_getsIgnored() {
dnsQueue.addHostRefreshTask("ns1.domain.com");
dnsQueue.addDomainRefreshTask("domain.net");
dnsQueue.addZoneRefreshTask("example");
@@ -420,7 +416,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_manyDomainsAndHosts() {
void testSuccess_manyDomainsAndHosts() {
for (int i = 0; i < 150; i++) {
// 0: domain; 1: host 1; 2: host 2
for (int thingType = 0; thingType < 3; thingType++) {
@@ -491,7 +487,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_lockGroupsHostBySuperordinateDomain() {
void testSuccess_lockGroupsHostBySuperordinateDomain() {
dnsQueue.addDomainRefreshTask("hello.multilock.uk");
dnsQueue.addHostRefreshTask("ns1.abc.hello.multilock.uk");
dnsQueue.addHostRefreshTask("ns2.hello.multilock.uk");
@@ -30,17 +30,14 @@ import google.registry.request.HttpException.BadRequestException;
import google.registry.request.HttpException.NotFoundException;
import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link RefreshDnsAction}. */
@RunWith(JUnit4.class)
public class RefreshDnsActionTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@@ -51,13 +48,13 @@ public class RefreshDnsActionTest {
new RefreshDnsAction(name, type, clock, dnsQueue).run();
}
@Before
public void before() {
@BeforeEach
void beforeEach() {
createTld("xn--q9jyb4c");
}
@Test
public void testSuccess_host() {
void testSuccess_host() {
DomainBase domain = persistActiveDomain("example.xn--q9jyb4c");
persistActiveSubordinateHost("ns1.example.xn--q9jyb4c", domain);
run(TargetType.HOST, "ns1.example.xn--q9jyb4c");
@@ -66,7 +63,7 @@ public class RefreshDnsActionTest {
}
@Test
public void testSuccess_externalHostNotEnqueued() {
void testSuccess_externalHostNotEnqueued() {
persistActiveDomain("example.xn--q9jyb4c");
persistActiveHost("ns1.example.xn--q9jyb4c");
BadRequestException thrown =
@@ -85,7 +82,7 @@ public class RefreshDnsActionTest {
}
@Test
public void testSuccess_domain() {
void testSuccess_domain() {
persistActiveDomain("example.xn--q9jyb4c");
run(TargetType.DOMAIN, "example.xn--q9jyb4c");
verify(dnsQueue).addDomainRefreshTask("example.xn--q9jyb4c");
@@ -93,17 +90,17 @@ public class RefreshDnsActionTest {
}
@Test
public void testFailure_unqualifiedName() {
void testFailure_unqualifiedName() {
assertThrows(BadRequestException.class, () -> run(TargetType.DOMAIN, "example"));
}
@Test
public void testFailure_hostDoesNotExist() {
void testFailure_hostDoesNotExist() {
assertThrows(NotFoundException.class, () -> run(TargetType.HOST, "ns1.example.xn--q9jyb4c"));
}
@Test
public void testFailure_domainDoesNotExist() {
void testFailure_domainDoesNotExist() {
assertThrows(NotFoundException.class, () -> run(TargetType.DOMAIN, "example.xn--q9jyb4c"));
}
}
@@ -17,13 +17,10 @@ package google.registry.dns.writer;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link BaseDnsWriter}. */
@RunWith(JUnit4.class)
public class BaseDnsWriterTest {
class BaseDnsWriterTest {
static class StubDnsWriter extends BaseDnsWriter {
@@ -46,7 +43,7 @@ public class BaseDnsWriterTest {
}
@Test
public void test_cannotBeCalledTwice() {
void test_cannotBeCalledTwice() {
StubDnsWriter writer = new StubDnsWriter();
assertThat(writer.commitCallCount).isEqualTo(0);
writer.commit();
@@ -53,27 +53,25 @@ import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
/** Test case for {@link CloudDnsWriter}. */
@RunWith(JUnit4.class)
@ExtendWith(MockitoExtension.class)
public class CloudDnsWriterTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
private static final Inet4Address IPv4 = (Inet4Address) InetAddresses.forString("127.0.0.1");
private static final Inet6Address IPv6 = (Inet6Address) InetAddresses.forString("::1");
private static final Duration DEFAULT_A_TTL = Duration.standardSeconds(11);
@@ -116,8 +114,8 @@ public class CloudDnsWriterTest {
return listResourceRecordSetsRequest;
}
@Before
public void setUp() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
createTld("tld");
writer =
new CloudDnsWriter(
@@ -312,15 +310,17 @@ public class CloudDnsWriterTest {
.build();
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testLoadDomain_nonExistentDomain() {
void testLoadDomain_nonExistentDomain() {
writer.publishDomain("example.tld");
verifyZone(ImmutableSet.of());
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testLoadDomain_noDsDataOrNameservers() {
void testLoadDomain_noDsDataOrNameservers() {
persistResource(fakeDomain("example.tld", ImmutableSet.of(), 0));
writer.publishDomain("example.tld");
@@ -328,7 +328,7 @@ public class CloudDnsWriterTest {
}
@Test
public void testLoadDomain_deleteOldData() {
void testLoadDomain_deleteOldData() {
stubZone = fakeDomainRecords("example.tld", 2, 2, 2, 2);
persistResource(fakeDomain("example.tld", ImmutableSet.of(), 0));
writer.publishDomain("example.tld");
@@ -337,7 +337,7 @@ public class CloudDnsWriterTest {
}
@Test
public void testLoadDomain_withExternalNs() {
void testLoadDomain_withExternalNs() {
persistResource(
fakeDomain("example.tld", ImmutableSet.of(persistResource(fakeHost("0.external"))), 0));
writer.publishDomain("example.tld");
@@ -346,7 +346,7 @@ public class CloudDnsWriterTest {
}
@Test
public void testLoadDomain_withDsData() {
void testLoadDomain_withDsData() {
persistResource(
fakeDomain("example.tld", ImmutableSet.of(persistResource(fakeHost("0.external"))), 1));
writer.publishDomain("example.tld");
@@ -355,7 +355,7 @@ public class CloudDnsWriterTest {
}
@Test
public void testLoadDomain_withInBailiwickNs_IPv4() {
void testLoadDomain_withInBailiwickNs_IPv4() {
persistResource(
fakeDomain(
"example.tld",
@@ -370,7 +370,7 @@ public class CloudDnsWriterTest {
}
@Test
public void testLoadDomain_withInBailiwickNs_IPv6() {
void testLoadDomain_withInBailiwickNs_IPv6() {
persistResource(
fakeDomain(
"example.tld",
@@ -385,7 +385,7 @@ public class CloudDnsWriterTest {
}
@Test
public void testLoadDomain_withNameserveThatEndsWithDomainName() {
void testLoadDomain_withNameserveThatEndsWithDomainName() {
persistResource(
fakeDomain(
"example.tld",
@@ -396,8 +396,9 @@ public class CloudDnsWriterTest {
verifyZone(fakeDomainRecords("example.tld", "ns.another-example.tld."));
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testLoadHost_externalHost() {
void testLoadHost_externalHost() {
writer.publishHost("ns1.example.com");
// external hosts should not be published in our zone
@@ -405,7 +406,7 @@ public class CloudDnsWriterTest {
}
@Test
public void testLoadHost_removeStaleNsRecords() {
void testLoadHost_removeStaleNsRecords() {
// Initialize the zone with both NS records
stubZone = fakeDomainRecords("example.tld", 2, 0, 0, 0);
@@ -426,8 +427,9 @@ public class CloudDnsWriterTest {
verifyZone(fakeDomainRecords("example.tld", 1, 0, 0, 0));
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void retryMutateZoneOnError() {
void retryMutateZoneOnError() {
CloudDnsWriter spyWriter = spy(writer);
// First call - throw. Second call - do nothing.
doThrow(ZoneStateException.class)
@@ -439,8 +441,9 @@ public class CloudDnsWriterTest {
verify(spyWriter, times(2)).mutateZone(ArgumentMatchers.any());
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testLoadDomain_withClientHold() {
void testLoadDomain_withClientHold() {
persistResource(
fakeDomain(
"example.tld",
@@ -454,8 +457,9 @@ public class CloudDnsWriterTest {
verifyZone(ImmutableSet.of());
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testLoadDomain_withServerHold() {
void testLoadDomain_withServerHold() {
persistResource(
fakeDomain(
"example.tld",
@@ -470,8 +474,9 @@ public class CloudDnsWriterTest {
verifyZone(ImmutableSet.of());
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testLoadDomain_withPendingDelete() {
void testLoadDomain_withPendingDelete() {
persistResource(
fakeDomain(
"example.tld",
@@ -486,7 +491,7 @@ public class CloudDnsWriterTest {
}
@Test
public void testDuplicateRecords() {
void testDuplicateRecords() {
// In publishing DNS records, we can end up publishing information on the same host twice
// (through a domain change and a host change), so this scenario needs to work.
persistResource(
@@ -504,7 +509,7 @@ public class CloudDnsWriterTest {
}
@Test
public void testInvalidZoneNames() {
void testInvalidZoneNames() {
createTld("triple.secret.tld");
persistResource(
fakeDomain(
@@ -518,8 +523,9 @@ public class CloudDnsWriterTest {
assertThat(zoneNameCaptor.getValue()).isEqualTo("triple-secret-tld");
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testEmptyCommit() {
void testEmptyCommit() {
writer.commit();
verify(dnsConnection, times(0)).changes();
}
@@ -33,10 +33,8 @@ import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.net.SocketFactory;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.xbill.DNS.ARecord;
import org.xbill.DNS.DClass;
import org.xbill.DNS.Flags;
@@ -49,8 +47,7 @@ import org.xbill.DNS.Type;
import org.xbill.DNS.Update;
/** Unit tests for {@link DnsMessageTransport}. */
@RunWith(JUnit4.class)
public class DnsMessageTransportTest {
class DnsMessageTransportTest {
private static final String UPDATE_HOST = "127.0.0.1";
@@ -60,8 +57,9 @@ public class DnsMessageTransportTest {
private Message simpleQuery;
private Message expectedResponse;
private DnsMessageTransport resolver;
@Before
public void before() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
simpleQuery =
Message.newQuery(Record.newRecord(Name.fromString("example.com."), Type.A, DClass.IN));
expectedResponse = responseMessageWithCode(simpleQuery, Rcode.NOERROR);
@@ -71,7 +69,7 @@ public class DnsMessageTransportTest {
}
@Test
public void testSentMessageHasCorrectLengthAndContent() throws Exception {
void testSentMessageHasCorrectLengthAndContent() throws Exception {
ByteArrayInputStream inputStream =
new ByteArrayInputStream(messageToBytesWithLength(expectedResponse));
when(mockSocket.getInputStream()).thenReturn(inputStream);
@@ -89,7 +87,7 @@ public class DnsMessageTransportTest {
}
@Test
public void testReceivedMessageWithLengthHasCorrectContent() throws Exception {
void testReceivedMessageWithLengthHasCorrectContent() throws Exception {
ByteArrayInputStream inputStream =
new ByteArrayInputStream(messageToBytesWithLength(expectedResponse));
when(mockSocket.getInputStream()).thenReturn(inputStream);
@@ -102,7 +100,7 @@ public class DnsMessageTransportTest {
}
@Test
public void testEofReceivingResponse() throws Exception {
void testEofReceivingResponse() throws Exception {
byte[] messageBytes = messageToBytesWithLength(expectedResponse);
ByteArrayInputStream inputStream =
new ByteArrayInputStream(Arrays.copyOf(messageBytes, messageBytes.length - 1));
@@ -112,7 +110,7 @@ public class DnsMessageTransportTest {
}
@Test
public void testTimeoutReceivingResponse() throws Exception {
void testTimeoutReceivingResponse() throws Exception {
InputStream mockInputStream = mock(InputStream.class);
when(mockInputStream.read()).thenThrow(new SocketTimeoutException("testing"));
when(mockSocket.getInputStream()).thenReturn(mockInputStream);
@@ -126,7 +124,7 @@ public class DnsMessageTransportTest {
}
@Test
public void testSentMessageTooLongThrowsException() throws Exception {
void testSentMessageTooLongThrowsException() throws Exception {
Update oversize = new Update(Name.fromString("tld", Name.root));
for (int i = 0; i < 2000; i++) {
oversize.add(
@@ -143,7 +141,7 @@ public class DnsMessageTransportTest {
}
@Test
public void testResponseIdMismatchThrowsExeption() throws Exception {
void testResponseIdMismatchThrowsExeption() throws Exception {
expectedResponse.getHeader().setID(1 + simpleQuery.getHeader().getID());
when(mockSocket.getInputStream())
.thenReturn(new ByteArrayInputStream(messageToBytesWithLength(expectedResponse)));
@@ -159,7 +157,7 @@ public class DnsMessageTransportTest {
}
@Test
public void testResponseOpcodeMismatchThrowsException() throws Exception {
void testResponseOpcodeMismatchThrowsException() throws Exception {
simpleQuery.getHeader().setOpcode(Opcode.QUERY);
expectedResponse.getHeader().setOpcode(Opcode.STATUS);
when(mockSocket.getInputStream())
@@ -29,7 +29,7 @@ import static google.registry.testing.DatastoreHelper.persistResource;
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import com.google.common.base.VerifyException;
@@ -49,16 +49,16 @@ import java.util.Collections;
import java.util.Iterator;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.xbill.DNS.Flags;
import org.xbill.DNS.Message;
import org.xbill.DNS.Opcode;
@@ -70,15 +70,14 @@ import org.xbill.DNS.Type;
import org.xbill.DNS.Update;
/** Unit tests for {@link DnsUpdateWriter}. */
@RunWith(JUnit4.class)
@ExtendWith(MockitoExtension.class)
public class DnsUpdateWriterTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@Rule public final InjectRule inject = new InjectRule();
@RegisterExtension public final InjectRule inject = new InjectRule();
@Mock private DnsMessageTransport mockResolver;
@Captor private ArgumentCaptor<Update> updateCaptor;
@@ -87,8 +86,8 @@ public class DnsUpdateWriterTest {
private DnsUpdateWriter writer;
@Before
public void setUp() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
inject.setStaticField(Ofy.class, "clock", clock);
createTld("tld");
@@ -99,7 +98,7 @@ public class DnsUpdateWriterTest {
}
@Test
public void testPublishDomainCreate_publishesNameServers() throws Exception {
void testPublishDomainCreate_publishesNameServers() throws Exception {
HostResource host1 = persistActiveHost("ns1.example.tld");
HostResource host2 = persistActiveHost("ns2.example.tld");
DomainBase domain =
@@ -120,8 +119,9 @@ public class DnsUpdateWriterTest {
assertThatTotalUpdateSetsIs(update, 2); // The delete and NS sets
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testPublishAtomic_noCommit() {
void testPublishAtomic_noCommit() {
HostResource host1 = persistActiveHost("ns.example1.tld");
DomainBase domain1 =
persistActiveDomain("example1.tld")
@@ -141,11 +141,11 @@ public class DnsUpdateWriterTest {
writer.publishDomain("example1.tld");
writer.publishDomain("example2.tld");
verifyZeroInteractions(mockResolver);
verifyNoInteractions(mockResolver);
}
@Test
public void testPublishAtomic_oneUpdate() throws Exception {
void testPublishAtomic_oneUpdate() throws Exception {
HostResource host1 = persistActiveHost("ns.example1.tld");
DomainBase domain1 =
persistActiveDomain("example1.tld")
@@ -177,7 +177,7 @@ public class DnsUpdateWriterTest {
}
@Test
public void testPublishDomainCreate_publishesDelegationSigner() throws Exception {
void testPublishDomainCreate_publishesDelegationSigner() throws Exception {
DomainBase domain =
persistActiveDomain("example.tld")
.asBuilder()
@@ -201,7 +201,7 @@ public class DnsUpdateWriterTest {
}
@Test
public void testPublishDomainWhenNotActive_removesDnsRecords() throws Exception {
void testPublishDomainWhenNotActive_removesDnsRecords() throws Exception {
DomainBase domain =
persistActiveDomain("example.tld")
.asBuilder()
@@ -221,7 +221,7 @@ public class DnsUpdateWriterTest {
}
@Test
public void testPublishDomainDelete_removesDnsRecords() throws Exception {
void testPublishDomainDelete_removesDnsRecords() throws Exception {
persistDeletedDomain("example.tld", clock.nowUtc().minusDays(1));
writer.publishDomain("example.tld");
@@ -235,7 +235,7 @@ public class DnsUpdateWriterTest {
}
@Test
public void testPublishHostCreate_publishesAddressRecords() throws Exception {
void testPublishHostCreate_publishesAddressRecords() throws Exception {
HostResource host =
persistResource(
newHostResource("ns1.example.tld")
@@ -268,7 +268,7 @@ public class DnsUpdateWriterTest {
}
@Test
public void testPublishHostDelete_removesDnsRecords() throws Exception {
void testPublishHostDelete_removesDnsRecords() throws Exception {
persistDeletedHost("ns1.example.tld", clock.nowUtc().minusDays(1));
persistActiveDomain("example.tld");
@@ -284,7 +284,7 @@ public class DnsUpdateWriterTest {
}
@Test
public void testPublishHostDelete_removesGlueRecords() throws Exception {
void testPublishHostDelete_removesGlueRecords() throws Exception {
persistDeletedHost("ns1.example.tld", clock.nowUtc().minusDays(1));
persistResource(
persistActiveDomain("example.tld")
@@ -305,7 +305,7 @@ public class DnsUpdateWriterTest {
}
@Test
public void testPublishDomainExternalAndInBailiwickNameServer() throws Exception {
void testPublishDomainExternalAndInBailiwickNameServer() throws Exception {
HostResource externalNameserver = persistResource(newHostResource("ns1.example.com"));
HostResource inBailiwickNameserver =
persistResource(
@@ -342,7 +342,7 @@ public class DnsUpdateWriterTest {
}
@Test
public void testPublishDomainDeleteOrphanGlues() throws Exception {
void testPublishDomainDeleteOrphanGlues() throws Exception {
HostResource inBailiwickNameserver =
persistResource(
newHostResource("ns1.example.tld")
@@ -377,9 +377,10 @@ public class DnsUpdateWriterTest {
assertThatTotalUpdateSetsIs(update, 6);
}
@Test
@MockitoSettings(strictness = Strictness.LENIENT)
@SuppressWarnings("AssertThrowsMultipleStatements")
public void testPublishDomainFails_whenDnsUpdateReturnsError() throws Exception {
@Test
void testPublishDomainFails_whenDnsUpdateReturnsError() throws Exception {
DomainBase domain =
persistActiveDomain("example.tld")
.asBuilder()
@@ -397,9 +398,10 @@ public class DnsUpdateWriterTest {
assertThat(thrown).hasMessageThat().contains("SERVFAIL");
}
@Test
@MockitoSettings(strictness = Strictness.LENIENT)
@SuppressWarnings("AssertThrowsMultipleStatements")
public void testPublishHostFails_whenDnsUpdateReturnsError() throws Exception {
@Test
void testPublishHostFails_whenDnsUpdateReturnsError() throws Exception {
HostResource host =
persistActiveSubordinateHost("ns1.example.tld", persistActiveDomain("example.tld"))
.asBuilder()
@@ -27,21 +27,19 @@ import google.registry.export.datastore.Operation;
import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeResponse;
import google.registry.testing.TaskQueueHelper.TaskMatcher;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.junit.jupiter.MockitoExtension;
/** Unit tests for {@link BackupDatastoreAction}. */
@RunWith(JUnit4.class)
@ExtendWith(MockitoExtension.class)
public class BackupDatastoreActionTest {
@Rule public final AppEngineRule appEngine = AppEngineRule.builder().withTaskQueue().build();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withTaskQueue().build();
@Mock private DatastoreAdmin datastoreAdmin;
@Mock private Export exportRequest;
@@ -50,8 +48,8 @@ public class BackupDatastoreActionTest {
private final FakeResponse response = new FakeResponse();
private final BackupDatastoreAction action = new BackupDatastoreAction();
@Before
public void before() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
action.datastoreAdmin = datastoreAdmin;
action.response = response;
@@ -66,7 +64,7 @@ public class BackupDatastoreActionTest {
}
@Test
public void testBackup_enqueuesPollTask() {
void testBackup_enqueuesPollTask() {
action.run();
assertTasksEnqueued(
CheckBackupAction.QUEUE,
@@ -52,17 +52,14 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link BigqueryPollJobAction}. */
@RunWith(JUnit4.class)
public class BigqueryPollJobActionTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@@ -79,8 +76,8 @@ public class BigqueryPollJobActionTest {
private final CapturingLogHandler logHandler = new CapturingLogHandler();
private BigqueryPollJobAction action = new BigqueryPollJobAction();
@Before
public void before() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
action.bigquery = bigquery;
when(bigquery.jobs()).thenReturn(bigqueryJobs);
when(bigqueryJobs.get(PROJECT_ID, JOB_ID)).thenReturn(bigqueryJobsGet);
@@ -100,14 +97,14 @@ public class BigqueryPollJobActionTest {
}
@Test
public void testSuccess_enqueuePollTask() {
void testSuccess_enqueuePollTask() {
new BigqueryPollJobEnqueuer(TASK_QUEUE_UTILS).enqueuePollTask(
new JobReference().setProjectId(PROJECT_ID).setJobId(JOB_ID));
assertTasksEnqueued(BigqueryPollJobAction.QUEUE, newPollJobTaskMatcher("GET"));
}
@Test
public void testSuccess_enqueuePollTask_withChainedTask() throws Exception {
void testSuccess_enqueuePollTask_withChainedTask() throws Exception {
TaskOptions chainedTask = TaskOptions.Builder
.withUrl("/_dr/something")
.method(Method.POST)
@@ -126,7 +123,7 @@ public class BigqueryPollJobActionTest {
}
@Test
public void testSuccess_jobCompletedSuccessfully() throws Exception {
void testSuccess_jobCompletedSuccessfully() throws Exception {
when(bigqueryJobsGet.execute()).thenReturn(
new Job().setStatus(new JobStatus().setState("DONE")));
action.run();
@@ -135,7 +132,7 @@ public class BigqueryPollJobActionTest {
}
@Test
public void testSuccess_chainedPayloadAndJobSucceeded_enqueuesChainedTask() throws Exception {
void testSuccess_chainedPayloadAndJobSucceeded_enqueuesChainedTask() throws Exception {
when(bigqueryJobsGet.execute()).thenReturn(
new Job().setStatus(new JobStatus().setState("DONE")));
@@ -167,7 +164,7 @@ public class BigqueryPollJobActionTest {
}
@Test
public void testJobFailed() throws Exception {
void testJobFailed() throws Exception {
when(bigqueryJobsGet.execute()).thenReturn(new Job().setStatus(
new JobStatus()
.setState("DONE")
@@ -179,20 +176,20 @@ public class BigqueryPollJobActionTest {
}
@Test
public void testJobPending() throws Exception {
void testJobPending() throws Exception {
when(bigqueryJobsGet.execute()).thenReturn(
new Job().setStatus(new JobStatus().setState("PENDING")));
assertThrows(NotModifiedException.class, action::run);
}
@Test
public void testJobStatusUnreadable() throws Exception {
void testJobStatusUnreadable() throws Exception {
when(bigqueryJobsGet.execute()).thenThrow(IOException.class);
assertThrows(NotModifiedException.class, action::run);
}
@Test
public void testFailure_badChainedTaskPayload() throws Exception {
void testFailure_badChainedTaskPayload() throws Exception {
when(bigqueryJobsGet.execute()).thenReturn(
new Job().setStatus(new JobStatus().setState("DONE")));
action.payload = "payload".getBytes(UTF_8);
@@ -42,26 +42,26 @@ import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.testing.TestDataHelper;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
/** Unit tests for {@link CheckBackupAction}. */
@RunWith(JUnit4.class)
@ExtendWith(MockitoExtension.class)
public class CheckBackupActionTest {
static final DateTime START_TIME = DateTime.parse("2014-08-01T01:02:03Z");
static final DateTime COMPLETE_TIME = START_TIME.plus(Duration.standardMinutes(30));
private static final DateTime START_TIME = DateTime.parse("2014-08-01T01:02:03Z");
private static final DateTime COMPLETE_TIME = START_TIME.plus(Duration.standardMinutes(30));
static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
@Rule public final AppEngineRule appEngine = AppEngineRule.builder().withTaskQueue().build();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withTaskQueue().build();
@Mock private DatastoreAdmin datastoreAdmin;
@Mock private Get getNotFoundBackupProgressRequest;
@@ -72,8 +72,8 @@ public class CheckBackupActionTest {
private final FakeClock clock = new FakeClock(COMPLETE_TIME.plusMillis(1000));
private final CheckBackupAction action = new CheckBackupAction();
@Before
public void before() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
action.requestMethod = Method.POST;
action.datastoreAdmin = datastoreAdmin;
action.clock = clock;
@@ -121,8 +121,9 @@ public class CheckBackupActionTest {
.param("kinds", kinds));
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testSuccess_enqueuePollTask() {
void testSuccess_enqueuePollTask() {
CheckBackupAction.enqueuePollTask("some_backup_name", ImmutableSet.of("one", "two", "three"));
assertTasksEnqueued(
CheckBackupAction.QUEUE,
@@ -134,7 +135,7 @@ public class CheckBackupActionTest {
}
@Test
public void testPost_forPendingBackup_returnsNotModified() throws Exception {
void testPost_forPendingBackup_returnsNotModified() throws Exception {
setPendingBackup();
NotModifiedException thrown = assertThrows(NotModifiedException.class, action::run);
@@ -144,7 +145,7 @@ public class CheckBackupActionTest {
}
@Test
public void testPost_forStalePendingBackupBackup_returnsNoContent() throws Exception {
void testPost_forStalePendingBackupBackup_returnsNoContent() throws Exception {
setPendingBackup();
clock.setTo(
START_TIME
@@ -161,7 +162,7 @@ public class CheckBackupActionTest {
}
@Test
public void testPost_forCompleteBackup_enqueuesLoadTask() throws Exception {
void testPost_forCompleteBackup_enqueuesLoadTask() throws Exception {
setCompleteBackup();
action.run();
assertLoadTaskEnqueued(
@@ -171,7 +172,7 @@ public class CheckBackupActionTest {
}
@Test
public void testPost_forCompleteBackup_withExtraKindsToLoad_enqueuesLoadTask() throws Exception {
void testPost_forCompleteBackup_withExtraKindsToLoad_enqueuesLoadTask() throws Exception {
setCompleteBackup();
action.kindsToLoadParam = "one,foo";
@@ -183,7 +184,7 @@ public class CheckBackupActionTest {
}
@Test
public void testPost_forCompleteBackup_withEmptyKindsToLoad_skipsLoadTask() throws Exception {
void testPost_forCompleteBackup_withEmptyKindsToLoad_skipsLoadTask() throws Exception {
setCompleteBackup();
action.kindsToLoadParam = "";
@@ -191,8 +192,9 @@ public class CheckBackupActionTest {
assertNoTasksEnqueued("export-snapshot");
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testPost_forBadBackup_returnsBadRequest() throws Exception {
void testPost_forBadBackup_returnsBadRequest() throws Exception {
setBackupNotFound();
BadRequestException thrown = assertThrows(BadRequestException.class, action::run);
@@ -200,7 +202,7 @@ public class CheckBackupActionTest {
}
@Test
public void testGet_returnsInformation() throws Exception {
void testGet_returnsInformation() throws Exception {
setCompleteBackup();
action.requestMethod = Method.GET;
@@ -212,8 +214,9 @@ public class CheckBackupActionTest {
.trim());
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testGet_forBadBackup_returnsError() throws Exception {
void testGet_forBadBackup_returnsError() throws Exception {
setBackupNotFound();
action.requestMethod = Method.GET;
@@ -29,13 +29,10 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Streams;
import com.google.re2j.Pattern;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link ExportConstants}. */
@RunWith(JUnit4.class)
public class ExportConstantsTest {
class ExportConstantsTest {
private static final String GOLDEN_BACKUP_KINDS_FILENAME = "backup_kinds.txt";
@@ -53,17 +50,17 @@ public class ExportConstantsTest {
"");
@Test
public void testBackupKinds_matchGoldenBackupKindsFile() {
void testBackupKinds_matchGoldenBackupKindsFile() {
checkKindsMatchGoldenFile("backed-up", GOLDEN_BACKUP_KINDS_FILENAME, getBackupKinds());
}
@Test
public void testReportingKinds_matchGoldenReportingKindsFile() {
void testReportingKinds_matchGoldenReportingKindsFile() {
checkKindsMatchGoldenFile("reporting", GOLDEN_REPORTING_KINDS_FILENAME, getReportingKinds());
}
@Test
public void testReportingKinds_areSubsetOfBackupKinds() {
void testReportingKinds_areSubsetOfBackupKinds() {
assertThat(getBackupKinds()).containsAtLeastElementsIn(getReportingKinds());
}
@@ -42,23 +42,20 @@ import google.registry.testing.FakeResponse;
import google.registry.testing.mapreduce.MapreduceTestCase;
import java.io.FileNotFoundException;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
/** Unit tests for {@link ExportDomainListsAction}. */
@RunWith(JUnit4.class)
public class ExportDomainListsActionTest extends MapreduceTestCase<ExportDomainListsAction> {
class ExportDomainListsActionTest extends MapreduceTestCase<ExportDomainListsAction> {
private GcsService gcsService;
private DriveConnection driveConnection = mock(DriveConnection.class);
private ArgumentCaptor<byte[]> bytesExportedToDrive = ArgumentCaptor.forClass(byte[].class);
private final FakeResponse response = new FakeResponse();
@Before
public void init() {
@BeforeEach
void beforeEach() {
createTld("tld");
createTld("testtld");
persistResource(Registry.get("tld").asBuilder().setDriveFolderId("brouhaha").build());
@@ -90,7 +87,7 @@ public class ExportDomainListsActionTest extends MapreduceTestCase<ExportDomainL
}
@Test
public void test_writesLinkToMapreduceConsoleToResponse() throws Exception {
void test_writesLinkToMapreduceConsoleToResponse() throws Exception {
runMapreduce();
assertThat(response.getPayload())
.startsWith(
@@ -99,7 +96,7 @@ public class ExportDomainListsActionTest extends MapreduceTestCase<ExportDomainL
}
@Test
public void test_outputsOnlyActiveDomains() throws Exception {
void test_outputsOnlyActiveDomains() throws Exception {
persistActiveDomain("onetwo.tld");
persistActiveDomain("rudnitzky.tld");
persistDeletedDomain("mortuary.tld", DateTime.parse("2001-03-14T10:11:12Z"));
@@ -113,7 +110,7 @@ public class ExportDomainListsActionTest extends MapreduceTestCase<ExportDomainL
}
@Test
public void test_outputsOnlyDomainsOnRealTlds() throws Exception {
void test_outputsOnlyDomainsOnRealTlds() throws Exception {
persistActiveDomain("onetwo.tld");
persistActiveDomain("rudnitzky.tld");
persistActiveDomain("wontgo.testtld");
@@ -134,7 +131,7 @@ public class ExportDomainListsActionTest extends MapreduceTestCase<ExportDomainL
}
@Test
public void test_outputsDomainsFromDifferentTldsToMultipleFiles() throws Exception {
void test_outputsDomainsFromDifferentTldsToMultipleFiles() throws Exception {
createTld("tldtwo");
persistResource(Registry.get("tldtwo").asBuilder().setDriveFolderId("hooray").build());
@@ -31,8 +31,8 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableList;
@@ -43,14 +43,12 @@ import google.registry.request.Response;
import google.registry.storage.drive.DriveConnection;
import google.registry.testing.AppEngineRule;
import java.io.IOException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.ArgumentMatchers;
@RunWith(JUnit4.class)
/** Unit tests for {@link ExportPremiumTermsAction}. */
public class ExportPremiumTermsActionTest {
private static final String DISCLAIMER_WITH_NEWLINE = "# Premium Terms Export Disclaimer\n";
@@ -59,7 +57,7 @@ public class ExportPremiumTermsActionTest {
private static final String EXPECTED_FILE_CONTENT =
DISCLAIMER_WITH_NEWLINE + "0,USD 549.00\n" + "2048,USD 549.00\n";
@Rule
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
private final DriveConnection driveConnection = mock(DriveConnection.class);
@@ -74,8 +72,8 @@ public class ExportPremiumTermsActionTest {
action.run();
}
@Before
public void setup() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
createTld("tld");
PremiumList pl = new PremiumList.Builder().setName("pl-name").build();
savePremiumListAndEntries(pl, PREMIUM_NAMES);
@@ -90,7 +88,7 @@ public class ExportPremiumTermsActionTest {
}
@Test
public void test_exportPremiumTerms_success() throws IOException {
void test_exportPremiumTerms_success() throws IOException {
runAction("tld");
verify(driveConnection)
@@ -108,7 +106,7 @@ public class ExportPremiumTermsActionTest {
}
@Test
public void test_exportPremiumTerms_success_emptyPremiumList() throws IOException {
void test_exportPremiumTerms_success_emptyPremiumList() throws IOException {
PremiumList pl = new PremiumList.Builder().setName("pl-name").build();
savePremiumListAndEntries(pl, ImmutableList.of());
runAction("tld");
@@ -128,11 +126,11 @@ public class ExportPremiumTermsActionTest {
}
@Test
public void test_exportPremiumTerms_doNothing_listNotConfigured() {
void test_exportPremiumTerms_doNothing_listNotConfigured() {
persistResource(Registry.get("tld").asBuilder().setPremiumList(null).build());
runAction("tld");
verifyZeroInteractions(driveConnection);
verifyNoInteractions(driveConnection);
verify(response).setStatus(SC_OK);
verify(response).setPayload("No premium lists configured");
verify(response).setContentType(PLAIN_TEXT_UTF_8);
@@ -140,11 +138,11 @@ public class ExportPremiumTermsActionTest {
}
@Test
public void testExportPremiumTerms_doNothing_driveIdNotConfiguredInTld() {
void testExportPremiumTerms_doNothing_driveIdNotConfiguredInTld() {
persistResource(Registry.get("tld").asBuilder().setDriveFolderId(null).build());
runAction("tld");
verifyZeroInteractions(driveConnection);
verifyNoInteractions(driveConnection);
verify(response).setStatus(SC_OK);
verify(response)
.setPayload("Skipping export because no Drive folder is associated with this TLD");
@@ -153,11 +151,11 @@ public class ExportPremiumTermsActionTest {
}
@Test
public void test_exportPremiumTerms_failure_noSuchTld() {
void test_exportPremiumTerms_failure_noSuchTld() {
deleteTld("tld");
assertThrows(RuntimeException.class, () -> runAction("tld"));
verifyZeroInteractions(driveConnection);
verifyNoInteractions(driveConnection);
verify(response).setStatus(SC_INTERNAL_SERVER_ERROR);
verify(response).setPayload(anyString());
verify(response).setContentType(PLAIN_TEXT_UTF_8);
@@ -165,11 +163,11 @@ public class ExportPremiumTermsActionTest {
}
@Test
public void test_exportPremiumTerms_failure_noPremiumList() {
void test_exportPremiumTerms_failure_noPremiumList() {
deletePremiumList(new PremiumList.Builder().setName("pl-name").build());
assertThrows(RuntimeException.class, () -> runAction("tld"));
verifyZeroInteractions(driveConnection);
verifyNoInteractions(driveConnection);
verify(response).setStatus(SC_INTERNAL_SERVER_ERROR);
verify(response).setPayload("Could not load premium list for " + "tld");
verify(response).setContentType(PLAIN_TEXT_UTF_8);
@@ -177,7 +175,7 @@ public class ExportPremiumTermsActionTest {
}
@Test
public void testExportPremiumTerms_failure_driveIdThrowsException() throws IOException {
void testExportPremiumTerms_failure_driveIdThrowsException() throws IOException {
persistResource(Registry.get("tld").asBuilder().setDriveFolderId("bad_folder_id").build());
assertThrows(RuntimeException.class, () -> runAction("tld"));
@@ -38,17 +38,14 @@ import google.registry.request.Response;
import google.registry.storage.drive.DriveConnection;
import google.registry.testing.AppEngineRule;
import java.io.IOException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link ExportReservedTermsAction}. */
@RunWith(JUnit4.class)
public class ExportReservedTermsActionTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
private final DriveConnection driveConnection = mock(DriveConnection.class);
@@ -63,8 +60,8 @@ public class ExportReservedTermsActionTest {
action.run();
}
@Before
public void init() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
ReservedList rl = persistReservedList(
"tld-reserved",
"lol,FULLY_BLOCKED",
@@ -81,7 +78,7 @@ public class ExportReservedTermsActionTest {
}
@Test
public void test_uploadFileToDrive_succeeds() throws Exception {
void test_uploadFileToDrive_succeeds() throws Exception {
runAction("tld");
byte[] expected = "# This is a disclaimer.\ncat\nlol\n".getBytes(UTF_8);
verify(driveConnection)
@@ -91,7 +88,7 @@ public class ExportReservedTermsActionTest {
}
@Test
public void test_uploadFileToDrive_doesNothingIfReservedListsNotConfigured() {
void test_uploadFileToDrive_doesNothingIfReservedListsNotConfigured() {
persistResource(
Registry.get("tld")
.asBuilder()
@@ -104,7 +101,7 @@ public class ExportReservedTermsActionTest {
}
@Test
public void test_uploadFileToDrive_doesNothingWhenDriveFolderIdIsNull() {
void test_uploadFileToDrive_doesNothingWhenDriveFolderIdIsNull() {
persistResource(Registry.get("tld").asBuilder().setDriveFolderId(null).build());
runAction("tld");
verify(response).setStatus(SC_OK);
@@ -113,7 +110,7 @@ public class ExportReservedTermsActionTest {
}
@Test
public void test_uploadFileToDrive_failsWhenDriveCannotBeReached() throws Exception {
void test_uploadFileToDrive_failsWhenDriveCannotBeReached() throws Exception {
when(driveConnection.createOrUpdateFile(
anyString(),
any(MediaType.class),
@@ -125,7 +122,7 @@ public class ExportReservedTermsActionTest {
}
@Test
public void test_uploadFileToDrive_failsWhenTldDoesntExist() {
void test_uploadFileToDrive_failsWhenTldDoesntExist() {
RuntimeException thrown = assertThrows(RuntimeException.class, () -> runAction("fakeTld"));
verify(response).setStatus(SC_INTERNAL_SERVER_ERROR);
assertThat(thrown)
@@ -22,20 +22,17 @@ import static google.registry.testing.DatastoreHelper.persistResource;
import google.registry.model.registry.Registry;
import google.registry.model.registry.label.ReservedList;
import google.registry.testing.AppEngineRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link ExportUtils}. */
@RunWith(JUnit4.class)
public class ExportUtilsTest {
class ExportUtilsTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Test
public void test_exportReservedTerms() {
void test_exportReservedTerms() {
ReservedList rl1 = persistReservedList(
"tld-reserved1",
"lol,FULLY_BLOCKED",
@@ -45,10 +45,8 @@ import google.registry.testing.FakeSleeper;
import google.registry.testing.InjectRule;
import google.registry.util.Retrier;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/**
* Unit tests for {@link SyncGroupMembersAction}.
@@ -56,14 +54,12 @@ import org.junit.runners.JUnit4;
* <p>Note that this relies on the registrars NewRegistrar and TheRegistrar created by default in
* {@link AppEngineRule}.
*/
@RunWith(JUnit4.class)
public class SyncGroupMembersActionTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Rule
public final InjectRule inject = new InjectRule();
@RegisterExtension public final InjectRule inject = new InjectRule();
private final DirectoryGroupsConnection connection = mock(DirectoryGroupsConnection.class);
private final Response response = mock(Response.class);
@@ -78,7 +74,7 @@ public class SyncGroupMembersActionTest {
}
@Test
public void test_getGroupEmailAddressForContactType_convertsToLowercase() {
void test_getGroupEmailAddressForContactType_convertsToLowercase() {
assertThat(getGroupEmailAddressForContactType(
"SomeRegistrar",
RegistrarContact.Type.ADMIN,
@@ -87,7 +83,7 @@ public class SyncGroupMembersActionTest {
}
@Test
public void test_getGroupEmailAddressForContactType_convertsNonAlphanumericChars() {
void test_getGroupEmailAddressForContactType_convertsNonAlphanumericChars() {
assertThat(getGroupEmailAddressForContactType(
"Weird.ಠ_ಠRegistrar",
MARKETING,
@@ -96,7 +92,7 @@ public class SyncGroupMembersActionTest {
}
@Test
public void test_doPost_noneModified() {
void test_doPost_noneModified() {
persistResource(
loadRegistrar("NewRegistrar").asBuilder().setContactsRequireSyncing(false).build());
persistResource(
@@ -109,7 +105,7 @@ public class SyncGroupMembersActionTest {
}
@Test
public void test_doPost_syncsNewContact() throws Exception {
void test_doPost_syncsNewContact() throws Exception {
runAction();
verify(connection).addMemberToGroup(
"newregistrar-primary-contacts@domain-registry.example",
@@ -121,7 +117,7 @@ public class SyncGroupMembersActionTest {
}
@Test
public void test_doPost_removesOldContact() throws Exception {
void test_doPost_removesOldContact() throws Exception {
when(connection.getMembersOfGroup("newregistrar-primary-contacts@domain-registry.example"))
.thenReturn(ImmutableSet.of("defunct@example.com", "janedoe@theregistrar.com"));
runAction();
@@ -132,7 +128,7 @@ public class SyncGroupMembersActionTest {
}
@Test
public void test_doPost_removesAllContactsFromGroup() throws Exception {
void test_doPost_removesAllContactsFromGroup() throws Exception {
when(connection.getMembersOfGroup("newregistrar-primary-contacts@domain-registry.example"))
.thenReturn(ImmutableSet.of("defunct@example.com", "janedoe@theregistrar.com"));
ofy().deleteWithoutBackup()
@@ -148,7 +144,7 @@ public class SyncGroupMembersActionTest {
}
@Test
public void test_doPost_addsAndRemovesContacts_acrossMultipleRegistrars() throws Exception {
void test_doPost_addsAndRemovesContacts_acrossMultipleRegistrars() throws Exception {
when(connection.getMembersOfGroup("newregistrar-primary-contacts@domain-registry.example"))
.thenReturn(ImmutableSet.of("defunct@example.com", "janedoe@theregistrar.com"));
when(connection.getMembersOfGroup("newregistrar-marketing-contacts@domain-registry.example"))
@@ -196,7 +192,7 @@ public class SyncGroupMembersActionTest {
}
@Test
public void test_doPost_gracefullyHandlesExceptionForSingleRegistrar() throws Exception {
void test_doPost_gracefullyHandlesExceptionForSingleRegistrar() throws Exception {
when(connection.getMembersOfGroup("newregistrar-primary-contacts@domain-registry.example"))
.thenReturn(ImmutableSet.of());
when(connection.getMembersOfGroup("theregistrar-primary-contacts@domain-registry.example"))
@@ -215,7 +211,7 @@ public class SyncGroupMembersActionTest {
}
@Test
public void test_doPost_retriesOnTransientException() throws Exception {
void test_doPost_retriesOnTransientException() throws Exception {
doThrow(IOException.class)
.doNothing()
.when(connection)
@@ -40,22 +40,18 @@ import google.registry.request.HttpException.InternalServerErrorException;
import google.registry.testing.AppEngineRule;
import google.registry.testing.TaskQueueHelper.TaskMatcher;
import java.io.IOException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
/** Unit tests for {@link UpdateSnapshotViewAction}. */
@RunWith(JUnit4.class)
public class UpdateSnapshotViewActionTest {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder()
.withTaskQueue()
.build();
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withTaskQueue().build();
private final CheckedBigquery checkedBigquery = mock(CheckedBigquery.class);
private final Bigquery bigquery = mock(Bigquery.class);
private final Bigquery.Datasets bigqueryDatasets = mock(Bigquery.Datasets.class);
@@ -66,8 +62,8 @@ public class UpdateSnapshotViewActionTest {
private UpdateSnapshotViewAction action;
@Before
public void before() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
when(checkedBigquery.ensureDataSetExists(anyString(), anyString())).thenReturn(bigquery);
when(bigquery.datasets()).thenReturn(bigqueryDatasets);
when(bigqueryDatasets.insert(anyString(), any(Dataset.class)))
@@ -86,7 +82,7 @@ public class UpdateSnapshotViewActionTest {
}
@Test
public void testSuccess_createViewUpdateTask() {
void testSuccess_createViewUpdateTask() {
getQueue(QUEUE)
.add(
createViewUpdateTask(
@@ -103,7 +99,7 @@ public class UpdateSnapshotViewActionTest {
}
@Test
public void testSuccess_doPost() throws Exception {
void testSuccess_doPost() throws Exception {
action.run();
InOrder factoryOrder = inOrder(checkedBigquery);
@@ -126,7 +122,7 @@ public class UpdateSnapshotViewActionTest {
}
@Test
public void testFailure_bigqueryConnectionThrowsError() throws Exception {
void testFailure_bigqueryConnectionThrowsError() throws Exception {
when(bigqueryTables.update(anyString(), anyString(), anyString(), any(Table.class)))
.thenThrow(new IOException("I'm sorry Dave, I can't let you do that"));
InternalServerErrorException thrown =
@@ -49,21 +49,17 @@ import google.registry.testing.AppEngineRule;
import google.registry.testing.TaskQueueHelper.TaskMatcher;
import java.io.IOException;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.ArgumentCaptor;
/** Unit tests for {@link UploadDatastoreBackupAction}. */
@RunWith(JUnit4.class)
public class UploadDatastoreBackupActionTest {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder()
.withTaskQueue()
.build();
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withTaskQueue().build();
private final CheckedBigquery checkedBigquery = mock(CheckedBigquery.class);
private final Bigquery bigquery = mock(Bigquery.class);
private final Bigquery.Jobs bigqueryJobs = mock(Bigquery.Jobs.class);
@@ -74,8 +70,8 @@ public class UploadDatastoreBackupActionTest {
private final BigqueryPollJobEnqueuer bigqueryPollEnqueuer = mock(BigqueryPollJobEnqueuer.class);
private UploadDatastoreBackupAction action;
@Before
public void before() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
when(checkedBigquery.ensureDataSetExists("Project-Id", BACKUP_DATASET)).thenReturn(bigquery);
when(bigquery.jobs()).thenReturn(bigqueryJobs);
when(bigqueryJobs.insert(eq("Project-Id"), any(Job.class))).thenReturn(bigqueryJobsInsert);
@@ -92,7 +88,7 @@ public class UploadDatastoreBackupActionTest {
}
@Test
public void testSuccess_enqueueLoadTask() {
void testSuccess_enqueueLoadTask() {
enqueueUploadBackupTask("id12345", "gs://bucket/path", ImmutableSet.of("one", "two", "three"));
assertTasksEnqueued(
QUEUE,
@@ -105,7 +101,7 @@ public class UploadDatastoreBackupActionTest {
}
@Test
public void testSuccess_doPost() throws Exception {
void testSuccess_doPost() throws Exception {
action.run();
// Verify that checkedBigquery was called in a way that would create the dataset if it didn't
@@ -187,7 +183,7 @@ public class UploadDatastoreBackupActionTest {
}
@Test
public void testFailure_doPost_bigqueryThrowsException() throws Exception {
void testFailure_doPost_bigqueryThrowsException() throws Exception {
when(bigqueryJobsInsert.execute()).thenThrow(new IOException("The Internet has gone missing"));
InternalServerErrorException thrown =
assertThrows(InternalServerErrorException.class, action::run);
@@ -197,7 +193,7 @@ public class UploadDatastoreBackupActionTest {
}
@Test
public void testgetBackupInfoFileForKind() {
void testgetBackupInfoFileForKind() {
assertThat(
getBackupInfoFileForKind(
"gs://BucketName/2018-11-11T00:00:00_12345", "AllocationToken"))
@@ -29,25 +29,20 @@ import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Optional;
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.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
/** Unit tests for {@link DatastoreAdmin}. */
@RunWith(JUnit4.class)
public class DatastoreAdminTest {
@ExtendWith(MockitoExtension.class)
class DatastoreAdminTest {
private static final String AUTH_HEADER_PREFIX = "Bearer ";
private static final String ACCESS_TOKEN = "MyAccessToken";
private static final ImmutableList<String> KINDS =
ImmutableList.of("Registry", "Registrar", "DomainBase");
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
private DatastoreAdmin datastoreAdmin;
private static HttpRequest simulateSendRequest(HttpRequest httpRequest) {
@@ -75,8 +70,8 @@ public class DatastoreAdminTest {
return Optional.of(outputStream.toString(StandardCharsets.UTF_8.name()));
}
@Before
public void setup() {
@BeforeEach
void beforeEach() {
Date oneHourLater = new Date(System.currentTimeMillis() + 3_600_000);
GoogleCredentials googleCredentials = GoogleCredentials
.create(new AccessToken(ACCESS_TOKEN, oneHourLater));
@@ -92,7 +87,7 @@ public class DatastoreAdminTest {
}
@Test
public void testExport() throws IOException {
void testExport() throws IOException {
DatastoreAdmin.Export export = datastoreAdmin.export("gs://mybucket/path", KINDS);
HttpRequest httpRequest = export.buildHttpRequest();
assertThat(httpRequest.getUrl().toString())
@@ -109,7 +104,7 @@ public class DatastoreAdminTest {
}
@Test
public void testGetOperation() throws IOException {
void testGetOperation() throws IOException {
DatastoreAdmin.Get get =
datastoreAdmin.get("projects/MyCloudProject/operations/ASAzNjMwOTEyNjUJ");
HttpRequest httpRequest = get.buildHttpRequest();
@@ -124,7 +119,7 @@ public class DatastoreAdminTest {
}
@Test
public void testListOperations_all() throws IOException {
void testListOperations_all() throws IOException {
DatastoreAdmin.ListOperations listOperations = datastoreAdmin.listAll();
HttpRequest httpRequest = listOperations.buildHttpRequest();
assertThat(httpRequest.getUrl().toString())
@@ -137,7 +132,7 @@ public class DatastoreAdminTest {
}
@Test
public void testListOperations_filterByStartTime() throws IOException {
void testListOperations_filterByStartTime() throws IOException {
DatastoreAdmin.ListOperations listOperations =
datastoreAdmin.list("metadata.common.startTime>\"2018-10-31T00:00:00.0Z\"");
HttpRequest httpRequest = listOperations.buildHttpRequest();
@@ -153,7 +148,7 @@ public class DatastoreAdminTest {
}
@Test
public void testListOperations_filterByState() throws IOException {
void testListOperations_filterByState() throws IOException {
// TODO(weiminyu): consider adding a method to DatastoreAdmin to support query by state.
DatastoreAdmin.ListOperations listOperations =
datastoreAdmin.list("metadata.common.state=PROCESSING");
@@ -22,23 +22,20 @@ import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.common.collect.ImmutableList;
import google.registry.testing.TestDataHelper;
import java.io.IOException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for the instantiation, marshalling and unmarshalling of {@link EntityFilter}. */
@RunWith(JUnit4.class)
public class EntityFilterTest {
class EntityFilterTest {
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
@Test
public void testEntityFilter_create_nullKinds() {
void testEntityFilter_create_nullKinds() {
assertThrows(NullPointerException.class, () -> new EntityFilter(null));
}
@Test
public void testEntityFilter_marshall() throws IOException {
void testEntityFilter_marshall() throws IOException {
EntityFilter entityFilter =
new EntityFilter(ImmutableList.of("Registry", "Registrar", "DomainBase"));
assertThat(JSON_FACTORY.toString(entityFilter))
@@ -46,7 +43,7 @@ public class EntityFilterTest {
}
@Test
public void testEntityFilter_unmarshall() throws IOException {
void testEntityFilter_unmarshall() throws IOException {
EntityFilter entityFilter = loadJson("entity_filter.json", EntityFilter.class);
assertThat(entityFilter.getKinds())
.containsExactly("Registry", "Registrar", "DomainBase")
@@ -54,13 +51,13 @@ public class EntityFilterTest {
}
@Test
public void testEntityFilter_unmarshall_noKinds() throws IOException {
void testEntityFilter_unmarshall_noKinds() throws IOException {
EntityFilter entityFilter = JSON_FACTORY.fromString("{}", EntityFilter.class);
assertThat(entityFilter.getKinds()).isEmpty();
}
@Test
public void testEntityFilter_unmarshall_emptyKinds() throws IOException {
void testEntityFilter_unmarshall_emptyKinds() throws IOException {
EntityFilter entityFilter = JSON_FACTORY.fromString("{ \"kinds\" : [] }", EntityFilter.class);
assertThat(entityFilter.getKinds()).isEmpty();
}
@@ -27,17 +27,15 @@ import google.registry.testing.TestDataHelper;
import java.io.IOException;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for unmarshalling {@link Operation} and its member types. */
@RunWith(JUnit4.class)
public class OperationTest {
class OperationTest {
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
@Test
public void testCommonMetadata_unmarshall() throws IOException {
void testCommonMetadata_unmarshall() throws IOException {
CommonMetadata commonMetadata = loadJson("common_metadata.json", CommonMetadata.class);
assertThat(commonMetadata.getState()).isEqualTo("SUCCESSFUL");
assertThat(commonMetadata.getOperationType()).isEqualTo("EXPORT_ENTITIES");
@@ -47,14 +45,14 @@ public class OperationTest {
}
@Test
public void testProgress_unmarshall() throws IOException {
void testProgress_unmarshall() throws IOException {
Progress progress = loadJson("progress.json", Progress.class);
assertThat(progress.getWorkCompleted()).isEqualTo(51797);
assertThat(progress.getWorkEstimated()).isEqualTo(54513);
}
@Test
public void testMetadata_unmarshall() throws IOException {
void testMetadata_unmarshall() throws IOException {
Metadata metadata = loadJson("metadata.json", Metadata.class);
assertThat(metadata.getCommonMetadata().getOperationType()).isEqualTo("EXPORT_ENTITIES");
assertThat(metadata.getCommonMetadata().getState()).isEqualTo("SUCCESSFUL");
@@ -67,7 +65,7 @@ public class OperationTest {
}
@Test
public void testOperation_unmarshall() throws IOException {
void testOperation_unmarshall() throws IOException {
Operation operation = loadJson("operation.json", Operation.class);
assertThat(operation.getName())
.startsWith("projects/domain-registry-alpha/operations/ASAzNjMwOTEyNjUJ");
@@ -86,7 +84,7 @@ public class OperationTest {
}
@Test
public void testOperationList_unmarshall() throws IOException {
void testOperationList_unmarshall() throws IOException {
Operation.OperationList operationList =
loadJson("operation_list.json", Operation.OperationList.class);
assertThat(operationList.toList()).hasSize(2);
@@ -18,7 +18,7 @@ import static com.google.common.collect.Lists.newArrayList;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import com.google.api.services.sheets.v4.Sheets;
@@ -33,14 +33,12 @@ import com.google.common.collect.ImmutableMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link SheetSynchronizer}. */
@RunWith(JUnit4.class)
public class SheetSynchronizerTest {
class SheetSynchronizerTest {
private final SheetSynchronizer sheetSynchronizer = new SheetSynchronizer();
private final Sheets sheetsService = mock(Sheets.class);
private final Sheets.Spreadsheets spreadsheets = mock(Sheets.Spreadsheets.class);
@@ -56,8 +54,8 @@ public class SheetSynchronizerTest {
private List<List<Object>> existingSheet;
private ImmutableList<ImmutableMap<String, String>> data;
@Before
public void before() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
sheetSynchronizer.sheetsService = sheetsService;
when(sheetsService.spreadsheets()).thenReturn(spreadsheets);
when(spreadsheets.values()).thenReturn(values);
@@ -88,23 +86,23 @@ public class SheetSynchronizerTest {
}
@Test
public void testSynchronize_dataAndSheetEmpty_doNothing() throws Exception {
void testSynchronize_dataAndSheetEmpty_doNothing() throws Exception {
existingSheet.add(createRow("a", "b"));
sheetSynchronizer.synchronize("aSheetId", data);
verifyZeroInteractions(appendReq);
verifyZeroInteractions(clearReq);
verifyZeroInteractions(updateReq);
verifyNoInteractions(appendReq);
verifyNoInteractions(clearReq);
verifyNoInteractions(updateReq);
}
@Test
public void testSynchronize_differentValues_updatesValues() throws Exception {
void testSynchronize_differentValues_updatesValues() throws Exception {
existingSheet.add(createRow("a", "b"));
existingSheet.add(createRow("diffVal1l", "diffVal2"));
data = ImmutableList.of(ImmutableMap.of("a", "val1", "b", "val2"));
sheetSynchronizer.synchronize("aSheetId", data);
verifyZeroInteractions(appendReq);
verifyZeroInteractions(clearReq);
verifyNoInteractions(appendReq);
verifyNoInteractions(clearReq);
BatchUpdateValuesRequest expectedRequest = new BatchUpdateValuesRequest();
List<List<Object>> expectedVals = newArrayList();
@@ -116,14 +114,14 @@ public class SheetSynchronizerTest {
}
@Test
public void testSynchronize_unknownFields_doesntUpdate() throws Exception {
void testSynchronize_unknownFields_doesntUpdate() throws Exception {
existingSheet.add(createRow("a", "c", "b"));
existingSheet.add(createRow("diffVal1", "sameVal", "diffVal2"));
data = ImmutableList.of(ImmutableMap.of("a", "val1", "b", "val2", "d", "val3"));
sheetSynchronizer.synchronize("aSheetId", data);
verifyZeroInteractions(appendReq);
verifyZeroInteractions(clearReq);
verifyNoInteractions(appendReq);
verifyNoInteractions(clearReq);
BatchUpdateValuesRequest expectedRequest = new BatchUpdateValuesRequest();
List<List<Object>> expectedVals = newArrayList();
@@ -135,14 +133,14 @@ public class SheetSynchronizerTest {
}
@Test
public void testSynchronize_notFullRow_getsPadded() throws Exception {
void testSynchronize_notFullRow_getsPadded() throws Exception {
existingSheet.add(createRow("a", "c", "b"));
existingSheet.add(createRow("diffVal1", "diffVal2"));
data = ImmutableList.of(ImmutableMap.of("a", "val1", "b", "paddedVal", "d", "val3"));
sheetSynchronizer.synchronize("aSheetId", data);
verifyZeroInteractions(appendReq);
verifyZeroInteractions(clearReq);
verifyNoInteractions(appendReq);
verifyNoInteractions(clearReq);
BatchUpdateValuesRequest expectedRequest = new BatchUpdateValuesRequest();
List<List<Object>> expectedVals = newArrayList();
@@ -154,22 +152,21 @@ public class SheetSynchronizerTest {
}
@Test
public void testSynchronize_moreData_appendsValues() throws Exception {
void testSynchronize_moreData_appendsValues() throws Exception {
existingSheet.add(createRow("a", "b"));
existingSheet.add(createRow("diffVal1", "diffVal2"));
data = ImmutableList.of(
ImmutableMap.of("a", "val1", "b", "val2"),
ImmutableMap.of("a", "val3", "b", "val4"));
data =
ImmutableList.of(
ImmutableMap.of("a", "val1", "b", "val2"), ImmutableMap.of("a", "val3", "b", "val4"));
sheetSynchronizer.synchronize("aSheetId", data);
verifyZeroInteractions(clearReq);
verifyNoInteractions(clearReq);
BatchUpdateValuesRequest expectedRequest = new BatchUpdateValuesRequest();
List<List<Object>> updatedVals = newArrayList();
updatedVals.add(createRow("val1", "val2"));
expectedRequest.setData(
newArrayList(
new ValueRange().setRange("Registrars!A2").setValues(updatedVals)));
newArrayList(new ValueRange().setRange("Registrars!A2").setValues(updatedVals)));
expectedRequest.setValueInputOption("RAW");
verify(values).batchUpdate("aSheetId", expectedRequest);
@@ -180,7 +177,7 @@ public class SheetSynchronizerTest {
}
@Test
public void testSynchronize_lessData_clearsValues() throws Exception {
void testSynchronize_lessData_clearsValues() throws Exception {
existingSheet.add(createRow("a", "b"));
existingSheet.add(createRow("val1", "val2"));
existingSheet.add(createRow("diffVal3", "diffVal4"));
@@ -188,6 +185,6 @@ public class SheetSynchronizerTest {
sheetSynchronizer.synchronize("aSheetId", data);
verify(values).clear("aSheetId", "Registrars!3:4", new ClearValuesRequest());
verifyZeroInteractions(updateReq);
verifyNoInteractions(updateReq);
}
}
@@ -19,8 +19,8 @@ import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import google.registry.testing.AppEngineRule;
@@ -29,17 +29,14 @@ import google.registry.testing.FakeResponse;
import java.util.Optional;
import javax.annotation.Nullable;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link SyncRegistrarsSheetAction}. */
@RunWith(JUnit4.class)
public class SyncRegistrarsSheetActionTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@@ -54,8 +51,8 @@ public class SyncRegistrarsSheetActionTest {
action.run();
}
@Before
public void setUp() {
@BeforeEach
void beforeEach() {
action = new SyncRegistrarsSheetAction();
action.response = response;
action.syncRegistrarsSheet = syncRegistrarsSheet;
@@ -64,14 +61,14 @@ public class SyncRegistrarsSheetActionTest {
}
@Test
public void testPost_withoutParamsOrSystemProperty_dropsTask() {
void testPost_withoutParamsOrSystemProperty_dropsTask() {
runAction(null, null);
assertThat(response.getPayload()).startsWith("MISSINGNO");
verifyZeroInteractions(syncRegistrarsSheet);
verifyNoInteractions(syncRegistrarsSheet);
}
@Test
public void testPost_withoutParams_runsSyncWithDefaultIdAndChecksIfModified() throws Exception {
void testPost_withoutParams_runsSyncWithDefaultIdAndChecksIfModified() throws Exception {
when(syncRegistrarsSheet.wereRegistrarsModified()).thenReturn(true);
runAction("jazz", null);
assertThat(response.getStatus()).isEqualTo(200);
@@ -83,7 +80,7 @@ public class SyncRegistrarsSheetActionTest {
}
@Test
public void testPost_noModificationsToRegistrarEntities_doesNothing() {
void testPost_noModificationsToRegistrarEntities_doesNothing() {
when(syncRegistrarsSheet.wereRegistrarsModified()).thenReturn(false);
runAction("NewRegistrar", null);
assertThat(response.getPayload()).startsWith("NOTMODIFIED");
@@ -92,7 +89,7 @@ public class SyncRegistrarsSheetActionTest {
}
@Test
public void testPost_overrideId_runsSyncWithCustomIdAndDoesNotCheckModified() throws Exception {
void testPost_overrideId_runsSyncWithCustomIdAndDoesNotCheckModified() throws Exception {
runAction(null, "foobar");
assertThat(response.getPayload()).startsWith("OK");
verify(syncRegistrarsSheet).run(eq("foobar"));
@@ -100,10 +97,10 @@ public class SyncRegistrarsSheetActionTest {
}
@Test
public void testPost_failToAquireLock_servletDoesNothingAndReturns() {
void testPost_failToAquireLock_servletDoesNothingAndReturns() {
action.lockHandler = new FakeLockHandler(false);
runAction(null, "foobar");
assertThat(response.getPayload()).startsWith("LOCKED");
verifyZeroInteractions(syncRegistrarsSheet);
verifyNoInteractions(syncRegistrarsSheet);
}
}
@@ -43,27 +43,23 @@ import google.registry.testing.DatastoreHelper;
import google.registry.testing.FakeClock;
import google.registry.testing.InjectRule;
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.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.junit.jupiter.MockitoExtension;
/** Unit tests for {@link SyncRegistrarsSheet}. */
@RunWith(JUnit4.class)
@ExtendWith(MockitoExtension.class)
public class SyncRegistrarsSheetTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@Rule public final InjectRule inject = new InjectRule();
@RegisterExtension public final InjectRule inject = new InjectRule();
@Captor private ArgumentCaptor<ImmutableList<ImmutableMap<String, String>>> rowsCaptor;
@Mock private SheetSynchronizer sheetSynchronizer;
@@ -77,8 +73,8 @@ public class SyncRegistrarsSheetTest {
return result;
}
@Before
public void before() {
@BeforeEach
void beforeEach() {
inject.setStaticField(Ofy.class, "clock", clock);
createTld("example");
// Remove Registrar entities created by AppEngineRule.
@@ -86,12 +82,12 @@ public class SyncRegistrarsSheetTest {
}
@Test
public void test_wereRegistrarsModified_noRegistrars_returnsFalse() {
void test_wereRegistrarsModified_noRegistrars_returnsFalse() {
assertThat(newSyncRegistrarsSheet().wereRegistrarsModified()).isFalse();
}
@Test
public void test_wereRegistrarsModified_atDifferentCursorTimes() {
void test_wereRegistrarsModified_atDifferentCursorTimes() {
persistNewRegistrar("SomeRegistrar", "Some Registrar Inc.", Registrar.Type.REAL, 8L);
persistResource(Cursor.createGlobal(SYNC_REGISTRAR_SHEET, clock.nowUtc().minusHours(1)));
assertThat(newSyncRegistrarsSheet().wereRegistrarsModified()).isTrue();
@@ -100,7 +96,7 @@ public class SyncRegistrarsSheetTest {
}
@Test
public void testRun() throws Exception {
void testRun() throws Exception {
DateTime beforeExecution = clock.nowUtc();
persistResource(new Registrar.Builder()
.setClientId("anotherregistrar")
@@ -329,7 +325,7 @@ public class SyncRegistrarsSheetTest {
}
@Test
public void testRun_missingValues_stillWorks() throws Exception {
void testRun_missingValues_stillWorks() throws Exception {
persistNewRegistrar("SomeRegistrar", "Some Registrar", Registrar.Type.REAL, 8L);
newSyncRegistrarsSheet().run("foobar");
@@ -39,35 +39,31 @@ import google.registry.testing.FakeResponse;
import java.util.Map;
import org.joda.time.DateTime;
import org.json.simple.JSONValue;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.junit.jupiter.MockitoExtension;
/** Tests for {@link CheckApiAction}. */
@RunWith(JUnit4.class)
public class CheckApiActionTest {
@ExtendWith(MockitoExtension.class)
class CheckApiActionTest {
private static final DateTime START_TIME = DateTime.parse("2000-01-01T00:00:00.0Z");
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@RegisterExtension
final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Mock private CheckApiMetrics checkApiMetrics;
@Captor private ArgumentCaptor<CheckApiMetric> metricCaptor;
private DateTime endTime;
@Before
public void init() {
@BeforeEach
void beforeEach() {
createTld("example");
persistResource(
Registry.get("example")
@@ -98,7 +94,7 @@ public class CheckApiActionTest {
}
@Test
public void testFailure_nullDomain() {
void testFailure_nullDomain() {
assertThat(getCheckResponse(null))
.containsExactly(
"status", "error",
@@ -108,7 +104,7 @@ public class CheckApiActionTest {
}
@Test
public void testFailure_emptyDomain() {
void testFailure_emptyDomain() {
assertThat(getCheckResponse(""))
.containsExactly(
"status", "error",
@@ -118,7 +114,7 @@ public class CheckApiActionTest {
}
@Test
public void testFailure_invalidDomain() {
void testFailure_invalidDomain() {
assertThat(getCheckResponse("@#$%^"))
.containsExactly(
"status", "error",
@@ -128,7 +124,7 @@ public class CheckApiActionTest {
}
@Test
public void testFailure_singlePartDomain() {
void testFailure_singlePartDomain() {
assertThat(getCheckResponse("foo"))
.containsExactly(
"status", "error",
@@ -138,7 +134,7 @@ public class CheckApiActionTest {
}
@Test
public void testFailure_nonExistentTld() {
void testFailure_nonExistentTld() {
assertThat(getCheckResponse("foo.bar"))
.containsExactly(
"status", "error",
@@ -148,7 +144,7 @@ public class CheckApiActionTest {
}
@Test
public void testFailure_invalidIdnTable() {
void testFailure_invalidIdnTable() {
assertThat(getCheckResponse("ΑΒΓ.example"))
.containsExactly(
"status", "error",
@@ -158,7 +154,7 @@ public class CheckApiActionTest {
}
@Test
public void testFailure_tldInPredelegation() {
void testFailure_tldInPredelegation() {
createTld("predelegated", PREDELEGATION);
assertThat(getCheckResponse("foo.predelegated"))
.containsExactly(
@@ -169,7 +165,7 @@ public class CheckApiActionTest {
}
@Test
public void testSuccess_availableStandard() {
void testSuccess_availableStandard() {
assertThat(getCheckResponse("somedomain.example"))
.containsExactly(
"status", "success",
@@ -180,7 +176,7 @@ public class CheckApiActionTest {
}
@Test
public void testSuccess_availableCapital() {
void testSuccess_availableCapital() {
assertThat(getCheckResponse("SOMEDOMAIN.EXAMPLE"))
.containsExactly(
"status", "success",
@@ -191,7 +187,7 @@ public class CheckApiActionTest {
}
@Test
public void testSuccess_availableUnicode() {
void testSuccess_availableUnicode() {
assertThat(getCheckResponse("ééé.example"))
.containsExactly(
"status", "success",
@@ -202,7 +198,7 @@ public class CheckApiActionTest {
}
@Test
public void testSuccess_availablePunycode() {
void testSuccess_availablePunycode() {
assertThat(getCheckResponse("xn--9caaa.example"))
.containsExactly(
"status", "success",
@@ -213,7 +209,7 @@ public class CheckApiActionTest {
}
@Test
public void testSuccess_availablePremium() {
void testSuccess_availablePremium() {
assertThat(getCheckResponse("rich.example"))
.containsExactly(
"status", "success",
@@ -224,7 +220,7 @@ public class CheckApiActionTest {
}
@Test
public void testSuccess_registered_standard() {
void testSuccess_registered_standard() {
persistActiveDomain("somedomain.example");
assertThat(getCheckResponse("somedomain.example"))
.containsExactly(
@@ -237,7 +233,7 @@ public class CheckApiActionTest {
}
@Test
public void testSuccess_reserved_standard() {
void testSuccess_reserved_standard() {
assertThat(getCheckResponse("foo.example"))
.containsExactly(
"tier", "standard",
@@ -249,7 +245,7 @@ public class CheckApiActionTest {
}
@Test
public void testSuccess_registered_premium() {
void testSuccess_registered_premium() {
persistActiveDomain("rich.example");
assertThat(getCheckResponse("rich.example"))
.containsExactly(
@@ -262,7 +258,7 @@ public class CheckApiActionTest {
}
@Test
public void testSuccess_reserved_premium() {
void testSuccess_reserved_premium() {
assertThat(getCheckResponse("platinum.example"))
.containsExactly(
"tier", "premium",
@@ -274,7 +270,7 @@ public class CheckApiActionTest {
}
@Test
public void testSuccess_reservedForSpecificUse_premium() {
void testSuccess_reservedForSpecificUse_premium() {
assertThat(getCheckResponse("gold.example"))
.containsExactly(
"tier", "premium",
@@ -36,28 +36,24 @@ import google.registry.testing.FakeClock;
import google.registry.testing.FakeHttpSession;
import google.registry.testing.InjectRule;
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.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Test that domain flows create the commit logs needed to reload at points in the past. */
@RunWith(JUnit4.class)
public class EppCommitLogsTest {
class EppCommitLogsTest {
@Rule
public final AppEngineRule appEngine =
@RegisterExtension
final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@Rule
public final InjectRule inject = new InjectRule();
@RegisterExtension final InjectRule inject = new InjectRule();
private final FakeClock clock = new FakeClock(DateTime.now(UTC));
private EppLoader eppLoader;
@Before
public void init() {
@BeforeEach
void beforeEach() {
createTld("tld");
inject.setStaticField(Ofy.class, "clock", clock);
}
@@ -66,8 +62,7 @@ public class EppCommitLogsTest {
SessionMetadata sessionMetadata = new HttpSessionMetadata(new FakeHttpSession());
sessionMetadata.setClientId("TheRegistrar");
DaggerEppTestComponent.builder()
.fakesAndMocksModule(
FakesAndMocksModule.create(clock, EppMetric.builderForRequest(clock)))
.fakesAndMocksModule(FakesAndMocksModule.create(clock, EppMetric.builderForRequest(clock)))
.build()
.startRequest()
.flowComponentBuilder()
@@ -87,8 +82,8 @@ public class EppCommitLogsTest {
}
@Test
public void testLoadAtPointInTime() throws Exception {
clock.setTo(DateTime.parse("1984-12-18T12:30Z")); // not midnight
void testLoadAtPointInTime() throws Exception {
clock.setTo(DateTime.parse("1984-12-18T12:30Z")); // not midnight
persistActiveHost("ns1.example.net");
persistActiveHost("ns2.example.net");
@@ -114,7 +109,7 @@ public class EppCommitLogsTest {
DomainBase domainAfterFirstUpdate = ofy().load().key(key).now();
assertThat(domainAfterCreate).isNotEqualTo(domainAfterFirstUpdate);
clock.advanceOneMilli(); // same day as first update
clock.advanceOneMilli(); // same day as first update
DateTime timeAtSecondUpdate = clock.nowUtc();
eppLoader = new EppLoader(this, "domain_update_dsdata_rem.xml");
runFlow();
@@ -146,8 +141,7 @@ public class EppCommitLogsTest {
// key to the first update should have been overwritten by the second, and its timestamp rolled
// forward. So we have to fall back to the last revision before midnight.
ofy().clearSessionCache();
assertThat(loadAtPointInTime(latest, timeAtFirstUpdate).now())
.isEqualTo(domainAfterCreate);
assertThat(loadAtPointInTime(latest, timeAtFirstUpdate).now()).isEqualTo(domainAfterCreate);
ofy().clearSessionCache();
assertThat(loadAtPointInTime(latest, timeAtSecondUpdate).now())
@@ -26,7 +26,7 @@ import static java.util.logging.Level.INFO;
import static java.util.logging.Level.SEVERE;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import com.google.common.base.Splitter;
@@ -50,26 +50,24 @@ import java.util.logging.LogRecord;
import java.util.logging.Logger;
import org.joda.time.DateTime;
import org.json.simple.JSONValue;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
/** Unit tests for {@link EppController}. */
@RunWith(JUnit4.class)
public class EppControllerTest {
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class EppControllerTest {
@Rule
public AppEngineRule appEngineRule =
new AppEngineRule.Builder().withDatastoreAndCloudSql().build();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@RegisterExtension
AppEngineRule appEngineRule = new AppEngineRule.Builder().withDatastoreAndCloudSql().build();
@Mock SessionMetadata sessionMetadata;
@Mock TransportCredentials transportCredentials;
@@ -96,8 +94,8 @@ public class EppControllerTest {
private EppController eppController;
@Before
public void setUp() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
loggerToIntercept.addHandler(logHandler);
when(sessionMetadata.getClientId()).thenReturn("some-client");
@@ -117,13 +115,13 @@ public class EppControllerTest {
eppController.serverTridProvider = new FakeServerTridProvider();
}
@After
public void tearDown() {
@AfterEach
void afterEach() {
loggerToIntercept.removeHandler(logHandler);
}
@Test
public void testMarshallingUnknownError() throws Exception {
void testMarshallingUnknownError() throws Exception {
marshal(
EppController.getErrorResponse(
Result.create(Code.COMMAND_FAILED), Trid.create(null, "server-trid")),
@@ -131,7 +129,7 @@ public class EppControllerTest {
}
@Test
public void testHandleEppCommand_regularEppCommand_exportsEppMetrics() {
void testHandleEppCommand_regularEppCommand_exportsEppMetrics() {
createTld("tld");
// Note that some of the EPP metric fields, like # of attempts and command name, are set in
// FlowRunner, not EppController, and since FlowRunner is mocked out for these tests they won't
@@ -155,7 +153,7 @@ public class EppControllerTest {
}
@Test
public void testHandleEppCommand_dryRunEppCommand_doesNotExportMetric() {
void testHandleEppCommand_dryRunEppCommand_doesNotExportMetric() {
eppController.handleEppCommand(
sessionMetadata,
transportCredentials,
@@ -163,11 +161,11 @@ public class EppControllerTest {
true,
true,
domainCreateXml.getBytes(UTF_8));
verifyZeroInteractions(eppMetrics);
verifyNoInteractions(eppMetrics);
}
@Test
public void testHandleEppCommand_unmarshallableData_loggedAtInfo_withJsonData() throws Exception {
void testHandleEppCommand_unmarshallableData_loggedAtInfo_withJsonData() throws Exception {
eppController.handleEppCommand(
sessionMetadata,
transportCredentials,
@@ -176,7 +174,8 @@ public class EppControllerTest {
false,
"GET / HTTP/1.1\n\n".getBytes(UTF_8));
assertAboutLogs().that(logHandler)
assertAboutLogs()
.that(logHandler)
.hasLogAtLevelWithMessage(INFO, "EPP request XML unmarshalling failed");
LogRecord logRecord =
findFirstLogRecordWithMessagePrefix(logHandler, "EPP request XML unmarshalling failed");
@@ -184,14 +183,14 @@ public class EppControllerTest {
assertThat(messageParts.size()).isAtLeast(2);
Map<String, Object> json = parseJsonMap(messageParts.get(1));
assertThat(json).containsEntry("clientId", "some-client");
assertThat(json).containsEntry("resultCode", 2001L); // Must be Long to compare equal.
assertThat(json).containsEntry("resultCode", 2001L); // Must be Long to compare equal.
assertThat(json).containsEntry("resultMessage", "Command syntax error");
assertThat(json)
.containsEntry("xmlBytes", base64().encode("GET / HTTP/1.1\n\n".getBytes(UTF_8)));
}
@Test
public void testHandleEppCommand_throwsEppException_loggedAtInfo() throws Exception {
void testHandleEppCommand_throwsEppException_loggedAtInfo() throws Exception {
when(flowRunner.run(eppController.eppMetricBuilder))
.thenThrow(new UnimplementedExtensionException());
eppController.handleEppCommand(
@@ -201,7 +200,8 @@ public class EppControllerTest {
false,
true,
domainCreateXml.getBytes(UTF_8));
assertAboutLogs().that(logHandler)
assertAboutLogs()
.that(logHandler)
.hasLogAtLevelWithMessage(INFO, "Flow returned failure response");
LogRecord logRecord =
findFirstLogRecordWithMessagePrefix(logHandler, "Flow returned failure response");
@@ -209,8 +209,7 @@ public class EppControllerTest {
}
@Test
public void testHandleEppCommand_throwsEppExceptionInProviderException_loggedAtInfo()
throws Exception {
void testHandleEppCommand_throwsEppExceptionInProviderException_loggedAtInfo() throws Exception {
when(flowRunner.run(eppController.eppMetricBuilder))
.thenThrow(new EppExceptionInProviderException(new UnimplementedExtensionException()));
eppController.handleEppCommand(
@@ -220,7 +219,8 @@ public class EppControllerTest {
false,
true,
domainCreateXml.getBytes(UTF_8));
assertAboutLogs().that(logHandler)
assertAboutLogs()
.that(logHandler)
.hasLogAtLevelWithMessage(INFO, "Flow returned failure response");
LogRecord logRecord =
findFirstLogRecordWithMessagePrefix(logHandler, "Flow returned failure response");
@@ -228,7 +228,7 @@ public class EppControllerTest {
}
@Test
public void testHandleEppCommand_throwsRuntimeException_loggedAtSevere() throws Exception {
void testHandleEppCommand_throwsRuntimeException_loggedAtSevere() throws Exception {
when(flowRunner.run(eppController.eppMetricBuilder)).thenThrow(new IllegalStateException());
eppController.handleEppCommand(
sessionMetadata,
@@ -237,7 +237,8 @@ public class EppControllerTest {
false,
true,
domainCreateXml.getBytes(UTF_8));
assertAboutLogs().that(logHandler)
assertAboutLogs()
.that(logHandler)
.hasLogAtLevelWithMessage(SEVERE, "Unexpected failure in flow execution");
LogRecord logRecord =
findFirstLogRecordWithMessagePrefix(logHandler, "Unexpected failure in flow execution");
@@ -22,21 +22,18 @@ import static google.registry.testing.EppMetricSubject.assertThat;
import com.google.common.collect.ImmutableMap;
import google.registry.testing.AppEngineRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Tests for contact lifecycle. */
@RunWith(JUnit4.class)
public class EppLifecycleContactTest extends EppTestCase {
class EppLifecycleContactTest extends EppTestCase {
@Rule
public final AppEngineRule appEngine =
@RegisterExtension
final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@Test
public void testContactLifecycle() throws Exception {
void testContactLifecycle() throws Exception {
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
assertThatCommand("contact_create_sh8013.xml")
.atTime("2000-06-01T00:00:00Z")
@@ -72,7 +69,7 @@ public class EppLifecycleContactTest extends EppTestCase {
}
@Test
public void testContactTransferPollMessage() throws Exception {
void testContactTransferPollMessage() throws Exception {
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
assertThatCommand("contact_create_sh8013.xml")
.atTime("2000-06-01T00:00:00Z")
@@ -48,15 +48,12 @@ import google.registry.model.reporting.HistoryEntry.Type;
import google.registry.testing.AppEngineRule;
import org.joda.money.Money;
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.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Tests for domain lifecycle. */
@RunWith(JUnit4.class)
public class EppLifecycleDomainTest extends EppTestCase {
class EppLifecycleDomainTest extends EppTestCase {
private static final ImmutableMap<String, String> DEFAULT_TRANSFER_RESPONSE_PARMS =
ImmutableMap.of(
@@ -64,17 +61,17 @@ public class EppLifecycleDomainTest extends EppTestCase {
"ACDATE", "2002-06-04T00:00:00Z",
"EXDATE", "2003-06-01T00:04:00Z");
@Rule
public final AppEngineRule appEngine =
@RegisterExtension
final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@Before
public void initTld() {
@BeforeEach
void beforeEach() {
createTlds("example", "tld");
}
@Test
public void testDomainDeleteRestore() throws Exception {
void testDomainDeleteRestore() throws Exception {
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
createContacts(DateTime.parse("2000-06-01T00:00:00Z"));
@@ -134,7 +131,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
}
@Test
public void testDomainDeleteRestore_duringAutorenewGracePeriod() throws Exception {
void testDomainDeleteRestore_duringAutorenewGracePeriod() throws Exception {
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
createContacts(DateTime.parse("2000-06-01T00:00:00Z"));
@@ -208,7 +205,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
}
@Test
public void testDomainDeleteRestore_duringRenewalGracePeriod() throws Exception {
void testDomainDeleteRestore_duringRenewalGracePeriod() throws Exception {
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
createContacts(DateTime.parse("2000-06-01T00:00:00Z"));
@@ -290,8 +287,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
}
@Test
public void testDomainDelete_duringAddAndRenewalGracePeriod_deletesImmediately()
throws Exception {
void testDomainDelete_duringAddAndRenewalGracePeriod_deletesImmediately() throws Exception {
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
createContacts(DateTime.parse("2000-06-01T00:00:00Z"));
@@ -386,7 +382,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
}
@Test
public void testDomainDeletion_withinAddGracePeriod_deletesImmediately() throws Exception {
void testDomainDeletion_withinAddGracePeriod_deletesImmediately() throws Exception {
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
createContacts(DateTime.parse("2000-06-01T00:00:00Z"));
@@ -442,7 +438,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
}
@Test
public void testDomainDeletion_outsideAddGracePeriod_showsRedemptionPeriod() throws Exception {
void testDomainDeletion_outsideAddGracePeriod_showsRedemptionPeriod() throws Exception {
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
createContacts(DateTime.parse("2000-06-01T00:00:00Z"));
@@ -504,7 +500,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
}
@Test
public void testEapDomainDeletion_withinAddGracePeriod_eapFeeIsNotRefunded() throws Exception {
void testEapDomainDeletion_withinAddGracePeriod_eapFeeIsNotRefunded() throws Exception {
assertThatCommand("login_valid_fee_extension.xml").hasResponse("generic_success_response.xml");
createContacts(DateTime.parse("2000-06-01T00:00:00Z"));
@@ -569,7 +565,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
}
@Test
public void testDomainDeletionWithSubordinateHost_fails() throws Exception {
void testDomainDeletionWithSubordinateHost_fails() throws Exception {
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
createFakesite();
createSubordinateHost();
@@ -582,7 +578,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
}
@Test
public void testDeletionOfDomain_afterRenameOfSubordinateHost_succeeds() throws Exception {
void testDeletionOfDomain_afterRenameOfSubordinateHost_succeeds() throws Exception {
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
assertThat(getRecordedEppMetric())
.hasClientId("NewRegistrar")
@@ -637,7 +633,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
}
@Test
public void testDeletionOfDomain_afterUpdateThatCreatesSubordinateHost_fails() throws Exception {
void testDeletionOfDomain_afterUpdateThatCreatesSubordinateHost_fails() throws Exception {
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
createFakesite();
@@ -680,7 +676,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
}
@Test
public void testDomainCreation_failsBeforeSunrise() throws Exception {
void testDomainCreation_failsBeforeSunrise() throws Exception {
DateTime sunriseDate = DateTime.parse("2000-05-30T00:00:00Z");
createTld(
"example",
@@ -714,7 +710,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
}
@Test
public void testDomainCheckFee_succeeds() throws Exception {
void testDomainCheckFee_succeeds() throws Exception {
DateTime gaDate = DateTime.parse("2000-05-30T00:00:00Z");
createTld(
"example",
@@ -740,7 +736,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
}
@Test
public void testDomainCreate_annualAutoRenewPollMessages_haveUniqueIds() throws Exception {
void testDomainCreate_annualAutoRenewPollMessages_haveUniqueIds() throws Exception {
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
// Create the domain.
createFakesite();
@@ -790,7 +786,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
}
@Test
public void testDomainTransferPollMessage_serverApproved() throws Exception {
void testDomainTransferPollMessage_serverApproved() throws Exception {
// As the losing registrar, create the domain.
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
createFakesite();
@@ -839,7 +835,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
}
@Test
public void testTransfer_autoRenewGraceActive_onlyAtAutomaticTransferTime_getsSubsumed()
void testTransfer_autoRenewGraceActive_onlyAtAutomaticTransferTime_getsSubsumed()
throws Exception {
// Register the domain as the first registrar.
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
@@ -877,7 +873,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
}
@Test
public void testNameserversTransferWithDomain_successfully() throws Exception {
void testNameserversTransferWithDomain_successfully() throws Exception {
// Log in as the first registrar and set up domains with hosts.
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
createFakesite();
@@ -914,7 +910,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
}
@Test
public void testRenewalFails_whenTotalTermExceeds10Years() throws Exception {
void testRenewalFails_whenTotalTermExceeds10Years() throws Exception {
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
// Creates domain with 2 year expiration.
createFakesite();
@@ -928,7 +924,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
}
@Test
public void testDomainDeletionCancelsPendingTransfer() throws Exception {
void testDomainDeletionCancelsPendingTransfer() throws Exception {
// Register the domain as the first registrar.
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
createFakesite();
@@ -966,7 +962,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
}
@Test
public void testDomainTransfer_subordinateHost_showsChangeInTransferQuery() throws Exception {
void testDomainTransfer_subordinateHost_showsChangeInTransferQuery() throws Exception {
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
createFakesite();
createSubordinateHost();
@@ -1002,7 +998,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
* superordinate domain, not whatever the transfer time from the second domain is.
*/
@Test
public void testSuccess_lastTransferTime_superordinateDomainTransferFollowedByHostUpdate()
void testSuccess_lastTransferTime_superordinateDomainTransferFollowedByHostUpdate()
throws Exception {
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
// Create fakesite.example with subordinate host ns3.fakesite.example
@@ -1056,7 +1052,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
* to be external, that the host retains the transfer time of the first superordinate domain.
*/
@Test
public void testSuccess_lastTransferTime_superordinateDomainTransferThenHostUpdateToExternal()
void testSuccess_lastTransferTime_superordinateDomainTransferThenHostUpdateToExternal()
throws Exception {
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
// Create fakesite.example with subordinate host ns3.fakesite.example
@@ -1099,7 +1095,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
}
@Test
public void testSuccess_multipartTldsWithSharedSuffixes() throws Exception {
void testSuccess_multipartTldsWithSharedSuffixes() throws Exception {
createTlds("bar.foo.tld", "foo.tld");
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
@@ -1143,7 +1139,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
}
@Test
public void testSuccess_multipartTldsWithSharedPrefixes() throws Exception {
void testSuccess_multipartTldsWithSharedPrefixes() throws Exception {
createTld("tld.foo");
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
@@ -1177,12 +1173,12 @@ public class EppLifecycleDomainTest extends EppTestCase {
/**
* Test a full launch of start-date sunrise.
*
* We show that we can't create during pre-delegation, can only create with an encoded mark during
* start-date sunrise - which we can then delete "as normal" (no need for a signed mark or
* <p>We show that we can't create during pre-delegation, can only create with an encoded mark
* during start-date sunrise - which we can then delete "as normal" (no need for a signed mark or
* anything for delete), and then use "regular" create during general-availability.
*/
@Test
public void testDomainCreation_startDateSunriseFull() throws Exception {
void testDomainCreation_startDateSunriseFull() throws Exception {
// The signed mark is valid between 2013 and 2017
DateTime sunriseDate = DateTime.parse("2014-09-08T09:09:09Z");
DateTime gaDate = sunriseDate.plusDays(30);
@@ -1278,7 +1274,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
/** Test that missing type= argument on launch create works in start-date sunrise. */
@Test
public void testDomainCreation_startDateSunrise_noType() throws Exception {
void testDomainCreation_startDateSunrise_noType() throws Exception {
// The signed mark is valid between 2013 and 2017
DateTime sunriseDate = DateTime.parse("2014-09-08T09:09:09Z");
DateTime gaDate = sunriseDate.plusDays(30);
@@ -1327,7 +1323,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
}
@Test
public void testDomainTransfer_duringAutorenewGrace() throws Exception {
void testDomainTransfer_duringAutorenewGrace() throws Exception {
// Creation date of fakesite: 2000-06-01T00:04:00.0Z
// Expiration date: 2002-06-01T00:04:00.0Z
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
@@ -1413,7 +1409,7 @@ public class EppLifecycleDomainTest extends EppTestCase {
}
@Test
public void testDomainTransfer_queryForServerApproved() throws Exception {
void testDomainTransfer_queryForServerApproved() throws Exception {
// Creation date of fakesite: 2000-06-01T00:04:00.0Z
// Expiration date: 2002-06-01T00:04:00.0Z
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
@@ -28,21 +28,18 @@ import google.registry.model.domain.DomainBase;
import google.registry.model.host.HostResource;
import google.registry.testing.AppEngineRule;
import org.joda.time.DateTime;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Tests for host lifecycle. */
@RunWith(JUnit4.class)
public class EppLifecycleHostTest extends EppTestCase {
class EppLifecycleHostTest extends EppTestCase {
@Rule
public final AppEngineRule appEngine =
@RegisterExtension
final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@Test
public void testLifecycle() throws Exception {
void testLifecycle() throws Exception {
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
assertThatCommand("hello.xml")
.atTime("2000-06-02T00:00:00Z")
@@ -90,7 +87,7 @@ public class EppLifecycleHostTest extends EppTestCase {
}
@Test
public void testRenamingHostToExistingHost_fails() throws Exception {
void testRenamingHostToExistingHost_fails() throws Exception {
createTld("example");
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
// Create the fakesite domain.
@@ -140,7 +137,7 @@ public class EppLifecycleHostTest extends EppTestCase {
}
@Test
public void testSuccess_multipartTldsWithSharedSuffixes() throws Exception {
void testSuccess_multipartTldsWithSharedSuffixes() throws Exception {
createTlds("bar.foo.tld", "foo.tld", "tld");
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
@@ -19,21 +19,18 @@ import static google.registry.model.eppoutput.Result.Code.SUCCESS_AND_CLOSE;
import static google.registry.testing.EppMetricSubject.assertThat;
import google.registry.testing.AppEngineRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Tests for login lifecycle. */
@RunWith(JUnit4.class)
public class EppLifecycleLoginTest extends EppTestCase {
class EppLifecycleLoginTest extends EppTestCase {
@Rule
public final AppEngineRule appEngine =
@RegisterExtension
final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@Test
public void testLoginAndLogout_recordsEppMetric() throws Exception {
void testLoginAndLogout_recordsEppMetric() throws Exception {
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
assertThat(getRecordedEppMetric())
.hasClientId("NewRegistrar")
@@ -20,20 +20,17 @@ import static org.joda.time.format.ISODateTimeFormat.dateTimeNoMillis;
import com.google.common.collect.ImmutableMap;
import google.registry.testing.AppEngineRule;
import org.joda.time.DateTime;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Test flows without login. */
@RunWith(JUnit4.class)
public class EppLoggedOutTest extends EppTestCase {
class EppLoggedOutTest extends EppTestCase {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@RegisterExtension
final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Test
public void testHello() throws Exception {
void testHello() throws Exception {
DateTime now = DateTime.now(UTC);
assertThatCommand("hello.xml", null)
.atTime(now)
@@ -41,7 +38,7 @@ public class EppLoggedOutTest extends EppTestCase {
}
@Test
public void testSyntaxError() throws Exception {
void testSyntaxError() throws Exception {
assertThatCommand("syntax_error.xml")
.hasResponse(
"response_error_no_cltrid.xml",
@@ -23,26 +23,23 @@ import google.registry.testing.AppEngineRule;
import google.registry.testing.CertificateSamples;
import java.util.Optional;
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.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Test logging in with TLS credentials. */
@RunWith(JUnit4.class)
public class EppLoginTlsTest extends EppTestCase {
class EppLoginTlsTest extends EppTestCase {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@RegisterExtension
final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
void setClientCertificateHash(String clientCertificateHash) {
setTransportCredentials(
new TlsCredentials(true, clientCertificateHash, Optional.of("192.168.1.100:54321")));
}
@Before
public void initTest() {
@BeforeEach
void beforeEach() {
persistResource(
loadRegistrar("NewRegistrar")
.asBuilder()
@@ -57,14 +54,14 @@ public class EppLoginTlsTest extends EppTestCase {
}
@Test
public void testLoginLogout() throws Exception {
void testLoginLogout() throws Exception {
setClientCertificateHash(CertificateSamples.SAMPLE_CERT_HASH);
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
assertThatLogoutSucceeds();
}
@Test
public void testLogin_wrongPasswordFails() throws Exception {
void testLogin_wrongPasswordFails() throws Exception {
setClientCertificateHash(CertificateSamples.SAMPLE_CERT_HASH);
// For TLS login, we also check the epp xml password.
assertThatLogin("NewRegistrar", "incorrect")
@@ -74,7 +71,7 @@ public class EppLoginTlsTest extends EppTestCase {
}
@Test
public void testMultiLogin() throws Exception {
void testMultiLogin() throws Exception {
setClientCertificateHash(CertificateSamples.SAMPLE_CERT_HASH);
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
assertThatLogoutSucceeds();
@@ -88,7 +85,7 @@ public class EppLoginTlsTest extends EppTestCase {
}
@Test
public void testNonAuthedLogin_fails() throws Exception {
void testNonAuthedLogin_fails() throws Exception {
setClientCertificateHash(CertificateSamples.SAMPLE_CERT_HASH);
assertThatLogin("TheRegistrar", "password2")
.hasResponse(
@@ -97,9 +94,8 @@ public class EppLoginTlsTest extends EppTestCase {
"CODE", "2200", "MSG", "Registrar certificate does not match stored certificate"));
}
@Test
public void testBadCertificate_failsBadCertificate2200() throws Exception {
void testBadCertificate_failsBadCertificate2200() throws Exception {
setClientCertificateHash("laffo");
assertThatLogin("NewRegistrar", "foo-BAR2")
.hasResponse(
@@ -109,7 +105,7 @@ public class EppLoginTlsTest extends EppTestCase {
}
@Test
public void testGfeDidntProvideClientCertificate_failsMissingCertificate2200() throws Exception {
void testGfeDidntProvideClientCertificate_failsMissingCertificate2200() throws Exception {
setClientCertificateHash("");
assertThatLogin("NewRegistrar", "foo-BAR2")
.hasResponse(
@@ -118,7 +114,7 @@ public class EppLoginTlsTest extends EppTestCase {
}
@Test
public void testGoodPrimaryCertificate() throws Exception {
void testGoodPrimaryCertificate() throws Exception {
setClientCertificateHash(CertificateSamples.SAMPLE_CERT_HASH);
DateTime now = DateTime.now(UTC);
persistResource(
@@ -131,7 +127,7 @@ public class EppLoginTlsTest extends EppTestCase {
}
@Test
public void testGoodFailoverCertificate() throws Exception {
void testGoodFailoverCertificate() throws Exception {
setClientCertificateHash(CertificateSamples.SAMPLE_CERT2_HASH);
DateTime now = DateTime.now(UTC);
persistResource(
@@ -144,7 +140,7 @@ public class EppLoginTlsTest extends EppTestCase {
}
@Test
public void testMissingPrimaryCertificateButHasFailover_usesFailover() throws Exception {
void testMissingPrimaryCertificateButHasFailover_usesFailover() throws Exception {
setClientCertificateHash(CertificateSamples.SAMPLE_CERT2_HASH);
DateTime now = DateTime.now(UTC);
persistResource(
@@ -157,7 +153,7 @@ public class EppLoginTlsTest extends EppTestCase {
}
@Test
public void testRegistrarHasNoCertificatesOnFile_fails() throws Exception {
void testRegistrarHasNoCertificatesOnFile_fails() throws Exception {
setClientCertificateHash("laffo");
DateTime now = DateTime.now(UTC);
persistResource(
@@ -52,16 +52,15 @@ import java.util.Optional;
import javax.annotation.Nullable;
import org.joda.money.Money;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.RegisterExtension;
public class EppTestCase {
private static final MediaType APPLICATION_EPP_XML_UTF8 =
MediaType.create("application", "epp+xml").withCharset(UTF_8);
@Rule
public final InjectRule inject = new InjectRule();
@RegisterExtension public final InjectRule inject = new InjectRule();
protected final FakeClock clock = new FakeClock();
@@ -70,8 +69,8 @@ public class EppTestCase {
private EppMetric.Builder eppMetricBuilder;
private boolean isSuperuser;
@Before
public void initTestCase() {
@BeforeEach
public void beforeEachEppTestCase() {
// For transactional flows
inject.setStaticField(Ofy.class, "clock", clock);
}
@@ -84,7 +83,7 @@ public class EppTestCase {
* such as {@link EppLoginUserTest}, {@link EppLoginAdminUserTest} and {@link EppLoginTlsTest}.
* Therefore, only those tests should call this method.
*/
protected void setTransportCredentials(TransportCredentials credentials) {
void setTransportCredentials(TransportCredentials credentials) {
this.credentials = credentials;
}
@@ -133,7 +132,7 @@ public class EppTestCase {
return new CommandAsserter(inputFilename, inputSubstitutions);
}
protected CommandAsserter assertThatLogin(String clientId, String password) {
CommandAsserter assertThatLogin(String clientId, String password) {
return assertThatCommand("login.xml", ImmutableMap.of("CLID", clientId, "PW", password));
}
@@ -202,12 +201,12 @@ public class EppTestCase {
return result;
}
protected EppMetric getRecordedEppMetric() {
EppMetric getRecordedEppMetric() {
return eppMetricBuilder.build();
}
/** Create the two administrative contacts and two hosts. */
protected void createContactsAndHosts() throws Exception {
void createContactsAndHosts() throws Exception {
DateTime createTime = DateTime.parse("2000-06-01T00:00:00Z");
createContacts(createTime);
assertThatCommand("host_create.xml", ImmutableMap.of("HOSTNAME", "ns1.example.external"))
@@ -239,7 +238,7 @@ public class EppTestCase {
}
/** Creates the domain fakesite.example with two nameservers on it. */
protected void createFakesite() throws Exception {
void createFakesite() throws Exception {
createContactsAndHosts();
assertThatCommand("domain_create_fakesite.xml")
.atTime("2000-06-01T00:04:00Z")
@@ -255,7 +254,7 @@ public class EppTestCase {
}
/** Creates ns3.fakesite.example as a host, then adds it to fakesite. */
protected void createSubordinateHost() throws Exception {
void createSubordinateHost() throws Exception {
// Add the fakesite nameserver (requires that domain is already created).
assertThatCommand("host_create_fakesite.xml")
.atTime("2000-06-06T00:01:00Z")
@@ -290,8 +289,7 @@ public class EppTestCase {
}
/** Makes a one-time billing event corresponding to the given domain's renewal. */
protected static BillingEvent.OneTime makeOneTimeRenewBillingEvent(
DomainBase domain, DateTime renewTime) {
static BillingEvent.OneTime makeOneTimeRenewBillingEvent(DomainBase domain, DateTime renewTime) {
return new BillingEvent.OneTime.Builder()
.setReason(Reason.RENEW)
.setTargetId(domain.getDomainName())
@@ -305,14 +303,14 @@ public class EppTestCase {
}
/** Makes a recurring billing event corresponding to the given domain's creation. */
protected static BillingEvent.Recurring makeRecurringCreateBillingEvent(
static BillingEvent.Recurring makeRecurringCreateBillingEvent(
DomainBase domain, DateTime eventTime, DateTime endTime) {
return makeRecurringBillingEvent(
domain, getOnlyHistoryEntryOfType(domain, Type.DOMAIN_CREATE), eventTime, endTime);
}
/** Makes a recurring billing event corresponding to the given domain's renewal. */
protected static BillingEvent.Recurring makeRecurringRenewBillingEvent(
static BillingEvent.Recurring makeRecurringRenewBillingEvent(
DomainBase domain, DateTime eventTime, DateTime endTime) {
return makeRecurringBillingEvent(
domain, getOnlyHistoryEntryOfType(domain, Type.DOMAIN_RENEW), eventTime, endTime);
@@ -333,7 +331,7 @@ public class EppTestCase {
}
/** Makes a cancellation billing event cancelling out the given domain create billing event. */
protected static BillingEvent.Cancellation makeCancellationBillingEventForCreate(
static BillingEvent.Cancellation makeCancellationBillingEventForCreate(
DomainBase domain, OneTime billingEventToCancel, DateTime createTime, DateTime deleteTime) {
return new BillingEvent.Cancellation.Builder()
.setTargetId(domain.getDomainName())
@@ -347,7 +345,7 @@ public class EppTestCase {
}
/** Makes a cancellation billing event cancelling out the given domain renew billing event. */
protected static BillingEvent.Cancellation makeCancellationBillingEventForRenew(
static BillingEvent.Cancellation makeCancellationBillingEventForRenew(
DomainBase domain, OneTime billingEventToCancel, DateTime renewTime, DateTime deleteTime) {
return new BillingEvent.Cancellation.Builder()
.setTargetId(domain.getDomainName())
@@ -369,7 +367,7 @@ public class EppTestCase {
* This is necessary because the ID will be different even though all the rest of the fields are
* the same.
*/
protected static Key<OneTime> findKeyToActualOneTimeBillingEvent(OneTime expectedBillingEvent) {
private static Key<OneTime> findKeyToActualOneTimeBillingEvent(OneTime expectedBillingEvent) {
Optional<OneTime> actualCreateBillingEvent =
ofy()
.load()
@@ -23,19 +23,16 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import google.registry.testing.FakeHttpSession;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
/** Tests for {@link EppTlsAction}. */
@RunWith(JUnit4.class)
public class EppTlsActionTest {
class EppTlsActionTest {
private static final byte[] INPUT_XML_BYTES = "<xml>".getBytes(UTF_8);
@Test
public void testPassesArgumentsThrough() {
void testPassesArgumentsThrough() {
EppTlsAction action = new EppTlsAction();
action.inputXmlBytes = INPUT_XML_BYTES;
action.tlsCredentials = mock(TlsCredentials.class);
@@ -21,14 +21,11 @@ import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
/** Tests for {@link EppToolAction}. */
@RunWith(JUnit4.class)
public class EppToolActionTest {
class EppToolActionTest {
private void doTest(boolean isDryRun, boolean isSuperuser) {
EppToolAction action = new EppToolAction();
@@ -50,22 +47,22 @@ public class EppToolActionTest {
}
@Test
public void testDryRunAndSuperuser() {
void testDryRunAndSuperuser() {
doTest(true, true);
}
@Test
public void testDryRun() {
void testDryRun() {
doTest(true, false);
}
@Test
public void testSuperuser() {
void testSuperuser() {
doTest(false, true);
}
@Test
public void testNeitherDryRunNorSuperuser() {
void testNeitherDryRunNorSuperuser() {
doTest(false, false);
}
}
@@ -24,25 +24,22 @@ import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.collect.ImmutableMap;
import google.registry.testing.EppLoader;
import java.util.Base64;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link EppXmlSanitizer}. */
@RunWith(JUnit4.class)
public class EppXmlSanitizerTest {
class EppXmlSanitizerTest {
private static final String UTF8_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
@Test
public void testSanitize_noSensitiveData_noop() throws Exception {
void testSanitize_noSensitiveData_noop() throws Exception {
byte[] inputXmlBytes = loadBytes(getClass(), "host_create.xml").read();
String expectedXml = UTF8_HEADER + new String(inputXmlBytes, UTF_8);
assertXmlEqualsIgnoreHeader(expectedXml, sanitizeEppXml(inputXmlBytes));
}
@Test
public void testSanitize_loginPasswords_sanitized() throws Exception {
void testSanitize_loginPasswords_sanitized() throws Exception {
String inputXml =
new EppLoader(
this,
@@ -60,7 +57,7 @@ public class EppXmlSanitizerTest {
}
@Test
public void testSanitize_loginPasswordTagWrongCase_sanitized() throws Exception {
void testSanitize_loginPasswordTagWrongCase_sanitized() throws Exception {
String inputXml =
new EppLoader(
this, "login_wrong_case.xml", ImmutableMap.of("PW", "oldpass", "NEWPW", "newPw"))
@@ -76,7 +73,7 @@ public class EppXmlSanitizerTest {
}
@Test
public void testSanitize_contactAuthInfo_sanitized() throws Exception {
void testSanitize_contactAuthInfo_sanitized() throws Exception {
byte[] inputXmlBytes = loadBytes(getClass(), "contact_info.xml").read();
String expectedXml =
UTF8_HEADER
@@ -85,7 +82,7 @@ public class EppXmlSanitizerTest {
}
@Test
public void testSanitize_contactCreateResponseAuthInfo_sanitized() throws Exception {
void testSanitize_contactCreateResponseAuthInfo_sanitized() throws Exception {
byte[] inputXmlBytes = loadBytes(getClass(), "contact_info_from_create_response.xml").read();
String expectedXml =
UTF8_HEADER
@@ -96,32 +93,32 @@ public class EppXmlSanitizerTest {
}
@Test
public void testSanitize_emptyElement_transformedToLongForm() throws Exception {
void testSanitize_emptyElement_transformedToLongForm() throws Exception {
byte[] inputXmlBytes = "<pw/>".getBytes(UTF_8);
assertXmlEqualsIgnoreHeader("<pw></pw>", sanitizeEppXml(inputXmlBytes));
}
@Test
public void testSanitize_invalidXML_throws() {
void testSanitize_invalidXML_throws() {
byte[] inputXmlBytes = "<pw>".getBytes(UTF_8);
assertThat(sanitizeEppXml(inputXmlBytes))
.isEqualTo(Base64.getMimeEncoder().encodeToString(inputXmlBytes));
}
@Test
public void testSanitize_unicode_hasCorrectCharCount() throws Exception {
void testSanitize_unicode_hasCorrectCharCount() throws Exception {
byte[] inputXmlBytes = "<pw>\u007F\u4E43x</pw>".getBytes(UTF_8);
assertXmlEqualsIgnoreHeader("<pw>C**</pw>", sanitizeEppXml(inputXmlBytes));
}
@Test
public void testSanitize_emptyString_encodedToBase64() {
void testSanitize_emptyString_encodedToBase64() {
byte[] inputXmlBytes = "".getBytes(UTF_8);
assertThat(sanitizeEppXml(inputXmlBytes)).isEqualTo("");
}
@Test
public void testSanitize_utf16_encodingPreserved() {
void testSanitize_utf16_encodingPreserved() {
// Test data should specify an endian-specific UTF-16 scheme for easy assertion. If 'UTF-16' is
// used, the XMLEventReader in sanitizer may resolve it to an endian-specific one.
String inputXml = "<?xml version=\"1.0\" encoding=\"UTF-16LE\"?><p>\u03bc</p>\n";
@@ -16,20 +16,17 @@ package google.registry.flows;
import com.google.common.collect.ImmutableMap;
import google.registry.testing.AppEngineRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Tests for <a href="https://en.wikipedia.org/wiki/XML_external_entity_attack">XXE</a> attacks. */
@RunWith(JUnit4.class)
public class EppXxeAttackTest extends EppTestCase {
class EppXxeAttackTest extends EppTestCase {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@RegisterExtension
final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Test
public void testRemoteXmlExternalEntity() throws Exception {
void testRemoteXmlExternalEntity() throws Exception {
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
assertThatCommand("contact_create_remote_xxe.xml")
.hasResponse(
@@ -42,7 +39,7 @@ public class EppXxeAttackTest extends EppTestCase {
}
@Test
public void testLocalXmlExtrernalEntity() throws Exception {
void testLocalXmlExtrernalEntity() throws Exception {
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
assertThatCommand("contact_create_local_xxe.xml")
.hasResponse(
@@ -55,7 +52,7 @@ public class EppXxeAttackTest extends EppTestCase {
}
@Test
public void testBillionLaughsAttack() throws Exception {
void testBillionLaughsAttack() throws Exception {
assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
assertThatCommand("contact_create_billion_laughs.xml")
.hasResponse(
@@ -38,20 +38,17 @@ import google.registry.model.eppinput.EppInput.CommandExtension;
import google.registry.testing.AppEngineRule;
import google.registry.util.TypeUtils;
import java.util.logging.LogRecord;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link ExtensionManager}. */
@RunWith(JUnit4.class)
public class ExtensionManagerTest {
class ExtensionManagerTest {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@RegisterExtension
final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Test
public void testDuplicateExtensionsForbidden() {
void testDuplicateExtensionsForbidden() {
ExtensionManager manager =
new TestInstanceBuilder()
.setEppRequestSource(EppRequestSource.TOOL)
@@ -66,7 +63,7 @@ public class ExtensionManagerTest {
}
@Test
public void testUndeclaredExtensionsLogged() throws Exception {
void testUndeclaredExtensionsLogged() throws Exception {
TestLogHandler handler = new TestLogHandler();
LoggerConfig.getConfig(ExtensionManager.class).addHandler(handler);
ExtensionManager manager =
@@ -88,7 +85,7 @@ public class ExtensionManagerTest {
}
@Test
public void testBlacklistedExtensions_forbiddenWhenUndeclared() {
void testBlacklistedExtensions_forbiddenWhenUndeclared() {
ExtensionManager manager =
new TestInstanceBuilder()
.setEppRequestSource(EppRequestSource.TOOL)
@@ -102,7 +99,7 @@ public class ExtensionManagerTest {
}
@Test
public void testBlacklistedExtensions_allowedWhenDeclared() throws Exception {
void testBlacklistedExtensions_allowedWhenDeclared() throws Exception {
ExtensionManager manager =
new TestInstanceBuilder()
.setEppRequestSource(EppRequestSource.TOOL)
@@ -114,7 +111,7 @@ public class ExtensionManagerTest {
}
@Test
public void testMetadataExtension_allowedForToolSource() throws Exception {
void testMetadataExtension_allowedForToolSource() throws Exception {
ExtensionManager manager =
new TestInstanceBuilder()
.setEppRequestSource(EppRequestSource.TOOL)
@@ -126,7 +123,7 @@ public class ExtensionManagerTest {
}
@Test
public void testMetadataExtension_forbiddenWhenNotToolSource() {
void testMetadataExtension_forbiddenWhenNotToolSource() {
ExtensionManager manager =
new TestInstanceBuilder()
.setEppRequestSource(EppRequestSource.CONSOLE)
@@ -139,7 +136,7 @@ public class ExtensionManagerTest {
}
@Test
public void testSuperuserExtension_allowedForToolSource() throws Exception {
void testSuperuserExtension_allowedForToolSource() throws Exception {
ExtensionManager manager =
new TestInstanceBuilder()
.setEppRequestSource(EppRequestSource.TOOL)
@@ -152,7 +149,7 @@ public class ExtensionManagerTest {
}
@Test
public void testSuperuserExtension_forbiddenWhenNotSuperuser() {
void testSuperuserExtension_forbiddenWhenNotSuperuser() {
ExtensionManager manager =
new TestInstanceBuilder()
.setEppRequestSource(EppRequestSource.TOOL)
@@ -167,7 +164,7 @@ public class ExtensionManagerTest {
}
@Test
public void testSuperuserExtension_forbiddenWhenNotToolSource() {
void testSuperuserExtension_forbiddenWhenNotToolSource() {
ExtensionManager manager =
new TestInstanceBuilder()
.setEppRequestSource(EppRequestSource.CONSOLE)
@@ -182,7 +179,7 @@ public class ExtensionManagerTest {
}
@Test
public void testUnimplementedExtensionsForbidden() {
void testUnimplementedExtensionsForbidden() {
ExtensionManager manager =
new TestInstanceBuilder()
.setEppRequestSource(EppRequestSource.TOOL)
@@ -32,14 +32,11 @@ import google.registry.model.reporting.IcannReportingTypes.ActivityReportField;
import java.util.Map;
import java.util.Optional;
import org.json.simple.JSONValue;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link FlowReporter}. */
@RunWith(JUnit4.class)
public class FlowReporterTest {
class FlowReporterTest {
static class TestCommandFlow implements Flow {
@Override
@@ -59,8 +56,8 @@ public class FlowReporterTest {
private final FlowReporter flowReporter = new FlowReporter();
private final TestLogHandler handler = new TestLogHandler();
@Before
public void before() {
@BeforeEach
void beforeEach() {
LoggerConfig.getConfig(FlowReporter.class).addHandler(handler);
flowReporter.trid = Trid.create("client-123", "server-456");
flowReporter.clientId = "TheRegistrar";
@@ -74,7 +71,7 @@ public class FlowReporterTest {
}
@Test
public void testRecordToLogs_metadata_basic() throws Exception {
void testRecordToLogs_metadata_basic() throws Exception {
when(flowReporter.eppInput.isDomainType()).thenReturn(true);
when(flowReporter.eppInput.getResourceType()).thenReturn(Optional.of("domain"));
flowReporter.recordToLogs();
@@ -93,7 +90,7 @@ public class FlowReporterTest {
}
@Test
public void testRecordToLogs_metadata_withReportingSpec() throws Exception {
void testRecordToLogs_metadata_withReportingSpec() throws Exception {
flowReporter.flowClass = TestReportingSpecCommandFlow.class;
flowReporter.recordToLogs();
Map<String, Object> json =
@@ -103,7 +100,7 @@ public class FlowReporterTest {
}
@Test
public void testRecordToLogs_metadata_noClientId() throws Exception {
void testRecordToLogs_metadata_noClientId() throws Exception {
flowReporter.clientId = "";
flowReporter.recordToLogs();
Map<String, Object> json =
@@ -112,7 +109,7 @@ public class FlowReporterTest {
}
@Test
public void testRecordToLogs_metadata_notResourceFlow_noResourceTypeOrTld() throws Exception {
void testRecordToLogs_metadata_notResourceFlow_noResourceTypeOrTld() throws Exception {
when(flowReporter.eppInput.isDomainType()).thenReturn(false);
when(flowReporter.eppInput.getResourceType()).thenReturn(Optional.empty());
flowReporter.recordToLogs();
@@ -123,9 +120,8 @@ public class FlowReporterTest {
assertThat(json).containsEntry("tlds", ImmutableList.of());
}
@Test
public void testRecordToLogs_metadata_notDomainFlow_noTld() throws Exception {
void testRecordToLogs_metadata_notDomainFlow_noTld() throws Exception {
when(flowReporter.eppInput.isDomainType()).thenReturn(false);
when(flowReporter.eppInput.getResourceType()).thenReturn(Optional.of("contact"));
flowReporter.recordToLogs();
@@ -137,7 +133,7 @@ public class FlowReporterTest {
}
@Test
public void testRecordToLogs_metadata_multipartDomainName_multipartTld() throws Exception {
void testRecordToLogs_metadata_multipartDomainName_multipartTld() throws Exception {
when(flowReporter.eppInput.isDomainType()).thenReturn(true);
when(flowReporter.eppInput.getResourceType()).thenReturn(Optional.of("domain"));
when(flowReporter.eppInput.getSingleTargetId()).thenReturn(Optional.of("target.co.uk"));
@@ -152,7 +148,7 @@ public class FlowReporterTest {
}
@Test
public void testRecordToLogs_metadata_multipleTargetIds_uniqueTldSet() throws Exception {
void testRecordToLogs_metadata_multipleTargetIds_uniqueTldSet() throws Exception {
when(flowReporter.eppInput.isDomainType()).thenReturn(true);
when(flowReporter.eppInput.getSingleTargetId()).thenReturn(Optional.empty());
when(flowReporter.eppInput.getTargetIds())
@@ -168,7 +164,7 @@ public class FlowReporterTest {
}
@Test
public void testRecordToLogs_metadata_uppercaseDomainName_lowercaseTld() throws Exception {
void testRecordToLogs_metadata_uppercaseDomainName_lowercaseTld() throws Exception {
when(flowReporter.eppInput.isDomainType()).thenReturn(true);
when(flowReporter.eppInput.getSingleTargetId()).thenReturn(Optional.of("TARGET.FOO"));
when(flowReporter.eppInput.getTargetIds()).thenReturn(ImmutableList.of("TARGET.FOO"));
@@ -182,7 +178,7 @@ public class FlowReporterTest {
}
@Test
public void testRecordToLogs_metadata_invalidDomainName_stillGuessesTld() throws Exception {
void testRecordToLogs_metadata_invalidDomainName_stillGuessesTld() throws Exception {
when(flowReporter.eppInput.isDomainType()).thenReturn(true);
when(flowReporter.eppInput.getSingleTargetId()).thenReturn(Optional.of("<foo@bar.com>"));
when(flowReporter.eppInput.getTargetIds()).thenReturn(ImmutableList.of("<foo@bar.com>"));
@@ -196,7 +192,7 @@ public class FlowReporterTest {
}
@Test
public void testRecordToLogs_metadata_domainWithoutPeriod_noTld() throws Exception {
void testRecordToLogs_metadata_domainWithoutPeriod_noTld() throws Exception {
when(flowReporter.eppInput.isDomainType()).thenReturn(true);
when(flowReporter.eppInput.getSingleTargetId()).thenReturn(Optional.of("target,foo"));
when(flowReporter.eppInput.getTargetIds()).thenReturn(ImmutableList.of("target,foo"));
@@ -38,19 +38,15 @@ import google.registry.testing.FakeClock;
import google.registry.testing.FakeHttpSession;
import java.util.List;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.Mockito;
/** Unit tests for {@link FlowRunner}. */
@RunWith(JUnit4.class)
public class FlowRunnerTest {
class FlowRunnerTest {
@Rule
public final AppEngineRule appEngineRule = new AppEngineRule.Builder().build();
@RegisterExtension final AppEngineRule appEngineRule = new AppEngineRule.Builder().build();
private final FlowRunner flowRunner = new FlowRunner();
private final EppMetric.Builder eppMetricBuilder = EppMetric.builderForRequest(new FakeClock());
@@ -64,8 +60,8 @@ public class FlowRunnerTest {
}
}
@Before
public void before() {
@BeforeEach
void beforeEach() {
LoggerConfig.getConfig(FlowRunner.class).addHandler(handler);
flowRunner.clientId = "TheRegistrar";
flowRunner.credentials = new PasswordOnlyTransportCredentials();
@@ -83,33 +79,33 @@ public class FlowRunnerTest {
}
@Test
public void testRun_nonTransactionalCommand_setsCommandNameOnMetric() throws Exception {
void testRun_nonTransactionalCommand_setsCommandNameOnMetric() throws Exception {
flowRunner.isTransactional = true;
flowRunner.run(eppMetricBuilder);
assertThat(eppMetricBuilder.build().getCommandName()).hasValue("TestCommand");
}
@Test
public void testRun_transactionalCommand_setsCommandNameOnMetric() throws Exception {
void testRun_transactionalCommand_setsCommandNameOnMetric() throws Exception {
flowRunner.run(eppMetricBuilder);
assertThat(eppMetricBuilder.build().getCommandName()).hasValue("TestCommand");
}
@Test
public void testRun_callsFlowReporterOnce() throws Exception {
void testRun_callsFlowReporterOnce() throws Exception {
flowRunner.run(eppMetricBuilder);
verify(flowRunner.flowReporter).recordToLogs();
}
@Test
public void testRun_dryRun_doesNotCallFlowReporter() throws Exception {
void testRun_dryRun_doesNotCallFlowReporter() throws Exception {
flowRunner.isDryRun = true;
flowRunner.run(eppMetricBuilder);
verify(flowRunner.flowReporter, never()).recordToLogs();
}
@Test
public void testRun_loggingStatement_basic() throws Exception {
void testRun_loggingStatement_basic() throws Exception {
flowRunner.run(eppMetricBuilder);
assertThat(Splitter.on("\n\t").split(findFirstLogMessageByPrefix(handler, "EPP Command\n\t")))
.containsExactly(
@@ -128,7 +124,7 @@ public class FlowRunnerTest {
}
@Test
public void testRun_loggingStatement_httpSessionMetadata() throws Exception {
void testRun_loggingStatement_httpSessionMetadata() throws Exception {
flowRunner.sessionMetadata = new HttpSessionMetadata(new FakeHttpSession());
flowRunner.sessionMetadata.setClientId("TheRegistrar");
flowRunner.run(eppMetricBuilder);
@@ -139,7 +135,7 @@ public class FlowRunnerTest {
}
@Test
public void testRun_loggingStatement_tlsCredentials() throws Exception {
void testRun_loggingStatement_tlsCredentials() throws Exception {
flowRunner.credentials = new TlsCredentials(true, "abc123def", Optional.of("127.0.0.1"));
flowRunner.run(eppMetricBuilder);
assertThat(Splitter.on("\n\t").split(findFirstLogMessageByPrefix(handler, "EPP Command\n\t")))
@@ -147,7 +143,7 @@ public class FlowRunnerTest {
}
@Test
public void testRun_loggingStatement_dryRun() throws Exception {
void testRun_loggingStatement_dryRun() throws Exception {
flowRunner.isDryRun = true;
flowRunner.run(eppMetricBuilder);
assertThat(Splitter.on("\n\t").split(findFirstLogMessageByPrefix(handler, "EPP Command\n\t")))
@@ -155,7 +151,7 @@ public class FlowRunnerTest {
}
@Test
public void testRun_loggingStatement_superuser() throws Exception {
void testRun_loggingStatement_superuser() throws Exception {
flowRunner.isSuperuser = true;
flowRunner.run(eppMetricBuilder);
assertThat(Splitter.on("\n\t").split(findFirstLogMessageByPrefix(handler, "EPP Command\n\t")))
@@ -163,7 +159,7 @@ public class FlowRunnerTest {
}
@Test
public void testRun_loggingStatement_complexEppInput() throws Exception {
void testRun_loggingStatement_complexEppInput() throws Exception {
String domainCreateXml = loadFile(getClass(), "domain_create_prettyprinted.xml");
String sanitizedDomainCreateXml = domainCreateXml.replace("2fooBAR", "*******");
flowRunner.inputXmlBytes = domainCreateXml.getBytes(UTF_8);
@@ -73,16 +73,22 @@ import org.junit.jupiter.api.extension.RegisterExtension;
public abstract class FlowTestCase<F extends Flow> {
/** Whether to actually write to Datastore or just simulate. */
public enum CommitMode { LIVE, DRY_RUN }
public enum CommitMode {
LIVE,
DRY_RUN
}
/** Whether to run in normal or superuser mode. */
public enum UserPrivileges { NORMAL, SUPERUSER }
public enum UserPrivileges {
NORMAL,
SUPERUSER
}
@RegisterExtension
public final AppEngineRule appEngine =
final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@RegisterExtension public final InjectRule inject = new InjectRule();
@RegisterExtension final InjectRule inject = new InjectRule();
protected EppLoader eppLoader;
protected SessionMetadata sessionMetadata;
@@ -94,7 +100,7 @@ public abstract class FlowTestCase<F extends Flow> {
private EppMetric.Builder eppMetricBuilder;
@BeforeEach
public void init() {
public void beforeEachFlowTestCase() {
sessionMetadata = new HttpSessionMetadata(new FakeHttpSession());
sessionMetadata.setClientId("TheRegistrar");
sessionMetadata.setServiceExtensionUris(ProtocolDefinition.getVisibleServiceExtensionUris());
@@ -26,7 +26,7 @@ import google.registry.model.eppoutput.CheckData;
* @param <F> the flow type
* @param <R> the resource type
*/
public class ResourceCheckFlowTestCase<F extends Flow, R extends EppResource>
public abstract class ResourceCheckFlowTestCase<F extends Flow, R extends EppResource>
extends ResourceFlowTestCase<F, R> {
protected void doCheckTest(CheckData.Check... expected) throws Exception {
@@ -28,27 +28,24 @@ import google.registry.testing.AppEngineRule;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import org.joda.time.DateTime;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link TlsCredentials}. */
@RunWith(JUnit4.class)
public final class TlsCredentialsTest {
final class TlsCredentialsTest {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@RegisterExtension
final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Test
public void testProvideClientCertificateHash() {
void testProvideClientCertificateHash() {
HttpServletRequest req = mock(HttpServletRequest.class);
when(req.getHeader("X-SSL-Certificate")).thenReturn("data");
assertThat(TlsCredentials.EppTlsModule.provideClientCertificateHash(req)).isEqualTo("data");
}
@Test
public void testProvideClientCertificateHash_missing() {
void testProvideClientCertificateHash_missing() {
HttpServletRequest req = mock(HttpServletRequest.class);
BadRequestException thrown =
assertThrows(
@@ -58,7 +55,7 @@ public final class TlsCredentialsTest {
}
@Test
public void test_validateCertificate_canBeConfiguredToBypassCertHashes() throws Exception {
void test_validateCertificate_canBeConfiguredToBypassCertHashes() throws Exception {
TlsCredentials tls = new TlsCredentials(false, "certHash", Optional.of("192.168.1.1"));
persistResource(
loadRegistrar("TheRegistrar")
@@ -36,8 +36,8 @@ import org.junit.jupiter.api.BeforeEach;
* @param <F> the flow type
* @param <R> the resource type
*/
public class ContactTransferFlowTestCase<F extends Flow, R extends EppResource>
extends ResourceFlowTestCase<F, R>{
abstract class ContactTransferFlowTestCase<F extends Flow, R extends EppResource>
extends ResourceFlowTestCase<F, R> {
// Transfer is requested on the 6th and expires on the 11th.
// The "now" of this flow is on the 9th, 3 days in.
@@ -55,7 +55,7 @@ public class ContactTransferFlowTestCase<F extends Flow, R extends EppResource>
}
@BeforeEach
void initContactTest() {
void beforeEachContactTransferFlowTestCase() {
// Registrar ClientZ is used in tests that need another registrar that definitely doesn't own
// the resources in question.
persistResource(
@@ -54,8 +54,8 @@ import org.junit.jupiter.api.BeforeEach;
* @param <F> the flow type
* @param <R> the resource type
*/
public class DomainTransferFlowTestCase<F extends Flow, R extends EppResource>
extends ResourceFlowTestCase<F, R>{
abstract class DomainTransferFlowTestCase<F extends Flow, R extends EppResource>
extends ResourceFlowTestCase<F, R> {
// Transfer is requested on the 6th and expires on the 11th.
// The "now" of this flow is on the 9th, 3 days in.
@@ -81,7 +81,7 @@ public class DomainTransferFlowTestCase<F extends Flow, R extends EppResource>
}
@BeforeEach
void makeClientZ() {
void beforeEachDomainTransferFlowTestCase() {
// Registrar ClientZ is used in tests that need another registrar that definitely doesn't own
// the resources in question.
persistResource(
@@ -49,29 +49,26 @@ import google.registry.model.registry.Registry;
import google.registry.model.reporting.HistoryEntry;
import google.registry.testing.AppEngineRule;
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.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link AllocationTokenFlowUtils}. */
@RunWith(JUnit4.class)
public class AllocationTokenFlowUtilsTest {
class AllocationTokenFlowUtilsTest {
private final AllocationTokenFlowUtils flowUtils =
new AllocationTokenFlowUtils(new AllocationTokenCustomLogic());
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@RegisterExtension
final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Before
public void initTest() {
@BeforeEach
void beforeEach() {
createTld("tld");
}
@Test
public void test_validateToken_successfullyVerifiesValidToken() throws Exception {
void test_validateToken_successfullyVerifiesValidToken() throws Exception {
AllocationToken token =
persistResource(
new AllocationToken.Builder().setToken("tokeN").setTokenType(SINGLE_USE).build());
@@ -86,12 +83,12 @@ public class AllocationTokenFlowUtilsTest {
}
@Test
public void test_validateToken_failsOnNonexistentToken() {
void test_validateToken_failsOnNonexistentToken() {
assertValidateThrowsEppException(InvalidAllocationTokenException.class);
}
@Test
public void test_validateToken_failsOnNullToken() {
void test_validateToken_failsOnNullToken() {
assertAboutEppExceptions()
.that(
assertThrows(
@@ -107,7 +104,7 @@ public class AllocationTokenFlowUtilsTest {
}
@Test
public void test_validateToken_callsCustomLogic() {
void test_validateToken_callsCustomLogic() {
AllocationTokenFlowUtils failingFlowUtils =
new AllocationTokenFlowUtils(new FailingAllocationTokenCustomLogic());
persistResource(
@@ -126,7 +123,7 @@ public class AllocationTokenFlowUtilsTest {
}
@Test
public void test_validateToken_invalidForClientId() {
void test_validateToken_invalidForClientId() {
persistResource(
createOneMonthPromoTokenBuilder(DateTime.now(UTC).minusDays(1))
.setAllowedClientIds(ImmutableSet.of("NewRegistrar"))
@@ -135,7 +132,7 @@ public class AllocationTokenFlowUtilsTest {
}
@Test
public void test_validateToken_invalidForTld() {
void test_validateToken_invalidForTld() {
persistResource(
createOneMonthPromoTokenBuilder(DateTime.now(UTC).minusDays(1))
.setAllowedTlds(ImmutableSet.of("nottld"))
@@ -144,19 +141,19 @@ public class AllocationTokenFlowUtilsTest {
}
@Test
public void test_validateToken_beforePromoStart() {
void test_validateToken_beforePromoStart() {
persistResource(createOneMonthPromoTokenBuilder(DateTime.now(UTC).plusDays(1)).build());
assertValidateThrowsEppException(AllocationTokenNotInPromotionException.class);
}
@Test
public void test_validateToken_afterPromoEnd() {
void test_validateToken_afterPromoEnd() {
persistResource(createOneMonthPromoTokenBuilder(DateTime.now(UTC).minusMonths(2)).build());
assertValidateThrowsEppException(AllocationTokenNotInPromotionException.class);
}
@Test
public void test_validateToken_promoCancelled() {
void test_validateToken_promoCancelled() {
// the promo would be valid but it was cancelled 12 hours ago
persistResource(
createOneMonthPromoTokenBuilder(DateTime.now(UTC).minusDays(1))
@@ -171,7 +168,7 @@ public class AllocationTokenFlowUtilsTest {
}
@Test
public void test_checkDomainsWithToken_successfullyVerifiesValidToken() {
void test_checkDomainsWithToken_successfullyVerifiesValidToken() {
persistResource(
new AllocationToken.Builder().setToken("tokeN").setTokenType(SINGLE_USE).build());
assertThat(
@@ -190,7 +187,7 @@ public class AllocationTokenFlowUtilsTest {
}
@Test
public void test_checkDomainsWithToken_showsFailureMessageForRedeemedToken() {
void test_checkDomainsWithToken_showsFailureMessageForRedeemedToken() {
persistResource(
new AllocationToken.Builder()
.setToken("tokeN")
@@ -216,7 +213,7 @@ public class AllocationTokenFlowUtilsTest {
}
@Test
public void test_checkDomainsWithToken_callsCustomLogic() {
void test_checkDomainsWithToken_callsCustomLogic() {
persistResource(
new AllocationToken.Builder().setToken("tokeN").setTokenType(SINGLE_USE).build());
AllocationTokenFlowUtils failingFlowUtils =
@@ -235,7 +232,7 @@ public class AllocationTokenFlowUtilsTest {
}
@Test
public void test_checkDomainsWithToken_resultsFromCustomLogicAreIntegrated() {
void test_checkDomainsWithToken_resultsFromCustomLogicAreIntegrated() {
persistResource(
new AllocationToken.Builder().setToken("tokeN").setTokenType(SINGLE_USE).build());
AllocationTokenFlowUtils customResultFlowUtils =
@@ -26,70 +26,66 @@ import google.registry.flows.host.HostFlowUtils.HostNameTooLongException;
import google.registry.flows.host.HostFlowUtils.HostNameTooShallowException;
import google.registry.flows.host.HostFlowUtils.InvalidHostNameException;
import google.registry.testing.AppEngineRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link HostFlowUtils}. */
@RunWith(JUnit4.class)
public class HostFlowUtilsTest {
class HostFlowUtilsTest {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@RegisterExtension
final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Test
public void test_validExternalHostName_validates() throws Exception {
void test_validExternalHostName_validates() throws Exception {
assertThat(validateHostName("host.example.com").toString()).isEqualTo("host.example.com");
}
@Test
public void test_validExternalHostNameOnRegistrySuffixList_validates() throws Exception {
void test_validExternalHostNameOnRegistrySuffixList_validates() throws Exception {
assertThat(validateHostName("host.blogspot.com").toString()).isEqualTo("host.blogspot.com");
}
@Test
public void test_validExternalHostNameOnRegistrySuffixList_multipartTLD_validates()
throws Exception {
void test_validExternalHostNameOnRegistrySuffixList_multipartTLD_validates() throws Exception {
assertThat(validateHostName("ns1.host.co.uk").toString()).isEqualTo("ns1.host.co.uk");
}
@Test
public void test_validExternalHostNameOnRegistrySuffixList_multipartTLD_tooShallow() {
void test_validExternalHostNameOnRegistrySuffixList_multipartTLD_tooShallow() {
assertThrows(
HostNameTooShallowException.class, () -> validateHostName("host.co.uk").toString());
}
@Test
public void test_validateHostName_hostNameTooLong() {
void test_validateHostName_hostNameTooLong() {
assertThrows(
HostNameTooLongException.class,
() -> validateHostName(Strings.repeat("na", 200) + ".wat.man"));
}
@Test
public void test_validateHostName_hostNameNotLowerCase() {
void test_validateHostName_hostNameNotLowerCase() {
assertThrows(HostNameNotLowerCaseException.class, () -> validateHostName("NA.CAPS.TLD"));
}
@Test
public void test_validateHostName_hostNameNotPunyCoded() {
void test_validateHostName_hostNameNotPunyCoded() {
assertThrows(
HostNameNotPunyCodedException.class, () -> validateHostName("motörhead.death.metal"));
}
@Test
public void test_validateHostName_hostNameNotNormalized() {
void test_validateHostName_hostNameNotNormalized() {
assertThrows(HostNameNotNormalizedException.class, () -> validateHostName("root.node.yeah."));
}
@Test
public void test_validateHostName_hostNameHasLeadingHyphen() {
void test_validateHostName_hostNameHasLeadingHyphen() {
assertThrows(InvalidHostNameException.class, () -> validateHostName("-giga.mega.tld"));
}
@Test
public void test_validateHostName_hostNameTooShallow() {
void test_validateHostName_hostNameTooShallow() {
assertThrows(HostNameTooShallowException.class, () -> validateHostName("domain.tld"));
}
}
@@ -44,7 +44,7 @@ public abstract class LoginFlowTestCase extends FlowTestCase<LoginFlow> {
private Registrar.Builder registrarBuilder;
@BeforeEach
void initRegistrar() {
void beforeEachLoginFlowTestCase() {
sessionMetadata.setClientId(null); // Don't implicitly log in (all other flows need to).
registrar = loadRegistrar("NewRegistrar");
registrarBuilder = registrar.asBuilder();
@@ -17,7 +17,7 @@ package google.registry.keyring.api;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;
import google.registry.testing.BouncyCastleProviderRule;
import google.registry.testing.BouncyCastleProviderExtension;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.bouncycastle.openpgp.PGPException;
@@ -35,7 +35,8 @@ import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link KeySerializer}. */
class KeySerializerTest {
@RegisterExtension final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule();
@RegisterExtension
final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
/**
* An Armored representation of a pgp secret key.
@@ -22,7 +22,7 @@ import google.registry.keyring.api.KeySerializer;
import google.registry.model.server.KmsSecret;
import google.registry.model.server.KmsSecretRevision;
import google.registry.testing.AppEngineRule;
import google.registry.testing.BouncyCastleProviderRule;
import google.registry.testing.BouncyCastleProviderExtension;
import org.bouncycastle.openpgp.PGPKeyPair;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
@@ -33,7 +33,8 @@ import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link KmsKeyring}. */
class KmsKeyringTest {
@RegisterExtension final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule();
@RegisterExtension
final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
@RegisterExtension
final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@@ -23,7 +23,7 @@ import google.registry.keyring.api.KeySerializer;
import google.registry.model.server.KmsSecret;
import google.registry.model.server.KmsSecretRevision;
import google.registry.testing.AppEngineRule;
import google.registry.testing.BouncyCastleProviderRule;
import google.registry.testing.BouncyCastleProviderExtension;
import java.io.IOException;
import org.bouncycastle.openpgp.PGPKeyPair;
import org.bouncycastle.openpgp.PGPPublicKey;
@@ -37,7 +37,8 @@ public class KmsUpdaterTest {
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@RegisterExtension public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule();
@RegisterExtension
public final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
private KmsUpdater updater;
@@ -24,7 +24,7 @@ import static google.registry.testing.DatastoreHelper.persistResource;
import com.google.common.collect.ImmutableList;
import google.registry.model.contact.ContactResource;
import google.registry.model.host.HostResource;
import google.registry.testing.TestCacheRule;
import google.registry.testing.TestCacheExtension;
import org.joda.time.Duration;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
@@ -33,8 +33,8 @@ import org.junit.jupiter.api.extension.RegisterExtension;
public class EppResourceTest extends EntityTestCase {
@RegisterExtension
public final TestCacheRule testCacheRule =
new TestCacheRule.Builder().withEppResourceCache(Duration.standardDays(1)).build();
public final TestCacheExtension testCacheExtension =
new TestCacheExtension.Builder().withEppResourceCache(Duration.standardDays(1)).build();
@Test
void test_loadCached_ignoresContactChange() {
@@ -0,0 +1,95 @@
// Copyright 2020 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.model;
import static com.google.common.truth.Truth.assertAbout;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableSet;
import com.google.common.truth.Correspondence;
import com.google.common.truth.Correspondence.BinaryPredicate;
import com.google.common.truth.FailureMetadata;
import com.google.common.truth.SimpleSubjectBuilder;
import com.google.common.truth.Subject;
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Nullable;
/** Truth subject for asserting things about ImmutableObjects that are not built in. */
public final class ImmutableObjectSubject extends Subject {
private final ImmutableObject actual;
protected ImmutableObjectSubject(FailureMetadata failureMetadata, ImmutableObject actual) {
super(failureMetadata, actual);
this.actual = actual;
}
public void isEqualExceptFields(ImmutableObject expected, String... ignoredFields) {
Map<Field, Object> actualFields = filterFields(actual, ignoredFields);
Map<Field, Object> expectedFields = filterFields(expected, ignoredFields);
assertThat(actualFields).containsExactlyEntriesIn(expectedFields);
}
public static Correspondence<ImmutableObject, ImmutableObject> immutableObjectCorrespondence(
String... ignoredFields) {
return Correspondence.from(
new ImmutableObjectBinaryPredicate(ignoredFields), "has all relevant fields equal to");
}
public static SimpleSubjectBuilder<ImmutableObjectSubject, ImmutableObject>
assertAboutImmutableObjects() {
return assertAbout(ImmutableObjectSubject::new);
}
private static class ImmutableObjectBinaryPredicate
implements BinaryPredicate<ImmutableObject, ImmutableObject> {
private final String[] ignoredFields;
private ImmutableObjectBinaryPredicate(String... ignoredFields) {
this.ignoredFields = ignoredFields;
}
@Override
public boolean apply(@Nullable ImmutableObject actual, @Nullable ImmutableObject expected) {
if (actual == null && expected == null) {
return true;
}
if (actual == null || expected == null) {
return false;
}
Map<Field, Object> actualFields = filterFields(actual, ignoredFields);
Map<Field, Object> expectedFields = filterFields(expected, ignoredFields);
return Objects.equals(actualFields, expectedFields);
}
}
private static Map<Field, Object> filterFields(
ImmutableObject original, String... ignoredFields) {
ImmutableSet<String> ignoredFieldSet = ImmutableSet.copyOf(ignoredFields);
Map<Field, Object> originalFields = ModelUtils.getFieldValues(original);
// don't use ImmutableMap or a stream->collect model since we can have nulls
Map<Field, Object> result = new LinkedHashMap<>();
for (Map.Entry<Field, Object> entry : originalFields.entrySet()) {
if (!ignoredFieldSet.contains(entry.getKey().getName())) {
result.put(entry.getKey(), entry.getValue());
}
}
return result;
}
}
@@ -14,7 +14,7 @@
package google.registry.model.history;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.testing.SqlHelper.saveRegistrar;
import static java.nio.charset.StandardCharsets.UTF_8;
@@ -74,14 +74,9 @@ public class HostHistoryTest extends EntityTestCase {
}
private void assertHostHistoriesEqual(HostHistory one, HostHistory two) {
// enough of the fields get changed during serialization that we can't depend on .equals()
assertThat(one.getClientId()).isEqualTo(two.getClientId());
assertThat(one.getHostRepoId()).isEqualTo(two.getHostRepoId());
assertThat(one.getBySuperuser()).isEqualTo(two.getBySuperuser());
assertThat(one.getRequestedByRegistrar()).isEqualTo(two.getRequestedByRegistrar());
assertThat(one.getReason()).isEqualTo(two.getReason());
assertThat(one.getTrid()).isEqualTo(two.getTrid());
assertThat(one.getType()).isEqualTo(two.getType());
assertThat(one.getHostBase().getHostName()).isEqualTo(two.getHostBase().getHostName());
assertAboutImmutableObjects().that(one).isEqualExceptFields(two, "hostBase");
assertAboutImmutableObjects()
.that(one.getHostBase())
.isEqualExceptFields(two.getHostBase(), "repoId");
}
}
@@ -31,7 +31,7 @@ import google.registry.model.EntityTestCase;
import google.registry.model.contact.ContactResource;
import google.registry.model.host.HostResource;
import google.registry.model.index.ForeignKeyIndex.ForeignKeyHostIndex;
import google.registry.testing.TestCacheRule;
import google.registry.testing.TestCacheExtension;
import org.joda.time.Duration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -41,8 +41,8 @@ import org.junit.jupiter.api.extension.RegisterExtension;
public class ForeignKeyIndexTest extends EntityTestCase {
@RegisterExtension
public final TestCacheRule testCacheRule =
new TestCacheRule.Builder().withForeignIndexKeyCache(Duration.standardDays(1)).build();
public final TestCacheExtension testCacheExtension =
new TestCacheExtension.Builder().withForeignIndexKeyCache(Duration.standardDays(1)).build();
@BeforeEach
void setUp() {
@@ -48,7 +48,7 @@ import google.registry.model.registry.Registry;
import google.registry.model.registry.label.PremiumList.PremiumListEntry;
import google.registry.model.registry.label.PremiumList.PremiumListRevision;
import google.registry.testing.AppEngineRule;
import google.registry.testing.TestCacheRule;
import google.registry.testing.TestCacheExtension;
import java.util.Map;
import org.joda.money.Money;
import org.junit.jupiter.api.BeforeEach;
@@ -63,8 +63,8 @@ public class PremiumListUtilsTest {
// Set long persist times on caches so they can be tested (cache times default to 0 in tests).
@RegisterExtension
public final TestCacheRule testCacheRule =
new TestCacheRule.Builder()
public final TestCacheExtension testCacheExtension =
new TestCacheExtension.Builder()
.withPremiumListsCache(standardDays(1))
.withPremiumListEntriesCache(standardDays(1))
.build();
@@ -21,7 +21,7 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import com.google.common.collect.ImmutableSet;
import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import java.lang.reflect.Method;
import javax.persistence.Embeddable;
import javax.persistence.Embedded;
@@ -36,21 +36,18 @@ import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;
import javax.persistence.Transient;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link EntityCallbacksListener}. */
@RunWith(JUnit4.class)
public class EntityCallbacksListenerTest {
class EntityCallbacksListenerTest {
@Rule
public final JpaUnitTestRule jpaRule =
@RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule();
@Test
public void verifyAllCallbacks_executedExpectedTimes() {
void verifyAllCallbacks_executedExpectedTimes() {
TestEntity testPersist = new TestEntity();
jpaTm().transact(() -> jpaTm().saveNew(testPersist));
checkAll(testPersist, 1, 0, 0, 0);
@@ -84,7 +81,7 @@ public class EntityCallbacksListenerTest {
}
@Test
public void verifyAllManagedEntities_haveNoMethodWithEmbedded() {
void verifyAllManagedEntities_haveNoMethodWithEmbedded() {
ImmutableSet<Class> violations =
PersistenceXmlUtility.getManagedClasses().stream()
.filter(clazz -> clazz.isAnnotationPresent(Entity.class))
@@ -98,7 +95,7 @@ public class EntityCallbacksListenerTest {
}
@Test
public void verifyHasMethodAnnotatedWithEmbedded_work() {
void verifyHasMethodAnnotatedWithEmbedded_work() {
assertThat(hasMethodAnnotatedWithEmbedded(ViolationEntity.class)).isTrue();
}
@@ -24,7 +24,7 @@ import google.registry.model.ImmutableObject;
import google.registry.model.common.TimedTransitionProperty;
import google.registry.model.registry.Registry.BillingCostTransition;
import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.joda.money.Money;
@@ -36,7 +36,7 @@ import org.junit.jupiter.api.extension.RegisterExtension;
public class BillingCostTransitionConverterTest {
@RegisterExtension
public final JpaUnitTestRule jpa =
public final JpaUnitTestExtension jpa =
new JpaTestRules.Builder()
.withInitScript("sql/flyway/V14__load_extension_for_hstore.sql")
.withEntityClass(TestEntity.class)
@@ -22,25 +22,22 @@ import com.google.common.collect.ImmutableSet;
import com.google.common.hash.BloomFilter;
import google.registry.model.ImmutableObject;
import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import google.registry.schema.replay.EntityTest.EntityForTesting;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link BloomFilterConverter}. */
@RunWith(JUnit4.class)
public class BloomFilterConverterTest {
class BloomFilterConverterTest {
@Rule
public final JpaUnitTestRule jpaRule =
@RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule();
@Test
public void roundTripConversion_returnsSameBloomFilter() {
void roundTripConversion_returnsSameBloomFilter() {
BloomFilter<String> bloomFilter = BloomFilter.create(stringFunnel(US_ASCII), 3);
ImmutableSet.of("foo", "bar", "baz").forEach(bloomFilter::put);
TestEntity entity = new TestEntity(bloomFilter);
@@ -20,25 +20,23 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import com.google.common.collect.ImmutableList;
import google.registry.model.ImmutableObject;
import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import google.registry.util.CidrAddressBlock;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link CidrAddressBlockListConverter}. */
@RunWith(JUnit4.class)
public class CidrAddressBlockListConverterTest {
@Rule
public final JpaUnitTestRule jpaRule =
@RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule();
@Test
public void roundTripConversion_returnsSameCidrAddressBlock() {
void roundTripConversion_returnsSameCidrAddressBlock() {
List<CidrAddressBlock> addresses =
ImmutableList.of(
CidrAddressBlock.create("0.0.0.0/32"),
@@ -19,32 +19,29 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import google.registry.model.CreateAutoTimestamp;
import google.registry.model.ImmutableObject;
import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import google.registry.schema.replay.EntityTest.EntityForTesting;
import google.registry.testing.FakeClock;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.joda.time.DateTime;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link CreateAutoTimestampConverter}. */
@RunWith(JUnit4.class)
public class CreateAutoTimestampConverterTest {
private final FakeClock fakeClock = new FakeClock();
@Rule
public final JpaUnitTestRule jpaRule =
@RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder()
.withClock(fakeClock)
.withEntityClass(TestEntity.class)
.buildUnitTestRule();
@Test
public void testTypeConversion() {
void testTypeConversion() {
CreateAutoTimestamp ts = CreateAutoTimestamp.create(DateTime.parse("2019-09-9T11:39:00Z"));
TestEntity ent = new TestEntity("myinst", ts);
@@ -55,7 +52,7 @@ public class CreateAutoTimestampConverterTest {
}
@Test
public void testAutoInitialization() {
void testAutoInitialization() {
CreateAutoTimestamp ts = CreateAutoTimestamp.create(null);
TestEntity ent = new TestEntity("autoinit", ts);
@@ -21,28 +21,26 @@ import com.google.common.collect.ImmutableMap;
import google.registry.model.ImmutableObject;
import google.registry.model.registrar.Registrar.BillingAccountEntry;
import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import java.util.Map;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.joda.money.CurrencyUnit;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link CurrencyToBillingConverter}. */
@RunWith(JUnit4.class)
public class CurrencyToBillingConverterTest {
@Rule
public final JpaUnitTestRule jpaRule =
@RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder()
.withInitScript("sql/flyway/V14__load_extension_for_hstore.sql")
.withEntityClass(TestEntity.class)
.buildUnitTestRule();
@Test
public void roundTripConversion_returnsSameCurrencyToBillingMap() {
void roundTripConversion_returnsSameCurrencyToBillingMap() {
ImmutableMap<CurrencyUnit, BillingAccountEntry> currencyToBilling =
ImmutableMap.of(
CurrencyUnit.of("USD"),
@@ -20,27 +20,24 @@ import static org.junit.Assert.assertThrows;
import google.registry.model.ImmutableObject;
import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import google.registry.schema.replay.EntityTest.EntityForTesting;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.PersistenceException;
import org.joda.money.CurrencyUnit;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link CurrencyUnitConverter}. */
@RunWith(JUnit4.class)
public class CurrencyUnitConverterTest {
@Rule
public final JpaUnitTestRule jpaRule =
@RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule();
@Test
public void roundTripConversion() {
void roundTripConversion() {
TestEntity entity = new TestEntity(CurrencyUnit.EUR);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(entity));
assertThat(
@@ -59,7 +56,7 @@ public class CurrencyUnitConverterTest {
}
@Test
public void invalidCurrency() {
void invalidCurrency() {
jpaTm()
.transact(
() ->
@@ -19,46 +19,43 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import google.registry.model.ImmutableObject;
import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import java.sql.Timestamp;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link DateTimeConverter}. */
@RunWith(JUnit4.class)
public class DateTimeConverterTest {
@Rule
public final JpaUnitTestRule jpaRule =
@RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule();
private final DateTimeConverter converter = new DateTimeConverter();
@Test
public void convertToDatabaseColumn_returnsNullIfInputIsNull() {
void convertToDatabaseColumn_returnsNullIfInputIsNull() {
assertThat(converter.convertToDatabaseColumn(null)).isNull();
}
@Test
public void convertToDatabaseColumn_convertsCorrectly() {
void convertToDatabaseColumn_convertsCorrectly() {
DateTime dateTime = DateTime.parse("2019-09-01T01:01:01");
assertThat(converter.convertToDatabaseColumn(dateTime).getTime())
.isEqualTo(dateTime.getMillis());
}
@Test
public void convertToEntityAttribute_returnsNullIfInputIsNull() {
void convertToEntityAttribute_returnsNullIfInputIsNull() {
assertThat(converter.convertToEntityAttribute(null)).isNull();
}
@Test
public void convertToEntityAttribute_convertsCorrectly() {
void convertToEntityAttribute_convertsCorrectly() {
DateTime dateTime = DateTime.parse("2019-09-01T01:01:01Z");
long millis = dateTime.getMillis();
assertThat(converter.convertToEntityAttribute(new Timestamp(millis))).isEqualTo(dateTime);
@@ -69,7 +66,7 @@ public class DateTimeConverterTest {
}
@Test
public void converter_generatesTimestampWithNormalizedZone() {
void converter_generatesTimestampWithNormalizedZone() {
DateTime dt = parseDateTime("2019-09-01T01:01:01Z");
TestEntity entity = new TestEntity("normalized_utc_time", dt);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(entity));
@@ -81,7 +78,7 @@ public class DateTimeConverterTest {
}
@Test
public void converter_convertsNonUtcZoneCorrectly() {
void converter_convertsNonUtcZoneCorrectly() {
DateTime dt = parseDateTime("2019-09-01T01:01:01-05:00");
TestEntity entity = new TestEntity("new_york_time", dt);

Some files were not shown because too many files have changed in this diff Show More