1
0
mirror of https://github.com/google/nomulus synced 2026-06-09 16:33:02 +00:00

Compare commits

...

25 Commits

Author SHA1 Message Date
Ben McIlwain 91b7d92cf8 Upgrade TestPipeline extension from JUnit 4 to 5 2020-07-23 21:21:58 -04:00
Ben McIlwain 33910613da Get presubmits passing
This involves Guava -> Java 8 util migrations and fixing the license header.
2020-07-23 21:21:58 -04:00
Ben McIlwain 1fde678250 Copy TestPipeline rule from Apache Beam project into our codebase
This is copied in here with the absolute minimum # of modifications required
(just a rename to JUnit 5 format and some small fixes required to enable
compilation to be successful).

This is in preparation for the next commit where I'll convert this Rule into a
JUnit 5 extension, which is the entire goal here. But I wanted to get the code
from Apache Beam in with the maximum possible fidelity so that my changes will
be in a separate commit and will thus be obvious.

Note that we do unfortunately need to modify/rewrite the Rule itself; merely
wrapping it in some manner isn't possible.
2020-07-23 21:21:58 -04:00
gbrodman 8d56577653 Don't run presubmits over the .git folder (#711) 2020-07-23 18:12:34 -04:00
Ben McIlwain 3891d411de Upgrade most of remaining tests from JUnit 4 to JUnit 5 (#708) 2020-07-23 15:43:59 -04:00
gbrodman cadecb15d8 Rename the email field in UI and include rlock email if it exists (#697)
* Rename the email field in UI and include rlock email if it exists

* Change the capitalization of fields and titles and add a description
2020-07-23 14:30:12 -04:00
gbrodman 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 McIlwain cd23748fe8 Upgrade rest of tools test classes to JUnit 5 (#705) 2020-07-22 11:09:21 -04:00
Ben McIlwain cf41f5d354 Upgrade all remaining flows tests to JUnit 5 (#704) 2020-07-21 19:52:33 -04:00
Ben McIlwain 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 Huang f5186f8476 Merge two PremiumList entities (#690) 2020-07-21 18:18:52 -04:00
Lai Jiang 4e0ca19d2e Remove IDN elements from BRDA (#670)
Also added unit tests for RdeStagingReducer.
2020-07-21 15:29:32 -04:00
Ben McIlwain 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 McIlwain 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
gbrodman 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
gbrodman 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
gbrodman 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
gbrodman 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
Legina Chen a22998e1bc Change clientId to registrarId to resolve the bug wrt the mismatch of the variable names (#692) 2020-07-15 11:03:52 -07:00
Weimin Yu 03d02ab299 Fix JpaIntegrationRule in JUnit4 (#687)
* Fix JpaIntegrationRule in JUnit4

Made DatastoreExtension a JUnit4 Rule.

Nomulus model objects need Datastore API when manipulating Ofy keys.
As a result, JpaIntegrationTestRule must be used with AppEngineRule
or DatastoreExtension.

Also fixed WriteToSqlTest, which is the only JUnit4 test that uses
JpaIntegrationTestRule.
2020-07-15 10:42:33 -04:00
Lai Jiang 47f65f70ab Fix a typo (#689) 2020-07-15 10:39:11 -04:00
Weimin Yu 1aa1f351bf Run rdeStaging twice daily in Sandbox (#684)
* Run rdeStaging twice daily in Sandbox

This will allow the cursor to catch up to current date if
it somehow falls behind.
2020-07-14 14:54:34 -04:00
Weimin Yu 94c8c6b9f3 Add lastUpdateTime column to epp resources (#683)
* Add lastUpdateTime column to epp resources

Property was inadvertently left out.

Renamed getter and setter to match the property name.

Added a test helper to compare EppResources while ignoring
lastUpdateTime, which changes every time an instance is persisted.
2020-07-14 14:53:05 -04:00
gbrodman e74a9e6f02 Allow overrides of ContactBase methods (#681)
Hibernate might (will?) need to override these, so they shouldn't be
final.
2020-07-14 14:47:47 -04:00
gbrodman 37d3cc44b4 Fix small naming issue in a test (#685) 2020-07-14 13:57:44 -04:00
420 changed files with 6967 additions and 6437 deletions
+1 -1
View File
@@ -22,7 +22,7 @@ import sys
import re
# We should never analyze any generated files
UNIVERSALLY_SKIPPED_PATTERNS = {"/build/", "cloudbuild-caches", "/out/"}
UNIVERSALLY_SKIPPED_PATTERNS = {"/build/", "cloudbuild-caches", "/out/", ".git/"}
# We can't rely on CI to have the Enum package installed so we do this instead.
FORBIDDEN = 1
REQUIRED = 2
+1
View File
@@ -256,6 +256,7 @@ dependencies {
compile deps['org.bouncycastle:bcpg-jdk15on']
testCompile deps['org.bouncycastle:bcpkix-jdk15on']
compile deps['org.bouncycastle:bcprov-jdk15on']
testCompile deps['com.fasterxml.jackson.core:jackson-databind']
runtime deps['org.glassfish.jaxb:jaxb-runtime']
compile deps['org.hibernate:hibernate-core']
compile deps['org.joda:joda-money']
@@ -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()))
@@ -532,7 +532,7 @@ public class DeleteContactsAndHostsAction implements Runnable {
resource.getClass().getSimpleName());
return new AutoValue_DeleteContactsAndHostsAction_DeletionRequest.Builder()
.setKey(resourceKey)
.setLastUpdateTime(resource.getUpdateAutoTimestamp().getTimestamp())
.setLastUpdateTime(resource.getUpdateTimestamp().getTimestamp())
.setRequestingClientId(
checkNotNull(
params.get(PARAM_REQUESTING_CLIENT_ID), "Requesting client id not specified"))
@@ -319,13 +319,13 @@ public class RefreshDnsOnHostRenameAction implements Runnable {
HostResource host =
checkNotNull(ofy().load().key(hostKey).now(), "Host to refresh doesn't exist");
boolean isHostDeleted =
isDeleted(host, latestOf(now, host.getUpdateAutoTimestamp().getTimestamp()));
isDeleted(host, latestOf(now, host.getUpdateTimestamp().getTimestamp()));
if (isHostDeleted) {
logger.atInfo().log("Host %s is already deleted, not refreshing DNS.", hostKey);
}
return new AutoValue_RefreshDnsOnHostRenameAction_DnsRefreshRequest.Builder()
.setHostKey(hostKey)
.setLastUpdateTime(host.getUpdateAutoTimestamp().getTimestamp())
.setLastUpdateTime(host.getUpdateTimestamp().getTimestamp())
.setRequestedTime(
DateTime.parse(
checkNotNull(params.get(PARAM_REQUESTED_TIME), "Requested time not specified")))
@@ -21,7 +21,7 @@
SELECT
domain.fullyQualifiedDomainName AS domainName,
domain.__key__.name AS domainRepoId,
registrar.clientId AS clientId,
registrar.clientId AS registrarId,
COALESCE(registrar.emailAddress, '') AS registrarEmailAddress
FROM ( (
SELECT
@@ -18,7 +18,14 @@
and streams it to cloud storage. When this job has finished successfully, it'll
launch a separate task that uploads the deposit file to Iron Mountain via SFTP.
</description>
<schedule>every day 00:07</schedule>
<!--
This only needs to run once per day, but we launch additional jobs in case the
cursor is lagging behind, so it'll catch up to the current date eventually.
See <a href="../../../production/default/WEB-INF/cron.xml">production config</a> for an
explanation of job starting times.
-->
<schedule>every 12 hours from 00:07 to 12:07</schedule>
<target>backend</target>
</cron>
@@ -14,16 +14,21 @@
package google.registry.model;
import com.google.common.annotations.VisibleForTesting;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.MappedSuperclass;
import javax.xml.bind.annotation.XmlTransient;
/**
* Base class for entities that are the root of a Registry 2.0 entity group that gets enrolled in
* commit logs for backup purposes.
*
* <p>The commit log system needs to preserve the ordering of closely timed mutations to entities
* in a single entity group. We require an {@link UpdateAutoTimestamp} field on the root of a group
* so that we can enforce strictly increasing timestamps.
* <p>The commit log system needs to preserve the ordering of closely timed mutations to entities in
* a single entity group. We require an {@link UpdateAutoTimestamp} field on the root of a group so
* that we can enforce strictly increasing timestamps.
*/
@MappedSuperclass
public abstract class BackupGroupRoot extends ImmutableObject {
/**
* An automatically managed timestamp of when this object was last written to Datastore.
@@ -32,10 +37,14 @@ public abstract class BackupGroupRoot extends ImmutableObject {
* that this is updated on every save, rather than only in response to an {@code <update>} command
*/
@XmlTransient
// Prevents subclasses from unexpectedly accessing as property (e.g., HostResource), which would
// require an unnecessary non-private setter method.
@Access(AccessType.FIELD)
@VisibleForTesting
UpdateAutoTimestamp updateTimestamp = UpdateAutoTimestamp.create(null);
/** Get the {@link UpdateAutoTimestamp} for this entity. */
public final UpdateAutoTimestamp getUpdateAutoTimestamp() {
public UpdateAutoTimestamp getUpdateTimestamp() {
return updateTimestamp;
}
}
@@ -155,7 +155,7 @@ public final class EppResourceUtils {
// time for writes.
return Optional.of(
cloneProjectedAtTime(
resource, latestOf(now, resource.getUpdateAutoTimestamp().getTimestamp())));
resource, latestOf(now, resource.getUpdateTimestamp().getTimestamp())));
}
/**
@@ -298,7 +298,7 @@ public final class EppResourceUtils {
// and returns it projected forward to exactly the desired timestamp, or null if the resource is
// deleted at that timestamp.
final Result<T> loadResult =
isAtOrAfter(timestamp, resource.getUpdateAutoTimestamp().getTimestamp())
isAtOrAfter(timestamp, resource.getUpdateTimestamp().getTimestamp())
? new ResultNow<>(resource)
: loadMostRecentRevisionAtTime(resource, timestamp);
return () -> {
@@ -224,12 +224,12 @@ public class ContactBase extends EppResource implements ResourceWithTransferData
return disclose;
}
public final String getCurrentSponsorClientId() {
public String getCurrentSponsorClientId() {
return getPersistedCurrentSponsorClientId();
}
@Override
public final ContactTransferData getTransferData() {
public ContactTransferData getTransferData() {
return Optional.ofNullable(transferData).orElse(ContactTransferData.EMPTY);
}
@@ -168,7 +168,7 @@ class CommitLoggedWork<R> implements Runnable {
DateTime transactionTime, Set<Entry<Key<BackupGroupRoot>, BackupGroupRoot>> bgrEntries) {
ImmutableMap.Builder<Key<BackupGroupRoot>, DateTime> builder = new ImmutableMap.Builder<>();
for (Entry<Key<BackupGroupRoot>, BackupGroupRoot> entry : bgrEntries) {
DateTime updateTime = entry.getValue().getUpdateAutoTimestamp().getTimestamp();
DateTime updateTime = entry.getValue().getUpdateTimestamp().getTimestamp();
if (!updateTime.isBefore(transactionTime)) {
builder.put(entry.getKey(), updateTime);
}
@@ -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;
}
}
@@ -89,7 +89,7 @@ public abstract class RdeModule {
@Provides
@Parameter(PARAM_LENIENT)
static boolean provideLenient(HttpServletRequest req) {
return extractBooleanParameter(req, PARAM_REVISION);
return extractBooleanParameter(req, PARAM_LENIENT);
}
@Provides
@@ -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,13 @@ 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 +168,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>
@@ -107,7 +107,7 @@
{@param readonly: bool}
{@param? registryLockAllowedForRegistrar: bool}
<form name="item" class="{css('item')} {css('registrar')}">
<h1>Contact Details</h1>
<h1>Contact details</h1>
{call .contactInfo data="all"}
{param namePrefix: $namePrefix /}
{param item: $item /}
@@ -142,11 +142,21 @@
{param name: 'name' /}
{/call}
{call registry.soy.forms.inputFieldRow data="all"}
{param label: 'Email' /}
{param label: 'Primary account email' /}
{param namePrefix: $namePrefix /}
{param name: 'emailAddress' /}
{param disabled: not $readonly and $item['emailAddress'] != null /}
{/call}
{if isNonnull($item['registryLockEmailAddress'])}
{call registry.soy.forms.inputFieldRow data="all"}
{param label: 'Registry lock email address' /}
{param namePrefix: $namePrefix /}
{param name: 'registryLockEmailAddress' /}
{param disabled: not $readonly /}
{param description: 'Address to which registry (un)lock confirmation emails will be ' +
'sent. This is not necessarily the account email address that is used for login.' /}
{/call}
{/if}
{call registry.soy.forms.inputFieldRow data="all"}
{param label: 'Phone' /}
{param namePrefix: $namePrefix /}
@@ -176,10 +186,6 @@
{if isNonnull($item['gaeUserId'])}
<input type="hidden" name="{$namePrefix}gaeUserId" value="{$item['gaeUserId']}">
{/if}
{if isNonnull($item['registryLockEmailAddress'])}
<input type="hidden" name="{$namePrefix}registryLockEmailAddress"
value="{$item['registryLockEmailAddress']}">
{/if}
</div>
{/template}
@@ -282,19 +288,19 @@
<hr>
</tr>
{call .whoisVisibleRadios_}
{param description: 'Show in Registrar WHOIS record as Admin contact' /}
{param description: 'Show in Registrar WHOIS record as admin contact' /}
{param fieldName: $namePrefix + 'visibleInWhoisAsAdmin' /}
{param visible: $item['visibleInWhoisAsAdmin'] == true /}
{/call}
{call .whoisVisibleRadios_}
{param description: 'Show in Registrar WHOIS record as Technical contact' /}
{param description: 'Show in Registrar WHOIS record as technical contact' /}
{param fieldName: $namePrefix + 'visibleInWhoisAsTech' /}
{param visible: $item['visibleInWhoisAsTech'] == true /}
{/call}
{call .whoisVisibleRadios_}
{param description:
'Show Phone and Email in Domain WHOIS Record as Registrar Abuse Contact' +
' (Per CL&D Requirements)' /}
'Show Phone and Email in Domain WHOIS Record as registrar abuse contact' +
' (per CL&D requirements)' /}
{param note:
'*Can only apply to one contact. Selecting Yes for this contact will' +
' force this setting for all other contacts to be No.' /}
@@ -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,19 +44,19 @@ public class ResaveAllEppResourcesActionTest
}
@Test
public void test_mapreduceSuccessfullyResavesEntity() throws Exception {
void test_mapreduceSuccessfullyResavesEntity() throws Exception {
ContactResource contact = persistActiveContact("test123");
DateTime creationTime = contact.getUpdateAutoTimestamp().getTimestamp();
assertThat(ofy().load().entity(contact).now().getUpdateAutoTimestamp().getTimestamp())
DateTime creationTime = contact.getUpdateTimestamp().getTimestamp();
assertThat(ofy().load().entity(contact).now().getUpdateTimestamp().getTimestamp())
.isEqualTo(creationTime);
ofy().clearSessionCache();
runMapreduce();
assertThat(ofy().load().entity(contact).now().getUpdateAutoTimestamp().getTimestamp())
assertThat(ofy().load().entity(contact).now().getUpdateTimestamp().getTimestamp())
.isGreaterThan(creationTime);
}
@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")
@@ -22,14 +22,11 @@ import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import org.apache.beam.sdk.io.gcp.bigquery.SchemaAndRecord;
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 BeamUtils} */
@RunWith(JUnit4.class)
public class BeamUtilsTest {
class BeamUtilsTest {
private static final String GENERIC_SCHEMA =
"{\"name\": \"AnObject\", "
@@ -41,8 +38,8 @@ public class BeamUtilsTest {
private SchemaAndRecord schemaAndRecord;
@Before
public void initializeRecord() {
@BeforeEach
void beforeEach() {
// Create a record with a given JSON schema.
GenericRecord record = new GenericData.Record(new Schema.Parser().parse(GENERIC_SCHEMA));
record.put("aString", "hello world");
@@ -51,26 +48,26 @@ public class BeamUtilsTest {
}
@Test
public void testExtractField_fieldExists_returnsExpectedStringValues() {
void testExtractField_fieldExists_returnsExpectedStringValues() {
assertThat(BeamUtils.extractField(schemaAndRecord.getRecord(), "aString"))
.isEqualTo("hello world");
assertThat(BeamUtils.extractField(schemaAndRecord.getRecord(), "aFloat")).isEqualTo("2.54");
}
@Test
public void testExtractField_fieldDoesntExist_returnsNull() {
void testExtractField_fieldDoesntExist_returnsNull() {
schemaAndRecord.getRecord().put("aFloat", null);
assertThat(BeamUtils.extractField(schemaAndRecord.getRecord(), "aFloat")).isEqualTo("null");
assertThat(BeamUtils.extractField(schemaAndRecord.getRecord(), "missing")).isEqualTo("null");
}
@Test
public void testCheckFieldsNotNull_noExceptionIfAllPresent() {
void testCheckFieldsNotNull_noExceptionIfAllPresent() {
BeamUtils.checkFieldsNotNull(ImmutableList.of("aString", "aFloat"), schemaAndRecord);
}
@Test
public void testCheckFieldsNotNull_fieldMissing_throwsException() {
void testCheckFieldsNotNull_fieldMissing_throwsException() {
IllegalStateException expected =
assertThrows(
IllegalStateException.class,
@@ -0,0 +1,542 @@
// Copyright 2020 The Nomulus Authors. All Rights Reserved.
// This applies to our modifications; the base file's license header is:
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.beam;
import static com.google.common.base.Preconditions.checkState;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Predicate;
import javax.annotation.Nullable;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.PipelineResult;
import org.apache.beam.sdk.annotations.Internal;
import org.apache.beam.sdk.io.FileSystems;
import org.apache.beam.sdk.metrics.MetricNameFilter;
import org.apache.beam.sdk.metrics.MetricResult;
import org.apache.beam.sdk.metrics.MetricsEnvironment;
import org.apache.beam.sdk.metrics.MetricsFilter;
import org.apache.beam.sdk.options.ApplicationNameOptions;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptions.CheckEnabled;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.options.ValueProvider;
import org.apache.beam.sdk.options.ValueProvider.StaticValueProvider;
import org.apache.beam.sdk.runners.TransformHierarchy;
import org.apache.beam.sdk.runners.TransformHierarchy.Node;
import org.apache.beam.sdk.testing.CrashingRunner;
import org.apache.beam.sdk.testing.NeedsRunner;
import org.apache.beam.sdk.testing.PAssert;
import org.apache.beam.sdk.testing.TestPipelineOptions;
import org.apache.beam.sdk.testing.ValidatesRunner;
import org.apache.beam.sdk.transforms.SerializableFunction;
import org.apache.beam.sdk.util.common.ReflectHelpers;
import org.junit.experimental.categories.Category;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
// NOTE: This file is copied from the Apache Beam distribution so that it can be locally modified to
// support JUnit 5.
/**
* A creator of test pipelines that can be used inside of tests that can be configured to run
* locally or against a remote pipeline runner.
*
* <p>In order to run tests on a pipeline runner, the following conditions must be met:
*
* <ul>
* <li>System property "beamTestPipelineOptions" must contain a JSON delimited list of pipeline
* options. For example:
* <pre>{@code [
* "--runner=TestDataflowRunner",
* "--project=mygcpproject",
* "--stagingLocation=gs://mygcsbucket/path"
* ]}</pre>
* Note that the set of pipeline options required is pipeline runner specific.
* <li>Jars containing the SDK and test classes must be available on the classpath.
* </ul>
*
* <p>Use {@link PAssert} for tests, as it integrates with this test harness in both direct and
* remote execution modes. For example:
*
* <pre><code>
* {@literal @Rule}
* public final transient TestPipeline p = TestPipeline.create();
*
* {@literal @Test}
* {@literal @Category}(NeedsRunner.class)
* public void myPipelineTest() throws Exception {
* final PCollection&lt;String&gt; pCollection = pipeline.apply(...)
* PAssert.that(pCollection).containsInAnyOrder(...);
* pipeline.run();
* }
* </code></pre>
*
* <p>For pipeline runners, it is required that they must throw an {@link AssertionError} containing
* the message from the {@link PAssert} that failed.
*
* <p>See also the <a href="https://beam.apache.org/contribute/testing/">Testing</a> documentation
* section.
*/
public class TestPipelineExtension extends Pipeline
implements BeforeEachCallback, AfterEachCallback {
private final PipelineOptions options;
private static class PipelineRunEnforcement {
@SuppressWarnings("WeakerAccess")
protected boolean enableAutoRunIfMissing;
protected final Pipeline pipeline;
protected boolean runAttempted;
private PipelineRunEnforcement(final Pipeline pipeline) {
this.pipeline = pipeline;
}
protected void enableAutoRunIfMissing(final boolean enable) {
enableAutoRunIfMissing = enable;
}
protected void beforePipelineExecution() {
runAttempted = true;
}
protected void afterPipelineExecution() {}
protected void afterUserCodeFinished() {
if (!runAttempted && enableAutoRunIfMissing) {
pipeline.run().waitUntilFinish();
}
}
}
private static class PipelineAbandonedNodeEnforcement extends PipelineRunEnforcement {
// Null until the pipeline has been run
@Nullable private List<TransformHierarchy.Node> runVisitedNodes;
private final Predicate<Node> isPAssertNode =
node ->
node.getTransform() instanceof PAssert.GroupThenAssert
|| node.getTransform() instanceof PAssert.GroupThenAssertForSingleton
|| node.getTransform() instanceof PAssert.OneSideInputAssert;
private static class NodeRecorder extends PipelineVisitor.Defaults {
private final List<TransformHierarchy.Node> visited = new ArrayList<>();
@Override
public void leaveCompositeTransform(final TransformHierarchy.Node node) {
visited.add(node);
}
@Override
public void visitPrimitiveTransform(final TransformHierarchy.Node node) {
visited.add(node);
}
}
private PipelineAbandonedNodeEnforcement(final TestPipelineExtension pipeline) {
super(pipeline);
runVisitedNodes = null;
}
private List<TransformHierarchy.Node> recordPipelineNodes(final Pipeline pipeline) {
final NodeRecorder nodeRecorder = new NodeRecorder();
pipeline.traverseTopologically(nodeRecorder);
return nodeRecorder.visited;
}
private boolean isEmptyPipeline(final Pipeline pipeline) {
final IsEmptyVisitor isEmptyVisitor = new IsEmptyVisitor();
pipeline.traverseTopologically(isEmptyVisitor);
return isEmptyVisitor.isEmpty();
}
private void verifyPipelineExecution() {
if (!isEmptyPipeline(pipeline)) {
if (!runAttempted && !enableAutoRunIfMissing) {
throw new PipelineRunMissingException("The pipeline has not been run.");
} else {
final List<TransformHierarchy.Node> pipelineNodes = recordPipelineNodes(pipeline);
if (pipelineRunSucceeded() && !visitedAll(pipelineNodes)) {
final boolean hasDanglingPAssert =
pipelineNodes.stream()
.filter(pn -> !runVisitedNodes.contains(pn))
.anyMatch(isPAssertNode);
if (hasDanglingPAssert) {
throw new AbandonedNodeException("The pipeline contains abandoned PAssert(s).");
} else {
throw new AbandonedNodeException("The pipeline contains abandoned PTransform(s).");
}
}
}
}
}
private boolean visitedAll(final List<TransformHierarchy.Node> pipelineNodes) {
return runVisitedNodes.equals(pipelineNodes);
}
private boolean pipelineRunSucceeded() {
return runVisitedNodes != null;
}
@Override
protected void afterPipelineExecution() {
runVisitedNodes = recordPipelineNodes(pipeline);
super.afterPipelineExecution();
}
@Override
protected void afterUserCodeFinished() {
super.afterUserCodeFinished();
verifyPipelineExecution();
}
}
/**
* An exception thrown in case an abandoned {@link org.apache.beam.sdk.transforms.PTransform} is
* detected, that is, a {@link org.apache.beam.sdk.transforms.PTransform} that has not been run.
*/
public static class AbandonedNodeException extends RuntimeException {
AbandonedNodeException(final String msg) {
super(msg);
}
}
/** An exception thrown in case a test finishes without invoking {@link Pipeline#run()}. */
public static class PipelineRunMissingException extends RuntimeException {
PipelineRunMissingException(final String msg) {
super(msg);
}
}
/** System property used to set {@link TestPipelineOptions}. */
public static final String PROPERTY_BEAM_TEST_PIPELINE_OPTIONS = "beamTestPipelineOptions";
static final String PROPERTY_USE_DEFAULT_DUMMY_RUNNER = "beamUseDummyRunner";
private static final ObjectMapper MAPPER =
new ObjectMapper()
.registerModules(ObjectMapper.findModules(ReflectHelpers.findClassLoader()));
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
private Optional<? extends PipelineRunEnforcement> enforcement = Optional.empty();
/**
* Creates and returns a new test pipeline.
*
* <p>Use {@link PAssert} to add tests, then call {@link Pipeline#run} to execute the pipeline and
* check the tests.
*/
public static TestPipelineExtension create() {
return fromOptions(testingPipelineOptions());
}
public static TestPipelineExtension fromOptions(PipelineOptions options) {
return new TestPipelineExtension(options);
}
private TestPipelineExtension(final PipelineOptions options) {
super(options);
this.options = options;
}
@Override
public PipelineOptions getOptions() {
return this.options;
}
@Override
public void beforeEach(ExtensionContext context) throws Exception {
options.as(ApplicationNameOptions.class).setAppName(getAppName(context));
// if the enforcement level has not been set by the user do auto-inference
if (!enforcement.isPresent()) {
final boolean isCrashingRunner = CrashingRunner.class.isAssignableFrom(options.getRunner());
checkState(
!isCrashingRunner,
"Cannot test using a [%s] runner. Please re-check your configuration.",
CrashingRunner.class.getSimpleName());
enableAbandonedNodeEnforcement(true);
}
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
enforcement.get().afterUserCodeFinished();
}
/** Returns the class + method name of the test. */
private String getAppName(ExtensionContext context) {
String methodName = context.getRequiredTestMethod().getName();
Class<?> testClass = context.getRequiredTestClass();
if (testClass.isMemberClass()) {
return String.format(
"%s$%s-%s",
testClass.getEnclosingClass().getSimpleName(), testClass.getSimpleName(), methodName);
} else {
return String.format("%s-%s", testClass.getSimpleName(), methodName);
}
}
/**
* Runs this {@link TestPipelineExtension}, unwrapping any {@code AssertionError} that is raised
* during testing.
*/
@Override
public PipelineResult run() {
return run(getOptions());
}
/** Like {@link #run} but with the given potentially modified options. */
@Override
public PipelineResult run(PipelineOptions options) {
checkState(
enforcement.isPresent(),
"Is your TestPipeline declaration missing a @Rule annotation? Usage: "
+ "@Rule public final transient TestPipeline pipeline = TestPipeline.create();");
final PipelineResult pipelineResult;
try {
enforcement.get().beforePipelineExecution();
PipelineOptions updatedOptions =
MAPPER.convertValue(MAPPER.valueToTree(options), PipelineOptions.class);
updatedOptions
.as(TestValueProviderOptions.class)
.setProviderRuntimeValues(StaticValueProvider.of(providerRuntimeValues));
pipelineResult = super.run(updatedOptions);
verifyPAssertsSucceeded(this, pipelineResult);
} catch (RuntimeException exc) {
Throwable cause = exc.getCause();
if (cause instanceof AssertionError) {
throw (AssertionError) cause;
} else {
throw exc;
}
}
// If we reach this point, the pipeline has been run and no exceptions have been thrown during
// its execution.
enforcement.get().afterPipelineExecution();
return pipelineResult;
}
/** Implementation detail of {@link #newProvider}, do not use. */
@Internal
public interface TestValueProviderOptions extends PipelineOptions {
ValueProvider<Map<String, Object>> getProviderRuntimeValues();
void setProviderRuntimeValues(ValueProvider<Map<String, Object>> runtimeValues);
}
/**
* Returns a new {@link ValueProvider} that is inaccessible before {@link #run}, but will be
* accessible while the pipeline runs.
*/
public <T> ValueProvider<T> newProvider(T runtimeValue) {
String uuid = UUID.randomUUID().toString();
providerRuntimeValues.put(uuid, runtimeValue);
return ValueProvider.NestedValueProvider.of(
options.as(TestValueProviderOptions.class).getProviderRuntimeValues(),
new GetFromRuntimeValues<T>(uuid));
}
private final Map<String, Object> providerRuntimeValues = Maps.newHashMap();
private static class GetFromRuntimeValues<T>
implements SerializableFunction<Map<String, Object>, T> {
private final String key;
private GetFromRuntimeValues(String key) {
this.key = key;
}
@Override
public T apply(Map<String, Object> input) {
return (T) input.get(key);
}
}
/**
* Enables the abandoned node detection. Abandoned nodes are <code>PTransforms</code>, <code>
* PAsserts</code> included, that were not executed by the pipeline runner. Abandoned nodes are
* most likely to occur due to the one of the following scenarios:
*
* <ul>
* <li>Lack of a <code>pipeline.run()</code> statement at the end of a test.
* <li>Addition of PTransforms after the pipeline has already run.
* </ul>
*
* Abandoned node detection is automatically enabled when a real pipeline runner (i.e. not a
* {@link CrashingRunner}) and/or a {@link NeedsRunner} or a {@link ValidatesRunner} annotation
* are detected.
*/
public TestPipelineExtension enableAbandonedNodeEnforcement(final boolean enable) {
enforcement =
enable
? Optional.of(new PipelineAbandonedNodeEnforcement(this))
: Optional.of(new PipelineRunEnforcement(this));
return this;
}
/**
* If enabled, a <code>pipeline.run()</code> statement will be added automatically in case it is
* missing in the test.
*/
public TestPipelineExtension enableAutoRunIfMissing(final boolean enable) {
enforcement.get().enableAutoRunIfMissing(enable);
return this;
}
@Override
public String toString() {
return "TestPipeline#" + options.as(ApplicationNameOptions.class).getAppName();
}
/** Creates {@link PipelineOptions} for testing. */
public static PipelineOptions testingPipelineOptions() {
try {
@Nullable
String beamTestPipelineOptions = System.getProperty(PROPERTY_BEAM_TEST_PIPELINE_OPTIONS);
PipelineOptions options =
Strings.isNullOrEmpty(beamTestPipelineOptions)
? PipelineOptionsFactory.create()
: PipelineOptionsFactory.fromArgs(
MAPPER.readValue(beamTestPipelineOptions, String[].class))
.as(TestPipelineOptions.class);
// If no options were specified, set some reasonable defaults
if (Strings.isNullOrEmpty(beamTestPipelineOptions)) {
// If there are no provided options, check to see if a dummy runner should be used.
String useDefaultDummy = System.getProperty(PROPERTY_USE_DEFAULT_DUMMY_RUNNER);
if (!Strings.isNullOrEmpty(useDefaultDummy) && Boolean.valueOf(useDefaultDummy)) {
options.setRunner(CrashingRunner.class);
}
}
options.setStableUniqueNames(CheckEnabled.ERROR);
FileSystems.setDefaultPipelineOptions(options);
return options;
} catch (IOException e) {
throw new RuntimeException(
"Unable to instantiate test options from system property "
+ PROPERTY_BEAM_TEST_PIPELINE_OPTIONS
+ ":"
+ System.getProperty(PROPERTY_BEAM_TEST_PIPELINE_OPTIONS),
e);
}
}
/**
* Verifies all {{@link PAssert PAsserts}} in the pipeline have been executed and were successful.
*
* <p>Note this only runs for runners which support Metrics. Runners which do not should verify
* this in some other way. See: https://issues.apache.org/jira/browse/BEAM-2001
*/
public static void verifyPAssertsSucceeded(Pipeline pipeline, PipelineResult pipelineResult) {
if (MetricsEnvironment.isMetricsSupported()) {
long expectedNumberOfAssertions = (long) PAssert.countAsserts(pipeline);
long successfulAssertions = 0;
Iterable<MetricResult<Long>> successCounterResults =
pipelineResult
.metrics()
.queryMetrics(
MetricsFilter.builder()
.addNameFilter(MetricNameFilter.named(PAssert.class, PAssert.SUCCESS_COUNTER))
.build())
.getCounters();
for (MetricResult<Long> counter : successCounterResults) {
if (counter.getAttempted() > 0) {
successfulAssertions++;
}
}
assertThat(
String.format(
"Expected %d successful assertions, but found %d.",
expectedNumberOfAssertions, successfulAssertions),
successfulAssertions,
is(expectedNumberOfAssertions));
}
}
private static class IsEmptyVisitor extends PipelineVisitor.Defaults {
private boolean empty = true;
public boolean isEmpty() {
return empty;
}
@Override
public void visitPrimitiveTransform(TransformHierarchy.Node node) {
empty = false;
}
}
/**
* A utility class for querying annotations.
*
* <p>NOTE: This was copied from the Apache Beam project from a separate file only for visibility
* reasons (it's package-private there).
*/
static class Annotations {
/** Annotation predicates. */
static class Predicates {
static Predicate<Annotation> isAnnotationOfType(final Class<? extends Annotation> clazz) {
return annotation ->
annotation.annotationType() != null && annotation.annotationType().equals(clazz);
}
static Predicate<Annotation> isCategoryOf(final Class<?> value, final boolean allowDerived) {
return category ->
Arrays.stream(((Category) category).value())
.anyMatch(
aClass -> allowDerived ? value.isAssignableFrom(aClass) : value.equals(aClass));
}
}
}
}
@@ -21,6 +21,7 @@ import static google.registry.testing.DatastoreHelper.newRegistry;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import google.registry.backup.VersionedEntity;
import google.registry.beam.TestPipelineExtension;
import google.registry.model.contact.ContactResource;
import google.registry.model.domain.DomainBase;
import google.registry.model.ofy.Ofy;
@@ -30,40 +31,37 @@ import google.registry.testing.InjectRule;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.beam.sdk.coders.StringUtf8Coder;
import org.apache.beam.sdk.io.fs.MatchResult.Metadata;
import org.apache.beam.sdk.testing.NeedsRunner;
import org.apache.beam.sdk.testing.PAssert;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.joda.time.DateTime;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;
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.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
/** Unit tests for {@link Transforms} related to loading CommitLogs. */
// TODO(weiminyu): Upgrade to JUnit5 when TestPipeline is upgraded. It is also easy to adapt with
// a wrapper.
@RunWith(JUnit4.class)
public class CommitLogTransformsTest implements Serializable {
class CommitLogTransformsTest implements Serializable {
private static final DateTime START_TIME = DateTime.parse("2000-01-01T00:00:00.0Z");
@Rule public final transient TemporaryFolder temporaryFolder = new TemporaryFolder();
@SuppressWarnings("WeakerAccess")
@TempDir
transient Path tmpDir;
@Rule public final transient InjectRule injectRule = new InjectRule();
@RegisterExtension final transient InjectRule injectRule = new InjectRule();
@Rule
public final transient TestPipeline pipeline =
TestPipeline.create().enableAbandonedNodeEnforcement(true);
@RegisterExtension
final transient TestPipelineExtension testPipeline =
TestPipelineExtension.create().enableAbandonedNodeEnforcement(true);
private FakeClock fakeClock;
private transient BackupTestStore store;
@@ -75,8 +73,8 @@ public class CommitLogTransformsTest implements Serializable {
private transient ContactResource contact;
private transient DomainBase domain;
@Before
public void beforeEach() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
fakeClock = new FakeClock(START_TIME);
store = new BackupTestStore(fakeClock);
injectRule.setStaticField(Ofy.class, "clock", fakeClock);
@@ -92,12 +90,12 @@ public class CommitLogTransformsTest implements Serializable {
contact = (ContactResource) store.loadAsOfyEntity(contact);
domain = (DomainBase) store.loadAsOfyEntity(domain);
commitLogsDir = temporaryFolder.newFolder();
commitLogsDir = Files.createDirectory(tmpDir.resolve("commit_logs")).toFile();
firstCommitLogFile = store.saveCommitLogs(commitLogsDir.getAbsolutePath());
}
@After
public void afterEach() throws Exception {
@AfterEach
void afterEach() throws Exception {
if (store != null) {
store.close();
store = null;
@@ -105,10 +103,9 @@ public class CommitLogTransformsTest implements Serializable {
}
@Test
@Category(NeedsRunner.class)
public void getCommitLogFilePatterns() {
void getCommitLogFilePatterns() {
PCollection<String> patterns =
pipeline.apply(
testPipeline.apply(
"Get CommitLog file patterns",
Transforms.getCommitLogFilePatterns(commitLogsDir.getAbsolutePath()));
@@ -117,14 +114,13 @@ public class CommitLogTransformsTest implements Serializable {
PAssert.that(patterns).containsInAnyOrder(expectedPatterns);
pipeline.run();
testPipeline.run();
}
@Test
@Category(NeedsRunner.class)
public void getFilesByPatterns() {
void getFilesByPatterns() {
PCollection<Metadata> fileMetas =
pipeline
testPipeline
.apply(
"File patterns to metadata",
Create.of(commitLogsDir.getAbsolutePath() + "/commit_diff_until_*")
@@ -149,12 +145,11 @@ public class CommitLogTransformsTest implements Serializable {
PAssert.that(fileNames).containsInAnyOrder(expectedFilenames);
pipeline.run();
testPipeline.run();
}
@Test
@Category(NeedsRunner.class)
public void filterCommitLogsByTime() throws IOException {
void filterCommitLogsByTime() throws IOException {
ImmutableList<String> commitLogFilenames =
ImmutableList.of(
"commit_diff_until_2000-01-01T00:00:00.000Z",
@@ -163,16 +158,15 @@ public class CommitLogTransformsTest implements Serializable {
"commit_diff_until_2000-01-01T00:00:00.003Z",
"commit_diff_until_2000-01-01T00:00:00.004Z");
File commitLogDir = temporaryFolder.newFolder();
for (String name : commitLogFilenames) {
new File(commitLogDir, name).createNewFile();
new File(commitLogsDir, name).createNewFile();
}
PCollection<String> filteredFilenames =
pipeline
testPipeline
.apply(
"Get commitlog file patterns",
Transforms.getCommitLogFilePatterns(commitLogDir.getAbsolutePath()))
Transforms.getCommitLogFilePatterns(commitLogsDir.getAbsolutePath()))
.apply("Find commitlog files", Transforms.getFilesByPatterns())
.apply(
"Filtered by Time",
@@ -194,14 +188,13 @@ public class CommitLogTransformsTest implements Serializable {
"commit_diff_until_2000-01-01T00:00:00.001Z",
"commit_diff_until_2000-01-01T00:00:00.002Z");
pipeline.run();
testPipeline.run();
}
@Test
@Category(NeedsRunner.class)
public void loadOneCommitLogFile() {
void loadOneCommitLogFile() {
PCollection<VersionedEntity> entities =
pipeline
testPipeline
.apply(
"Get CommitLog file patterns",
Transforms.getCommitLogFilePatterns(commitLogsDir.getAbsolutePath()))
@@ -216,14 +209,13 @@ public class CommitLogTransformsTest implements Serializable {
KV.of(fakeClock.nowUtc().getMillis() - 1, store.loadAsDatastoreEntity(contact)),
KV.of(fakeClock.nowUtc().getMillis() - 1, store.loadAsDatastoreEntity(domain)));
pipeline.run();
testPipeline.run();
}
@Test
@Category(NeedsRunner.class)
public void loadOneCommitLogFile_filterByKind() {
void loadOneCommitLogFile_filterByKind() {
PCollection<VersionedEntity> entities =
pipeline
testPipeline
.apply(
"Get CommitLog file patterns",
Transforms.getCommitLogFilePatterns(commitLogsDir.getAbsolutePath()))
@@ -236,6 +228,6 @@ public class CommitLogTransformsTest implements Serializable {
KV.of(fakeClock.nowUtc().getMillis() - 2, store.loadAsDatastoreEntity(registry)),
KV.of(fakeClock.nowUtc().getMillis() - 1, store.loadAsDatastoreEntity(contact)));
pipeline.run();
testPipeline.run();
}
}
@@ -22,6 +22,7 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.googlecode.objectify.Key;
import google.registry.backup.VersionedEntity;
import google.registry.beam.TestPipelineExtension;
import google.registry.model.contact.ContactResource;
import google.registry.model.domain.DomainBase;
import google.registry.model.ofy.Ofy;
@@ -30,36 +31,30 @@ import google.registry.testing.FakeClock;
import google.registry.testing.InjectRule;
import java.io.File;
import java.io.Serializable;
import java.nio.file.Path;
import java.util.Collections;
import org.apache.beam.sdk.coders.StringUtf8Coder;
import org.apache.beam.sdk.io.fs.MatchResult.Metadata;
import org.apache.beam.sdk.testing.NeedsRunner;
import org.apache.beam.sdk.testing.PAssert;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.joda.time.DateTime;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;
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.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
/**
* Unit tests for {@link Transforms} related to loading Datastore exports.
*
* <p>This class implements {@link Serializable} so that test {@link DoFn} classes may be inlined.
*/
// TODO(weiminyu): Upgrade to JUnit5 when TestPipeline is upgraded. It is also easy to adapt with
// a wrapper.
@RunWith(JUnit4.class)
public class ExportloadingTransformsTest implements Serializable {
class ExportloadingTransformsTest implements Serializable {
private static final DateTime START_TIME = DateTime.parse("2000-01-01T00:00:00.0Z");
private static final ImmutableList<Class<?>> ALL_KINDS =
@@ -67,13 +62,15 @@ public class ExportloadingTransformsTest implements Serializable {
private static final ImmutableSet<String> ALL_KIND_STRS =
ALL_KINDS.stream().map(Key::getKind).collect(ImmutableSet.toImmutableSet());
@Rule public final transient TemporaryFolder exportRootDir = new TemporaryFolder();
@SuppressWarnings("WeakerAccess")
@TempDir
transient Path tmpDir;
@Rule public final transient InjectRule injectRule = new InjectRule();
@RegisterExtension final transient InjectRule injectRule = new InjectRule();
@Rule
public final transient TestPipeline pipeline =
TestPipeline.create().enableAbandonedNodeEnforcement(true);
@RegisterExtension
final transient TestPipelineExtension testPipeline =
TestPipelineExtension.create().enableAbandonedNodeEnforcement(true);
private FakeClock fakeClock;
private transient BackupTestStore store;
@@ -84,8 +81,8 @@ public class ExportloadingTransformsTest implements Serializable {
private transient ContactResource contact;
private transient DomainBase domain;
@Before
public void beforeEach() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
fakeClock = new FakeClock(START_TIME);
store = new BackupTestStore(fakeClock);
injectRule.setStaticField(Ofy.class, "clock", fakeClock);
@@ -102,12 +99,11 @@ public class ExportloadingTransformsTest implements Serializable {
contact = (ContactResource) store.loadAsOfyEntity(contact);
domain = (DomainBase) store.loadAsOfyEntity(domain);
exportDir =
store.export(exportRootDir.getRoot().getAbsolutePath(), ALL_KINDS, Collections.EMPTY_SET);
exportDir = store.export(tmpDir.toAbsolutePath().toString(), ALL_KINDS, Collections.EMPTY_SET);
}
@After
public void afterEach() throws Exception {
@AfterEach
void afterEach() throws Exception {
if (store != null) {
store.close();
store = null;
@@ -115,10 +111,9 @@ public class ExportloadingTransformsTest implements Serializable {
}
@Test
@Category(NeedsRunner.class)
public void getExportFilePatterns() {
void getExportFilePatterns() {
PCollection<String> patterns =
pipeline.apply(
testPipeline.apply(
"Get Datastore file patterns",
Transforms.getDatastoreExportFilePatterns(exportDir.getAbsolutePath(), ALL_KIND_STRS));
@@ -130,14 +125,13 @@ public class ExportloadingTransformsTest implements Serializable {
PAssert.that(patterns).containsInAnyOrder(expectedPatterns);
pipeline.run();
testPipeline.run();
}
@Test
@Category(NeedsRunner.class)
public void getFilesByPatterns() {
void getFilesByPatterns() {
PCollection<Metadata> fileMetas =
pipeline
testPipeline
.apply(
"File patterns to metadata",
Create.of(
@@ -169,14 +163,13 @@ public class ExportloadingTransformsTest implements Serializable {
PAssert.that(fileNames).containsInAnyOrder(expectedFilenames);
pipeline.run();
testPipeline.run();
}
@Test
@Category(NeedsRunner.class)
public void loadDataFromFiles() {
void loadDataFromFiles() {
PCollection<VersionedEntity> entities =
pipeline
testPipeline
.apply(
"Get Datastore file patterns",
Transforms.getDatastoreExportFilePatterns(
@@ -190,6 +183,6 @@ public class ExportloadingTransformsTest implements Serializable {
KV.of(Transforms.EXPORT_ENTITY_TIME_STAMP, store.loadAsDatastoreEntity(contact)),
KV.of(Transforms.EXPORT_ENTITY_TIME_STAMP, store.loadAsDatastoreEntity(domain)));
pipeline.run();
testPipeline.run();
}
}
@@ -22,6 +22,7 @@ import com.google.appengine.api.datastore.Entity;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.googlecode.objectify.Key;
import google.registry.beam.TestPipelineExtension;
import google.registry.model.contact.ContactResource;
import google.registry.model.domain.DomainAuthInfo;
import google.registry.model.domain.DomainBase;
@@ -31,18 +32,15 @@ import google.registry.model.registry.Registry;
import google.registry.testing.FakeClock;
import google.registry.testing.InjectRule;
import java.io.File;
import org.apache.beam.sdk.testing.NeedsRunner;
import org.apache.beam.sdk.testing.TestPipeline;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollectionTuple;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;
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.junit.jupiter.api.io.TempDir;
/**
* Unit test for {@link Transforms#loadDatastoreSnapshot}.
@@ -71,8 +69,8 @@ import org.junit.runners.JUnit4;
* <li>Deletes are properly handled.
* </ul>
*/
@RunWith(JUnit4.class)
public class LoadDatastoreSnapshotTest {
class LoadDatastoreSnapshotTest {
private static final DateTime START_TIME = DateTime.parse("2000-01-01T00:00:00.0Z");
private static final ImmutableList<Class<?>> ALL_KINDS =
@@ -80,13 +78,15 @@ public class LoadDatastoreSnapshotTest {
private static final ImmutableSet<String> ALL_KIND_STRS =
ALL_KINDS.stream().map(Key::getKind).collect(ImmutableSet.toImmutableSet());
@Rule public final transient TemporaryFolder temporaryFolder = new TemporaryFolder();
@SuppressWarnings("WeakerAccess")
@TempDir
transient Path tmpDir;
@Rule public final transient InjectRule injectRule = new InjectRule();
@RegisterExtension final transient InjectRule injectRule = new InjectRule();
@Rule
public final transient TestPipeline pipeline =
TestPipeline.create().enableAbandonedNodeEnforcement(true);
@RegisterExtension
final transient TestPipelineExtension testPipeline =
TestPipelineExtension.create().enableAbandonedNodeEnforcement(true);
private FakeClock fakeClock;
private File exportRootDir;
@@ -102,14 +102,14 @@ public class LoadDatastoreSnapshotTest {
private transient DateTime contactLastUpdateTime;
private transient DateTime domainLastUpdateTime;
@Before
public void beforeEach() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
fakeClock = new FakeClock(START_TIME);
try (BackupTestStore store = new BackupTestStore(fakeClock)) {
injectRule.setStaticField(Ofy.class, "clock", fakeClock);
exportRootDir = temporaryFolder.newFolder();
commitLogsDir = temporaryFolder.newFolder();
exportRootDir = Files.createDirectory(tmpDir.resolve("export_root")).toFile();
commitLogsDir = Files.createDirectory(tmpDir.resolve("commit_logs")).toFile();
Registry registry = newRegistry("tld1", "TLD1");
ContactResource fillerContact = newContactResource("contact_filler");
@@ -154,10 +154,9 @@ public class LoadDatastoreSnapshotTest {
}
@Test
@Category(NeedsRunner.class)
public void loadDatastoreSnapshot() {
void loadDatastoreSnapshot() {
PCollectionTuple snapshot =
pipeline.apply(
testPipeline.apply(
Transforms.loadDatastoreSnapshot(
exportDir.getAbsolutePath(),
commitLogsDir.getAbsolutePath(),
@@ -173,6 +172,6 @@ public class LoadDatastoreSnapshotTest {
InitSqlTestUtils.assertContainsExactlyElementsIn(
snapshot.get(Transforms.createTagForKind("ContactResource")),
KV.of(contactLastUpdateTime.getMillis(), dsContact));
pipeline.run();
testPipeline.run();
}
}
@@ -20,56 +20,62 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import com.google.appengine.api.datastore.Entity;
import com.google.common.collect.ImmutableList;
import google.registry.backup.VersionedEntity;
import google.registry.beam.TestPipelineExtension;
import google.registry.model.contact.ContactResource;
import google.registry.model.ofy.Ofy;
import google.registry.model.registrar.Registrar;
import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaIntegrationTestRule;
import google.registry.testing.AppEngineRule;
import google.registry.testing.DatastoreEntityExtension;
import google.registry.testing.DatastoreHelper;
import google.registry.testing.FakeClock;
import google.registry.testing.InjectRule;
import java.io.File;
import java.io.PrintStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Collectors;
import org.apache.beam.sdk.testing.NeedsRunner;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.transforms.Create;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
/** Unit test for {@link Transforms#writeToSql}. */
@RunWith(JUnit4.class)
public class WriteToSqlTest implements Serializable {
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);
@Rule public final transient InjectRule injectRule = new InjectRule();
@RegisterExtension final transient InjectRule injectRule = new InjectRule();
@Rule
public transient JpaIntegrationTestRule jpaRule =
@RegisterExtension
final transient JpaIntegrationTestRule database =
new JpaTestRules.Builder().withClock(fakeClock).buildIntegrationTestRule();
@Rule public transient TemporaryFolder temporaryFolder = new TemporaryFolder();
@RegisterExtension
@Order(value = 1)
final transient DatastoreEntityExtension datastore = new DatastoreEntityExtension();
@Rule
public final transient TestPipeline pipeline =
TestPipeline.create().enableAbandonedNodeEnforcement(true);
@SuppressWarnings("WeakerAccess")
@TempDir
transient Path tmpDir;
@RegisterExtension
final transient TestPipelineExtension testPipeline =
TestPipelineExtension.create().enableAbandonedNodeEnforcement(true);
private ImmutableList<Entity> contacts;
private File credentialFile;
@Before
public void beforeEach() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
try (BackupTestStore store = new BackupTestStore(fakeClock)) {
injectRule.setStaticField(Ofy.class, "clock", fakeClock);
@@ -87,18 +93,19 @@ public class WriteToSqlTest implements Serializable {
}
contacts = builder.build();
}
credentialFile = temporaryFolder.newFile();
credentialFile = Files.createFile(tmpDir.resolve("credential.dat")).toFile();
new PrintStream(credentialFile)
.printf(
"%s %s %s",
jpaRule.getDatabaseUrl(), jpaRule.getDatabaseUsername(), jpaRule.getDatabasePassword())
database.getDatabaseUrl(),
database.getDatabaseUsername(),
database.getDatabasePassword())
.close();
}
@Test
@Category(NeedsRunner.class)
public void writeToSql_twoWriters() {
pipeline
void writeToSql_twoWriters() {
testPipeline
.apply(
Create.of(
contacts.stream()
@@ -115,7 +122,7 @@ public class WriteToSqlTest implements Serializable {
.beamJpaModule(new BeamJpaModule(credentialFile.getAbsolutePath()))
.build()
.localDbJpaTransactionManager()));
pipeline.run().waitUntilFinish();
testPipeline.run().waitUntilFinish();
ImmutableList<?> sqlContacts = jpaTm().transact(() -> jpaTm().loadAll(ContactResource.class));
// TODO(weiminyu): compare load entities with originals. Note: lastUpdateTimes won't match by
@@ -29,14 +29,11 @@ import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import org.apache.beam.sdk.io.gcp.bigquery.SchemaAndRecord;
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 BillingEvent} */
@RunWith(JUnit4.class)
public class BillingEventTest {
class BillingEventTest {
private static final String BILLING_EVENT_SCHEMA =
"{\"name\": \"BillingEvent\", "
@@ -60,8 +57,8 @@ public class BillingEventTest {
private SchemaAndRecord schemaAndRecord;
@Before
public void initializeRecord() {
@BeforeEach
void beforeEach() {
// Create a record with a given JSON schema.
schemaAndRecord = new SchemaAndRecord(createRecord(), null);
}
@@ -86,7 +83,7 @@ public class BillingEventTest {
}
@Test
public void testParseBillingEventFromRecord_success() {
void testParseBillingEventFromRecord_success() {
BillingEvent event = BillingEvent.parseFromRecord(schemaAndRecord);
assertThat(event.id()).isEqualTo(1);
assertThat(event.billingTime())
@@ -107,7 +104,7 @@ public class BillingEventTest {
}
@Test
public void testParseBillingEventFromRecord_sunriseCreate_reducedPrice_success() {
void testParseBillingEventFromRecord_sunriseCreate_reducedPrice_success() {
schemaAndRecord.getRecord().put("flags", "SUNRISE");
BillingEvent event = BillingEvent.parseFromRecord(schemaAndRecord);
assertThat(event.amount()).isEqualTo(17.43);
@@ -115,7 +112,7 @@ public class BillingEventTest {
}
@Test
public void testParseBillingEventFromRecord_anchorTenant_zeroPrice_success() {
void testParseBillingEventFromRecord_anchorTenant_zeroPrice_success() {
schemaAndRecord.getRecord().put("flags", "SUNRISE ANCHOR_TENANT");
BillingEvent event = BillingEvent.parseFromRecord(schemaAndRecord);
assertThat(event.amount()).isZero();
@@ -123,13 +120,13 @@ public class BillingEventTest {
}
@Test
public void testParseBillingEventFromRecord_nullValue_throwsException() {
void testParseBillingEventFromRecord_nullValue_throwsException() {
schemaAndRecord.getRecord().put("tld", null);
assertThrows(IllegalStateException.class, () -> BillingEvent.parseFromRecord(schemaAndRecord));
}
@Test
public void testConvertBillingEvent_toCsv() {
void testConvertBillingEvent_toCsv() {
BillingEvent event = BillingEvent.parseFromRecord(schemaAndRecord);
assertThat(event.toCsv())
.isEqualTo(
@@ -138,7 +135,7 @@ public class BillingEventTest {
}
@Test
public void testConvertBillingEvent_nonNullPoNumber_toCsv() {
void testConvertBillingEvent_nonNullPoNumber_toCsv() {
GenericRecord record = createRecord();
record.put("poNumber", "905610");
BillingEvent event = BillingEvent.parseFromRecord(new SchemaAndRecord(record, null));
@@ -149,13 +146,13 @@ public class BillingEventTest {
}
@Test
public void testGenerateBillingEventFilename() {
void testGenerateBillingEventFilename() {
BillingEvent event = BillingEvent.parseFromRecord(schemaAndRecord);
assertThat(event.toFilename("2017-10")).isEqualTo("invoice_details_2017-10_myRegistrar_test");
}
@Test
public void testGetInvoiceGroupingKey_fromBillingEvent() {
void testGetInvoiceGroupingKey_fromBillingEvent() {
BillingEvent event = BillingEvent.parseFromRecord(schemaAndRecord);
InvoiceGroupingKey invoiceKey = event.getInvoiceGroupingKey();
assertThat(invoiceKey.startDate()).isEqualTo("2017-10-01");
@@ -169,7 +166,7 @@ public class BillingEventTest {
}
@Test
public void test_nonNullPoNumber() {
void test_nonNullPoNumber() {
GenericRecord record = createRecord();
record.put("poNumber", "905610");
BillingEvent event = BillingEvent.parseFromRecord(new SchemaAndRecord(record, null));
@@ -179,7 +176,7 @@ public class BillingEventTest {
}
@Test
public void testConvertInvoiceGroupingKey_toCsv() {
void testConvertInvoiceGroupingKey_toCsv() {
BillingEvent event = BillingEvent.parseFromRecord(schemaAndRecord);
InvoiceGroupingKey invoiceKey = event.getInvoiceGroupingKey();
assertThat(invoiceKey.toCsv(3L))
@@ -189,7 +186,7 @@ public class BillingEventTest {
}
@Test
public void testInvoiceGroupingKeyCoder_deterministicSerialization() throws IOException {
void testInvoiceGroupingKeyCoder_deterministicSerialization() throws IOException {
InvoiceGroupingKey invoiceKey =
BillingEvent.parseFromRecord(schemaAndRecord).getInvoiceGroupingKey();
InvoiceGroupingKeyCoder coder = new InvoiceGroupingKeyCoder();
@@ -200,7 +197,7 @@ public class BillingEventTest {
}
@Test
public void testGetDetailReportHeader() {
void testGetDetailReportHeader() {
assertThat(BillingEvent.getHeader())
.isEqualTo(
"id,billingTime,eventTime,registrarId,billingId,poNumber,tld,action,"
@@ -208,7 +205,7 @@ public class BillingEventTest {
}
@Test
public void testGetOverallInvoiceHeader() {
void testGetOverallInvoiceHeader() {
assertThat(InvoiceGroupingKey.invoiceHeader())
.isEqualTo("StartDate,EndDate,ProductAccountKey,Amount,AmountCurrency,BillingProductCode,"
+ "SalesChannel,LineItemType,UsageGroupingKey,Quantity,Description,UnitPrice,"
@@ -19,10 +19,13 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import google.registry.beam.TestPipelineExtension;
import google.registry.util.GoogleCredentialsBundle;
import google.registry.util.ResourceUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Map.Entry;
@@ -30,47 +33,48 @@ import org.apache.beam.runners.direct.DirectRunner;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.options.ValueProvider.StaticValueProvider;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.values.PCollection;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
/** Unit tests for {@link InvoicingPipeline}. */
@RunWith(JUnit4.class)
public class InvoicingPipelineTest {
class InvoicingPipelineTest {
private static PipelineOptions pipelineOptions;
@BeforeClass
public static void initializePipelineOptions() {
@BeforeAll
static void beforeAll() {
pipelineOptions = PipelineOptionsFactory.create();
pipelineOptions.setRunner(DirectRunner.class);
}
@Rule public final transient TestPipeline p = TestPipeline.fromOptions(pipelineOptions);
@Rule public final TemporaryFolder tempFolder = new TemporaryFolder();
@RegisterExtension
final transient TestPipelineExtension testPipeline =
TestPipelineExtension.fromOptions(pipelineOptions);
@SuppressWarnings("WeakerAccess")
@TempDir
transient Path tmpDir;
private InvoicingPipeline invoicingPipeline;
@Before
public void initializePipeline() throws IOException {
File beamTempFolder = tempFolder.newFolder();
String beamTempFolderPath = beamTempFolder.getAbsolutePath();
invoicingPipeline = new InvoicingPipeline(
"test-project",
beamTempFolderPath,
beamTempFolderPath + "/templates/invoicing",
beamTempFolderPath + "/staging",
tempFolder.getRoot().getAbsolutePath(),
"REG-INV",
GoogleCredentialsBundle.create(GoogleCredentials.create(null))
);
@BeforeEach
void beforeEach() throws IOException {
String beamTempFolder =
Files.createDirectory(tmpDir.resolve("beam_temp")).toAbsolutePath().toString();
invoicingPipeline =
new InvoicingPipeline(
"test-project",
beamTempFolder,
beamTempFolder + "/templates/invoicing",
beamTempFolder + "/staging",
tmpDir.toAbsolutePath().toString(),
"REG-INV",
GoogleCredentialsBundle.create(GoogleCredentials.create(null)));
}
private ImmutableList<BillingEvent> getInputEvents() {
@@ -186,17 +190,18 @@ public class InvoicingPipelineTest {
}
@Test
public void testEndToEndPipeline_generatesExpectedFiles() throws Exception {
void testEndToEndPipeline_generatesExpectedFiles() throws Exception {
ImmutableList<BillingEvent> inputRows = getInputEvents();
PCollection<BillingEvent> input = p.apply(Create.of(inputRows));
PCollection<BillingEvent> input = testPipeline.apply(Create.of(inputRows));
invoicingPipeline.applyTerminalTransforms(input, StaticValueProvider.of("2017-10"));
p.run();
testPipeline.run();
for (Entry<String, ImmutableList<String>> entry : getExpectedDetailReportMap().entrySet()) {
ImmutableList<String> detailReport = resultFileContents(entry.getKey());
assertThat(detailReport.get(0))
.isEqualTo("id,billingTime,eventTime,registrarId,billingId,poNumber,tld,action,"
+ "domain,repositoryId,years,currency,amount,flags");
.isEqualTo(
"id,billingTime,eventTime,registrarId,billingId,poNumber,tld,action,"
+ "domain,repositoryId,years,currency,amount,flags");
assertThat(detailReport.subList(1, detailReport.size()))
.containsExactlyElementsIn(entry.getValue());
}
@@ -215,8 +220,7 @@ public class InvoicingPipelineTest {
private ImmutableList<String> resultFileContents(String filename) throws Exception {
File resultFile =
new File(
String.format(
"%s/invoices/2017-10/%s", tempFolder.getRoot().getAbsolutePath(), filename));
String.format("%s/invoices/2017-10/%s", tmpDir.toAbsolutePath().toString(), filename));
return ImmutableList.copyOf(
ResourceUtils.readResourceUtf8(resultFile.toURI().toURL()).split("\n"));
}
@@ -25,16 +25,13 @@ import org.apache.beam.sdk.io.FileBasedSink;
import org.apache.beam.sdk.options.ValueProvider;
import org.apache.beam.sdk.options.ValueProvider.StaticValueProvider;
import org.apache.beam.sdk.transforms.SerializableFunction;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link InvoicingUtils}. */
@RunWith(JUnit4.class)
public class InvoicingUtilsTest {
class InvoicingUtilsTest {
@Test
public void testDestinationFunction_generatesProperFileParams() {
void testDestinationFunction_generatesProperFileParams() {
SerializableFunction<BillingEvent, Params> destinationFunction =
InvoicingUtils.makeDestinationFunction("my/directory", StaticValueProvider.of("2017-10"));
@@ -53,7 +50,7 @@ public class InvoicingUtilsTest {
}
@Test
public void testEmptyDestinationParams() {
void testEmptyDestinationParams() {
assertThat(InvoicingUtils.makeEmptyDestinationParams("my/directory"))
.isEqualTo(
new Params()
@@ -63,7 +60,7 @@ public class InvoicingUtilsTest {
/** Asserts that the instantiated sql template matches a golden expected file. */
@Test
public void testMakeQueryProvider() {
void testMakeQueryProvider() {
ValueProvider<String> queryProvider =
InvoicingUtils.makeQueryProvider(StaticValueProvider.of("2017-10"), "my-project-id");
assertThat(queryProvider.get()).isEqualTo(loadFile("billing_events_test.sql"));
@@ -24,6 +24,7 @@ import static org.mockito.Mockito.withSettings;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.common.collect.ImmutableList;
import com.google.common.io.CharStreams;
import google.registry.beam.TestPipelineExtension;
import google.registry.beam.spec11.SafeBrowsingTransforms.EvaluateSafeBrowsingFn;
import google.registry.testing.FakeClock;
import google.registry.testing.FakeSleeper;
@@ -37,13 +38,14 @@ import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.function.Supplier;
import org.apache.beam.runners.direct.DirectRunner;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.options.ValueProvider.StaticValueProvider;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.values.PCollection;
import org.apache.http.ProtocolVersion;
@@ -56,44 +58,47 @@ import org.joda.time.DateTime;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
/** Unit tests for {@link Spec11Pipeline}. */
@RunWith(JUnit4.class)
public class Spec11PipelineTest {
class Spec11PipelineTest {
private static PipelineOptions pipelineOptions;
@BeforeClass
public static void initializePipelineOptions() {
@BeforeAll
static void beforeAll() {
pipelineOptions = PipelineOptionsFactory.create();
pipelineOptions.setRunner(DirectRunner.class);
}
@Rule public final transient TestPipeline p = TestPipeline.fromOptions(pipelineOptions);
@Rule public final TemporaryFolder tempFolder = new TemporaryFolder();
@RegisterExtension
final transient TestPipelineExtension testPipeline =
TestPipelineExtension.fromOptions(pipelineOptions);
@SuppressWarnings("WeakerAccess")
@TempDir
Path tmpDir;
private final Retrier retrier =
new Retrier(new FakeSleeper(new FakeClock(DateTime.parse("2019-07-15TZ"))), 1);
private Spec11Pipeline spec11Pipeline;
@Before
public void initializePipeline() throws IOException {
File beamTempFolder = tempFolder.newFolder();
@BeforeEach
void beforeEach() throws IOException {
String beamTempFolder =
Files.createDirectory(tmpDir.resolve("beam_temp")).toAbsolutePath().toString();
spec11Pipeline =
new Spec11Pipeline(
"test-project",
beamTempFolder.getAbsolutePath() + "/staging",
beamTempFolder.getAbsolutePath() + "/templates/invoicing",
tempFolder.getRoot().getAbsolutePath(),
beamTempFolder + "/staging",
beamTempFolder + "/templates/invoicing",
tmpDir.toAbsolutePath().toString(),
GoogleCredentialsBundle.create(GoogleCredentials.create(null)),
retrier);
}
@@ -127,7 +132,7 @@ public class Spec11PipelineTest {
*/
@Test
@SuppressWarnings("unchecked")
public void testEndToEndPipeline_generatesExpectedFiles() throws Exception {
void testEndToEndPipeline_generatesExpectedFiles() throws Exception {
// Establish mocks for testing
ImmutableList<Subdomain> inputRows = getInputDomains();
CloseableHttpClient httpClient = mock(CloseableHttpClient.class, withSettings().serializable());
@@ -142,9 +147,9 @@ public class Spec11PipelineTest {
(Serializable & Supplier) () -> httpClient);
// Apply input and evaluation transforms
PCollection<Subdomain> input = p.apply(Create.of(inputRows));
PCollection<Subdomain> input = testPipeline.apply(Create.of(inputRows));
spec11Pipeline.evaluateUrlHealth(input, evalFn, StaticValueProvider.of("2018-06-01"));
p.run();
testPipeline.run();
// Verify header and 4 threat matches for 3 registrars are found
ImmutableList<String> generatedReport = resultFileContents();
@@ -292,7 +297,7 @@ public class Spec11PipelineTest {
new File(
String.format(
"%s/icann/spec11/2018-06/SPEC11_MONTHLY_REPORT_2018-06-01",
tempFolder.getRoot().getAbsolutePath()));
tmpDir.toAbsolutePath().toString()));
return ImmutableList.copyOf(
ResourceUtils.readResourceUtf8(resultFile.toURI().toURL()).split("\n"));
}
@@ -1,31 +0,0 @@
// Copyright 2017 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.bigquery;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link BigqueryConnection}. */
@RunWith(JUnit4.class)
public class BigqueryConnectionTest {
@Test
public void testNothing() {
// Placeholder test class for now.
// TODO(b/16569089): figure out a good way for testing our Bigquery usage overall - maybe unit
// tests here, maybe end-to-end testing.
}
}
@@ -27,20 +27,18 @@ import com.google.api.services.bigquery.model.JobReference;
import java.util.concurrent.TimeUnit;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link BigqueryUtils}. */
@RunWith(JUnit4.class)
public class BigqueryUtilsTest {
class BigqueryUtilsTest {
private static final DateTime DATE_0 = DateTime.parse("2014-07-17T20:35:42Z");
private static final DateTime DATE_1 = DateTime.parse("2014-07-17T20:35:42.1Z");
private static final DateTime DATE_2 = DateTime.parse("2014-07-17T20:35:42.12Z");
private static final DateTime DATE_3 = DateTime.parse("2014-07-17T20:35:42.123Z");
@Test
public void test_toBigqueryTimestampString() {
void test_toBigqueryTimestampString() {
assertThat(toBigqueryTimestampString(START_OF_TIME)).isEqualTo("1970-01-01 00:00:00.000");
assertThat(toBigqueryTimestampString(DATE_0)).isEqualTo("2014-07-17 20:35:42.000");
assertThat(toBigqueryTimestampString(DATE_1)).isEqualTo("2014-07-17 20:35:42.100");
@@ -50,7 +48,7 @@ public class BigqueryUtilsTest {
}
@Test
public void test_toBigqueryTimestampString_convertsToUtc() {
void test_toBigqueryTimestampString_convertsToUtc() {
assertThat(toBigqueryTimestampString(START_OF_TIME.withZone(DateTimeZone.forOffsetHours(5))))
.isEqualTo("1970-01-01 00:00:00.000");
assertThat(toBigqueryTimestampString(DateTime.parse("1970-01-01T00:00:00-0500")))
@@ -58,13 +56,13 @@ public class BigqueryUtilsTest {
}
@Test
public void test_fromBigqueryTimestampString_startAndEndOfTime() {
void test_fromBigqueryTimestampString_startAndEndOfTime() {
assertThat(fromBigqueryTimestampString("1970-01-01 00:00:00 UTC")).isEqualTo(START_OF_TIME);
assertThat(fromBigqueryTimestampString("294247-01-10 04:00:54.775 UTC")).isEqualTo(END_OF_TIME);
}
@Test
public void test_fromBigqueryTimestampString_trailingZerosOkay() {
void test_fromBigqueryTimestampString_trailingZerosOkay() {
assertThat(fromBigqueryTimestampString("2014-07-17 20:35:42 UTC")).isEqualTo(DATE_0);
assertThat(fromBigqueryTimestampString("2014-07-17 20:35:42.0 UTC")).isEqualTo(DATE_0);
assertThat(fromBigqueryTimestampString("2014-07-17 20:35:42.00 UTC")).isEqualTo(DATE_0);
@@ -78,27 +76,27 @@ public class BigqueryUtilsTest {
}
@Test
public void testFailure_fromBigqueryTimestampString_nonUtcTimeZone() {
void testFailure_fromBigqueryTimestampString_nonUtcTimeZone() {
assertThrows(
IllegalArgumentException.class,
() -> fromBigqueryTimestampString("2014-01-01 01:01:01 +05:00"));
}
@Test
public void testFailure_fromBigqueryTimestampString_noTimeZone() {
void testFailure_fromBigqueryTimestampString_noTimeZone() {
assertThrows(
IllegalArgumentException.class, () -> fromBigqueryTimestampString("2014-01-01 01:01:01"));
}
@Test
public void testFailure_fromBigqueryTimestampString_tooManyMillisecondDigits() {
void testFailure_fromBigqueryTimestampString_tooManyMillisecondDigits() {
assertThrows(
IllegalArgumentException.class,
() -> fromBigqueryTimestampString("2014-01-01 01:01:01.1234 UTC"));
}
@Test
public void test_toBigqueryTimestamp_timeunitConversion() {
void test_toBigqueryTimestamp_timeunitConversion() {
assertThat(toBigqueryTimestamp(1234567890L, TimeUnit.SECONDS))
.isEqualTo("1234567890.000000");
assertThat(toBigqueryTimestamp(1234567890123L, TimeUnit.MILLISECONDS))
@@ -110,14 +108,14 @@ public class BigqueryUtilsTest {
}
@Test
public void test_toBigqueryTimestamp_timeunitConversionForZero() {
void test_toBigqueryTimestamp_timeunitConversionForZero() {
assertThat(toBigqueryTimestamp(0L, TimeUnit.SECONDS)).isEqualTo("0.000000");
assertThat(toBigqueryTimestamp(0L, TimeUnit.MILLISECONDS)).isEqualTo("0.000000");
assertThat(toBigqueryTimestamp(0L, TimeUnit.MICROSECONDS)).isEqualTo("0.000000");
}
@Test
public void test_toBigqueryTimestamp_datetimeConversion() {
void test_toBigqueryTimestamp_datetimeConversion() {
assertThat(toBigqueryTimestamp(START_OF_TIME)).isEqualTo("0.000000");
assertThat(toBigqueryTimestamp(DATE_0)).isEqualTo("1405629342.000000");
assertThat(toBigqueryTimestamp(DATE_1)).isEqualTo("1405629342.100000");
@@ -127,18 +125,18 @@ public class BigqueryUtilsTest {
}
@Test
public void test_toJobReferenceString_normalSucceeds() {
void test_toJobReferenceString_normalSucceeds() {
assertThat(toJobReferenceString(new JobReference().setProjectId("foo").setJobId("bar")))
.isEqualTo("foo:bar");
}
@Test
public void test_toJobReferenceString_emptyReferenceSucceeds() {
void test_toJobReferenceString_emptyReferenceSucceeds() {
assertThat(toJobReferenceString(new JobReference())).isEqualTo("null:null");
}
@Test
public void test_toJobReferenceString_nullThrowsNpe() {
void test_toJobReferenceString_nullThrowsNpe() {
assertThrows(NullPointerException.class, () -> toJobReferenceString(null));
}
}
@@ -29,15 +29,12 @@ import com.google.api.services.bigquery.model.TableFieldSchema;
import com.google.api.services.bigquery.model.TableReference;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
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 CheckedBigquery}. */
@RunWith(JUnit4.class)
public class CheckedBigqueryTest {
class CheckedBigqueryTest {
private final Bigquery bigquery = mock(Bigquery.class);
private final Bigquery.Datasets bigqueryDatasets = mock(Bigquery.Datasets.class);
@@ -48,8 +45,8 @@ public class CheckedBigqueryTest {
private CheckedBigquery checkedBigquery;
@Before
public void before() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
when(bigquery.datasets()).thenReturn(bigqueryDatasets);
when(bigqueryDatasets.insert(eq("Project-Id"), any(Dataset.class)))
.thenReturn(bigqueryDatasetsInsert);
@@ -70,7 +67,7 @@ public class CheckedBigqueryTest {
}
@Test
public void testSuccess_datastoreCreation() throws Exception {
void testSuccess_datastoreCreation() throws Exception {
checkedBigquery.ensureDataSetExists("Project-Id", "Dataset-Id");
ArgumentCaptor<Dataset> datasetArg = ArgumentCaptor.forClass(Dataset.class);
@@ -83,7 +80,7 @@ public class CheckedBigqueryTest {
}
@Test
public void testSuccess_datastoreAndTableCreation() throws Exception {
void testSuccess_datastoreAndTableCreation() throws Exception {
checkedBigquery.ensureDataSetAndTableExist("Project-Id", "Dataset2", "Table2");
ArgumentCaptor<Dataset> datasetArg = ArgumentCaptor.forClass(Dataset.class);
@@ -18,15 +18,13 @@ import static com.google.common.truth.Truth.assertThat;
import static google.registry.config.RegistryConfig.CONFIG_SETTINGS;
import static google.registry.config.RegistryConfig.ConfigModule.provideReservedTermsExportDisclaimer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
@RunWith(JUnit4.class)
public class RegistryConfigTest {
/** Unit tests for {@link RegistryConfig}. */
class RegistryConfigTest {
@Test
public void test_reservedTermsExportDisclaimer_isPrependedWithOctothorpes() {
void test_reservedTermsExportDisclaimer_isPrependedWithOctothorpes() {
assertThat(provideReservedTermsExportDisclaimer(CONFIG_SETTINGS.get()))
.isEqualTo("# Disclaimer line 1.\n" + "# Line 2 is this 1.");
}
@@ -14,16 +14,13 @@
package google.registry.config;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link RegistryEnvironment}. */
@RunWith(JUnit4.class)
public class RegistryEnvironmentTest {
class RegistryEnvironmentTest {
@Test
public void testGet() {
void testGet() {
RegistryEnvironment.get();
}
}
@@ -26,20 +26,17 @@ import google.registry.util.TaskQueueUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
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 CommitLogFanoutAction}. */
@RunWith(JUnit4.class)
public class CommitLogFanoutActionTest {
class CommitLogFanoutActionTest {
private static final String ENDPOINT = "/the/servlet";
private static final String QUEUE = "the-queue";
@Rule
public final AppEngineRule appEngine =
@RegisterExtension
final AppEngineRule appEngineRule =
AppEngineRule.builder()
.withDatastoreAndCloudSql()
.withTaskQueue(
@@ -55,7 +52,7 @@ public class CommitLogFanoutActionTest {
.build();
@Test
public void testSuccess() {
void testSuccess() {
CommitLogFanoutAction action = new CommitLogFanoutAction();
action.taskQueueUtils = new TaskQueueUtils(new Retrier(null, 1));
action.endpoint = ENDPOINT;
@@ -39,22 +39,19 @@ import google.registry.util.TaskQueueUtils;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
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 TldFanoutAction}. */
@RunWith(JUnit4.class)
public class TldFanoutActionTest {
class TldFanoutActionTest {
private static final String ENDPOINT = "/the/servlet";
private static final String QUEUE = "the-queue";
private final FakeResponse response = new FakeResponse();
@Rule
public final AppEngineRule appEngine =
@RegisterExtension
final AppEngineRule appEngine =
AppEngineRule.builder()
.withDatastoreAndCloudSql()
.withTaskQueue(
@@ -96,8 +93,8 @@ public class TldFanoutActionTest {
action.run();
}
@Before
public void before() {
@BeforeEach
void beforeEach() {
createTlds("com", "net", "org", "example");
persistResource(Registry.get("example").asBuilder().setTldType(TldType.TEST).build());
}
@@ -123,36 +120,36 @@ public class TldFanoutActionTest {
}
@Test
public void testSuccess_methodPostIsDefault() {
void testSuccess_methodPostIsDefault() {
run(getParamsMap("runInEmpty", ""));
assertTasksEnqueued(QUEUE, new TaskMatcher().method("POST"));
}
@Test
public void testFailure_noTlds() {
void testFailure_noTlds() {
assertThrows(IllegalArgumentException.class, () -> run(getParamsMap()));
}
@Test
public void testSuccess_runInEmpty() {
void testSuccess_runInEmpty() {
run(getParamsMap("runInEmpty", ""));
assertTaskWithoutTld();
}
@Test
public void testSuccess_forEachRealTld() {
void testSuccess_forEachRealTld() {
run(getParamsMap("forEachRealTld", ""));
assertTasks("com", "net", "org");
}
@Test
public void testSuccess_forEachTestTld() {
void testSuccess_forEachTestTld() {
run(getParamsMap("forEachTestTld", ""));
assertTasks("example");
}
@Test
public void testSuccess_forEachTestTldAndForEachRealTld() {
void testSuccess_forEachTestTldAndForEachRealTld() {
run(getParamsMap(
"forEachTestTld", "",
"forEachRealTld", ""));
@@ -160,13 +157,13 @@ public class TldFanoutActionTest {
}
@Test
public void testSuccess_runEverywhere() {
void testSuccess_runEverywhere() {
run(getParamsMap("forEachTestTld", "", "forEachRealTld", ""));
assertTasks("com", "net", "org", "example");
}
@Test
public void testSuccess_excludeRealTlds() {
void testSuccess_excludeRealTlds() {
run(getParamsMap(
"forEachRealTld", "",
"exclude", "com,net"));
@@ -174,7 +171,7 @@ public class TldFanoutActionTest {
}
@Test
public void testSuccess_excludeTestTlds() {
void testSuccess_excludeTestTlds() {
run(getParamsMap(
"forEachTestTld", "",
"exclude", "example"));
@@ -182,7 +179,7 @@ public class TldFanoutActionTest {
}
@Test
public void testSuccess_excludeNonexistentTlds() {
void testSuccess_excludeNonexistentTlds() {
run(getParamsMap(
"forEachTestTld", "",
"forEachRealTld", "",
@@ -191,7 +188,7 @@ public class TldFanoutActionTest {
}
@Test
public void testFailure_runInEmptyAndTest() {
void testFailure_runInEmptyAndTest() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -202,7 +199,7 @@ public class TldFanoutActionTest {
}
@Test
public void testFailure_runInEmptyAndReal() {
void testFailure_runInEmptyAndReal() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -213,7 +210,7 @@ public class TldFanoutActionTest {
}
@Test
public void testFailure_runInEmptyAndExclude() {
void testFailure_runInEmptyAndExclude() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -224,14 +221,14 @@ public class TldFanoutActionTest {
}
@Test
public void testSuccess_additionalArgsFlowThroughToPostParams() {
void testSuccess_additionalArgsFlowThroughToPostParams() {
run(getParamsMap("forEachTestTld", "", "newkey", "newval"));
assertTasksEnqueued(QUEUE,
new TaskMatcher().url("/the/servlet").param("newkey", "newval"));
}
@Test
public void testSuccess_returnHttpResponse() {
void testSuccess_returnHttpResponse() {
run(getParamsMap("forEachRealTld", "", "endpoint", "/the/servlet"));
List<TaskStateInfo> taskList =
@@ -250,7 +247,7 @@ public class TldFanoutActionTest {
}
@Test
public void testSuccess_returnHttpResponse_runInEmpty() {
void testSuccess_returnHttpResponse_runInEmpty() {
run(getParamsMap("runInEmpty", "", "endpoint", "/the/servlet"));
List<TaskStateInfo> taskList =
@@ -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()
@@ -22,13 +22,10 @@ import com.google.common.base.Joiner;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Tests to ensure that generated flow documentation matches the expected documentation. */
@RunWith(JUnit4.class)
public class FlowDocumentationTest {
class FlowDocumentationTest {
private static final Path GOLDEN_MARKDOWN_FILEPATH = getProjectRoot().resolve("docs/flows.md");
private static final String UPDATE_COMMAND = "./gradlew :core:flowDocsTool";
@@ -43,7 +40,7 @@ public class FlowDocumentationTest {
"");
@Test
public void testGeneratedMatchesGolden() throws IOException {
void testGeneratedMatchesGolden() throws IOException {
// Read the markdown file.
Path goldenMarkdownPath =
GOLDEN_MARKDOWN_FILEPATH;
@@ -21,9 +21,7 @@ import com.google.common.flogger.FluentLogger;
import google.registry.documentation.FlowDocumentation.ErrorCase;
import java.io.IOException;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/**
* Test to ensure accurate documentation of flow exceptions.
@@ -47,13 +45,12 @@ import org.junit.runners.JUnit4;
* removing the javadoc tag.
*/
@SuppressWarnings("javadoc")
@RunWith(JUnit4.class)
public class FlowExceptionsTest {
class FlowExceptionsTest {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
@Test
public void testExceptionCorrespondence() throws IOException {
void testExceptionCorrespondence() throws IOException {
DocumentationGenerator docGenerator = new DocumentationGenerator();
Set<ErrorCase> possibleErrors = Sets.newHashSet(docGenerator.getAllErrors());
Set<String> mismatchingFlows = Sets.newHashSet();
@@ -18,15 +18,13 @@ import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Test conversion of javadocs to markdown. */
@RunWith(JUnit4.class)
public class MarkdownDocumentationFormatterTest {
class MarkdownDocumentationFormatterTest {
@Test
public void testHtmlSanitization() {
void testHtmlSanitization() {
assertThat(
MarkdownDocumentationFormatter.fixHtml(
"First. <p>Second. &lt; &gt; &amp; &squot; &quot;"))
@@ -38,55 +36,55 @@ public class MarkdownDocumentationFormatterTest {
}
@Test
public void testDedents() {
assertThat(MarkdownDocumentationFormatter.fixHtml(
"First line\n\n <p>Second line.\n Third line."))
void testDedents() {
assertThat(
MarkdownDocumentationFormatter.fixHtml("First line\n\n <p>Second line.\n Third line."))
.isEqualTo("First line\n\nSecond line.\nThird line.");
}
@Test
public void testUnknownSequences() {
void testUnknownSequences() {
assertThrows(
IllegalArgumentException.class, () -> MarkdownDocumentationFormatter.fixHtml("&blech;"));
}
@Test
public void testParagraphFormatting() {
void testParagraphFormatting() {
String[] words = {"first", "second", "third", "really-really-long-word", "more", "stuff"};
String formatted = MarkdownDocumentationFormatter.formatParagraph(Arrays.asList(words), 16);
assertThat(formatted).isEqualTo("first second\nthird\nreally-really-long-word\nmore stuff\n");
}
@Test
public void testReflow() {
void testReflow() {
String input =
"This is the very first line.\n"
+ " \n" // add a little blank space to this line just to make things interesting.
+ "This is the second paragraph. Aint\n"
+ "it sweet?\n"
+ "\n"
+ "This is our third and final paragraph.\n"
+ "It is multi-line and ends with no blank\n"
+ "line.";
+ " \n" // add a little blank space to this line just to make things interesting.
+ "This is the second paragraph. Aint\n"
+ "it sweet?\n"
+ "\n"
+ "This is our third and final paragraph.\n"
+ "It is multi-line and ends with no blank\n"
+ "line.";
String expected =
"This is the very\n"
+ "first line.\n"
+ "\n"
+ "This is the\n"
+ "second\n"
+ "paragraph. Aint\n"
+ "it sweet?\n"
+ "\n"
+ "This is our\n"
+ "third and final\n"
+ "paragraph. It is\n"
+ "multi-line and\n"
+ "ends with no\n"
+ "blank line.\n";
+ "first line.\n"
+ "\n"
+ "This is the\n"
+ "second\n"
+ "paragraph. Aint\n"
+ "it sweet?\n"
+ "\n"
+ "This is our\n"
+ "third and final\n"
+ "paragraph. It is\n"
+ "multi-line and\n"
+ "ends with no\n"
+ "blank line.\n";
assertThat(MarkdownDocumentationFormatter.reflow(input, 16)).isEqualTo(expected);
}
assertThat(MarkdownDocumentationFormatter.reflow(input, 16)).isEqualTo(expected);
}
public MarkdownDocumentationFormatterTest() {}
MarkdownDocumentationFormatterTest() {}
}
@@ -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()

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