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

Compare commits

..

13 Commits

Author SHA1 Message Date
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
180 changed files with 2674 additions and 2553 deletions
@@ -169,10 +169,12 @@ public final class AsyncTaskEnqueuer {
lock.getRelockDuration().isPresent(),
"Lock with ID %s not configured for relock",
lock.getRevisionId());
String backendHostname = appEngineServiceUtils.getServiceHostname("backend");
addTaskToQueueWithRetry(
asyncActionsPushQueue,
TaskOptions.Builder.withUrl(RelockDomainAction.PATH)
.method(Method.POST)
.header("Host", backendHostname)
.param(
RelockDomainAction.OLD_UNLOCK_REVISION_ID_PARAM,
String.valueOf(lock.getRevisionId()))
@@ -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);
}
@@ -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
@@ -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();
@@ -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");
@@ -52,23 +52,19 @@ 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 SystemPropertyRule systemPropertyRule = new SystemPropertyRule();
@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
@@ -105,7 +101,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 +116,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 +132,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 +142,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,7 +152,7 @@ public class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDa
}
@Test
public void testFail_givenNonDotTestTldOnProd() {
void testFail_givenNonDotTestTldOnProd() {
action.tlds = ImmutableSet.of("example");
RegistryEnvironment.PRODUCTION.setup(systemPropertyRule);
IllegalArgumentException thrown =
@@ -167,7 +163,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 +174,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 +184,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 +199,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 +216,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 +230,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 +242,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 +259,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")
@@ -26,6 +26,7 @@ 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;
@@ -41,6 +42,7 @@ import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.RuleChain;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -54,10 +56,14 @@ public class WriteToSqlTest implements Serializable {
@Rule public final transient InjectRule injectRule = new InjectRule();
@Rule
public transient JpaIntegrationTestRule jpaRule =
// For use in the RuleChain below. Saves a reference to retrieve Database connection config.
public final transient JpaIntegrationTestRule database =
new JpaTestRules.Builder().withClock(fakeClock).buildIntegrationTestRule();
@Rule
public final transient RuleChain jpaRules =
RuleChain.outerRule(new DatastoreEntityExtension()).around(database);
@Rule public transient TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
@@ -91,7 +97,9 @@ public class WriteToSqlTest implements Serializable {
new PrintStream(credentialFile)
.printf(
"%s %s %s",
jpaRule.getDatabaseUrl(), jpaRule.getDatabaseUsername(), jpaRule.getDatabasePassword())
database.getDatabaseUrl(),
database.getDatabaseUsername(),
database.getDatabasePassword())
.close();
}
@@ -35,22 +35,18 @@ import java.io.StringWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for Dagger injection of the DNS package. */
@RunWith(JUnit4.class)
public final class DnsInjectionTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@Rule
public final InjectRule inject = new InjectRule();
@RegisterExtension public final InjectRule inject = new InjectRule();
private final HttpServletRequest req = mock(HttpServletRequest.class);
private final HttpServletResponse rsp = mock(HttpServletResponse.class);
@@ -59,8 +55,8 @@ public final class DnsInjectionTest {
private DnsTestComponent component;
private DnsQueue dnsQueue;
@Before
public void setUp() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
inject.setStaticField(Ofy.class, "clock", clock);
when(rsp.getWriter()).thenReturn(new PrintWriter(httpOutput));
component = DaggerDnsTestComponent.builder()
@@ -71,7 +67,7 @@ public final class DnsInjectionTest {
}
@Test
public void testReadDnsQueueAction_injectsAndWorks() {
void testReadDnsQueueAction_injectsAndWorks() {
persistActiveSubordinateHost("ns1.example.lol", persistActiveDomain("example.lol"));
clock.advanceOneMilli();
dnsQueue.addDomainRefreshTask("example.lol");
@@ -81,7 +77,7 @@ public final class DnsInjectionTest {
}
@Test
public void testRefreshDns_domain_injectsAndWorks() {
void testRefreshDns_domain_injectsAndWorks() {
persistActiveDomain("example.lol");
when(req.getParameter("type")).thenReturn("domain");
when(req.getParameter("name")).thenReturn("example.lol");
@@ -90,7 +86,7 @@ public final class DnsInjectionTest {
}
@Test
public void testRefreshDns_missingDomain_throwsNotFound() {
void testRefreshDns_missingDomain_throwsNotFound() {
when(req.getParameter("type")).thenReturn("domain");
when(req.getParameter("name")).thenReturn("example.lol");
NotFoundException thrown =
@@ -99,7 +95,7 @@ public final class DnsInjectionTest {
}
@Test
public void testRefreshDns_host_injectsAndWorks() {
void testRefreshDns_host_injectsAndWorks() {
persistActiveSubordinateHost("ns1.example.lol", persistActiveDomain("example.lol"));
when(req.getParameter("type")).thenReturn("host");
when(req.getParameter("name")).thenReturn("ns1.example.lol");
@@ -108,7 +104,7 @@ public final class DnsInjectionTest {
}
@Test
public void testRefreshDns_missingHost_throwsNotFound() {
void testRefreshDns_missingHost_throwsNotFound() {
when(req.getParameter("type")).thenReturn("host");
when(req.getParameter("name")).thenReturn("ns1.example.lol");
NotFoundException thrown =
@@ -24,31 +24,28 @@ import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock;
import google.registry.testing.TaskQueueHelper.TaskMatcher;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link DnsQueue}. */
@RunWith(JUnit4.class)
public class DnsQueueTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
private DnsQueue dnsQueue;
private final FakeClock clock = new FakeClock(DateTime.parse("2010-01-01T10:00:00Z"));
@Before
public void init() {
@BeforeEach
void beforeEach() {
dnsQueue = DnsQueue.createForTesting(clock);
dnsQueue.leaseTasksBatchSize = 10;
}
@Test
public void test_addHostRefreshTask_success() {
void test_addHostRefreshTask_success() {
createTld("tld");
dnsQueue.addHostRefreshTask("octopus.tld");
assertTasksEnqueued(
@@ -61,7 +58,7 @@ public class DnsQueueTest {
}
@Test
public void test_addHostRefreshTask_failsOnUnknownTld() {
void test_addHostRefreshTask_failsOnUnknownTld() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -78,7 +75,7 @@ public class DnsQueueTest {
}
@Test
public void test_addDomainRefreshTask_success() {
void test_addDomainRefreshTask_success() {
createTld("tld");
dnsQueue.addDomainRefreshTask("octopus.tld");
assertTasksEnqueued(
@@ -91,7 +88,7 @@ public class DnsQueueTest {
}
@Test
public void test_addDomainRefreshTask_failsOnUnknownTld() {
void test_addDomainRefreshTask_failsOnUnknownTld() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -44,22 +44,18 @@ import google.registry.testing.FakeLockHandler;
import google.registry.testing.InjectRule;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link PublishDnsUpdatesAction}. */
@RunWith(JUnit4.class)
public class PublishDnsUpdatesActionTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@Rule
public final InjectRule inject = new InjectRule();
@RegisterExtension public final InjectRule inject = new InjectRule();
private final FakeClock clock = new FakeClock(DateTime.parse("1971-01-01TZ"));
private final FakeLockHandler lockHandler = new FakeLockHandler(true);
private final DnsWriter dnsWriter = mock(DnsWriter.class);
@@ -67,8 +63,8 @@ public class PublishDnsUpdatesActionTest {
private final DnsQueue dnsQueue = mock(DnsQueue.class);
private PublishDnsUpdatesAction action;
@Before
public void setUp() {
@BeforeEach
void beforeEach() {
inject.setStaticField(Ofy.class, "clock", clock);
createTld("xn--q9jyb4c");
persistResource(
@@ -104,7 +100,7 @@ public class PublishDnsUpdatesActionTest {
}
@Test
public void testHost_published() {
void testHost_published() {
action = createAction("xn--q9jyb4c");
action.hosts = ImmutableSet.of("ns1.example.xn--q9jyb4c");
@@ -132,7 +128,7 @@ public class PublishDnsUpdatesActionTest {
}
@Test
public void testDomain_published() {
void testDomain_published() {
action = createAction("xn--q9jyb4c");
action.domains = ImmutableSet.of("example.xn--q9jyb4c");
@@ -160,7 +156,7 @@ public class PublishDnsUpdatesActionTest {
}
@Test
public void testAction_acquiresCorrectLock() {
void testAction_acquiresCorrectLock() {
persistResource(Registry.get("xn--q9jyb4c").asBuilder().setNumDnsPublishLocks(4).build());
action = createAction("xn--q9jyb4c");
action.lockIndex = 2;
@@ -178,7 +174,7 @@ public class PublishDnsUpdatesActionTest {
}
@Test
public void testPublish_commitFails() {
void testPublish_commitFails() {
action = createAction("xn--q9jyb4c");
action.domains = ImmutableSet.of("example.xn--q9jyb4c", "example2.xn--q9jyb4c");
action.hosts =
@@ -207,11 +203,12 @@ public class PublishDnsUpdatesActionTest {
}
@Test
public void testHostAndDomain_published() {
void testHostAndDomain_published() {
action = createAction("xn--q9jyb4c");
action.domains = ImmutableSet.of("example.xn--q9jyb4c", "example2.xn--q9jyb4c");
action.hosts = ImmutableSet.of(
"ns1.example.xn--q9jyb4c", "ns2.example.xn--q9jyb4c", "ns1.example2.xn--q9jyb4c");
action.hosts =
ImmutableSet.of(
"ns1.example.xn--q9jyb4c", "ns2.example.xn--q9jyb4c", "ns1.example2.xn--q9jyb4c");
action.run();
@@ -241,7 +238,7 @@ public class PublishDnsUpdatesActionTest {
}
@Test
public void testWrongTld_notPublished() {
void testWrongTld_notPublished() {
action = createAction("xn--q9jyb4c");
action.domains = ImmutableSet.of("example.com", "example2.com");
action.hosts = ImmutableSet.of("ns1.example.com", "ns2.example.com", "ns1.example2.com");
@@ -269,7 +266,7 @@ public class PublishDnsUpdatesActionTest {
}
@Test
public void testLockIsntAvailable() {
void testLockIsntAvailable() {
action = createAction("xn--q9jyb4c");
action.domains = ImmutableSet.of("example.com", "example2.com");
action.hosts = ImmutableSet.of("ns1.example.com", "ns2.example.com", "ns1.example2.com");
@@ -293,7 +290,7 @@ public class PublishDnsUpdatesActionTest {
}
@Test
public void testParam_invalidLockIndex() {
void testParam_invalidLockIndex() {
persistResource(Registry.get("xn--q9jyb4c").asBuilder().setNumDnsPublishLocks(4).build());
action = createAction("xn--q9jyb4c");
action.domains = ImmutableSet.of("example.com");
@@ -319,7 +316,7 @@ public class PublishDnsUpdatesActionTest {
}
@Test
public void testRegistryParam_mismatchedMaxLocks() {
void testRegistryParam_mismatchedMaxLocks() {
persistResource(Registry.get("xn--q9jyb4c").asBuilder().setNumDnsPublishLocks(4).build());
action = createAction("xn--q9jyb4c");
action.domains = ImmutableSet.of("example.com");
@@ -345,7 +342,7 @@ public class PublishDnsUpdatesActionTest {
}
@Test
public void testWrongDnsWriter() {
void testWrongDnsWriter() {
action = createAction("xn--q9jyb4c");
action.domains = ImmutableSet.of("example.com", "example2.com");
action.hosts = ImmutableSet.of("ns1.example.com", "ns2.example.com", "ns1.example2.com");
@@ -56,14 +56,11 @@ import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link ReadDnsQueueAction}. */
@RunWith(JUnit4.class)
public class ReadDnsQueueActionTest {
private static final int TEST_TLD_UPDATE_BATCH_SIZE = 100;
@@ -72,7 +69,7 @@ public class ReadDnsQueueActionTest {
// test in the future. Set to year 3000 so it'll remain in the future for a very long time.
private FakeClock clock = new FakeClock(DateTime.parse("3000-01-01TZ"));
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder()
.withDatastoreAndCloudSql()
@@ -93,8 +90,8 @@ public class ReadDnsQueueActionTest {
.withClock(clock)
.build();
@Before
public void before() {
@BeforeEach
void beforeEach() {
// Because of b/73372999 - the FakeClock can't be in the past, or the TaskQueues stop working.
// To make sure it's never in the past, we set the date far-far into the future
clock.setTo(DateTime.parse("3000-01-01TZ"));
@@ -171,7 +168,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_methodPostIsDefault() {
void testSuccess_methodPostIsDefault() {
dnsQueue.addDomainRefreshTask("domain.com");
dnsQueue.addDomainRefreshTask("domain.net");
dnsQueue.addDomainRefreshTask("domain.example");
@@ -187,7 +184,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_allSingleLockTlds() {
void testSuccess_allSingleLockTlds() {
dnsQueue.addDomainRefreshTask("domain.com");
dnsQueue.addDomainRefreshTask("domain.net");
dnsQueue.addDomainRefreshTask("domain.example");
@@ -200,7 +197,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_moreUpdatesThanQueueBatchSize() {
void testSuccess_moreUpdatesThanQueueBatchSize() {
// The task queue has a batch size of 1000 (that's the maximum number of items you can lease at
// once).
ImmutableList<String> domains =
@@ -219,15 +216,14 @@ public class ReadDnsQueueActionTest {
assertThat(queuedParams).hasSize(15);
// Check all the expected domains are indeed enqueued
assertThat(
queuedParams
.stream()
queuedParams.stream()
.map(params -> params.get("domains").stream().collect(onlyElement()))
.flatMap(values -> Splitter.on(',').splitToList(values).stream()))
.containsExactlyElementsIn(domains);
}
@Test
public void testSuccess_twoDnsWriters() {
void testSuccess_twoDnsWriters() {
persistResource(
Registry.get("com")
.asBuilder()
@@ -242,7 +238,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_differentUpdateTimes_usesMinimum() {
void testSuccess_differentUpdateTimes_usesMinimum() {
clock.setTo(DateTime.parse("3000-02-03TZ"));
dnsQueue.addDomainRefreshTask("domain1.com");
clock.setTo(DateTime.parse("3000-02-04TZ"));
@@ -256,18 +252,18 @@ public class ReadDnsQueueActionTest {
assertThat(getQueuedParams(DNS_PUBLISH_PUSH_QUEUE_NAME)).hasSize(1);
assertThat(getQueuedParams(DNS_PUBLISH_PUSH_QUEUE_NAME).get(0))
.containsExactly(
"enqueued", "3000-02-05T01:00:00.000Z",
"itemsCreated", "3000-02-03T00:00:00.000Z",
"tld", "com",
"dnsWriter", "comWriter",
"domains", "domain1.com,domain2.com,domain3.com",
"hosts", "",
"lockIndex", "1",
"numPublishLocks", "1");
"enqueued", "3000-02-05T01:00:00.000Z",
"itemsCreated", "3000-02-03T00:00:00.000Z",
"tld", "com",
"dnsWriter", "comWriter",
"domains", "domain1.com,domain2.com,domain3.com",
"hosts", "",
"lockIndex", "1",
"numPublishLocks", "1");
}
@Test
public void testSuccess_oneTldPaused_returnedToQueue() {
void testSuccess_oneTldPaused_returnedToQueue() {
persistResource(Registry.get("net").asBuilder().setDnsPaused(true).build());
dnsQueue.addDomainRefreshTask("domain.com");
dnsQueue.addDomainRefreshTask("domain.net");
@@ -281,7 +277,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_oneTldUnknown_returnedToQueue() {
void testSuccess_oneTldUnknown_returnedToQueue() {
dnsQueue.addDomainRefreshTask("domain.com");
dnsQueue.addDomainRefreshTask("domain.example");
QueueFactory.getQueue(DNS_PULL_QUEUE_NAME)
@@ -301,7 +297,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_corruptTaskTldMismatch_published() {
void testSuccess_corruptTaskTldMismatch_published() {
// TODO(mcilwain): what's the correct action to take in this case?
dnsQueue.addDomainRefreshTask("domain.com");
dnsQueue.addDomainRefreshTask("domain.example");
@@ -322,7 +318,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_corruptTaskNoTld_discarded() {
void testSuccess_corruptTaskNoTld_discarded() {
dnsQueue.addDomainRefreshTask("domain.com");
dnsQueue.addDomainRefreshTask("domain.example");
QueueFactory.getQueue(DNS_PULL_QUEUE_NAME)
@@ -341,7 +337,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_corruptTaskNoName_discarded() {
void testSuccess_corruptTaskNoName_discarded() {
dnsQueue.addDomainRefreshTask("domain.com");
dnsQueue.addDomainRefreshTask("domain.example");
QueueFactory.getQueue(DNS_PULL_QUEUE_NAME)
@@ -360,7 +356,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_corruptTaskNoType_discarded() {
void testSuccess_corruptTaskNoType_discarded() {
dnsQueue.addDomainRefreshTask("domain.com");
dnsQueue.addDomainRefreshTask("domain.example");
QueueFactory.getQueue(DNS_PULL_QUEUE_NAME)
@@ -379,7 +375,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_corruptTaskWrongType_discarded() {
void testSuccess_corruptTaskWrongType_discarded() {
dnsQueue.addDomainRefreshTask("domain.com");
dnsQueue.addDomainRefreshTask("domain.example");
QueueFactory.getQueue(DNS_PULL_QUEUE_NAME)
@@ -399,7 +395,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_zone_getsIgnored() {
void testSuccess_zone_getsIgnored() {
dnsQueue.addHostRefreshTask("ns1.domain.com");
dnsQueue.addDomainRefreshTask("domain.net");
dnsQueue.addZoneRefreshTask("example");
@@ -420,7 +416,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_manyDomainsAndHosts() {
void testSuccess_manyDomainsAndHosts() {
for (int i = 0; i < 150; i++) {
// 0: domain; 1: host 1; 2: host 2
for (int thingType = 0; thingType < 3; thingType++) {
@@ -491,7 +487,7 @@ public class ReadDnsQueueActionTest {
}
@Test
public void testSuccess_lockGroupsHostBySuperordinateDomain() {
void testSuccess_lockGroupsHostBySuperordinateDomain() {
dnsQueue.addDomainRefreshTask("hello.multilock.uk");
dnsQueue.addHostRefreshTask("ns1.abc.hello.multilock.uk");
dnsQueue.addHostRefreshTask("ns2.hello.multilock.uk");
@@ -30,17 +30,14 @@ import google.registry.request.HttpException.BadRequestException;
import google.registry.request.HttpException.NotFoundException;
import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link RefreshDnsAction}. */
@RunWith(JUnit4.class)
public class RefreshDnsActionTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@@ -51,13 +48,13 @@ public class RefreshDnsActionTest {
new RefreshDnsAction(name, type, clock, dnsQueue).run();
}
@Before
public void before() {
@BeforeEach
void beforeEach() {
createTld("xn--q9jyb4c");
}
@Test
public void testSuccess_host() {
void testSuccess_host() {
DomainBase domain = persistActiveDomain("example.xn--q9jyb4c");
persistActiveSubordinateHost("ns1.example.xn--q9jyb4c", domain);
run(TargetType.HOST, "ns1.example.xn--q9jyb4c");
@@ -66,7 +63,7 @@ public class RefreshDnsActionTest {
}
@Test
public void testSuccess_externalHostNotEnqueued() {
void testSuccess_externalHostNotEnqueued() {
persistActiveDomain("example.xn--q9jyb4c");
persistActiveHost("ns1.example.xn--q9jyb4c");
BadRequestException thrown =
@@ -85,7 +82,7 @@ public class RefreshDnsActionTest {
}
@Test
public void testSuccess_domain() {
void testSuccess_domain() {
persistActiveDomain("example.xn--q9jyb4c");
run(TargetType.DOMAIN, "example.xn--q9jyb4c");
verify(dnsQueue).addDomainRefreshTask("example.xn--q9jyb4c");
@@ -93,17 +90,17 @@ public class RefreshDnsActionTest {
}
@Test
public void testFailure_unqualifiedName() {
void testFailure_unqualifiedName() {
assertThrows(BadRequestException.class, () -> run(TargetType.DOMAIN, "example"));
}
@Test
public void testFailure_hostDoesNotExist() {
void testFailure_hostDoesNotExist() {
assertThrows(NotFoundException.class, () -> run(TargetType.HOST, "ns1.example.xn--q9jyb4c"));
}
@Test
public void testFailure_domainDoesNotExist() {
void testFailure_domainDoesNotExist() {
assertThrows(NotFoundException.class, () -> run(TargetType.DOMAIN, "example.xn--q9jyb4c"));
}
}
@@ -17,13 +17,10 @@ package google.registry.dns.writer;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link BaseDnsWriter}. */
@RunWith(JUnit4.class)
public class BaseDnsWriterTest {
class BaseDnsWriterTest {
static class StubDnsWriter extends BaseDnsWriter {
@@ -46,7 +43,7 @@ public class BaseDnsWriterTest {
}
@Test
public void test_cannotBeCalledTwice() {
void test_cannotBeCalledTwice() {
StubDnsWriter writer = new StubDnsWriter();
assertThat(writer.commitCallCount).isEqualTo(0);
writer.commit();
@@ -53,27 +53,25 @@ import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
/** Test case for {@link CloudDnsWriter}. */
@RunWith(JUnit4.class)
@ExtendWith(MockitoExtension.class)
public class CloudDnsWriterTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
private static final Inet4Address IPv4 = (Inet4Address) InetAddresses.forString("127.0.0.1");
private static final Inet6Address IPv6 = (Inet6Address) InetAddresses.forString("::1");
private static final Duration DEFAULT_A_TTL = Duration.standardSeconds(11);
@@ -116,8 +114,8 @@ public class CloudDnsWriterTest {
return listResourceRecordSetsRequest;
}
@Before
public void setUp() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
createTld("tld");
writer =
new CloudDnsWriter(
@@ -312,15 +310,17 @@ public class CloudDnsWriterTest {
.build();
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testLoadDomain_nonExistentDomain() {
void testLoadDomain_nonExistentDomain() {
writer.publishDomain("example.tld");
verifyZone(ImmutableSet.of());
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testLoadDomain_noDsDataOrNameservers() {
void testLoadDomain_noDsDataOrNameservers() {
persistResource(fakeDomain("example.tld", ImmutableSet.of(), 0));
writer.publishDomain("example.tld");
@@ -328,7 +328,7 @@ public class CloudDnsWriterTest {
}
@Test
public void testLoadDomain_deleteOldData() {
void testLoadDomain_deleteOldData() {
stubZone = fakeDomainRecords("example.tld", 2, 2, 2, 2);
persistResource(fakeDomain("example.tld", ImmutableSet.of(), 0));
writer.publishDomain("example.tld");
@@ -337,7 +337,7 @@ public class CloudDnsWriterTest {
}
@Test
public void testLoadDomain_withExternalNs() {
void testLoadDomain_withExternalNs() {
persistResource(
fakeDomain("example.tld", ImmutableSet.of(persistResource(fakeHost("0.external"))), 0));
writer.publishDomain("example.tld");
@@ -346,7 +346,7 @@ public class CloudDnsWriterTest {
}
@Test
public void testLoadDomain_withDsData() {
void testLoadDomain_withDsData() {
persistResource(
fakeDomain("example.tld", ImmutableSet.of(persistResource(fakeHost("0.external"))), 1));
writer.publishDomain("example.tld");
@@ -355,7 +355,7 @@ public class CloudDnsWriterTest {
}
@Test
public void testLoadDomain_withInBailiwickNs_IPv4() {
void testLoadDomain_withInBailiwickNs_IPv4() {
persistResource(
fakeDomain(
"example.tld",
@@ -370,7 +370,7 @@ public class CloudDnsWriterTest {
}
@Test
public void testLoadDomain_withInBailiwickNs_IPv6() {
void testLoadDomain_withInBailiwickNs_IPv6() {
persistResource(
fakeDomain(
"example.tld",
@@ -385,7 +385,7 @@ public class CloudDnsWriterTest {
}
@Test
public void testLoadDomain_withNameserveThatEndsWithDomainName() {
void testLoadDomain_withNameserveThatEndsWithDomainName() {
persistResource(
fakeDomain(
"example.tld",
@@ -396,8 +396,9 @@ public class CloudDnsWriterTest {
verifyZone(fakeDomainRecords("example.tld", "ns.another-example.tld."));
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testLoadHost_externalHost() {
void testLoadHost_externalHost() {
writer.publishHost("ns1.example.com");
// external hosts should not be published in our zone
@@ -405,7 +406,7 @@ public class CloudDnsWriterTest {
}
@Test
public void testLoadHost_removeStaleNsRecords() {
void testLoadHost_removeStaleNsRecords() {
// Initialize the zone with both NS records
stubZone = fakeDomainRecords("example.tld", 2, 0, 0, 0);
@@ -426,8 +427,9 @@ public class CloudDnsWriterTest {
verifyZone(fakeDomainRecords("example.tld", 1, 0, 0, 0));
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void retryMutateZoneOnError() {
void retryMutateZoneOnError() {
CloudDnsWriter spyWriter = spy(writer);
// First call - throw. Second call - do nothing.
doThrow(ZoneStateException.class)
@@ -439,8 +441,9 @@ public class CloudDnsWriterTest {
verify(spyWriter, times(2)).mutateZone(ArgumentMatchers.any());
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testLoadDomain_withClientHold() {
void testLoadDomain_withClientHold() {
persistResource(
fakeDomain(
"example.tld",
@@ -454,8 +457,9 @@ public class CloudDnsWriterTest {
verifyZone(ImmutableSet.of());
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testLoadDomain_withServerHold() {
void testLoadDomain_withServerHold() {
persistResource(
fakeDomain(
"example.tld",
@@ -470,8 +474,9 @@ public class CloudDnsWriterTest {
verifyZone(ImmutableSet.of());
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testLoadDomain_withPendingDelete() {
void testLoadDomain_withPendingDelete() {
persistResource(
fakeDomain(
"example.tld",
@@ -486,7 +491,7 @@ public class CloudDnsWriterTest {
}
@Test
public void testDuplicateRecords() {
void testDuplicateRecords() {
// In publishing DNS records, we can end up publishing information on the same host twice
// (through a domain change and a host change), so this scenario needs to work.
persistResource(
@@ -504,7 +509,7 @@ public class CloudDnsWriterTest {
}
@Test
public void testInvalidZoneNames() {
void testInvalidZoneNames() {
createTld("triple.secret.tld");
persistResource(
fakeDomain(
@@ -518,8 +523,9 @@ public class CloudDnsWriterTest {
assertThat(zoneNameCaptor.getValue()).isEqualTo("triple-secret-tld");
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testEmptyCommit() {
void testEmptyCommit() {
writer.commit();
verify(dnsConnection, times(0)).changes();
}
@@ -33,10 +33,8 @@ import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.net.SocketFactory;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.xbill.DNS.ARecord;
import org.xbill.DNS.DClass;
import org.xbill.DNS.Flags;
@@ -49,8 +47,7 @@ import org.xbill.DNS.Type;
import org.xbill.DNS.Update;
/** Unit tests for {@link DnsMessageTransport}. */
@RunWith(JUnit4.class)
public class DnsMessageTransportTest {
class DnsMessageTransportTest {
private static final String UPDATE_HOST = "127.0.0.1";
@@ -60,8 +57,9 @@ public class DnsMessageTransportTest {
private Message simpleQuery;
private Message expectedResponse;
private DnsMessageTransport resolver;
@Before
public void before() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
simpleQuery =
Message.newQuery(Record.newRecord(Name.fromString("example.com."), Type.A, DClass.IN));
expectedResponse = responseMessageWithCode(simpleQuery, Rcode.NOERROR);
@@ -71,7 +69,7 @@ public class DnsMessageTransportTest {
}
@Test
public void testSentMessageHasCorrectLengthAndContent() throws Exception {
void testSentMessageHasCorrectLengthAndContent() throws Exception {
ByteArrayInputStream inputStream =
new ByteArrayInputStream(messageToBytesWithLength(expectedResponse));
when(mockSocket.getInputStream()).thenReturn(inputStream);
@@ -89,7 +87,7 @@ public class DnsMessageTransportTest {
}
@Test
public void testReceivedMessageWithLengthHasCorrectContent() throws Exception {
void testReceivedMessageWithLengthHasCorrectContent() throws Exception {
ByteArrayInputStream inputStream =
new ByteArrayInputStream(messageToBytesWithLength(expectedResponse));
when(mockSocket.getInputStream()).thenReturn(inputStream);
@@ -102,7 +100,7 @@ public class DnsMessageTransportTest {
}
@Test
public void testEofReceivingResponse() throws Exception {
void testEofReceivingResponse() throws Exception {
byte[] messageBytes = messageToBytesWithLength(expectedResponse);
ByteArrayInputStream inputStream =
new ByteArrayInputStream(Arrays.copyOf(messageBytes, messageBytes.length - 1));
@@ -112,7 +110,7 @@ public class DnsMessageTransportTest {
}
@Test
public void testTimeoutReceivingResponse() throws Exception {
void testTimeoutReceivingResponse() throws Exception {
InputStream mockInputStream = mock(InputStream.class);
when(mockInputStream.read()).thenThrow(new SocketTimeoutException("testing"));
when(mockSocket.getInputStream()).thenReturn(mockInputStream);
@@ -126,7 +124,7 @@ public class DnsMessageTransportTest {
}
@Test
public void testSentMessageTooLongThrowsException() throws Exception {
void testSentMessageTooLongThrowsException() throws Exception {
Update oversize = new Update(Name.fromString("tld", Name.root));
for (int i = 0; i < 2000; i++) {
oversize.add(
@@ -143,7 +141,7 @@ public class DnsMessageTransportTest {
}
@Test
public void testResponseIdMismatchThrowsExeption() throws Exception {
void testResponseIdMismatchThrowsExeption() throws Exception {
expectedResponse.getHeader().setID(1 + simpleQuery.getHeader().getID());
when(mockSocket.getInputStream())
.thenReturn(new ByteArrayInputStream(messageToBytesWithLength(expectedResponse)));
@@ -159,7 +157,7 @@ public class DnsMessageTransportTest {
}
@Test
public void testResponseOpcodeMismatchThrowsException() throws Exception {
void testResponseOpcodeMismatchThrowsException() throws Exception {
simpleQuery.getHeader().setOpcode(Opcode.QUERY);
expectedResponse.getHeader().setOpcode(Opcode.STATUS);
when(mockSocket.getInputStream())
@@ -29,7 +29,7 @@ import static google.registry.testing.DatastoreHelper.persistResource;
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import com.google.common.base.VerifyException;
@@ -49,16 +49,16 @@ import java.util.Collections;
import java.util.Iterator;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.xbill.DNS.Flags;
import org.xbill.DNS.Message;
import org.xbill.DNS.Opcode;
@@ -70,15 +70,14 @@ import org.xbill.DNS.Type;
import org.xbill.DNS.Update;
/** Unit tests for {@link DnsUpdateWriter}. */
@RunWith(JUnit4.class)
@ExtendWith(MockitoExtension.class)
public class DnsUpdateWriterTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@Rule public final InjectRule inject = new InjectRule();
@RegisterExtension public final InjectRule inject = new InjectRule();
@Mock private DnsMessageTransport mockResolver;
@Captor private ArgumentCaptor<Update> updateCaptor;
@@ -87,8 +86,8 @@ public class DnsUpdateWriterTest {
private DnsUpdateWriter writer;
@Before
public void setUp() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
inject.setStaticField(Ofy.class, "clock", clock);
createTld("tld");
@@ -99,7 +98,7 @@ public class DnsUpdateWriterTest {
}
@Test
public void testPublishDomainCreate_publishesNameServers() throws Exception {
void testPublishDomainCreate_publishesNameServers() throws Exception {
HostResource host1 = persistActiveHost("ns1.example.tld");
HostResource host2 = persistActiveHost("ns2.example.tld");
DomainBase domain =
@@ -120,8 +119,9 @@ public class DnsUpdateWriterTest {
assertThatTotalUpdateSetsIs(update, 2); // The delete and NS sets
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testPublishAtomic_noCommit() {
void testPublishAtomic_noCommit() {
HostResource host1 = persistActiveHost("ns.example1.tld");
DomainBase domain1 =
persistActiveDomain("example1.tld")
@@ -141,11 +141,11 @@ public class DnsUpdateWriterTest {
writer.publishDomain("example1.tld");
writer.publishDomain("example2.tld");
verifyZeroInteractions(mockResolver);
verifyNoInteractions(mockResolver);
}
@Test
public void testPublishAtomic_oneUpdate() throws Exception {
void testPublishAtomic_oneUpdate() throws Exception {
HostResource host1 = persistActiveHost("ns.example1.tld");
DomainBase domain1 =
persistActiveDomain("example1.tld")
@@ -177,7 +177,7 @@ public class DnsUpdateWriterTest {
}
@Test
public void testPublishDomainCreate_publishesDelegationSigner() throws Exception {
void testPublishDomainCreate_publishesDelegationSigner() throws Exception {
DomainBase domain =
persistActiveDomain("example.tld")
.asBuilder()
@@ -201,7 +201,7 @@ public class DnsUpdateWriterTest {
}
@Test
public void testPublishDomainWhenNotActive_removesDnsRecords() throws Exception {
void testPublishDomainWhenNotActive_removesDnsRecords() throws Exception {
DomainBase domain =
persistActiveDomain("example.tld")
.asBuilder()
@@ -221,7 +221,7 @@ public class DnsUpdateWriterTest {
}
@Test
public void testPublishDomainDelete_removesDnsRecords() throws Exception {
void testPublishDomainDelete_removesDnsRecords() throws Exception {
persistDeletedDomain("example.tld", clock.nowUtc().minusDays(1));
writer.publishDomain("example.tld");
@@ -235,7 +235,7 @@ public class DnsUpdateWriterTest {
}
@Test
public void testPublishHostCreate_publishesAddressRecords() throws Exception {
void testPublishHostCreate_publishesAddressRecords() throws Exception {
HostResource host =
persistResource(
newHostResource("ns1.example.tld")
@@ -268,7 +268,7 @@ public class DnsUpdateWriterTest {
}
@Test
public void testPublishHostDelete_removesDnsRecords() throws Exception {
void testPublishHostDelete_removesDnsRecords() throws Exception {
persistDeletedHost("ns1.example.tld", clock.nowUtc().minusDays(1));
persistActiveDomain("example.tld");
@@ -284,7 +284,7 @@ public class DnsUpdateWriterTest {
}
@Test
public void testPublishHostDelete_removesGlueRecords() throws Exception {
void testPublishHostDelete_removesGlueRecords() throws Exception {
persistDeletedHost("ns1.example.tld", clock.nowUtc().minusDays(1));
persistResource(
persistActiveDomain("example.tld")
@@ -305,7 +305,7 @@ public class DnsUpdateWriterTest {
}
@Test
public void testPublishDomainExternalAndInBailiwickNameServer() throws Exception {
void testPublishDomainExternalAndInBailiwickNameServer() throws Exception {
HostResource externalNameserver = persistResource(newHostResource("ns1.example.com"));
HostResource inBailiwickNameserver =
persistResource(
@@ -342,7 +342,7 @@ public class DnsUpdateWriterTest {
}
@Test
public void testPublishDomainDeleteOrphanGlues() throws Exception {
void testPublishDomainDeleteOrphanGlues() throws Exception {
HostResource inBailiwickNameserver =
persistResource(
newHostResource("ns1.example.tld")
@@ -377,9 +377,10 @@ public class DnsUpdateWriterTest {
assertThatTotalUpdateSetsIs(update, 6);
}
@Test
@MockitoSettings(strictness = Strictness.LENIENT)
@SuppressWarnings("AssertThrowsMultipleStatements")
public void testPublishDomainFails_whenDnsUpdateReturnsError() throws Exception {
@Test
void testPublishDomainFails_whenDnsUpdateReturnsError() throws Exception {
DomainBase domain =
persistActiveDomain("example.tld")
.asBuilder()
@@ -397,9 +398,10 @@ public class DnsUpdateWriterTest {
assertThat(thrown).hasMessageThat().contains("SERVFAIL");
}
@Test
@MockitoSettings(strictness = Strictness.LENIENT)
@SuppressWarnings("AssertThrowsMultipleStatements")
public void testPublishHostFails_whenDnsUpdateReturnsError() throws Exception {
@Test
void testPublishHostFails_whenDnsUpdateReturnsError() throws Exception {
HostResource host =
persistActiveSubordinateHost("ns1.example.tld", persistActiveDomain("example.tld"))
.asBuilder()
@@ -27,21 +27,19 @@ import google.registry.export.datastore.Operation;
import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeResponse;
import google.registry.testing.TaskQueueHelper.TaskMatcher;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.junit.jupiter.MockitoExtension;
/** Unit tests for {@link BackupDatastoreAction}. */
@RunWith(JUnit4.class)
@ExtendWith(MockitoExtension.class)
public class BackupDatastoreActionTest {
@Rule public final AppEngineRule appEngine = AppEngineRule.builder().withTaskQueue().build();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withTaskQueue().build();
@Mock private DatastoreAdmin datastoreAdmin;
@Mock private Export exportRequest;
@@ -50,8 +48,8 @@ public class BackupDatastoreActionTest {
private final FakeResponse response = new FakeResponse();
private final BackupDatastoreAction action = new BackupDatastoreAction();
@Before
public void before() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
action.datastoreAdmin = datastoreAdmin;
action.response = response;
@@ -66,7 +64,7 @@ public class BackupDatastoreActionTest {
}
@Test
public void testBackup_enqueuesPollTask() {
void testBackup_enqueuesPollTask() {
action.run();
assertTasksEnqueued(
CheckBackupAction.QUEUE,
@@ -52,17 +52,14 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link BigqueryPollJobAction}. */
@RunWith(JUnit4.class)
public class BigqueryPollJobActionTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@@ -79,8 +76,8 @@ public class BigqueryPollJobActionTest {
private final CapturingLogHandler logHandler = new CapturingLogHandler();
private BigqueryPollJobAction action = new BigqueryPollJobAction();
@Before
public void before() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
action.bigquery = bigquery;
when(bigquery.jobs()).thenReturn(bigqueryJobs);
when(bigqueryJobs.get(PROJECT_ID, JOB_ID)).thenReturn(bigqueryJobsGet);
@@ -100,14 +97,14 @@ public class BigqueryPollJobActionTest {
}
@Test
public void testSuccess_enqueuePollTask() {
void testSuccess_enqueuePollTask() {
new BigqueryPollJobEnqueuer(TASK_QUEUE_UTILS).enqueuePollTask(
new JobReference().setProjectId(PROJECT_ID).setJobId(JOB_ID));
assertTasksEnqueued(BigqueryPollJobAction.QUEUE, newPollJobTaskMatcher("GET"));
}
@Test
public void testSuccess_enqueuePollTask_withChainedTask() throws Exception {
void testSuccess_enqueuePollTask_withChainedTask() throws Exception {
TaskOptions chainedTask = TaskOptions.Builder
.withUrl("/_dr/something")
.method(Method.POST)
@@ -126,7 +123,7 @@ public class BigqueryPollJobActionTest {
}
@Test
public void testSuccess_jobCompletedSuccessfully() throws Exception {
void testSuccess_jobCompletedSuccessfully() throws Exception {
when(bigqueryJobsGet.execute()).thenReturn(
new Job().setStatus(new JobStatus().setState("DONE")));
action.run();
@@ -135,7 +132,7 @@ public class BigqueryPollJobActionTest {
}
@Test
public void testSuccess_chainedPayloadAndJobSucceeded_enqueuesChainedTask() throws Exception {
void testSuccess_chainedPayloadAndJobSucceeded_enqueuesChainedTask() throws Exception {
when(bigqueryJobsGet.execute()).thenReturn(
new Job().setStatus(new JobStatus().setState("DONE")));
@@ -167,7 +164,7 @@ public class BigqueryPollJobActionTest {
}
@Test
public void testJobFailed() throws Exception {
void testJobFailed() throws Exception {
when(bigqueryJobsGet.execute()).thenReturn(new Job().setStatus(
new JobStatus()
.setState("DONE")
@@ -179,20 +176,20 @@ public class BigqueryPollJobActionTest {
}
@Test
public void testJobPending() throws Exception {
void testJobPending() throws Exception {
when(bigqueryJobsGet.execute()).thenReturn(
new Job().setStatus(new JobStatus().setState("PENDING")));
assertThrows(NotModifiedException.class, action::run);
}
@Test
public void testJobStatusUnreadable() throws Exception {
void testJobStatusUnreadable() throws Exception {
when(bigqueryJobsGet.execute()).thenThrow(IOException.class);
assertThrows(NotModifiedException.class, action::run);
}
@Test
public void testFailure_badChainedTaskPayload() throws Exception {
void testFailure_badChainedTaskPayload() throws Exception {
when(bigqueryJobsGet.execute()).thenReturn(
new Job().setStatus(new JobStatus().setState("DONE")));
action.payload = "payload".getBytes(UTF_8);
@@ -42,26 +42,26 @@ import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.testing.TestDataHelper;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
/** Unit tests for {@link CheckBackupAction}. */
@RunWith(JUnit4.class)
@ExtendWith(MockitoExtension.class)
public class CheckBackupActionTest {
static final DateTime START_TIME = DateTime.parse("2014-08-01T01:02:03Z");
static final DateTime COMPLETE_TIME = START_TIME.plus(Duration.standardMinutes(30));
private static final DateTime START_TIME = DateTime.parse("2014-08-01T01:02:03Z");
private static final DateTime COMPLETE_TIME = START_TIME.plus(Duration.standardMinutes(30));
static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
@Rule public final AppEngineRule appEngine = AppEngineRule.builder().withTaskQueue().build();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withTaskQueue().build();
@Mock private DatastoreAdmin datastoreAdmin;
@Mock private Get getNotFoundBackupProgressRequest;
@@ -72,8 +72,8 @@ public class CheckBackupActionTest {
private final FakeClock clock = new FakeClock(COMPLETE_TIME.plusMillis(1000));
private final CheckBackupAction action = new CheckBackupAction();
@Before
public void before() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
action.requestMethod = Method.POST;
action.datastoreAdmin = datastoreAdmin;
action.clock = clock;
@@ -121,8 +121,9 @@ public class CheckBackupActionTest {
.param("kinds", kinds));
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testSuccess_enqueuePollTask() {
void testSuccess_enqueuePollTask() {
CheckBackupAction.enqueuePollTask("some_backup_name", ImmutableSet.of("one", "two", "three"));
assertTasksEnqueued(
CheckBackupAction.QUEUE,
@@ -134,7 +135,7 @@ public class CheckBackupActionTest {
}
@Test
public void testPost_forPendingBackup_returnsNotModified() throws Exception {
void testPost_forPendingBackup_returnsNotModified() throws Exception {
setPendingBackup();
NotModifiedException thrown = assertThrows(NotModifiedException.class, action::run);
@@ -144,7 +145,7 @@ public class CheckBackupActionTest {
}
@Test
public void testPost_forStalePendingBackupBackup_returnsNoContent() throws Exception {
void testPost_forStalePendingBackupBackup_returnsNoContent() throws Exception {
setPendingBackup();
clock.setTo(
START_TIME
@@ -161,7 +162,7 @@ public class CheckBackupActionTest {
}
@Test
public void testPost_forCompleteBackup_enqueuesLoadTask() throws Exception {
void testPost_forCompleteBackup_enqueuesLoadTask() throws Exception {
setCompleteBackup();
action.run();
assertLoadTaskEnqueued(
@@ -171,7 +172,7 @@ public class CheckBackupActionTest {
}
@Test
public void testPost_forCompleteBackup_withExtraKindsToLoad_enqueuesLoadTask() throws Exception {
void testPost_forCompleteBackup_withExtraKindsToLoad_enqueuesLoadTask() throws Exception {
setCompleteBackup();
action.kindsToLoadParam = "one,foo";
@@ -183,7 +184,7 @@ public class CheckBackupActionTest {
}
@Test
public void testPost_forCompleteBackup_withEmptyKindsToLoad_skipsLoadTask() throws Exception {
void testPost_forCompleteBackup_withEmptyKindsToLoad_skipsLoadTask() throws Exception {
setCompleteBackup();
action.kindsToLoadParam = "";
@@ -191,8 +192,9 @@ public class CheckBackupActionTest {
assertNoTasksEnqueued("export-snapshot");
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testPost_forBadBackup_returnsBadRequest() throws Exception {
void testPost_forBadBackup_returnsBadRequest() throws Exception {
setBackupNotFound();
BadRequestException thrown = assertThrows(BadRequestException.class, action::run);
@@ -200,7 +202,7 @@ public class CheckBackupActionTest {
}
@Test
public void testGet_returnsInformation() throws Exception {
void testGet_returnsInformation() throws Exception {
setCompleteBackup();
action.requestMethod = Method.GET;
@@ -212,8 +214,9 @@ public class CheckBackupActionTest {
.trim());
}
@MockitoSettings(strictness = Strictness.LENIENT)
@Test
public void testGet_forBadBackup_returnsError() throws Exception {
void testGet_forBadBackup_returnsError() throws Exception {
setBackupNotFound();
action.requestMethod = Method.GET;
@@ -29,13 +29,10 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Streams;
import com.google.re2j.Pattern;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link ExportConstants}. */
@RunWith(JUnit4.class)
public class ExportConstantsTest {
class ExportConstantsTest {
private static final String GOLDEN_BACKUP_KINDS_FILENAME = "backup_kinds.txt";
@@ -53,17 +50,17 @@ public class ExportConstantsTest {
"");
@Test
public void testBackupKinds_matchGoldenBackupKindsFile() {
void testBackupKinds_matchGoldenBackupKindsFile() {
checkKindsMatchGoldenFile("backed-up", GOLDEN_BACKUP_KINDS_FILENAME, getBackupKinds());
}
@Test
public void testReportingKinds_matchGoldenReportingKindsFile() {
void testReportingKinds_matchGoldenReportingKindsFile() {
checkKindsMatchGoldenFile("reporting", GOLDEN_REPORTING_KINDS_FILENAME, getReportingKinds());
}
@Test
public void testReportingKinds_areSubsetOfBackupKinds() {
void testReportingKinds_areSubsetOfBackupKinds() {
assertThat(getBackupKinds()).containsAtLeastElementsIn(getReportingKinds());
}
@@ -42,23 +42,20 @@ import google.registry.testing.FakeResponse;
import google.registry.testing.mapreduce.MapreduceTestCase;
import java.io.FileNotFoundException;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
/** Unit tests for {@link ExportDomainListsAction}. */
@RunWith(JUnit4.class)
public class ExportDomainListsActionTest extends MapreduceTestCase<ExportDomainListsAction> {
class ExportDomainListsActionTest extends MapreduceTestCase<ExportDomainListsAction> {
private GcsService gcsService;
private DriveConnection driveConnection = mock(DriveConnection.class);
private ArgumentCaptor<byte[]> bytesExportedToDrive = ArgumentCaptor.forClass(byte[].class);
private final FakeResponse response = new FakeResponse();
@Before
public void init() {
@BeforeEach
void beforeEach() {
createTld("tld");
createTld("testtld");
persistResource(Registry.get("tld").asBuilder().setDriveFolderId("brouhaha").build());
@@ -90,7 +87,7 @@ public class ExportDomainListsActionTest extends MapreduceTestCase<ExportDomainL
}
@Test
public void test_writesLinkToMapreduceConsoleToResponse() throws Exception {
void test_writesLinkToMapreduceConsoleToResponse() throws Exception {
runMapreduce();
assertThat(response.getPayload())
.startsWith(
@@ -99,7 +96,7 @@ public class ExportDomainListsActionTest extends MapreduceTestCase<ExportDomainL
}
@Test
public void test_outputsOnlyActiveDomains() throws Exception {
void test_outputsOnlyActiveDomains() throws Exception {
persistActiveDomain("onetwo.tld");
persistActiveDomain("rudnitzky.tld");
persistDeletedDomain("mortuary.tld", DateTime.parse("2001-03-14T10:11:12Z"));
@@ -113,7 +110,7 @@ public class ExportDomainListsActionTest extends MapreduceTestCase<ExportDomainL
}
@Test
public void test_outputsOnlyDomainsOnRealTlds() throws Exception {
void test_outputsOnlyDomainsOnRealTlds() throws Exception {
persistActiveDomain("onetwo.tld");
persistActiveDomain("rudnitzky.tld");
persistActiveDomain("wontgo.testtld");
@@ -134,7 +131,7 @@ public class ExportDomainListsActionTest extends MapreduceTestCase<ExportDomainL
}
@Test
public void test_outputsDomainsFromDifferentTldsToMultipleFiles() throws Exception {
void test_outputsDomainsFromDifferentTldsToMultipleFiles() throws Exception {
createTld("tldtwo");
persistResource(Registry.get("tldtwo").asBuilder().setDriveFolderId("hooray").build());
@@ -31,8 +31,8 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableList;
@@ -43,14 +43,12 @@ import google.registry.request.Response;
import google.registry.storage.drive.DriveConnection;
import google.registry.testing.AppEngineRule;
import java.io.IOException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.ArgumentMatchers;
@RunWith(JUnit4.class)
/** Unit tests for {@link ExportPremiumTermsAction}. */
public class ExportPremiumTermsActionTest {
private static final String DISCLAIMER_WITH_NEWLINE = "# Premium Terms Export Disclaimer\n";
@@ -59,7 +57,7 @@ public class ExportPremiumTermsActionTest {
private static final String EXPECTED_FILE_CONTENT =
DISCLAIMER_WITH_NEWLINE + "0,USD 549.00\n" + "2048,USD 549.00\n";
@Rule
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
private final DriveConnection driveConnection = mock(DriveConnection.class);
@@ -74,8 +72,8 @@ public class ExportPremiumTermsActionTest {
action.run();
}
@Before
public void setup() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
createTld("tld");
PremiumList pl = new PremiumList.Builder().setName("pl-name").build();
savePremiumListAndEntries(pl, PREMIUM_NAMES);
@@ -90,7 +88,7 @@ public class ExportPremiumTermsActionTest {
}
@Test
public void test_exportPremiumTerms_success() throws IOException {
void test_exportPremiumTerms_success() throws IOException {
runAction("tld");
verify(driveConnection)
@@ -108,7 +106,7 @@ public class ExportPremiumTermsActionTest {
}
@Test
public void test_exportPremiumTerms_success_emptyPremiumList() throws IOException {
void test_exportPremiumTerms_success_emptyPremiumList() throws IOException {
PremiumList pl = new PremiumList.Builder().setName("pl-name").build();
savePremiumListAndEntries(pl, ImmutableList.of());
runAction("tld");
@@ -128,11 +126,11 @@ public class ExportPremiumTermsActionTest {
}
@Test
public void test_exportPremiumTerms_doNothing_listNotConfigured() {
void test_exportPremiumTerms_doNothing_listNotConfigured() {
persistResource(Registry.get("tld").asBuilder().setPremiumList(null).build());
runAction("tld");
verifyZeroInteractions(driveConnection);
verifyNoInteractions(driveConnection);
verify(response).setStatus(SC_OK);
verify(response).setPayload("No premium lists configured");
verify(response).setContentType(PLAIN_TEXT_UTF_8);
@@ -140,11 +138,11 @@ public class ExportPremiumTermsActionTest {
}
@Test
public void testExportPremiumTerms_doNothing_driveIdNotConfiguredInTld() {
void testExportPremiumTerms_doNothing_driveIdNotConfiguredInTld() {
persistResource(Registry.get("tld").asBuilder().setDriveFolderId(null).build());
runAction("tld");
verifyZeroInteractions(driveConnection);
verifyNoInteractions(driveConnection);
verify(response).setStatus(SC_OK);
verify(response)
.setPayload("Skipping export because no Drive folder is associated with this TLD");
@@ -153,11 +151,11 @@ public class ExportPremiumTermsActionTest {
}
@Test
public void test_exportPremiumTerms_failure_noSuchTld() {
void test_exportPremiumTerms_failure_noSuchTld() {
deleteTld("tld");
assertThrows(RuntimeException.class, () -> runAction("tld"));
verifyZeroInteractions(driveConnection);
verifyNoInteractions(driveConnection);
verify(response).setStatus(SC_INTERNAL_SERVER_ERROR);
verify(response).setPayload(anyString());
verify(response).setContentType(PLAIN_TEXT_UTF_8);
@@ -165,11 +163,11 @@ public class ExportPremiumTermsActionTest {
}
@Test
public void test_exportPremiumTerms_failure_noPremiumList() {
void test_exportPremiumTerms_failure_noPremiumList() {
deletePremiumList(new PremiumList.Builder().setName("pl-name").build());
assertThrows(RuntimeException.class, () -> runAction("tld"));
verifyZeroInteractions(driveConnection);
verifyNoInteractions(driveConnection);
verify(response).setStatus(SC_INTERNAL_SERVER_ERROR);
verify(response).setPayload("Could not load premium list for " + "tld");
verify(response).setContentType(PLAIN_TEXT_UTF_8);
@@ -177,7 +175,7 @@ public class ExportPremiumTermsActionTest {
}
@Test
public void testExportPremiumTerms_failure_driveIdThrowsException() throws IOException {
void testExportPremiumTerms_failure_driveIdThrowsException() throws IOException {
persistResource(Registry.get("tld").asBuilder().setDriveFolderId("bad_folder_id").build());
assertThrows(RuntimeException.class, () -> runAction("tld"));
@@ -38,17 +38,14 @@ import google.registry.request.Response;
import google.registry.storage.drive.DriveConnection;
import google.registry.testing.AppEngineRule;
import java.io.IOException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link ExportReservedTermsAction}. */
@RunWith(JUnit4.class)
public class ExportReservedTermsActionTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
private final DriveConnection driveConnection = mock(DriveConnection.class);
@@ -63,8 +60,8 @@ public class ExportReservedTermsActionTest {
action.run();
}
@Before
public void init() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
ReservedList rl = persistReservedList(
"tld-reserved",
"lol,FULLY_BLOCKED",
@@ -81,7 +78,7 @@ public class ExportReservedTermsActionTest {
}
@Test
public void test_uploadFileToDrive_succeeds() throws Exception {
void test_uploadFileToDrive_succeeds() throws Exception {
runAction("tld");
byte[] expected = "# This is a disclaimer.\ncat\nlol\n".getBytes(UTF_8);
verify(driveConnection)
@@ -91,7 +88,7 @@ public class ExportReservedTermsActionTest {
}
@Test
public void test_uploadFileToDrive_doesNothingIfReservedListsNotConfigured() {
void test_uploadFileToDrive_doesNothingIfReservedListsNotConfigured() {
persistResource(
Registry.get("tld")
.asBuilder()
@@ -104,7 +101,7 @@ public class ExportReservedTermsActionTest {
}
@Test
public void test_uploadFileToDrive_doesNothingWhenDriveFolderIdIsNull() {
void test_uploadFileToDrive_doesNothingWhenDriveFolderIdIsNull() {
persistResource(Registry.get("tld").asBuilder().setDriveFolderId(null).build());
runAction("tld");
verify(response).setStatus(SC_OK);
@@ -113,7 +110,7 @@ public class ExportReservedTermsActionTest {
}
@Test
public void test_uploadFileToDrive_failsWhenDriveCannotBeReached() throws Exception {
void test_uploadFileToDrive_failsWhenDriveCannotBeReached() throws Exception {
when(driveConnection.createOrUpdateFile(
anyString(),
any(MediaType.class),
@@ -125,7 +122,7 @@ public class ExportReservedTermsActionTest {
}
@Test
public void test_uploadFileToDrive_failsWhenTldDoesntExist() {
void test_uploadFileToDrive_failsWhenTldDoesntExist() {
RuntimeException thrown = assertThrows(RuntimeException.class, () -> runAction("fakeTld"));
verify(response).setStatus(SC_INTERNAL_SERVER_ERROR);
assertThat(thrown)
@@ -22,20 +22,17 @@ import static google.registry.testing.DatastoreHelper.persistResource;
import google.registry.model.registry.Registry;
import google.registry.model.registry.label.ReservedList;
import google.registry.testing.AppEngineRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link ExportUtils}. */
@RunWith(JUnit4.class)
public class ExportUtilsTest {
class ExportUtilsTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Test
public void test_exportReservedTerms() {
void test_exportReservedTerms() {
ReservedList rl1 = persistReservedList(
"tld-reserved1",
"lol,FULLY_BLOCKED",
@@ -45,10 +45,8 @@ import google.registry.testing.FakeSleeper;
import google.registry.testing.InjectRule;
import google.registry.util.Retrier;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/**
* Unit tests for {@link SyncGroupMembersAction}.
@@ -56,14 +54,12 @@ import org.junit.runners.JUnit4;
* <p>Note that this relies on the registrars NewRegistrar and TheRegistrar created by default in
* {@link AppEngineRule}.
*/
@RunWith(JUnit4.class)
public class SyncGroupMembersActionTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Rule
public final InjectRule inject = new InjectRule();
@RegisterExtension public final InjectRule inject = new InjectRule();
private final DirectoryGroupsConnection connection = mock(DirectoryGroupsConnection.class);
private final Response response = mock(Response.class);
@@ -78,7 +74,7 @@ public class SyncGroupMembersActionTest {
}
@Test
public void test_getGroupEmailAddressForContactType_convertsToLowercase() {
void test_getGroupEmailAddressForContactType_convertsToLowercase() {
assertThat(getGroupEmailAddressForContactType(
"SomeRegistrar",
RegistrarContact.Type.ADMIN,
@@ -87,7 +83,7 @@ public class SyncGroupMembersActionTest {
}
@Test
public void test_getGroupEmailAddressForContactType_convertsNonAlphanumericChars() {
void test_getGroupEmailAddressForContactType_convertsNonAlphanumericChars() {
assertThat(getGroupEmailAddressForContactType(
"Weird.ಠ_ಠRegistrar",
MARKETING,
@@ -96,7 +92,7 @@ public class SyncGroupMembersActionTest {
}
@Test
public void test_doPost_noneModified() {
void test_doPost_noneModified() {
persistResource(
loadRegistrar("NewRegistrar").asBuilder().setContactsRequireSyncing(false).build());
persistResource(
@@ -109,7 +105,7 @@ public class SyncGroupMembersActionTest {
}
@Test
public void test_doPost_syncsNewContact() throws Exception {
void test_doPost_syncsNewContact() throws Exception {
runAction();
verify(connection).addMemberToGroup(
"newregistrar-primary-contacts@domain-registry.example",
@@ -121,7 +117,7 @@ public class SyncGroupMembersActionTest {
}
@Test
public void test_doPost_removesOldContact() throws Exception {
void test_doPost_removesOldContact() throws Exception {
when(connection.getMembersOfGroup("newregistrar-primary-contacts@domain-registry.example"))
.thenReturn(ImmutableSet.of("defunct@example.com", "janedoe@theregistrar.com"));
runAction();
@@ -132,7 +128,7 @@ public class SyncGroupMembersActionTest {
}
@Test
public void test_doPost_removesAllContactsFromGroup() throws Exception {
void test_doPost_removesAllContactsFromGroup() throws Exception {
when(connection.getMembersOfGroup("newregistrar-primary-contacts@domain-registry.example"))
.thenReturn(ImmutableSet.of("defunct@example.com", "janedoe@theregistrar.com"));
ofy().deleteWithoutBackup()
@@ -148,7 +144,7 @@ public class SyncGroupMembersActionTest {
}
@Test
public void test_doPost_addsAndRemovesContacts_acrossMultipleRegistrars() throws Exception {
void test_doPost_addsAndRemovesContacts_acrossMultipleRegistrars() throws Exception {
when(connection.getMembersOfGroup("newregistrar-primary-contacts@domain-registry.example"))
.thenReturn(ImmutableSet.of("defunct@example.com", "janedoe@theregistrar.com"));
when(connection.getMembersOfGroup("newregistrar-marketing-contacts@domain-registry.example"))
@@ -196,7 +192,7 @@ public class SyncGroupMembersActionTest {
}
@Test
public void test_doPost_gracefullyHandlesExceptionForSingleRegistrar() throws Exception {
void test_doPost_gracefullyHandlesExceptionForSingleRegistrar() throws Exception {
when(connection.getMembersOfGroup("newregistrar-primary-contacts@domain-registry.example"))
.thenReturn(ImmutableSet.of());
when(connection.getMembersOfGroup("theregistrar-primary-contacts@domain-registry.example"))
@@ -215,7 +211,7 @@ public class SyncGroupMembersActionTest {
}
@Test
public void test_doPost_retriesOnTransientException() throws Exception {
void test_doPost_retriesOnTransientException() throws Exception {
doThrow(IOException.class)
.doNothing()
.when(connection)
@@ -40,22 +40,18 @@ import google.registry.request.HttpException.InternalServerErrorException;
import google.registry.testing.AppEngineRule;
import google.registry.testing.TaskQueueHelper.TaskMatcher;
import java.io.IOException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
/** Unit tests for {@link UpdateSnapshotViewAction}. */
@RunWith(JUnit4.class)
public class UpdateSnapshotViewActionTest {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder()
.withTaskQueue()
.build();
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withTaskQueue().build();
private final CheckedBigquery checkedBigquery = mock(CheckedBigquery.class);
private final Bigquery bigquery = mock(Bigquery.class);
private final Bigquery.Datasets bigqueryDatasets = mock(Bigquery.Datasets.class);
@@ -66,8 +62,8 @@ public class UpdateSnapshotViewActionTest {
private UpdateSnapshotViewAction action;
@Before
public void before() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
when(checkedBigquery.ensureDataSetExists(anyString(), anyString())).thenReturn(bigquery);
when(bigquery.datasets()).thenReturn(bigqueryDatasets);
when(bigqueryDatasets.insert(anyString(), any(Dataset.class)))
@@ -86,7 +82,7 @@ public class UpdateSnapshotViewActionTest {
}
@Test
public void testSuccess_createViewUpdateTask() {
void testSuccess_createViewUpdateTask() {
getQueue(QUEUE)
.add(
createViewUpdateTask(
@@ -103,7 +99,7 @@ public class UpdateSnapshotViewActionTest {
}
@Test
public void testSuccess_doPost() throws Exception {
void testSuccess_doPost() throws Exception {
action.run();
InOrder factoryOrder = inOrder(checkedBigquery);
@@ -126,7 +122,7 @@ public class UpdateSnapshotViewActionTest {
}
@Test
public void testFailure_bigqueryConnectionThrowsError() throws Exception {
void testFailure_bigqueryConnectionThrowsError() throws Exception {
when(bigqueryTables.update(anyString(), anyString(), anyString(), any(Table.class)))
.thenThrow(new IOException("I'm sorry Dave, I can't let you do that"));
InternalServerErrorException thrown =
@@ -49,21 +49,17 @@ import google.registry.testing.AppEngineRule;
import google.registry.testing.TaskQueueHelper.TaskMatcher;
import java.io.IOException;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.ArgumentCaptor;
/** Unit tests for {@link UploadDatastoreBackupAction}. */
@RunWith(JUnit4.class)
public class UploadDatastoreBackupActionTest {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder()
.withTaskQueue()
.build();
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withTaskQueue().build();
private final CheckedBigquery checkedBigquery = mock(CheckedBigquery.class);
private final Bigquery bigquery = mock(Bigquery.class);
private final Bigquery.Jobs bigqueryJobs = mock(Bigquery.Jobs.class);
@@ -74,8 +70,8 @@ public class UploadDatastoreBackupActionTest {
private final BigqueryPollJobEnqueuer bigqueryPollEnqueuer = mock(BigqueryPollJobEnqueuer.class);
private UploadDatastoreBackupAction action;
@Before
public void before() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
when(checkedBigquery.ensureDataSetExists("Project-Id", BACKUP_DATASET)).thenReturn(bigquery);
when(bigquery.jobs()).thenReturn(bigqueryJobs);
when(bigqueryJobs.insert(eq("Project-Id"), any(Job.class))).thenReturn(bigqueryJobsInsert);
@@ -92,7 +88,7 @@ public class UploadDatastoreBackupActionTest {
}
@Test
public void testSuccess_enqueueLoadTask() {
void testSuccess_enqueueLoadTask() {
enqueueUploadBackupTask("id12345", "gs://bucket/path", ImmutableSet.of("one", "two", "three"));
assertTasksEnqueued(
QUEUE,
@@ -105,7 +101,7 @@ public class UploadDatastoreBackupActionTest {
}
@Test
public void testSuccess_doPost() throws Exception {
void testSuccess_doPost() throws Exception {
action.run();
// Verify that checkedBigquery was called in a way that would create the dataset if it didn't
@@ -187,7 +183,7 @@ public class UploadDatastoreBackupActionTest {
}
@Test
public void testFailure_doPost_bigqueryThrowsException() throws Exception {
void testFailure_doPost_bigqueryThrowsException() throws Exception {
when(bigqueryJobsInsert.execute()).thenThrow(new IOException("The Internet has gone missing"));
InternalServerErrorException thrown =
assertThrows(InternalServerErrorException.class, action::run);
@@ -197,7 +193,7 @@ public class UploadDatastoreBackupActionTest {
}
@Test
public void testgetBackupInfoFileForKind() {
void testgetBackupInfoFileForKind() {
assertThat(
getBackupInfoFileForKind(
"gs://BucketName/2018-11-11T00:00:00_12345", "AllocationToken"))
@@ -29,25 +29,20 @@ import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
/** Unit tests for {@link DatastoreAdmin}. */
@RunWith(JUnit4.class)
public class DatastoreAdminTest {
@ExtendWith(MockitoExtension.class)
class DatastoreAdminTest {
private static final String AUTH_HEADER_PREFIX = "Bearer ";
private static final String ACCESS_TOKEN = "MyAccessToken";
private static final ImmutableList<String> KINDS =
ImmutableList.of("Registry", "Registrar", "DomainBase");
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
private DatastoreAdmin datastoreAdmin;
private static HttpRequest simulateSendRequest(HttpRequest httpRequest) {
@@ -75,8 +70,8 @@ public class DatastoreAdminTest {
return Optional.of(outputStream.toString(StandardCharsets.UTF_8.name()));
}
@Before
public void setup() {
@BeforeEach
void beforeEach() {
Date oneHourLater = new Date(System.currentTimeMillis() + 3_600_000);
GoogleCredentials googleCredentials = GoogleCredentials
.create(new AccessToken(ACCESS_TOKEN, oneHourLater));
@@ -92,7 +87,7 @@ public class DatastoreAdminTest {
}
@Test
public void testExport() throws IOException {
void testExport() throws IOException {
DatastoreAdmin.Export export = datastoreAdmin.export("gs://mybucket/path", KINDS);
HttpRequest httpRequest = export.buildHttpRequest();
assertThat(httpRequest.getUrl().toString())
@@ -109,7 +104,7 @@ public class DatastoreAdminTest {
}
@Test
public void testGetOperation() throws IOException {
void testGetOperation() throws IOException {
DatastoreAdmin.Get get =
datastoreAdmin.get("projects/MyCloudProject/operations/ASAzNjMwOTEyNjUJ");
HttpRequest httpRequest = get.buildHttpRequest();
@@ -124,7 +119,7 @@ public class DatastoreAdminTest {
}
@Test
public void testListOperations_all() throws IOException {
void testListOperations_all() throws IOException {
DatastoreAdmin.ListOperations listOperations = datastoreAdmin.listAll();
HttpRequest httpRequest = listOperations.buildHttpRequest();
assertThat(httpRequest.getUrl().toString())
@@ -137,7 +132,7 @@ public class DatastoreAdminTest {
}
@Test
public void testListOperations_filterByStartTime() throws IOException {
void testListOperations_filterByStartTime() throws IOException {
DatastoreAdmin.ListOperations listOperations =
datastoreAdmin.list("metadata.common.startTime>\"2018-10-31T00:00:00.0Z\"");
HttpRequest httpRequest = listOperations.buildHttpRequest();
@@ -153,7 +148,7 @@ public class DatastoreAdminTest {
}
@Test
public void testListOperations_filterByState() throws IOException {
void testListOperations_filterByState() throws IOException {
// TODO(weiminyu): consider adding a method to DatastoreAdmin to support query by state.
DatastoreAdmin.ListOperations listOperations =
datastoreAdmin.list("metadata.common.state=PROCESSING");
@@ -22,23 +22,20 @@ import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.common.collect.ImmutableList;
import google.registry.testing.TestDataHelper;
import java.io.IOException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for the instantiation, marshalling and unmarshalling of {@link EntityFilter}. */
@RunWith(JUnit4.class)
public class EntityFilterTest {
class EntityFilterTest {
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
@Test
public void testEntityFilter_create_nullKinds() {
void testEntityFilter_create_nullKinds() {
assertThrows(NullPointerException.class, () -> new EntityFilter(null));
}
@Test
public void testEntityFilter_marshall() throws IOException {
void testEntityFilter_marshall() throws IOException {
EntityFilter entityFilter =
new EntityFilter(ImmutableList.of("Registry", "Registrar", "DomainBase"));
assertThat(JSON_FACTORY.toString(entityFilter))
@@ -46,7 +43,7 @@ public class EntityFilterTest {
}
@Test
public void testEntityFilter_unmarshall() throws IOException {
void testEntityFilter_unmarshall() throws IOException {
EntityFilter entityFilter = loadJson("entity_filter.json", EntityFilter.class);
assertThat(entityFilter.getKinds())
.containsExactly("Registry", "Registrar", "DomainBase")
@@ -54,13 +51,13 @@ public class EntityFilterTest {
}
@Test
public void testEntityFilter_unmarshall_noKinds() throws IOException {
void testEntityFilter_unmarshall_noKinds() throws IOException {
EntityFilter entityFilter = JSON_FACTORY.fromString("{}", EntityFilter.class);
assertThat(entityFilter.getKinds()).isEmpty();
}
@Test
public void testEntityFilter_unmarshall_emptyKinds() throws IOException {
void testEntityFilter_unmarshall_emptyKinds() throws IOException {
EntityFilter entityFilter = JSON_FACTORY.fromString("{ \"kinds\" : [] }", EntityFilter.class);
assertThat(entityFilter.getKinds()).isEmpty();
}
@@ -27,17 +27,15 @@ import google.registry.testing.TestDataHelper;
import java.io.IOException;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for unmarshalling {@link Operation} and its member types. */
@RunWith(JUnit4.class)
public class OperationTest {
class OperationTest {
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
@Test
public void testCommonMetadata_unmarshall() throws IOException {
void testCommonMetadata_unmarshall() throws IOException {
CommonMetadata commonMetadata = loadJson("common_metadata.json", CommonMetadata.class);
assertThat(commonMetadata.getState()).isEqualTo("SUCCESSFUL");
assertThat(commonMetadata.getOperationType()).isEqualTo("EXPORT_ENTITIES");
@@ -47,14 +45,14 @@ public class OperationTest {
}
@Test
public void testProgress_unmarshall() throws IOException {
void testProgress_unmarshall() throws IOException {
Progress progress = loadJson("progress.json", Progress.class);
assertThat(progress.getWorkCompleted()).isEqualTo(51797);
assertThat(progress.getWorkEstimated()).isEqualTo(54513);
}
@Test
public void testMetadata_unmarshall() throws IOException {
void testMetadata_unmarshall() throws IOException {
Metadata metadata = loadJson("metadata.json", Metadata.class);
assertThat(metadata.getCommonMetadata().getOperationType()).isEqualTo("EXPORT_ENTITIES");
assertThat(metadata.getCommonMetadata().getState()).isEqualTo("SUCCESSFUL");
@@ -67,7 +65,7 @@ public class OperationTest {
}
@Test
public void testOperation_unmarshall() throws IOException {
void testOperation_unmarshall() throws IOException {
Operation operation = loadJson("operation.json", Operation.class);
assertThat(operation.getName())
.startsWith("projects/domain-registry-alpha/operations/ASAzNjMwOTEyNjUJ");
@@ -86,7 +84,7 @@ public class OperationTest {
}
@Test
public void testOperationList_unmarshall() throws IOException {
void testOperationList_unmarshall() throws IOException {
Operation.OperationList operationList =
loadJson("operation_list.json", Operation.OperationList.class);
assertThat(operationList.toList()).hasSize(2);
@@ -18,7 +18,7 @@ import static com.google.common.collect.Lists.newArrayList;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import com.google.api.services.sheets.v4.Sheets;
@@ -33,14 +33,12 @@ import com.google.common.collect.ImmutableMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link SheetSynchronizer}. */
@RunWith(JUnit4.class)
public class SheetSynchronizerTest {
class SheetSynchronizerTest {
private final SheetSynchronizer sheetSynchronizer = new SheetSynchronizer();
private final Sheets sheetsService = mock(Sheets.class);
private final Sheets.Spreadsheets spreadsheets = mock(Sheets.Spreadsheets.class);
@@ -56,8 +54,8 @@ public class SheetSynchronizerTest {
private List<List<Object>> existingSheet;
private ImmutableList<ImmutableMap<String, String>> data;
@Before
public void before() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
sheetSynchronizer.sheetsService = sheetsService;
when(sheetsService.spreadsheets()).thenReturn(spreadsheets);
when(spreadsheets.values()).thenReturn(values);
@@ -88,23 +86,23 @@ public class SheetSynchronizerTest {
}
@Test
public void testSynchronize_dataAndSheetEmpty_doNothing() throws Exception {
void testSynchronize_dataAndSheetEmpty_doNothing() throws Exception {
existingSheet.add(createRow("a", "b"));
sheetSynchronizer.synchronize("aSheetId", data);
verifyZeroInteractions(appendReq);
verifyZeroInteractions(clearReq);
verifyZeroInteractions(updateReq);
verifyNoInteractions(appendReq);
verifyNoInteractions(clearReq);
verifyNoInteractions(updateReq);
}
@Test
public void testSynchronize_differentValues_updatesValues() throws Exception {
void testSynchronize_differentValues_updatesValues() throws Exception {
existingSheet.add(createRow("a", "b"));
existingSheet.add(createRow("diffVal1l", "diffVal2"));
data = ImmutableList.of(ImmutableMap.of("a", "val1", "b", "val2"));
sheetSynchronizer.synchronize("aSheetId", data);
verifyZeroInteractions(appendReq);
verifyZeroInteractions(clearReq);
verifyNoInteractions(appendReq);
verifyNoInteractions(clearReq);
BatchUpdateValuesRequest expectedRequest = new BatchUpdateValuesRequest();
List<List<Object>> expectedVals = newArrayList();
@@ -116,14 +114,14 @@ public class SheetSynchronizerTest {
}
@Test
public void testSynchronize_unknownFields_doesntUpdate() throws Exception {
void testSynchronize_unknownFields_doesntUpdate() throws Exception {
existingSheet.add(createRow("a", "c", "b"));
existingSheet.add(createRow("diffVal1", "sameVal", "diffVal2"));
data = ImmutableList.of(ImmutableMap.of("a", "val1", "b", "val2", "d", "val3"));
sheetSynchronizer.synchronize("aSheetId", data);
verifyZeroInteractions(appendReq);
verifyZeroInteractions(clearReq);
verifyNoInteractions(appendReq);
verifyNoInteractions(clearReq);
BatchUpdateValuesRequest expectedRequest = new BatchUpdateValuesRequest();
List<List<Object>> expectedVals = newArrayList();
@@ -135,14 +133,14 @@ public class SheetSynchronizerTest {
}
@Test
public void testSynchronize_notFullRow_getsPadded() throws Exception {
void testSynchronize_notFullRow_getsPadded() throws Exception {
existingSheet.add(createRow("a", "c", "b"));
existingSheet.add(createRow("diffVal1", "diffVal2"));
data = ImmutableList.of(ImmutableMap.of("a", "val1", "b", "paddedVal", "d", "val3"));
sheetSynchronizer.synchronize("aSheetId", data);
verifyZeroInteractions(appendReq);
verifyZeroInteractions(clearReq);
verifyNoInteractions(appendReq);
verifyNoInteractions(clearReq);
BatchUpdateValuesRequest expectedRequest = new BatchUpdateValuesRequest();
List<List<Object>> expectedVals = newArrayList();
@@ -154,22 +152,21 @@ public class SheetSynchronizerTest {
}
@Test
public void testSynchronize_moreData_appendsValues() throws Exception {
void testSynchronize_moreData_appendsValues() throws Exception {
existingSheet.add(createRow("a", "b"));
existingSheet.add(createRow("diffVal1", "diffVal2"));
data = ImmutableList.of(
ImmutableMap.of("a", "val1", "b", "val2"),
ImmutableMap.of("a", "val3", "b", "val4"));
data =
ImmutableList.of(
ImmutableMap.of("a", "val1", "b", "val2"), ImmutableMap.of("a", "val3", "b", "val4"));
sheetSynchronizer.synchronize("aSheetId", data);
verifyZeroInteractions(clearReq);
verifyNoInteractions(clearReq);
BatchUpdateValuesRequest expectedRequest = new BatchUpdateValuesRequest();
List<List<Object>> updatedVals = newArrayList();
updatedVals.add(createRow("val1", "val2"));
expectedRequest.setData(
newArrayList(
new ValueRange().setRange("Registrars!A2").setValues(updatedVals)));
newArrayList(new ValueRange().setRange("Registrars!A2").setValues(updatedVals)));
expectedRequest.setValueInputOption("RAW");
verify(values).batchUpdate("aSheetId", expectedRequest);
@@ -180,7 +177,7 @@ public class SheetSynchronizerTest {
}
@Test
public void testSynchronize_lessData_clearsValues() throws Exception {
void testSynchronize_lessData_clearsValues() throws Exception {
existingSheet.add(createRow("a", "b"));
existingSheet.add(createRow("val1", "val2"));
existingSheet.add(createRow("diffVal3", "diffVal4"));
@@ -188,6 +185,6 @@ public class SheetSynchronizerTest {
sheetSynchronizer.synchronize("aSheetId", data);
verify(values).clear("aSheetId", "Registrars!3:4", new ClearValuesRequest());
verifyZeroInteractions(updateReq);
verifyNoInteractions(updateReq);
}
}
@@ -19,8 +19,8 @@ import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import google.registry.testing.AppEngineRule;
@@ -29,17 +29,14 @@ import google.registry.testing.FakeResponse;
import java.util.Optional;
import javax.annotation.Nullable;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link SyncRegistrarsSheetAction}. */
@RunWith(JUnit4.class)
public class SyncRegistrarsSheetActionTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@@ -54,8 +51,8 @@ public class SyncRegistrarsSheetActionTest {
action.run();
}
@Before
public void setUp() {
@BeforeEach
void beforeEach() {
action = new SyncRegistrarsSheetAction();
action.response = response;
action.syncRegistrarsSheet = syncRegistrarsSheet;
@@ -64,14 +61,14 @@ public class SyncRegistrarsSheetActionTest {
}
@Test
public void testPost_withoutParamsOrSystemProperty_dropsTask() {
void testPost_withoutParamsOrSystemProperty_dropsTask() {
runAction(null, null);
assertThat(response.getPayload()).startsWith("MISSINGNO");
verifyZeroInteractions(syncRegistrarsSheet);
verifyNoInteractions(syncRegistrarsSheet);
}
@Test
public void testPost_withoutParams_runsSyncWithDefaultIdAndChecksIfModified() throws Exception {
void testPost_withoutParams_runsSyncWithDefaultIdAndChecksIfModified() throws Exception {
when(syncRegistrarsSheet.wereRegistrarsModified()).thenReturn(true);
runAction("jazz", null);
assertThat(response.getStatus()).isEqualTo(200);
@@ -83,7 +80,7 @@ public class SyncRegistrarsSheetActionTest {
}
@Test
public void testPost_noModificationsToRegistrarEntities_doesNothing() {
void testPost_noModificationsToRegistrarEntities_doesNothing() {
when(syncRegistrarsSheet.wereRegistrarsModified()).thenReturn(false);
runAction("NewRegistrar", null);
assertThat(response.getPayload()).startsWith("NOTMODIFIED");
@@ -92,7 +89,7 @@ public class SyncRegistrarsSheetActionTest {
}
@Test
public void testPost_overrideId_runsSyncWithCustomIdAndDoesNotCheckModified() throws Exception {
void testPost_overrideId_runsSyncWithCustomIdAndDoesNotCheckModified() throws Exception {
runAction(null, "foobar");
assertThat(response.getPayload()).startsWith("OK");
verify(syncRegistrarsSheet).run(eq("foobar"));
@@ -100,10 +97,10 @@ public class SyncRegistrarsSheetActionTest {
}
@Test
public void testPost_failToAquireLock_servletDoesNothingAndReturns() {
void testPost_failToAquireLock_servletDoesNothingAndReturns() {
action.lockHandler = new FakeLockHandler(false);
runAction(null, "foobar");
assertThat(response.getPayload()).startsWith("LOCKED");
verifyZeroInteractions(syncRegistrarsSheet);
verifyNoInteractions(syncRegistrarsSheet);
}
}
@@ -43,27 +43,23 @@ import google.registry.testing.DatastoreHelper;
import google.registry.testing.FakeClock;
import google.registry.testing.InjectRule;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.junit.jupiter.MockitoExtension;
/** Unit tests for {@link SyncRegistrarsSheet}. */
@RunWith(JUnit4.class)
@ExtendWith(MockitoExtension.class)
public class SyncRegistrarsSheetTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@Rule public final InjectRule inject = new InjectRule();
@RegisterExtension public final InjectRule inject = new InjectRule();
@Captor private ArgumentCaptor<ImmutableList<ImmutableMap<String, String>>> rowsCaptor;
@Mock private SheetSynchronizer sheetSynchronizer;
@@ -77,8 +73,8 @@ public class SyncRegistrarsSheetTest {
return result;
}
@Before
public void before() {
@BeforeEach
void beforeEach() {
inject.setStaticField(Ofy.class, "clock", clock);
createTld("example");
// Remove Registrar entities created by AppEngineRule.
@@ -86,12 +82,12 @@ public class SyncRegistrarsSheetTest {
}
@Test
public void test_wereRegistrarsModified_noRegistrars_returnsFalse() {
void test_wereRegistrarsModified_noRegistrars_returnsFalse() {
assertThat(newSyncRegistrarsSheet().wereRegistrarsModified()).isFalse();
}
@Test
public void test_wereRegistrarsModified_atDifferentCursorTimes() {
void test_wereRegistrarsModified_atDifferentCursorTimes() {
persistNewRegistrar("SomeRegistrar", "Some Registrar Inc.", Registrar.Type.REAL, 8L);
persistResource(Cursor.createGlobal(SYNC_REGISTRAR_SHEET, clock.nowUtc().minusHours(1)));
assertThat(newSyncRegistrarsSheet().wereRegistrarsModified()).isTrue();
@@ -100,7 +96,7 @@ public class SyncRegistrarsSheetTest {
}
@Test
public void testRun() throws Exception {
void testRun() throws Exception {
DateTime beforeExecution = clock.nowUtc();
persistResource(new Registrar.Builder()
.setClientId("anotherregistrar")
@@ -329,7 +325,7 @@ public class SyncRegistrarsSheetTest {
}
@Test
public void testRun_missingValues_stillWorks() throws Exception {
void testRun_missingValues_stillWorks() throws Exception {
persistNewRegistrar("SomeRegistrar", "Some Registrar", Registrar.Type.REAL, 8L);
newSyncRegistrarsSheet().run("foobar");
@@ -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;
@@ -163,7 +163,7 @@ public class EppControllerTest {
true,
true,
domainCreateXml.getBytes(UTF_8));
verifyZeroInteractions(eppMetrics);
verifyNoInteractions(eppMetrics);
}
@Test
@@ -0,0 +1,35 @@
// Copyright 2020 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.model;
import static com.google.common.truth.Truth.assertThat;
import java.util.Objects;
/** Test helpers for {@link EppResource}. */
public final class EppResourceTestUtils {
private EppResourceTestUtils() {}
public static <E extends EppResource> void assertEqualsIgnoreLastUpdateTime(
E actual, E expected) {
if (Objects.equals(actual, expected)) {
return;
}
actual = (E) actual.asBuilder().build();
actual.updateTimestamp = expected.getUpdateTimestamp();
assertThat(actual).isEqualTo(expected);
}
}
@@ -165,8 +165,10 @@ public class EppResourceUtilsTest {
assertThat(host.getRevisions()).hasSize(2);
// Even though there is no revision, make a best effort guess to use the oldest revision.
assertThat(
loadAtPointInTime(host, clock.nowUtc().minus(Duration.standardDays(32)))
.now().getUpdateAutoTimestamp().getTimestamp())
.isEqualTo(host.getRevisions().firstKey());
loadAtPointInTime(host, clock.nowUtc().minus(Duration.standardDays(32)))
.now()
.getUpdateTimestamp()
.getTimestamp())
.isEqualTo(host.getRevisions().firstKey());
}
}
@@ -0,0 +1,95 @@
// Copyright 2020 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.model;
import static com.google.common.truth.Truth.assertAbout;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableSet;
import com.google.common.truth.Correspondence;
import com.google.common.truth.Correspondence.BinaryPredicate;
import com.google.common.truth.FailureMetadata;
import com.google.common.truth.SimpleSubjectBuilder;
import com.google.common.truth.Subject;
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Nullable;
/** Truth subject for asserting things about ImmutableObjects that are not built in. */
public final class ImmutableObjectSubject extends Subject {
private final ImmutableObject actual;
protected ImmutableObjectSubject(FailureMetadata failureMetadata, ImmutableObject actual) {
super(failureMetadata, actual);
this.actual = actual;
}
public void isEqualExceptFields(ImmutableObject expected, String... ignoredFields) {
Map<Field, Object> actualFields = filterFields(actual, ignoredFields);
Map<Field, Object> expectedFields = filterFields(expected, ignoredFields);
assertThat(actualFields).containsExactlyEntriesIn(expectedFields);
}
public static Correspondence<ImmutableObject, ImmutableObject> immutableObjectCorrespondence(
String... ignoredFields) {
return Correspondence.from(
new ImmutableObjectBinaryPredicate(ignoredFields), "has all relevant fields equal to");
}
public static SimpleSubjectBuilder<ImmutableObjectSubject, ImmutableObject>
assertAboutImmutableObjects() {
return assertAbout(ImmutableObjectSubject::new);
}
private static class ImmutableObjectBinaryPredicate
implements BinaryPredicate<ImmutableObject, ImmutableObject> {
private final String[] ignoredFields;
private ImmutableObjectBinaryPredicate(String... ignoredFields) {
this.ignoredFields = ignoredFields;
}
@Override
public boolean apply(@Nullable ImmutableObject actual, @Nullable ImmutableObject expected) {
if (actual == null && expected == null) {
return true;
}
if (actual == null || expected == null) {
return false;
}
Map<Field, Object> actualFields = filterFields(actual, ignoredFields);
Map<Field, Object> expectedFields = filterFields(expected, ignoredFields);
return Objects.equals(actualFields, expectedFields);
}
}
private static Map<Field, Object> filterFields(
ImmutableObject original, String... ignoredFields) {
ImmutableSet<String> ignoredFieldSet = ImmutableSet.copyOf(ignoredFields);
Map<Field, Object> originalFields = ModelUtils.getFieldValues(original);
// don't use ImmutableMap or a stream->collect model since we can have nulls
Map<Field, Object> result = new LinkedHashMap<>();
for (Map.Entry<Field, Object> entry : originalFields.entrySet()) {
if (!ignoredFieldSet.contains(entry.getKey().getName())) {
result.put(entry.getKey(), entry.getValue());
}
}
return result;
}
}
@@ -16,6 +16,7 @@ package google.registry.model.contact;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import static google.registry.model.EppResourceTestUtils.assertEqualsIgnoreLastUpdateTime;
import static google.registry.model.EppResourceUtils.loadByForeignKey;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.testing.ContactResourceSubject.assertAboutContacts;
@@ -154,7 +155,7 @@ public class ContactResourceTest extends EntityTestCase {
.setServerApproveEntities(null)
.build())
.build();
assertThat(persisted).isEqualTo(fixed);
assertEqualsIgnoreLastUpdateTime(persisted, fixed);
}
@Test
@@ -14,7 +14,7 @@
package google.registry.model.domain;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.EppResourceTestUtils.assertEqualsIgnoreLastUpdateTime;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.testing.SqlHelper.assertThrowForeignKeyViolation;
import static google.registry.testing.SqlHelper.saveRegistrar;
@@ -154,7 +154,7 @@ public class DomainBaseSqlTest {
DomainBase org = domain.asBuilder().setCreationTime(result.getCreationTime()).build();
// Note that the equality comparison forces a lazy load of all fields.
assertThat(result).isEqualTo(org);
assertEqualsIgnoreLastUpdateTime(result, org);
});
}
@@ -14,7 +14,7 @@
package google.registry.model.history;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.testing.SqlHelper.saveRegistrar;
import static java.nio.charset.StandardCharsets.UTF_8;
@@ -74,14 +74,9 @@ public class HostHistoryTest extends EntityTestCase {
}
private void assertHostHistoriesEqual(HostHistory one, HostHistory two) {
// enough of the fields get changed during serialization that we can't depend on .equals()
assertThat(one.getClientId()).isEqualTo(two.getClientId());
assertThat(one.getHostRepoId()).isEqualTo(two.getHostRepoId());
assertThat(one.getBySuperuser()).isEqualTo(two.getBySuperuser());
assertThat(one.getRequestedByRegistrar()).isEqualTo(two.getRequestedByRegistrar());
assertThat(one.getReason()).isEqualTo(two.getReason());
assertThat(one.getTrid()).isEqualTo(two.getTrid());
assertThat(one.getType()).isEqualTo(two.getType());
assertThat(one.getHostBase().getHostName()).isEqualTo(two.getHostBase().getHostName());
assertAboutImmutableObjects().that(one).isEqualExceptFields(two, "hostBase");
assertAboutImmutableObjects()
.that(one.getHostBase())
.isEqualExceptFields(two.getHostBase(), "repoId");
}
}
@@ -247,8 +247,14 @@ public class OfyCommitLogTest {
void testSavingRootAndChild_updatesTimestampOnBackupGroupRoot() {
tm().transact(() -> ofy().save().entity(Root.create(1, getCrossTldKey())));
ofy().clearSessionCache();
assertThat(ofy().load().key(Key.create(getCrossTldKey(), Root.class, 1)).now()
.getUpdateAutoTimestamp().getTimestamp()).isEqualTo(clock.nowUtc());
assertThat(
ofy()
.load()
.key(Key.create(getCrossTldKey(), Root.class, 1))
.now()
.getUpdateTimestamp()
.getTimestamp())
.isEqualTo(clock.nowUtc());
clock.advanceOneMilli();
tm()
.transact(
@@ -257,43 +263,79 @@ public class OfyCommitLogTest {
ofy().save().entity(new Child());
});
ofy().clearSessionCache();
assertThat(ofy().load().key(Key.create(getCrossTldKey(), Root.class, 1)).now()
.getUpdateAutoTimestamp().getTimestamp()).isEqualTo(clock.nowUtc());
assertThat(
ofy()
.load()
.key(Key.create(getCrossTldKey(), Root.class, 1))
.now()
.getUpdateTimestamp()
.getTimestamp())
.isEqualTo(clock.nowUtc());
}
@Test
void testSavingOnlyChild_updatesTimestampOnBackupGroupRoot() {
tm().transact(() -> ofy().save().entity(Root.create(1, getCrossTldKey())));
ofy().clearSessionCache();
assertThat(ofy().load().key(Key.create(getCrossTldKey(), Root.class, 1)).now()
.getUpdateAutoTimestamp().getTimestamp()).isEqualTo(clock.nowUtc());
assertThat(
ofy()
.load()
.key(Key.create(getCrossTldKey(), Root.class, 1))
.now()
.getUpdateTimestamp()
.getTimestamp())
.isEqualTo(clock.nowUtc());
clock.advanceOneMilli();
tm().transact(() -> ofy().save().entity(new Child()));
ofy().clearSessionCache();
assertThat(ofy().load().key(Key.create(getCrossTldKey(), Root.class, 1)).now()
.getUpdateAutoTimestamp().getTimestamp()).isEqualTo(clock.nowUtc());
assertThat(
ofy()
.load()
.key(Key.create(getCrossTldKey(), Root.class, 1))
.now()
.getUpdateTimestamp()
.getTimestamp())
.isEqualTo(clock.nowUtc());
}
@Test
void testDeletingChild_updatesTimestampOnBackupGroupRoot() {
tm().transact(() -> ofy().save().entity(Root.create(1, getCrossTldKey())));
ofy().clearSessionCache();
assertThat(ofy().load().key(Key.create(getCrossTldKey(), Root.class, 1)).now()
.getUpdateAutoTimestamp().getTimestamp()).isEqualTo(clock.nowUtc());
assertThat(
ofy()
.load()
.key(Key.create(getCrossTldKey(), Root.class, 1))
.now()
.getUpdateTimestamp()
.getTimestamp())
.isEqualTo(clock.nowUtc());
clock.advanceOneMilli();
// The fact that the child was never persisted is irrelevant.
tm().transact(() -> ofy().delete().entity(new Child()));
ofy().clearSessionCache();
assertThat(ofy().load().key(Key.create(getCrossTldKey(), Root.class, 1)).now()
.getUpdateAutoTimestamp().getTimestamp()).isEqualTo(clock.nowUtc());
assertThat(
ofy()
.load()
.key(Key.create(getCrossTldKey(), Root.class, 1))
.now()
.getUpdateTimestamp()
.getTimestamp())
.isEqualTo(clock.nowUtc());
}
@Test
void testReadingRoot_doesntUpdateTimestamp() {
tm().transact(() -> ofy().save().entity(Root.create(1, getCrossTldKey())));
ofy().clearSessionCache();
assertThat(ofy().load().key(Key.create(getCrossTldKey(), Root.class, 1)).now()
.getUpdateAutoTimestamp().getTimestamp()).isEqualTo(clock.nowUtc());
assertThat(
ofy()
.load()
.key(Key.create(getCrossTldKey(), Root.class, 1))
.now()
.getUpdateTimestamp()
.getTimestamp())
.isEqualTo(clock.nowUtc());
clock.advanceOneMilli();
tm()
.transact(
@@ -304,16 +346,28 @@ public class OfyCommitLogTest {
ofy().load().entity(Root.create(1, getCrossTldKey()));
});
ofy().clearSessionCache();
assertThat(ofy().load().key(Key.create(getCrossTldKey(), Root.class, 1)).now()
.getUpdateAutoTimestamp().getTimestamp()).isEqualTo(clock.nowUtc().minusMillis(1));
assertThat(
ofy()
.load()
.key(Key.create(getCrossTldKey(), Root.class, 1))
.now()
.getUpdateTimestamp()
.getTimestamp())
.isEqualTo(clock.nowUtc().minusMillis(1));
}
@Test
void testReadingChild_doesntUpdateTimestampOnBackupGroupRoot() {
tm().transact(() -> ofy().save().entity(Root.create(1, getCrossTldKey())));
ofy().clearSessionCache();
assertThat(ofy().load().key(Key.create(getCrossTldKey(), Root.class, 1)).now()
.getUpdateAutoTimestamp().getTimestamp()).isEqualTo(clock.nowUtc());
assertThat(
ofy()
.load()
.key(Key.create(getCrossTldKey(), Root.class, 1))
.now()
.getUpdateTimestamp()
.getTimestamp())
.isEqualTo(clock.nowUtc());
clock.advanceOneMilli();
tm()
.transact(
@@ -324,8 +378,14 @@ public class OfyCommitLogTest {
ofy().load().entity(new Child()); // All Child objects are under Root(1).
});
ofy().clearSessionCache();
assertThat(ofy().load().key(Key.create(getCrossTldKey(), Root.class, 1)).now()
.getUpdateAutoTimestamp().getTimestamp()).isEqualTo(clock.nowUtc().minusMillis(1));
assertThat(
ofy()
.load()
.key(Key.create(getCrossTldKey(), Root.class, 1))
.now()
.getUpdateTimestamp()
.getTimestamp())
.isEqualTo(clock.nowUtc().minusMillis(1));
}
@Test
@@ -340,8 +400,14 @@ public class OfyCommitLogTest {
});
ofy().clearSessionCache();
for (int i = 1; i <= 3; i++) {
assertThat(ofy().load().key(Key.create(getCrossTldKey(), Root.class, i)).now()
.getUpdateAutoTimestamp().getTimestamp()).isEqualTo(clock.nowUtc());
assertThat(
ofy()
.load()
.key(Key.create(getCrossTldKey(), Root.class, i))
.now()
.getUpdateTimestamp()
.getTimestamp())
.isEqualTo(clock.nowUtc());
}
clock.advanceOneMilli();
// Mutate one root, and a child of a second, ignoring the third.
@@ -353,14 +419,32 @@ public class OfyCommitLogTest {
});
ofy().clearSessionCache();
// Child was touched.
assertThat(ofy().load().key(Key.create(getCrossTldKey(), Root.class, 1)).now()
.getUpdateAutoTimestamp().getTimestamp()).isEqualTo(clock.nowUtc());
assertThat(
ofy()
.load()
.key(Key.create(getCrossTldKey(), Root.class, 1))
.now()
.getUpdateTimestamp()
.getTimestamp())
.isEqualTo(clock.nowUtc());
// Directly touched.
assertThat(ofy().load().key(Key.create(getCrossTldKey(), Root.class, 2)).now()
.getUpdateAutoTimestamp().getTimestamp()).isEqualTo(clock.nowUtc());
assertThat(
ofy()
.load()
.key(Key.create(getCrossTldKey(), Root.class, 2))
.now()
.getUpdateTimestamp()
.getTimestamp())
.isEqualTo(clock.nowUtc());
// Wasn't touched.
assertThat(ofy().load().key(Key.create(getCrossTldKey(), Root.class, 3)).now()
.getUpdateAutoTimestamp().getTimestamp()).isEqualTo(clock.nowUtc().minusMillis(1));
assertThat(
ofy()
.load()
.key(Key.create(getCrossTldKey(), Root.class, 3))
.now()
.getUpdateTimestamp()
.getTimestamp())
.isEqualTo(clock.nowUtc().minusMillis(1));
}
@Entity
@@ -79,8 +79,8 @@ public class OfyTest {
}
private void doBackupGroupRootTimestampInversionTest(Runnable runnable) {
DateTime groupTimestamp = ofy().load().key(someObject.getParent()).now()
.getUpdateAutoTimestamp().getTimestamp();
DateTime groupTimestamp =
ofy().load().key(someObject.getParent()).now().getUpdateTimestamp().getTimestamp();
// Set the clock in Ofy to the same time as the backup group root's save time.
Ofy ofy = new Ofy(new FakeClock(groupTimestamp));
TimestampInversionException thrown =
@@ -41,31 +41,31 @@ public class ReservedListSqlDaoTest {
JpaIntegrationWithCoverageExtension jpa =
new JpaTestRules.Builder().withClock(fakeClock).buildIntegrationWithCoverageExtension();
private ImmutableMap<String, ReservedListEntry> test_reservations;
private ImmutableMap<String, ReservedListEntry> testReservations;
private ReservedList test_reserved_list;
private ReservedList testReservedList;
@BeforeEach
void setUp() {
test_reservations =
testReservations =
ImmutableMap.of(
"food",
ReservedListEntry.create("food", ReservationType.RESERVED_FOR_SPECIFIC_USE, null),
"music",
ReservedListEntry.create("music", ReservationType.FULLY_BLOCKED, "fully blocked"));
test_reserved_list =
testReservedList =
new ReservedList.Builder()
.setName("testlist")
.setLastUpdateTime(fakeClock.nowUtc())
.setShouldPublish(false)
.setReservedListMap(test_reservations)
.setReservedListMap(testReservations)
.build();
}
@Test
public void save_worksSuccessfully() {
ReservedListSqlDao.save(test_reserved_list);
ReservedListSqlDao.save(testReservedList);
jpaTm()
.transact(
() -> {
@@ -76,7 +76,7 @@ public class ReservedListSqlDaoTest {
.setParameter("name", "testlist")
.getSingleResult();
assertThat(persistedList.getReservedListEntries())
.containsExactlyEntriesIn(test_reservations);
.containsExactlyEntriesIn(testReservations);
assertThat(persistedList.getLastUpdateTime()).isEqualTo(fakeClock.nowUtc());
});
}
@@ -84,20 +84,20 @@ public class ReservedListSqlDaoTest {
@Test
public void checkExists_worksSuccessfully() {
assertThat(ReservedListSqlDao.checkExists("testlist")).isFalse();
ReservedListSqlDao.save(test_reserved_list);
ReservedListSqlDao.save(testReservedList);
assertThat(ReservedListSqlDao.checkExists("testlist")).isTrue();
}
@Test
public void getLatestRevision_worksSuccessfully() {
assertThat(ReservedListSqlDao.getLatestRevision("testlist").isPresent()).isFalse();
ReservedListSqlDao.save(test_reserved_list);
ReservedListSqlDao.save(testReservedList);
ReservedList persistedList = ReservedListSqlDao.getLatestRevision("testlist").get();
assertThat(persistedList.getRevisionId()).isNotNull();
assertThat(persistedList.getLastUpdateTime()).isEqualTo(fakeClock.nowUtc());
assertThat(persistedList.getName()).isEqualTo("testlist");
assertThat(persistedList.getShouldPublish()).isFalse();
assertThat(persistedList.getReservedListEntries()).containsExactlyEntriesIn(test_reservations);
assertThat(persistedList.getReservedListEntries()).containsExactlyEntriesIn(testReservations);
}
@Test
@@ -113,12 +113,12 @@ public class ReservedListSqlDaoTest {
ReservedListEntry.create(
"old", ReservationType.RESERVED_FOR_SPECIFIC_USE, null)))
.build());
ReservedListSqlDao.save(test_reserved_list);
ReservedListSqlDao.save(testReservedList);
ReservedList persistedList = ReservedListSqlDao.getLatestRevision("testlist").get();
assertThat(persistedList.getRevisionId()).isNotNull();
assertThat(persistedList.getLastUpdateTime()).isEqualTo(fakeClock.nowUtc());
assertThat(persistedList.getName()).isEqualTo("testlist");
assertThat(persistedList.getShouldPublish()).isFalse();
assertThat(persistedList.getReservedListEntries()).containsExactlyEntriesIn(test_reservations);
assertThat(persistedList.getReservedListEntries()).containsExactlyEntriesIn(testReservations);
}
}
@@ -25,8 +25,8 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
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.appengine.tools.cloudstorage.GcsFilename;
@@ -208,7 +208,7 @@ public class CopyDetailReportsActionTest {
new GcsFilename("test-bucket", "results/invoice_details_2017-10_notExistent_hello.csv"),
"hola,mundo\n3,4".getBytes(UTF_8));
action.run();
verifyZeroInteractions(driveConnection);
verifyNoInteractions(driveConnection);
}
@Test
@@ -220,6 +220,6 @@ public class CopyDetailReportsActionTest {
"test-bucket", "results/invoice_details_2017-10_TheRegistrar_hello.csv"),
"hola,mundo\n3,4".getBytes(UTF_8));
action.run();
verifyZeroInteractions(driveConnection);
verifyNoInteractions(driveConnection);
}
}
@@ -24,8 +24,8 @@ import static org.mockito.ArgumentMatchers.any;
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.appengine.api.users.User;
@@ -245,7 +245,7 @@ public final class RequestHandlerTest {
handler.handleRequest(req, rsp);
verifyZeroInteractions(rsp);
verifyNoInteractions(rsp);
verify(bumblebeeTask).run();
assertMetric("/bumblebee", GET, AuthLevel.NONE, true);
}
@@ -24,7 +24,7 @@ import static google.registry.testing.LogsSubject.assertAboutLogs;
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.appengine.api.users.User;
@@ -150,7 +150,7 @@ public class AuthenticatedRegistrarAccessorTest {
NO_USER, ADMIN_CLIENT_ID, SUPPORT_GROUP, lazyGroupsConnection);
assertThat(registrarAccessor.getAllClientIdWithRoles()).isEmpty();
verifyZeroInteractions(lazyGroupsConnection);
verifyNoInteractions(lazyGroupsConnection);
}
/**
@@ -182,7 +182,7 @@ public class AuthenticatedRegistrarAccessorTest {
ADMIN_CLIENT_ID, ADMIN,
ADMIN_CLIENT_ID, OWNER);
verifyZeroInteractions(lazyGroupsConnection);
verifyNoInteractions(lazyGroupsConnection);
}
/**
@@ -228,7 +228,7 @@ public class AuthenticatedRegistrarAccessorTest {
assertThat(registrarAccessor.getAllClientIdWithRoles())
.containsExactly(CLIENT_ID_WITH_CONTACT, OWNER);
// Make sure we didn't instantiate the lazyGroupsConnection
verifyZeroInteractions(lazyGroupsConnection);
verifyNoInteractions(lazyGroupsConnection);
}
/** Support group check throws - continue anyway. */
@@ -287,7 +287,7 @@ public class AuthenticatedRegistrarAccessorTest {
CLIENT_ID_WITH_CONTACT,
NO_USER,
"<logged-out user> doesn't have access to registrar TheRegistrar");
verifyZeroInteractions(lazyGroupsConnection);
verifyNoInteractions(lazyGroupsConnection);
}
/** Succeed loading registrar if user has access to it. */
@@ -307,7 +307,7 @@ public class AuthenticatedRegistrarAccessorTest {
CLIENT_ID_WITH_CONTACT,
GAE_ADMIN,
"admin admin@gmail.com has [OWNER, ADMIN] access to registrar TheRegistrar");
verifyZeroInteractions(lazyGroupsConnection);
verifyNoInteractions(lazyGroupsConnection);
}
/** Succeed loading registrar for admin even if they aren't on the approved contacts list. */
@@ -317,7 +317,7 @@ public class AuthenticatedRegistrarAccessorTest {
REAL_CLIENT_ID_WITHOUT_CONTACT,
GAE_ADMIN,
"admin admin@gmail.com has [ADMIN] access to registrar NewRegistrar.");
verifyZeroInteractions(lazyGroupsConnection);
verifyNoInteractions(lazyGroupsConnection);
}
@Test
@@ -332,7 +332,7 @@ public class AuthenticatedRegistrarAccessorTest {
REAL_CLIENT_ID_WITHOUT_CONTACT,
GAE_ADMIN,
"admin admin@gmail.com has [OWNER, ADMIN] access to registrar NewRegistrar.");
verifyZeroInteractions(lazyGroupsConnection);
verifyNoInteractions(lazyGroupsConnection);
}
/** Succeed loading non-REAL registrar for admin. */
@@ -342,7 +342,7 @@ public class AuthenticatedRegistrarAccessorTest {
OTE_CLIENT_ID_WITHOUT_CONTACT,
GAE_ADMIN,
"admin admin@gmail.com has [OWNER, ADMIN] access to registrar OteRegistrar.");
verifyZeroInteractions(lazyGroupsConnection);
verifyNoInteractions(lazyGroupsConnection);
}
/** Fail loading registrar even if admin, if registrar doesn't exist. */
@@ -352,7 +352,7 @@ public class AuthenticatedRegistrarAccessorTest {
"BadClientId",
GAE_ADMIN,
"Registrar BadClientId does not exist");
verifyZeroInteractions(lazyGroupsConnection);
verifyNoInteractions(lazyGroupsConnection);
}
private void expectGetRegistrarSuccess(String clientId, AuthResult authResult, String message)
@@ -19,7 +19,7 @@ import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import com.google.appengine.api.users.User;
@@ -138,7 +138,7 @@ public class RequestAuthenticatorTest {
public void testNoAuthNeeded_noneFound() {
Optional<AuthResult> authResult = runTest(mockUserService, AUTH_NONE);
verifyZeroInteractions(mockUserService);
verifyNoInteractions(mockUserService);
assertThat(authResult).isPresent();
assertThat(authResult.get().authLevel()).isEqualTo(AuthLevel.NONE);
}
@@ -149,7 +149,7 @@ public class RequestAuthenticatorTest {
Optional<AuthResult> authResult = runTest(mockUserService, AUTH_NONE);
verifyZeroInteractions(mockUserService);
verifyNoInteractions(mockUserService);
assertThat(authResult).isPresent();
assertThat(authResult.get().authLevel()).isEqualTo(AuthLevel.APP);
assertThat(authResult.get().userAuthInfo()).isEmpty();
@@ -159,7 +159,7 @@ public class RequestAuthenticatorTest {
public void testInternalAuth_notInvokedInternally() {
Optional<AuthResult> authResult = runTest(mockUserService, AUTH_INTERNAL_OR_ADMIN);
verifyZeroInteractions(mockUserService);
verifyNoInteractions(mockUserService);
assertThat(authResult).isEmpty();
}
@@ -169,7 +169,7 @@ public class RequestAuthenticatorTest {
Optional<AuthResult> authResult = runTest(mockUserService, AUTH_INTERNAL_OR_ADMIN);
verifyZeroInteractions(mockUserService);
verifyNoInteractions(mockUserService);
assertThat(authResult).isPresent();
assertThat(authResult.get().authLevel()).isEqualTo(AuthLevel.APP);
assertThat(authResult.get().userAuthInfo()).isEmpty();
@@ -20,6 +20,7 @@ import java.util.Map;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.rules.ExternalResource;
import org.testcontainers.shaded.com.google.common.collect.ImmutableMap;
/**
@@ -33,7 +34,8 @@ import org.testcontainers.shaded.com.google.common.collect.ImmutableMap;
* href="https://junit.org/junit5/docs/current/user-guide/#extensions-registration-programmatic">
* JUnit 5 User Guide</a> for details of extension ordering.
*/
public class DatastoreEntityExtension implements BeforeEachCallback, AfterEachCallback {
public class DatastoreEntityExtension extends ExternalResource
implements BeforeEachCallback, AfterEachCallback {
private static final Environment PLACEHOLDER_ENV = new PlaceholderEnvironment();
@@ -48,6 +50,16 @@ public class DatastoreEntityExtension implements BeforeEachCallback, AfterEachCa
ApiProxy.setEnvironmentForCurrentThread(null);
}
@Override
protected void before() {
beforeEach(null);
}
@Override
protected void after() {
afterEach(null);
}
private static final class PlaceholderEnvironment implements Environment {
@Override
@@ -50,15 +50,11 @@ import java.util.Optional;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Rule;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.Mock;
import org.mockito.Mockito;
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;
@@ -86,19 +82,16 @@ public abstract class MapreduceTestCase<T> {
private final PipelineServlet pipelineServlet = new PipelineServlet();
private LocalTaskQueue taskQueue;
@RegisterExtension @Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withLocalModules().withTaskQueue().build();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
private AppEngineServiceUtils appEngineServiceUtils;
@Mock ModulesService modulesService;
@Before
@BeforeEach
public void setUp() {
public void beforeEachMapreduceTestCase() {
taskQueue = LocalTaskQueueTestConfig.getLocalTaskQueue();
ApiProxyLocal proxy = (ApiProxyLocal) ApiProxy.getDelegate();
// Creating files is not allowed in some test execution environments, so don't.
@@ -31,25 +31,25 @@ import google.registry.persistence.VKey;
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.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link AckPollMessagesCommand}. */
public class AckPollMessagesCommandTest extends CommandTestCase<AckPollMessagesCommand> {
private FakeClock clock = new FakeClock(DateTime.parse("2015-02-04T08:16:32.064Z"));
@Rule public final InjectRule inject = new InjectRule();
@RegisterExtension public final InjectRule inject = new InjectRule();
@Before
public final void before() {
@BeforeEach
final void beforeEach() {
inject.setStaticField(Ofy.class, "clock", clock);
command.clock = clock;
}
@Test
public void testSuccess_doesntDeletePollMessagesInFuture() throws Exception {
void testSuccess_doesntDeletePollMessagesInFuture() throws Exception {
VKey<OneTime> pm1 =
persistPollMessage(316L, DateTime.parse("2014-01-01T22:33:44Z"), "foobar").createVKey();
VKey<OneTime> pm2 =
@@ -70,7 +70,7 @@ public class AckPollMessagesCommandTest extends CommandTestCase<AckPollMessagesC
}
@Test
public void testSuccess_resavesAutorenewPollMessages() throws Exception {
void testSuccess_resavesAutorenewPollMessages() throws Exception {
VKey<OneTime> pm1 =
persistPollMessage(316L, DateTime.parse("2014-01-01T22:33:44Z"), "foobar").createVKey();
VKey<OneTime> pm2 =
@@ -98,7 +98,7 @@ public class AckPollMessagesCommandTest extends CommandTestCase<AckPollMessagesC
}
@Test
public void testSuccess_deletesExpiredAutorenewPollMessages() throws Exception {
void testSuccess_deletesExpiredAutorenewPollMessages() throws Exception {
VKey<OneTime> pm1 =
persistPollMessage(316L, DateTime.parse("2014-01-01T22:33:44Z"), "foobar").createVKey();
VKey<OneTime> pm2 =
@@ -125,7 +125,7 @@ public class AckPollMessagesCommandTest extends CommandTestCase<AckPollMessagesC
}
@Test
public void testSuccess_onlyDeletesPollMessagesMatchingMessage() throws Exception {
void testSuccess_onlyDeletesPollMessagesMatchingMessage() throws Exception {
VKey<OneTime> pm1 =
persistPollMessage(316L, DateTime.parse("2014-01-01T22:33:44Z"), "food is good")
.createVKey();
@@ -143,7 +143,7 @@ public class AckPollMessagesCommandTest extends CommandTestCase<AckPollMessagesC
}
@Test
public void testSuccess_onlyDeletesPollMessagesMatchingClientId() throws Exception {
void testSuccess_onlyDeletesPollMessagesMatchingClientId() throws Exception {
VKey<OneTime> pm1 =
persistPollMessage(316L, DateTime.parse("2014-01-01T22:33:44Z"), "food is good")
.createVKey();
@@ -167,7 +167,7 @@ public class AckPollMessagesCommandTest extends CommandTestCase<AckPollMessagesC
}
@Test
public void testSuccess_dryRunDoesntDeleteAnything() throws Exception {
void testSuccess_dryRunDoesntDeleteAnything() throws Exception {
OneTime pm1 = persistPollMessage(316L, DateTime.parse("2014-01-01T22:33:44Z"), "foobar");
OneTime pm2 = persistPollMessage(624L, DateTime.parse("2013-05-01T22:33:44Z"), "ninelives");
OneTime pm3 = persistPollMessage(791L, DateTime.parse("2015-01-08T22:33:44Z"), "ginger");
@@ -27,23 +27,19 @@ import com.google.common.net.MediaType;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
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.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.junit.jupiter.MockitoExtension;
@RunWith(JUnit4.class)
public final class AppEngineConnectionTest {
/** Unit tests for {@link google.registry.tools.AppEngineConnection}. */
@ExtendWith(MockitoExtension.class)
final class AppEngineConnectionTest {
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
AppEngineConnection connection;
TestHttpTransport httpTransport;
TestLowLevelHttpRequest lowLevelHttpRequest;
private AppEngineConnection connection;
private TestHttpTransport httpTransport;
private TestLowLevelHttpRequest lowLevelHttpRequest;
@Mock LowLevelHttpResponse lowLevelHttpResponse;
private final class TestHttpTransport extends HttpTransport {
@@ -81,8 +77,8 @@ public final class AppEngineConnectionTest {
}
}
@Before
public void setUp() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
lowLevelHttpRequest = new TestLowLevelHttpRequest();
when(lowLevelHttpResponse.getContent())
.thenReturn(new ByteArrayInputStream("MyContent".getBytes(UTF_8)));
@@ -94,7 +90,7 @@ public final class AppEngineConnectionTest {
}
@Test
public void testSendGetRequest() throws Exception {
void testSendGetRequest() throws Exception {
assertThat(
connection.sendGetRequest(
"/my/path?query", ImmutableMap.of("key1", "value1", "key2", "value2")))
@@ -107,7 +103,7 @@ public final class AppEngineConnectionTest {
}
@Test
public void testSendPostRequest() throws Exception {
void testSendPostRequest() throws Exception {
assertThat(
connection.sendPostRequest(
"/my/path?query",
@@ -125,7 +121,7 @@ public final class AppEngineConnectionTest {
}
@Test
public void testSendJsonRequest() throws Exception {
void testSendJsonRequest() throws Exception {
when(lowLevelHttpResponse.getContent())
.thenReturn(
new ByteArrayInputStream((JSON_SAFETY_PREFIX + "{\"key\":\"value\"}").getBytes(UTF_8)));
@@ -17,7 +17,6 @@ package google.registry.tools;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.api.client.auth.oauth2.ClientParametersAuthentication;
@@ -37,25 +36,29 @@ import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import org.junit.Before;
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.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
/** Unit tests for {@link AuthModule}. */
@RunWith(JUnit4.class)
public class AuthModuleTest {
@ExtendWith(MockitoExtension.class)
class AuthModuleTest {
private static final String CLIENT_ID = "UNITTEST-CLIENT-ID";
private static final String CLIENT_SECRET = "UNITTEST-CLIENT-SECRET";
private static final String ACCESS_TOKEN = "FakeAccessToken";
private static final String REFRESH_TOKEN = "FakeReFreshToken";
@Rule
public final TemporaryFolder folder = new TemporaryFolder();
@SuppressWarnings("WeakerAccess")
@TempDir
Path folder;
private final Credential fakeCredential =
new Credential.Builder(
@@ -77,8 +80,7 @@ public class AuthModuleTest {
.setClientAuthentication(new ClientParametersAuthentication(CLIENT_ID, CLIENT_SECRET))
.build();
@SuppressWarnings("unchecked")
DataStore<StoredCredential> dataStore = mock(DataStore.class);
@Mock DataStore<StoredCredential> dataStore;
class FakeDataStoreFactory extends AbstractDataStoreFactory {
@Override
@@ -89,14 +91,15 @@ public class AuthModuleTest {
}
}
@Before
public void setUp() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
fakeCredential.setRefreshToken(REFRESH_TOKEN);
when(dataStore.get(CLIENT_ID + " scope1")).thenReturn(new StoredCredential(fakeCredential));
}
@Test
public void test_clientScopeQualifier() {
@MockitoSettings(strictness = Strictness.LENIENT)
void test_clientScopeQualifier() {
String simpleQualifier =
AuthModule.provideClientScopeQualifier("client-id", ImmutableList.of("foo", "bar"));
@@ -161,7 +164,7 @@ public class AuthModuleTest {
}
@Test
public void test_provideLocalCredentialJson() {
void test_provideLocalCredentialJson() {
String credentialJson =
AuthModule.provideLocalCredentialJson(this::getSecrets, this::getCredential, null);
Map<String, String> jsonMap =
@@ -173,8 +176,9 @@ public class AuthModuleTest {
}
@Test
public void test_provideExternalCredentialJson() throws Exception {
File credentialFile = folder.newFile("credential.json");
@MockitoSettings(strictness = Strictness.LENIENT)
void test_provideExternalCredentialJson() throws Exception {
File credentialFile = folder.resolve("credential.json").toFile();
Files.write(credentialFile.toPath(), "{some_field: some_value}".getBytes(UTF_8));
String credentialJson =
AuthModule.provideLocalCredentialJson(
@@ -183,7 +187,7 @@ public class AuthModuleTest {
}
@Test
public void test_provideCredential() {
void test_provideCredential() {
Credential cred = getCredential();
assertThat(cred.getAccessToken()).isEqualTo(fakeCredential.getAccessToken());
assertThat(cred.getRefreshToken()).isEqualTo(fakeCredential.getRefreshToken());
@@ -192,7 +196,7 @@ public class AuthModuleTest {
}
@Test
public void test_provideCredential_notStored() throws IOException {
void test_provideCredential_notStored() throws IOException {
when(dataStore.get(CLIENT_ID + " scope1")).thenReturn(null);
assertThrows(AuthModule.LoginRequiredException.class, this::getCredential);
}
@@ -19,26 +19,26 @@ import static org.junit.Assert.assertThrows;
import com.beust.jcommander.ParameterException;
import google.registry.model.registrar.Registrar.Type;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link CheckDomainClaimsCommand}. */
public class CheckDomainClaimsCommandTest extends EppToolCommandTestCase<CheckDomainClaimsCommand> {
class CheckDomainClaimsCommandTest extends EppToolCommandTestCase<CheckDomainClaimsCommand> {
@Before
public void before() {
@BeforeEach
void beforeEach() {
persistNewRegistrar("adminreg", "Admin Registrar", Type.REAL, 693L);
command.registryAdminClientId = "adminreg";
}
@Test
public void testSuccess() throws Exception {
void testSuccess() throws Exception {
runCommand("--client=NewRegistrar", "example.tld");
eppVerifier.expectDryRun().verifySent("domain_check_claims.xml");
}
@Test
public void testSuccess_multipleTlds() throws Exception {
void testSuccess_multipleTlds() throws Exception {
runCommand("--client=NewRegistrar", "example.tld", "example.tld2");
eppVerifier
.expectDryRun()
@@ -47,7 +47,7 @@ public class CheckDomainClaimsCommandTest extends EppToolCommandTestCase<CheckDo
}
@Test
public void testSuccess_multipleDomains() throws Exception {
void testSuccess_multipleDomains() throws Exception {
runCommand(
"--client=NewRegistrar",
"example.tld",
@@ -57,7 +57,7 @@ public class CheckDomainClaimsCommandTest extends EppToolCommandTestCase<CheckDo
}
@Test
public void testSuccess_multipleDomainsAndTlds() throws Exception {
void testSuccess_multipleDomainsAndTlds() throws Exception {
runCommand(
"--client=NewRegistrar",
"example.tld",
@@ -71,18 +71,18 @@ public class CheckDomainClaimsCommandTest extends EppToolCommandTestCase<CheckDo
}
@Test
public void testSuccess_unspecifiedClientId_defaultsToRegistryRegistrar() throws Exception {
void testSuccess_unspecifiedClientId_defaultsToRegistryRegistrar() throws Exception {
runCommand("example.tld");
eppVerifier.expectDryRun().expectClientId("adminreg").verifySent("domain_check_claims.xml");
}
@Test
public void testFailure_NoMainParameter() {
void testFailure_NoMainParameter() {
assertThrows(ParameterException.class, () -> runCommand("--client=NewRegistrar"));
}
@Test
public void testFailure_unknownFlag() {
void testFailure_unknownFlag() {
assertThrows(
ParameterException.class,
() -> runCommand("--client=NewRegistrar", "--unrecognized=foo", "example.tld"));
@@ -19,26 +19,26 @@ import static org.junit.Assert.assertThrows;
import com.beust.jcommander.ParameterException;
import google.registry.model.registrar.Registrar.Type;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link CheckDomainCommand}. */
public class CheckDomainCommandTest extends EppToolCommandTestCase<CheckDomainCommand> {
class CheckDomainCommandTest extends EppToolCommandTestCase<CheckDomainCommand> {
@Before
public void before() {
@BeforeEach
void beforeEach() {
persistNewRegistrar("adminreg", "Admin Registrar", Type.REAL, 693L);
command.registryAdminClientId = "adminreg";
}
@Test
public void testSuccess() throws Exception {
void testSuccess() throws Exception {
runCommand("--client=NewRegistrar", "example.tld");
eppVerifier.expectDryRun().verifySent("domain_check_fee.xml");
}
@Test
public void testSuccess_multipleTlds() throws Exception {
void testSuccess_multipleTlds() throws Exception {
runCommand("--client=NewRegistrar", "example.tld", "example.tld2");
eppVerifier
.expectDryRun()
@@ -47,7 +47,7 @@ public class CheckDomainCommandTest extends EppToolCommandTestCase<CheckDomainCo
}
@Test
public void testSuccess_multipleDomains() throws Exception {
void testSuccess_multipleDomains() throws Exception {
runCommand(
"--client=NewRegistrar",
"example.tld",
@@ -57,7 +57,7 @@ public class CheckDomainCommandTest extends EppToolCommandTestCase<CheckDomainCo
}
@Test
public void testSuccess_multipleDomainsAndTlds() throws Exception {
void testSuccess_multipleDomainsAndTlds() throws Exception {
runCommand(
"--client=NewRegistrar",
"example.tld",
@@ -71,24 +71,24 @@ public class CheckDomainCommandTest extends EppToolCommandTestCase<CheckDomainCo
}
@Test
public void testSuccess_unspecifiedClientId_defaultsToRegistryRegistrar() throws Exception {
void testSuccess_unspecifiedClientId_defaultsToRegistryRegistrar() throws Exception {
runCommand("example.tld");
eppVerifier.expectDryRun().expectClientId("adminreg").verifySent("domain_check_fee.xml");
}
@Test
public void testSuccess_allocationToken_reserved() throws Exception {
void testSuccess_allocationToken_reserved() throws Exception {
runCommand("--client=NewRegistrar", "--token=abc123", "example.tld");
eppVerifier.expectDryRun().verifySent("domain_check_fee_allocationtoken.xml");
}
@Test
public void testFailure_NoMainParameter() {
void testFailure_NoMainParameter() {
assertThrows(ParameterException.class, () -> runCommand("--client=NewRegistrar"));
}
@Test
public void testFailure_unknownFlag() {
void testFailure_unknownFlag() {
assertThrows(
ParameterException.class,
() -> runCommand("--client=NewRegistrar", "--unrecognized=foo", "example.tld"));
@@ -35,27 +35,25 @@ import google.registry.testing.FakeClock;
import google.registry.testing.SystemPropertyRule;
import google.registry.tools.params.ParameterFactory;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
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.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.junit.jupiter.MockitoExtension;
/**
* Base class for all command tests.
*
* @param <C> the command type
*/
@RunWith(JUnit4.class)
@ExtendWith(MockitoExtension.class)
public abstract class CommandTestCase<C extends Command> {
// Lock for stdout/stderr. Note that this is static: since we're dealing with globals, we need
@@ -70,7 +68,7 @@ public abstract class CommandTestCase<C extends Command> {
public final FakeClock fakeClock = new FakeClock();
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder()
.withDatastoreAndCloudSql()
@@ -78,15 +76,12 @@ public abstract class CommandTestCase<C extends Command> {
.withTaskQueue()
.build();
@Rule public final SystemPropertyRule systemPropertyRule = new SystemPropertyRule();
@RegisterExtension final SystemPropertyRule systemPropertyRule = new SystemPropertyRule();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@TempDir public Path tmpDir;
@Rule
public TemporaryFolder tmpDir = new TemporaryFolder();
@Before
public final void beforeCommandTestCase() throws Exception {
@BeforeEach
public final void beforeEachCommandTestCase() throws Exception {
// Ensure the UNITTEST environment has been set before constructing a new command instance.
RegistryToolEnvironment.UNITTEST.setup(systemPropertyRule);
command = newCommandInstance();
@@ -101,8 +96,8 @@ public abstract class CommandTestCase<C extends Command> {
System.setErr(new PrintStream(new OutputSplitter(System.err, stderr)));
}
@After
public final void afterCommandTestCase() throws Exception {
@AfterEach
public final void afterEachCommandTestCase() {
System.setOut(oldStdout);
System.setErr(oldStderr);
streamsLock.unlock();
@@ -144,10 +139,10 @@ public abstract class CommandTestCase<C extends Command> {
}
/** Writes the data to a named temporary file and then returns a path to the file. */
String writeToNamedTmpFile(String filename, byte[] data) throws IOException {
File tmpFile = tmpDir.newFile(filename);
Files.write(data, tmpFile);
return tmpFile.getPath();
private String writeToNamedTmpFile(String filename, byte[] data) throws IOException {
Path tmpFile = tmpDir.resolve(filename);
Files.write(data, tmpFile.toFile());
return tmpFile.toString();
}
/** Writes the data to a named temporary file and then returns a path to the file. */
@@ -199,7 +194,7 @@ public abstract class CommandTestCase<C extends Command> {
.isEqualTo(stripImmutableObjectHashCodes(expected).trim());
}
protected void assertStdoutIs(String expected) {
void assertStdoutIs(String expected) {
assertThat(getStdoutAsString()).isEqualTo(expected);
}
@@ -210,34 +205,34 @@ public abstract class CommandTestCase<C extends Command> {
}
}
protected void assertInStderr(String... expected) {
void assertInStderr(String... expected) {
String stderror = new String(stderr.toByteArray(), UTF_8);
for (String line : expected) {
assertThat(stderror).contains(line);
}
}
protected void assertNotInStdout(String expected) {
void assertNotInStdout(String expected) {
assertThat(getStdoutAsString()).doesNotContain(expected);
}
protected void assertNotInStderr(String expected) {
void assertNotInStderr(String expected) {
assertThat(getStderrAsString()).doesNotContain(expected);
}
protected String getStdoutAsString() {
String getStdoutAsString() {
return new String(stdout.toByteArray(), UTF_8);
}
protected String getStderrAsString() {
String getStderrAsString() {
return new String(stderr.toByteArray(), UTF_8);
}
protected List<String> getStdoutAsLines() {
List<String> getStdoutAsLines() {
return Splitter.on('\n').omitEmptyStrings().trimResults().splitToList(getStdoutAsString());
}
protected String stripImmutableObjectHashCodes(String string) {
private String stripImmutableObjectHashCodes(String string) {
return string.replaceAll("\\(@\\d+\\)", "(@)");
}
@@ -22,14 +22,15 @@ import google.registry.testing.DatastoreEntityExtension;
import google.registry.tools.EntityWrapper.Property;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
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.rules.TemporaryFolder;
import org.junit.jupiter.api.io.TempDir;
public class CompareDbBackupsTest {
@@ -39,26 +40,24 @@ public class CompareDbBackupsTest {
private final ByteArrayOutputStream stdout = new ByteArrayOutputStream();
private PrintStream orgStdout;
public final TemporaryFolder tempFs = new TemporaryFolder();
@TempDir Path tmpDir;
@RegisterExtension
public DatastoreEntityExtension datastoreEntityExtension = new DatastoreEntityExtension();
@BeforeEach
public void before() throws IOException {
void beforeEach() {
orgStdout = System.out;
System.setOut(new PrintStream(stdout));
tempFs.create();
}
@AfterEach
public void after() {
void afterEach() {
System.setOut(orgStdout);
tempFs.delete();
}
@Test
public void testLoadBackup() {
void testLoadBackup() {
URL backupRootFolder = Resources.getResource("google/registry/tools/datastore-export");
CompareDbBackups.main(new String[] {backupRootFolder.getPath(), backupRootFolder.getPath()});
String output = new String(stdout.toByteArray(), UTF_8);
@@ -66,11 +65,12 @@ public class CompareDbBackupsTest {
}
@Test
public void testCompareBackups() throws Exception {
void testCompareBackups() throws Exception {
// Create two directories corresponding to data dumps.
File dump1 = tempFs.newFolder("dump1");
LevelDbFileBuilder builder = new LevelDbFileBuilder(new File(dump1, "output-data1"));
Path dump1 = Files.createDirectory(tmpDir.resolve("dump1"));
Path dump2 = Files.createDirectory(tmpDir.resolve("dump2"));
LevelDbFileBuilder builder = new LevelDbFileBuilder(new File(dump1.toFile(), "output-data1"));
builder.addEntity(
EntityWrapper.from(
BASE_ID,
@@ -87,8 +87,7 @@ public class CompareDbBackupsTest {
.getEntity());
builder.build();
File dump2 = tempFs.newFolder("dump2");
builder = new LevelDbFileBuilder(new File(dump2, "output-data2"));
builder = new LevelDbFileBuilder(new File(dump2.toFile(), "output-data2"));
builder.addEntity(
EntityWrapper.from(
BASE_ID + 1,
@@ -105,7 +104,7 @@ public class CompareDbBackupsTest {
.getEntity());
builder.build();
CompareDbBackups.main(new String[] {dump1.getCanonicalPath(), dump2.getCanonicalPath()});
CompareDbBackups.main(new String[] {dump1.toString(), dump2.toString()});
String output = new String(stdout.toByteArray(), UTF_8);
assertThat(output)
.containsMatch("(?s)1 records were removed.*eeny.*1 records were added.*blutzy");
@@ -23,26 +23,26 @@ import google.registry.model.ofy.Ofy;
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.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link CountDomainsCommand}. */
public class CountDomainsCommandTest extends CommandTestCase<CountDomainsCommand> {
protected FakeClock clock = new FakeClock(DateTime.now(UTC));
@Rule public final InjectRule inject = new InjectRule();
@RegisterExtension public final InjectRule inject = new InjectRule();
@Before
public final void before() {
@BeforeEach
final void beforeEach() {
inject.setStaticField(Ofy.class, "clock", clock);
command.clock = clock;
createTlds("foo", "bar", "baz", "qux");
}
@Test
public void testSuccess_singleTld() throws Exception {
void testSuccess_singleTld() throws Exception {
for (int i = 0; i < 51; i++) {
persistActiveDomain(String.format("test-%d.foo", i));
if (i > 31) {
@@ -54,7 +54,7 @@ public class CountDomainsCommandTest extends CommandTestCase<CountDomainsCommand
}
@Test
public void testSuccess_multipleTlds() throws Exception {
void testSuccess_multipleTlds() throws Exception {
command.clock = clock;
for (int i = 0; i < 29; i++) {
persistActiveDomain(String.format("test-%d.foo", i));
@@ -22,34 +22,33 @@ import static org.junit.Assert.assertThrows;
import com.beust.jcommander.ParameterException;
import google.registry.model.registry.Registry;
import google.registry.testing.DeterministicStringGenerator;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link CreateAnchorTenantCommand}. */
public class CreateAnchorTenantCommandTest
extends EppToolCommandTestCase<CreateAnchorTenantCommand> {
class CreateAnchorTenantCommandTest extends EppToolCommandTestCase<CreateAnchorTenantCommand> {
@Before
public void initCommand() {
@BeforeEach
void beforeEach() {
command.passwordGenerator = new DeterministicStringGenerator("abcdefghijklmnopqrstuvwxyz");
}
@Test
public void testSuccess() throws Exception {
void testSuccess() throws Exception {
runCommandForced("--client=NewRegistrar", "--superuser",
"--reason=anchor-tenant-test", "--contact=jd1234", "--domain_name=example.tld");
eppVerifier.expectSuperuser().verifySent("domain_create_anchor_tenant.xml");
}
@Test
public void testSuccess_suppliedPassword() throws Exception {
void testSuccess_suppliedPassword() throws Exception {
runCommandForced("--client=NewRegistrar", "--superuser", "--password=foo",
"--reason=anchor-tenant-test", "--contact=jd1234", "--domain_name=example.tld");
eppVerifier.expectSuperuser().verifySent("domain_create_anchor_tenant_password.xml");
}
@Test
public void testSuccess_multipleWordReason() throws Exception {
void testSuccess_multipleWordReason() throws Exception {
runCommandForced("--client=NewRegistrar", "--superuser",
"--reason=\"anchor tenant test\"", "--contact=jd1234", "--domain_name=example.tld");
eppVerifier
@@ -58,21 +57,21 @@ public class CreateAnchorTenantCommandTest
}
@Test
public void testSuccess_noReason() throws Exception {
void testSuccess_noReason() throws Exception {
runCommandForced("--client=NewRegistrar", "--superuser",
"--contact=jd1234", "--domain_name=example.tld");
eppVerifier.expectSuperuser().verifySent("domain_create_anchor_tenant_no_reason.xml");
}
@Test
public void testSuccess_feeStandard() throws Exception {
void testSuccess_feeStandard() throws Exception {
runCommandForced("--client=NewRegistrar", "--superuser", "--fee",
"--reason=anchor-tenant-test", "--contact=jd1234", "--domain_name=example.tld");
eppVerifier.expectSuperuser().verifySent("domain_create_anchor_tenant_fee_standard.xml");
}
@Test
public void testSuccess_feePremium() throws Exception {
void testSuccess_feePremium() throws Exception {
createTld("tld");
persistResource(
Registry.get("tld")
@@ -85,7 +84,7 @@ public class CreateAnchorTenantCommandTest
}
@Test
public void testFailure_mainParameter() {
void testFailure_mainParameter() {
assertThrows(
ParameterException.class,
() ->
@@ -100,7 +99,7 @@ public class CreateAnchorTenantCommandTest
}
@Test
public void testFailure_missingClientId() {
void testFailure_missingClientId() {
assertThrows(
ParameterException.class,
() ->
@@ -112,7 +111,7 @@ public class CreateAnchorTenantCommandTest
}
@Test
public void testFailure_unknownFlag() {
void testFailure_unknownFlag() {
assertThrows(
ParameterException.class,
() ->
@@ -126,7 +125,7 @@ public class CreateAnchorTenantCommandTest
}
@Test
public void testFailure_missingDomainName() {
void testFailure_missingDomainName() {
assertThrows(
ParameterException.class,
() ->
@@ -139,7 +138,7 @@ public class CreateAnchorTenantCommandTest
}
@Test
public void testFailure_missingContact() {
void testFailure_missingContact() {
assertThrows(
ParameterException.class,
() ->
@@ -152,7 +151,7 @@ public class CreateAnchorTenantCommandTest
}
@Test
public void testFailure_notAsSuperuser() {
void testFailure_notAsSuperuser() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -22,14 +22,16 @@ import static org.mockito.Mockito.when;
import com.google.api.services.dns.Dns;
import com.google.api.services.dns.model.ManagedZone;
import com.google.api.services.dns.model.ManagedZoneDnsSecConfig;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
/** Unit tests for {@link CreateCdnsTld}. */
public class CreateCdnsTldTest extends CommandTestCase<CreateCdnsTld> {
class CreateCdnsTldTest extends CommandTestCase<CreateCdnsTld> {
@Mock Dns dnsService;
@Mock Dns.ManagedZones managedZones;
@@ -37,8 +39,8 @@ public class CreateCdnsTldTest extends CommandTestCase<CreateCdnsTld> {
@Captor ArgumentCaptor<String> projectId;
@Captor ArgumentCaptor<ManagedZone> requestBody;
@Before
public void setUp() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
when(dnsService.managedZones()).thenReturn(managedZones);
when(managedZones.create(projectId.capture(), requestBody.capture())).thenReturn(request);
command = new CreateCdnsTld();
@@ -57,7 +59,7 @@ public class CreateCdnsTldTest extends CommandTestCase<CreateCdnsTld> {
}
@Test
public void testBasicFunctionality() throws Exception {
void testBasicFunctionality() throws Exception {
runCommand("--dns_name=tld.", "--name=tld", "--description=test run", "--force");
verify(request).execute();
assertThat(projectId.getValue()).isEqualTo("test-project");
@@ -66,14 +68,15 @@ public class CreateCdnsTldTest extends CommandTestCase<CreateCdnsTld> {
}
@Test
public void testNameDefault() throws Exception {
void testNameDefault() throws Exception {
runCommand("--dns_name=tld.", "--description=test run", "--force");
ManagedZone zone = requestBody.getValue();
assertThat(zone).isEqualTo(createZone("cloud-dns-registry-test", "test run", "tld.", "tld."));
}
@Test
public void testSandboxTldRestrictions() throws Exception {
@MockitoSettings(strictness = Strictness.LENIENT)
void testSandboxTldRestrictions() throws Exception {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -18,19 +18,19 @@ import static org.junit.Assert.assertThrows;
import com.beust.jcommander.ParameterException;
import google.registry.testing.DeterministicStringGenerator;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link CreateContactCommand}. */
public class CreateContactCommandTest extends EppToolCommandTestCase<CreateContactCommand> {
class CreateContactCommandTest extends EppToolCommandTestCase<CreateContactCommand> {
@Before
public void initCommand() {
@BeforeEach
void beforeEach() {
command.passwordGenerator = new DeterministicStringGenerator("abcdefghijklmnopqrstuvwxyz");
}
@Test
public void testSuccess_complete() throws Exception {
void testSuccess_complete() throws Exception {
runCommandForced(
"--client=NewRegistrar",
"--id=sh8013",
@@ -51,7 +51,7 @@ public class CreateContactCommandTest extends EppToolCommandTestCase<CreateConta
}
@Test
public void testSuccess_minimal() throws Exception {
void testSuccess_minimal() throws Exception {
// Will never be the case, but tests that each field can be omitted.
// Also tests the auto-gen password.
runCommandForced("--client=NewRegistrar");
@@ -59,12 +59,12 @@ public class CreateContactCommandTest extends EppToolCommandTestCase<CreateConta
}
@Test
public void testFailure_missingClientId() {
void testFailure_missingClientId() {
assertThrows(ParameterException.class, this::runCommandForced);
}
@Test
public void testFailure_tooManyStreetLines() {
void testFailure_tooManyStreetLines() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -77,13 +77,13 @@ public class CreateContactCommandTest extends EppToolCommandTestCase<CreateConta
}
@Test
public void testFailure_badPhone() {
void testFailure_badPhone() {
assertThrows(
ParameterException.class, () -> runCommandForced("--client=NewRegistrar", "--phone=3"));
}
@Test
public void testFailure_badFax() {
void testFailure_badFax() {
assertThrows(
ParameterException.class, () -> runCommandForced("--client=NewRegistrar", "--fax=3"));
}
@@ -24,19 +24,19 @@ import com.beust.jcommander.ParameterException;
import google.registry.model.registry.Registry;
import google.registry.model.registry.label.PremiumList;
import google.registry.testing.DeterministicStringGenerator;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link CreateDomainCommand}. */
public class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomainCommand> {
class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomainCommand> {
@Before
public void initCommand() {
@BeforeEach
void beforeEach() {
command.passwordGenerator = new DeterministicStringGenerator("abcdefghijklmnopqrstuvwxyz");
}
@Test
public void testSuccess_complete() throws Exception {
void testSuccess_complete() throws Exception {
runCommandForced(
"--client=NewRegistrar",
"--period=1",
@@ -52,7 +52,7 @@ public class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomain
}
@Test
public void testSuccess_completeWithSquareBrackets() throws Exception {
void testSuccess_completeWithSquareBrackets() throws Exception {
runCommandForced(
"--client=NewRegistrar",
"--period=1",
@@ -68,7 +68,7 @@ public class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomain
}
@Test
public void testSuccess_minimal() throws Exception {
void testSuccess_minimal() throws Exception {
// Test that each optional field can be omitted. Also tests the auto-gen password.
runCommandForced(
"--client=NewRegistrar",
@@ -80,7 +80,7 @@ public class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomain
}
@Test
public void testSuccess_multipleDomains() throws Exception {
void testSuccess_multipleDomains() throws Exception {
createTld("abc");
runCommandForced(
"--client=NewRegistrar",
@@ -95,7 +95,7 @@ public class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomain
}
@Test
public void testSuccess_premiumJpyDomain() throws Exception {
void testSuccess_premiumJpyDomain() throws Exception {
createTld("baar");
persistPremiumList("baar", "parajiumu,JPY 96083");
persistResource(
@@ -118,7 +118,7 @@ public class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomain
}
@Test
public void testSuccess_multipleDomainsWithPremium() throws Exception {
void testSuccess_multipleDomainsWithPremium() throws Exception {
createTld("abc");
runCommandForced(
"--client=NewRegistrar",
@@ -139,7 +139,7 @@ public class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomain
}
@Test
public void testFailure_duplicateDomains() {
void testFailure_duplicateDomains() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -155,7 +155,7 @@ public class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomain
}
@Test
public void testFailure_missingDomain() {
void testFailure_missingDomain() {
ParameterException thrown =
assertThrows(
ParameterException.class,
@@ -169,7 +169,7 @@ public class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomain
}
@Test
public void testFailure_missingClientId() {
void testFailure_missingClientId() {
ParameterException thrown =
assertThrows(
ParameterException.class,
@@ -183,7 +183,7 @@ public class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomain
}
@Test
public void testFailure_missingRegistrant() {
void testFailure_missingRegistrant() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -197,7 +197,7 @@ public class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomain
}
@Test
public void testFailure_missingAdmins() {
void testFailure_missingAdmins() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -211,7 +211,7 @@ public class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomain
}
@Test
public void testFailure_missingTechs() {
void testFailure_missingTechs() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -225,7 +225,7 @@ public class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomain
}
@Test
public void testFailure_tooManyNameServers() {
void testFailure_tooManyNameServers() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -244,7 +244,7 @@ public class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomain
}
@Test
public void testFailure_tooManyNameServers_usingSquareBracketRange() {
void testFailure_tooManyNameServers_usingSquareBracketRange() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -260,7 +260,7 @@ public class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomain
}
@Test
public void testFailure_badPeriod() {
void testFailure_badPeriod() {
ParameterException thrown =
assertThrows(
ParameterException.class,
@@ -276,7 +276,7 @@ public class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomain
}
@Test
public void testFailure_dsRecordsNot4Parts() {
void testFailure_dsRecordsNot4Parts() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -292,7 +292,7 @@ public class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomain
}
@Test
public void testFailure_keyTagNotNumber() {
void testFailure_keyTagNotNumber() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -308,7 +308,7 @@ public class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomain
}
@Test
public void testFailure_algNotNumber() {
void testFailure_algNotNumber() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -324,7 +324,7 @@ public class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomain
}
@Test
public void testFailure_digestTypeNotNumber() {
void testFailure_digestTypeNotNumber() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -340,7 +340,7 @@ public class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomain
}
@Test
public void testFailure_digestNotHex() {
void testFailure_digestNotHex() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -356,7 +356,7 @@ public class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomain
}
@Test
public void testFailure_digestNotEvenLengthed() {
void testFailure_digestNotEvenLengthed() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -372,7 +372,7 @@ public class CreateDomainCommandTest extends EppToolCommandTestCase<CreateDomain
}
@Test
public void testFailure_cantForceCreatePremiumDomain_withoutForcePremiums() {
void testFailure_cantForceCreatePremiumDomain_withoutForcePremiums() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -19,13 +19,13 @@ import static google.registry.testing.DatastoreHelper.createTld;
import static org.junit.Assert.assertThrows;
import com.beust.jcommander.ParameterException;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link CreateHostCommand}. */
public class CreateHostCommandTest extends EppToolCommandTestCase<CreateHostCommand> {
class CreateHostCommandTest extends EppToolCommandTestCase<CreateHostCommand> {
@Test
public void testSuccess_complete() throws Exception {
void testSuccess_complete() throws Exception {
createTld("tld");
runCommandForced(
"--client=NewRegistrar",
@@ -35,7 +35,7 @@ public class CreateHostCommandTest extends EppToolCommandTestCase<CreateHostComm
}
@Test
public void testSuccess_minimal() throws Exception {
void testSuccess_minimal() throws Exception {
// Test that each optional field can be omitted.
runCommandForced(
"--client=NewRegistrar",
@@ -44,12 +44,12 @@ public class CreateHostCommandTest extends EppToolCommandTestCase<CreateHostComm
}
@Test
public void testFailure_missingHost() {
void testFailure_missingHost() {
assertThrows(ParameterException.class, () -> runCommandForced("--client=NewRegistrar"));
}
@Test
public void testFailure_invalidIpAddress() {
void testFailure_invalidIpAddress() {
createTld("tld");
IllegalArgumentException thrown =
assertThrows(
@@ -28,11 +28,9 @@ import java.nio.charset.StandardCharsets;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
/**
* Base class for common testing setup for create and update commands for Premium Lists.
*/
public abstract class CreateOrUpdatePremiumListCommandTestCase<
T extends CreateOrUpdatePremiumListCommand> extends CommandTestCase<T> {
/** Base class for common testing setup for create and update commands for Premium Lists. */
abstract class CreateOrUpdatePremiumListCommandTestCase<T extends CreateOrUpdatePremiumListCommand>
extends CommandTestCase<T> {
@Captor
ArgumentCaptor<ImmutableMap<String, String>> urlParamCaptor;
@@ -32,25 +32,25 @@ import java.io.File;
import java.io.IOException;
import javax.persistence.EntityManager;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Base class for common testing setup for create and update commands for Reserved Lists.
*
* @param <T> command type
*/
public abstract class CreateOrUpdateReservedListCommandTestCase<
abstract class CreateOrUpdateReservedListCommandTestCase<
T extends CreateOrUpdateReservedListCommand>
extends CommandTestCase<T> {
String reservedTermsPath;
String invalidReservedTermsPath;
private String invalidReservedTermsPath;
@Before
public void init() throws IOException {
File reservedTermsFile = tmpDir.newFile("xn--q9jyb4c_common-reserved.txt");
File invalidReservedTermsFile = tmpDir.newFile("reserved-terms-wontparse.csv");
@BeforeEach
void beforeEachCreateOrUpdateReservedListCommandTestCase() throws IOException {
File reservedTermsFile = tmpDir.resolve("xn--q9jyb4c_common-reserved.txt").toFile();
File invalidReservedTermsFile = tmpDir.resolve("reserved-terms-wontparse.csv").toFile();
String reservedTermsCsv =
loadFile(CreateOrUpdateReservedListCommandTestCase.class, "example_reserved_terms.csv");
Files.asCharSink(reservedTermsFile, UTF_8).write(reservedTermsCsv);
@@ -61,7 +61,7 @@ public abstract class CreateOrUpdateReservedListCommandTestCase<
}
@Test
public void testFailure_fileDoesntExist() {
void testFailure_fileDoesntExist() {
assertThat(
assertThrows(
ParameterException.class,
@@ -74,7 +74,7 @@ public abstract class CreateOrUpdateReservedListCommandTestCase<
}
@Test
public void testFailure_fileDoesntParse() {
void testFailure_fileDoesntParse() {
assertThat(
assertThrows(
IllegalArgumentException.class,
@@ -87,7 +87,7 @@ public abstract class CreateOrUpdateReservedListCommandTestCase<
}
@Test
public void testFailure_invalidLabel_includesFullDomainName() throws Exception {
void testFailure_invalidLabel_includesFullDomainName() throws Exception {
Files.asCharSink(new File(invalidReservedTermsPath), UTF_8)
.write("example.tld,FULLY_BLOCKED\n\n");
assertThat(
@@ -29,23 +29,25 @@ import com.google.common.base.VerifyException;
import com.google.common.collect.ImmutableMap;
import com.google.common.net.MediaType;
import google.registry.tools.server.CreatePremiumListAction;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
/** Unit tests for {@link CreatePremiumListCommand}. */
public class CreatePremiumListCommandTest<C extends CreatePremiumListCommand>
class CreatePremiumListCommandTest<C extends CreatePremiumListCommand>
extends CreateOrUpdatePremiumListCommandTestCase<C> {
@Mock AppEngineConnection connection;
String premiumTermsPath;
private String premiumTermsPath;
String premiumTermsCsv;
String servletPath;
private String servletPath;
@Before
public void init() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
command.setConnection(connection);
premiumTermsPath =
writeToNamedTmpFile(
@@ -61,7 +63,7 @@ public class CreatePremiumListCommandTest<C extends CreatePremiumListCommand>
}
@Test
public void testRun() throws Exception {
void testRun() throws Exception {
runCommandForced("-i=" + premiumTermsPath, "-n=foo");
assertInStdout("Successfully");
verifySentParams(
@@ -71,7 +73,7 @@ public class CreatePremiumListCommandTest<C extends CreatePremiumListCommand>
}
@Test
public void testRun_noProvidedName_usesBasenameOfInputFile() throws Exception {
void testRun_noProvidedName_usesBasenameOfInputFile() throws Exception {
runCommandForced("-i=" + premiumTermsPath);
assertInStdout("Successfully");
verifySentParams(
@@ -82,7 +84,7 @@ public class CreatePremiumListCommandTest<C extends CreatePremiumListCommand>
}
@Test
public void testRun_errorResponse() throws Exception {
void testRun_errorResponse() throws Exception {
reset(connection);
command.setConnection(connection);
when(connection.sendPostRequest(
@@ -95,13 +97,15 @@ public class CreatePremiumListCommandTest<C extends CreatePremiumListCommand>
}
@Test
public void testRun_noInputFileSpecified_throwsException() {
@MockitoSettings(strictness = Strictness.LENIENT)
void testRun_noInputFileSpecified_throwsException() {
ParameterException thrown = assertThrows(ParameterException.class, this::runCommand);
assertThat(thrown).hasMessageThat().contains("The following option is required");
}
@Test
public void testRun_invalidInputData() throws Exception {
@MockitoSettings(strictness = Strictness.LENIENT)
void testRun_invalidInputData() throws Exception {
premiumTermsPath =
writeToNamedTmpFile(
"tmp_file2",
@@ -26,7 +26,7 @@ import static org.joda.time.DateTimeZone.UTC;
import static org.junit.Assert.assertThrows;
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.beust.jcommander.ParameterException;
@@ -39,23 +39,23 @@ import java.io.IOException;
import java.util.Optional;
import org.joda.money.CurrencyUnit;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
/** Unit tests for {@link CreateRegistrarCommand}. */
public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarCommand> {
class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarCommand> {
@Mock private AppEngineConnection connection;
@Before
public void init() {
@BeforeEach
void beforeEach() {
command.setConnection(connection);
}
@Test
public void testSuccess() throws Exception {
void testSuccess() throws Exception {
DateTime before = DateTime.now(UTC);
runCommandForced(
"--name=blobio",
@@ -102,7 +102,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_alsoSaveToCloudSql() throws Exception {
void testSuccess_alsoSaveToCloudSql() throws Exception {
runCommandForced(
"--name=blobio",
"--password=\"some_password\"",
@@ -124,7 +124,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_quotedPassword() throws Exception {
void testSuccess_quotedPassword() throws Exception {
runCommandForced(
"--name=blobio",
"--password=\"some_password\"",
@@ -145,7 +145,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_registrarTypeFlag() throws Exception {
void testSuccess_registrarTypeFlag() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -165,7 +165,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_registrarStateFlag() throws Exception {
void testSuccess_registrarStateFlag() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -187,7 +187,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_allowedTldsInNonProductionEnvironment() throws Exception {
void testSuccess_allowedTldsInNonProductionEnvironment() throws Exception {
createTlds("xn--q9jyb4c", "foobar");
runCommandInEnvironment(
@@ -214,7 +214,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_allowedTldsInPDT() throws Exception {
void testSuccess_allowedTldsInPDT() throws Exception {
createTlds("xn--q9jyb4c", "foobar");
runCommandInEnvironment(
@@ -241,7 +241,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_groupCreationCanBeDisabled() throws Exception {
void testSuccess_groupCreationCanBeDisabled() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -256,11 +256,11 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
"--cc US",
"clientz");
verifyZeroInteractions(connection);
verifyNoInteractions(connection);
}
@Test
public void testFailure_groupCreationFails() throws Exception {
void testFailure_groupCreationFails() throws Exception {
when(connection.sendPostRequest(
ArgumentMatchers.anyString(),
ArgumentMatchers.anyMap(),
@@ -287,7 +287,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_groupCreationDoesntOccurOnAlphaEnv() throws Exception {
void testSuccess_groupCreationDoesntOccurOnAlphaEnv() throws Exception {
runCommandInEnvironment(
RegistryToolEnvironment.ALPHA,
"--name=blobio",
@@ -303,11 +303,11 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
"--force",
"clientz");
verifyZeroInteractions(connection);
verifyNoInteractions(connection);
}
@Test
public void testSuccess_ipAllowListFlag() throws Exception {
void testSuccess_ipAllowListFlag() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -331,7 +331,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_ipAllowListFlagNull() throws Exception {
void testSuccess_ipAllowListFlagNull() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -353,7 +353,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_clientCertFileFlag() throws Exception {
void testSuccess_clientCertFileFlag() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -376,7 +376,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_clientCertHashFlag() throws Exception {
void testSuccess_clientCertHashFlag() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -399,7 +399,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_failoverClientCertFileFlag() throws Exception {
void testSuccess_failoverClientCertFileFlag() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -425,7 +425,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_ianaId() throws Exception {
void testSuccess_ianaId() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -446,7 +446,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_billingId() throws Exception {
void testSuccess_billingId() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -468,7 +468,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_poNumber() throws Exception {
void testSuccess_poNumber() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -490,7 +490,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_billingAccountMap() throws Exception {
void testSuccess_billingAccountMap() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -513,7 +513,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_billingAccountMap_doesNotContainEntryForTldAllowed() {
void testFailure_billingAccountMap_doesNotContainEntryForTldAllowed() {
createTlds("foo");
IllegalArgumentException thrown =
@@ -541,7 +541,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_billingAccountMap_onlyAppliesToRealRegistrar() throws Exception {
void testSuccess_billingAccountMap_onlyAppliesToRealRegistrar() throws Exception {
createTlds("foo");
runCommandForced(
@@ -565,7 +565,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_streetAddress() throws Exception {
void testSuccess_streetAddress() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -597,7 +597,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_email() throws Exception {
void testSuccess_email() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -619,7 +619,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_fallBackToIcannReferralEmail() throws Exception {
void testSuccess_fallBackToIcannReferralEmail() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -640,7 +640,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_url() throws Exception {
void testSuccess_url() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -662,7 +662,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_phone() throws Exception {
void testSuccess_phone() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -684,7 +684,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_optionalParamsAsNull() throws Exception {
void testSuccess_optionalParamsAsNull() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -715,7 +715,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_optionalParamsAsEmptyString() throws Exception {
void testSuccess_optionalParamsAsEmptyString() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -746,7 +746,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_blockPremiumNames() throws Exception {
void testSuccess_blockPremiumNames() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -768,7 +768,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_noBlockPremiumNames() throws Exception {
void testSuccess_noBlockPremiumNames() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -790,7 +790,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_registryLockAllowed() throws Exception {
void testSuccess_registryLockAllowed() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -812,7 +812,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_registryLockDisallowed() throws Exception {
void testSuccess_registryLockDisallowed() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -834,7 +834,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_badPhoneNumber() {
void testFailure_badPhoneNumber() {
ParameterException thrown =
assertThrows(
ParameterException.class,
@@ -857,7 +857,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_badPhoneNumber2() {
void testFailure_badPhoneNumber2() {
ParameterException thrown =
assertThrows(
ParameterException.class,
@@ -880,7 +880,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_fax() throws Exception {
void testSuccess_fax() throws Exception {
runCommandForced(
"--name=blobio",
"--password=some_password",
@@ -902,7 +902,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_missingRegistrarType() {
void testFailure_missingRegistrarType() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -922,7 +922,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_invalidRegistrarType() {
void testFailure_invalidRegistrarType() {
assertThrows(
ParameterException.class,
() ->
@@ -940,7 +940,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_invalidRegistrarState() {
void testFailure_invalidRegistrarState() {
assertThrows(
ParameterException.class,
() ->
@@ -961,7 +961,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_allowedTldDoesNotExist() {
void testFailure_allowedTldDoesNotExist() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -982,7 +982,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_allowedTldsInRealWithoutAbuseContact() {
void testFailure_allowedTldsInRealWithoutAbuseContact() {
createTlds("xn--q9jyb4c", "foobar");
IllegalArgumentException thrown =
assertThrows(
@@ -1008,7 +1008,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_invalidIpAllowListFlag() {
void testFailure_invalidIpAllowListFlag() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -1029,7 +1029,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testSuccess_ipAllowListFlagWithNull() {
void testSuccess_ipAllowListFlagWithNull() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -1050,7 +1050,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_invalidCertFileContents() {
void testFailure_invalidCertFileContents() {
assertThrows(
Exception.class,
() ->
@@ -1071,7 +1071,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_invalidFailoverCertFileContents() {
void testFailure_invalidFailoverCertFileContents() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -1092,7 +1092,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_certHashAndCertFile() {
void testFailure_certHashAndCertFile() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -1114,7 +1114,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_certHashNotBase64() {
void testFailure_certHashNotBase64() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -1137,7 +1137,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_certHashNotA256BitValue() {
void testFailure_certHashNotA256BitValue() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -1160,7 +1160,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_missingName() {
void testFailure_missingName() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -1181,7 +1181,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_missingPassword() {
void testFailure_missingPassword() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -1202,7 +1202,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_emptyPassword() {
void testFailure_emptyPassword() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -1224,7 +1224,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_clientIdTooShort() {
void testFailure_clientIdTooShort() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -1244,7 +1244,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_clientIdTooLong() {
void testFailure_clientIdTooLong() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -1264,7 +1264,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_missingClientId() {
void testFailure_missingClientId() {
assertThrows(
ParameterException.class,
() ->
@@ -1284,7 +1284,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_missingStreetLines() {
void testFailure_missingStreetLines() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -1303,7 +1303,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_missingCity() {
void testFailure_missingCity() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -1324,7 +1324,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_missingState() {
void testFailure_missingState() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -1345,7 +1345,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_missingZip() {
void testFailure_missingZip() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -1366,7 +1366,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_missingCc() {
void testFailure_missingCc() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -1387,7 +1387,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_invalidCc() {
void testFailure_invalidCc() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -1409,7 +1409,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_tooManyStreetLines() {
void testFailure_tooManyStreetLines() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -1432,7 +1432,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_tooFewStreetLines() {
void testFailure_tooFewStreetLines() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -1452,7 +1452,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_missingIanaIdForRealRegistrar() {
void testFailure_missingIanaIdForRealRegistrar() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -1471,7 +1471,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_negativeIanaId() {
void testFailure_negativeIanaId() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -1491,7 +1491,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_nonIntegerIanaId() {
void testFailure_nonIntegerIanaId() {
assertThrows(
ParameterException.class,
() ->
@@ -1511,7 +1511,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_negativeBillingId() {
void testFailure_negativeBillingId() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -1532,7 +1532,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_nonIntegerBillingId() {
void testFailure_nonIntegerBillingId() {
assertThrows(
ParameterException.class,
() ->
@@ -1553,7 +1553,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_missingPhonePasscode() {
void testFailure_missingPhonePasscode() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -1572,7 +1572,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_missingIcannReferralEmail() {
void testFailure_missingIcannReferralEmail() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -1593,7 +1593,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_passcodeTooShort() {
void testFailure_passcodeTooShort() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -1613,7 +1613,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_passcodeTooLong() {
void testFailure_passcodeTooLong() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -1633,7 +1633,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_invalidPasscode() {
void testFailure_invalidPasscode() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -1653,7 +1653,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_twoClientsSpecified() {
void testFailure_twoClientsSpecified() {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -1674,7 +1674,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_unknownFlag() {
void testFailure_unknownFlag() {
assertThrows(
ParameterException.class,
() ->
@@ -1695,7 +1695,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_alreadyExists() {
void testFailure_alreadyExists() {
persistNewRegistrar("existing", "Existing Registrar", Registrar.Type.REAL, 1L);
IllegalStateException thrown =
assertThrows(
@@ -1718,7 +1718,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_registrarNameSimilarToExisting() {
void testFailure_registrarNameSimilarToExisting() {
// Note that "tHeRe GiStRaR" normalizes identically to "The Registrar", which is created by
// AppEngineRule.
IllegalArgumentException thrown =
@@ -1746,7 +1746,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_clientIdNormalizesToExisting() {
void testFailure_clientIdNormalizesToExisting() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -1772,7 +1772,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_clientIdIsInvalidFormat() {
void testFailure_clientIdIsInvalidFormat() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -1797,7 +1797,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_phone() {
void testFailure_phone() {
assertThrows(
ParameterException.class,
() ->
@@ -1818,7 +1818,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_fax() {
void testFailure_fax() {
assertThrows(
ParameterException.class,
() ->
@@ -1839,7 +1839,7 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
}
@Test
public void testFailure_badEmail() {
void testFailure_badEmail() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -21,23 +21,22 @@ import static org.mockito.Mockito.verify;
import com.google.common.collect.ImmutableMap;
import com.google.common.net.MediaType;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
/** Unit tests for {@link CreateRegistrarGroupsCommand}. */
public class CreateRegistrarGroupsCommandTest extends
CommandTestCase<CreateRegistrarGroupsCommand> {
class CreateRegistrarGroupsCommandTest extends CommandTestCase<CreateRegistrarGroupsCommand> {
@Mock private AppEngineConnection connection;
@Before
public void init() {
@BeforeEach
void beforeEach() {
command.setConnection(connection);
}
@Test
public void test_createGroupsForTwoRegistrars() throws Exception {
void test_createGroupsForTwoRegistrars() throws Exception {
runCommandForced("NewRegistrar", "TheRegistrar");
verify(connection)
.sendPostRequest(
@@ -55,7 +54,7 @@ public class CreateRegistrarGroupsCommandTest extends
}
@Test
public void test_throwsExceptionForNonExistentRegistrar() {
void test_throwsExceptionForNonExistentRegistrar() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -30,20 +30,20 @@ import google.registry.model.registry.label.ReservedList;
import google.registry.model.registry.label.ReservedList.ReservedListEntry;
import google.registry.model.registry.label.ReservedListSqlDao;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link CreateReservedListCommand}. */
public class CreateReservedListCommandTest extends
CreateOrUpdateReservedListCommandTestCase<CreateReservedListCommand> {
class CreateReservedListCommandTest
extends CreateOrUpdateReservedListCommandTestCase<CreateReservedListCommand> {
@Before
public void initTest() {
@BeforeEach
void beforeEach() {
createTlds("xn--q9jyb4c", "soy");
}
@Test
public void testSuccess() throws Exception {
void testSuccess() throws Exception {
runCommandForced("--name=xn--q9jyb4c_common-reserved", "--input=" + reservedTermsPath);
assertThat(ReservedList.get("xn--q9jyb4c_common-reserved")).isPresent();
ReservedList reservedList = ReservedList.get("xn--q9jyb4c_common-reserved").get();
@@ -53,13 +53,13 @@ public class CreateReservedListCommandTest extends
}
@Test
public void testSuccess_unspecifiedNameDefaultsToFileName() throws Exception {
void testSuccess_unspecifiedNameDefaultsToFileName() throws Exception {
runCommandForced("--input=" + reservedTermsPath);
assertThat(ReservedList.get("xn--q9jyb4c_common-reserved")).isPresent();
}
@Test
public void testSuccess_timestampsSetCorrectly() throws Exception {
void testSuccess_timestampsSetCorrectly() throws Exception {
DateTime before = DateTime.now(UTC);
runCommandForced("--input=" + reservedTermsPath);
assertThat(ReservedList.get("xn--q9jyb4c_common-reserved")).isPresent();
@@ -69,28 +69,28 @@ public class CreateReservedListCommandTest extends
}
@Test
public void testSuccess_shouldPublishDefaultsToTrue() throws Exception {
void testSuccess_shouldPublishDefaultsToTrue() throws Exception {
runCommandForced("--input=" + reservedTermsPath);
assertThat(ReservedList.get("xn--q9jyb4c_common-reserved")).isPresent();
assertThat(ReservedList.get("xn--q9jyb4c_common-reserved").get().getShouldPublish()).isTrue();
}
@Test
public void testSuccess_shouldPublishSetToTrue_works() throws Exception {
void testSuccess_shouldPublishSetToTrue_works() throws Exception {
runCommandForced("--input=" + reservedTermsPath, "--should_publish=true");
assertThat(ReservedList.get("xn--q9jyb4c_common-reserved")).isPresent();
assertThat(ReservedList.get("xn--q9jyb4c_common-reserved").get().getShouldPublish()).isTrue();
}
@Test
public void testSuccess_shouldPublishSetToFalse_works() throws Exception {
void testSuccess_shouldPublishSetToFalse_works() throws Exception {
runCommandForced("--input=" + reservedTermsPath, "--should_publish=false");
assertThat(ReservedList.get("xn--q9jyb4c_common-reserved")).isPresent();
assertThat(ReservedList.get("xn--q9jyb4c_common-reserved").get().getShouldPublish()).isFalse();
}
@Test
public void testFailure_reservedListWithThatNameAlreadyExists() {
void testFailure_reservedListWithThatNameAlreadyExists() {
ReservedList rl = persistReservedList("xn--q9jyb4c_foo", "jones,FULLY_BLOCKED");
persistResource(Registry.get("xn--q9jyb4c").asBuilder().setReservedLists(rl).build());
IllegalArgumentException thrown =
@@ -101,90 +101,90 @@ public class CreateReservedListCommandTest extends
}
@Test
public void testNamingRules_commonReservedList() throws Exception {
void testNamingRules_commonReservedList() throws Exception {
runCommandForced("--name=common_abuse-list", "--input=" + reservedTermsPath);
assertThat(ReservedList.get("common_abuse-list")).isPresent();
}
@Test
public void testNamingRules_tldThatDoesNotExist_succeedsWithOverride() throws Exception {
void testNamingRules_tldThatDoesNotExist_succeedsWithOverride() throws Exception {
runNameTestWithOverride("footld_reserved-list");
}
@Test
public void testNamingRules_tldThatDoesNotExist_failsWithoutOverride() {
void testNamingRules_tldThatDoesNotExist_failsWithoutOverride() {
runNameTestExpectedFailure("footld_reserved-list", "TLD footld does not exist");
}
@Test
public void testNamingRules_underscoreIsMissing_succeedsWithOverride() throws Exception {
void testNamingRules_underscoreIsMissing_succeedsWithOverride() throws Exception {
runNameTestWithOverride("random-reserved-list");
}
@Test
public void testNamingRules_underscoreIsMissing_failsWithoutOverride() {
void testNamingRules_underscoreIsMissing_failsWithoutOverride() {
runNameTestExpectedFailure("random-reserved-list", INVALID_FORMAT_ERROR_MESSAGE);
}
@Test
public void testNamingRules_secondHalfOfNameIsMissing_succeedsWithOverride() throws Exception {
void testNamingRules_secondHalfOfNameIsMissing_succeedsWithOverride() throws Exception {
runNameTestWithOverride("soy_");
}
@Test
public void testNamingRules_secondHalfOfNameIsMissing_failsWithoutOverride() {
void testNamingRules_secondHalfOfNameIsMissing_failsWithoutOverride() {
runNameTestExpectedFailure("soy_", INVALID_FORMAT_ERROR_MESSAGE);
}
@Test
public void testNamingRules_onlyTldIsSpecifiedAsName_succeedsWithOverride() throws Exception {
void testNamingRules_onlyTldIsSpecifiedAsName_succeedsWithOverride() throws Exception {
runNameTestWithOverride("soy");
}
@Test
public void testNamingRules_onlyTldIsSpecifiedAsName_failsWithoutOverride() {
void testNamingRules_onlyTldIsSpecifiedAsName_failsWithoutOverride() {
runNameTestExpectedFailure("soy", INVALID_FORMAT_ERROR_MESSAGE);
}
@Test
public void testNamingRules_commonAsListName_succeedsWithOverride() throws Exception {
void testNamingRules_commonAsListName_succeedsWithOverride() throws Exception {
runNameTestWithOverride("invalidtld_common");
}
@Test
public void testNamingRules_commonAsListName_failsWithoutOverride() {
void testNamingRules_commonAsListName_failsWithoutOverride() {
runNameTestExpectedFailure("invalidtld_common", "TLD invalidtld does not exist");
}
@Test
public void testNamingRules_too_many_underscores_succeedsWithOverride() throws Exception {
void testNamingRules_too_many_underscores_succeedsWithOverride() throws Exception {
runNameTestWithOverride("soy_buffalo_buffalo_buffalo");
}
@Test
public void testNamingRules_too_many_underscores_failsWithoutOverride() {
void testNamingRules_too_many_underscores_failsWithoutOverride() {
runNameTestExpectedFailure("soy_buffalo_buffalo_buffalo", INVALID_FORMAT_ERROR_MESSAGE);
}
@Test
public void testNamingRules_withWeirdCharacters_succeedsWithOverride() throws Exception {
void testNamingRules_withWeirdCharacters_succeedsWithOverride() throws Exception {
runNameTestWithOverride("soy_$oy");
}
@Test
public void testNamingRules_withWeirdCharacters_failsWithoutOverride() {
void testNamingRules_withWeirdCharacters_failsWithoutOverride() {
runNameTestExpectedFailure("soy_$oy", INVALID_FORMAT_ERROR_MESSAGE);
}
@Test
public void testSaveToCloudSql_succeeds() throws Exception {
void testSaveToCloudSql_succeeds() throws Exception {
runCommandForced("--name=xn--q9jyb4c_common-reserved", "--input=" + reservedTermsPath);
verifyXnq9jyb4cInDatastore();
verifyXnq9jyb4cInCloudSql();
}
@Test
public void testSaveToCloudSql_noExceptionThrownWhenSaveFail() throws Exception {
void testSaveToCloudSql_noExceptionThrownWhenSaveFail() throws Exception {
// Note that, during the dual-write phase, we want to make sure that no exception will be
// thrown if saving reserved list to Cloud SQL fails.
ReservedListSqlDao.save(
@@ -38,14 +38,14 @@ import java.math.BigDecimal;
import org.joda.money.Money;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link CreateTldCommand}. */
public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
@Before
public void init() {
@BeforeEach
void beforeEach() {
persistReservedList("common_abuse", "baa,FULLY_BLOCKED");
persistReservedList("xn--q9jyb4c_abuse", "lamb,FULLY_BLOCKED");
persistReservedList("tld_banned", "kilo,FULLY_BLOCKED", "lima,FULLY_BLOCKED");
@@ -55,7 +55,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess() throws Exception {
void testSuccess() throws Exception {
DateTime before = DateTime.now(UTC);
runCommandForced("xn--q9jyb4c", "--roid_suffix=Q9JYB4C", "--dns_writers=FooDnsWriter");
DateTime after = DateTime.now(UTC);
@@ -72,7 +72,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testFailure_multipleArguments() {
void testFailure_multipleArguments() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -83,7 +83,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testFailure_multipleDuplicateArguments() {
void testFailure_multipleDuplicateArguments() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -94,7 +94,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess_initialTldStateFlag() throws Exception {
void testSuccess_initialTldStateFlag() throws Exception {
runCommandForced(
"--initial_tld_state=GENERAL_AVAILABILITY",
"--roid_suffix=Q9JYB4C",
@@ -105,7 +105,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess_initialRenewBillingCostFlag() throws Exception {
void testSuccess_initialRenewBillingCostFlag() throws Exception {
runCommandForced(
"--initial_renew_billing_cost=\"USD 42.42\"",
"--roid_suffix=Q9JYB4C",
@@ -116,7 +116,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess_eapFeeSchedule() throws Exception {
void testSuccess_eapFeeSchedule() throws Exception {
DateTime now = DateTime.now(UTC);
DateTime tomorrow = now.plusDays(1);
runCommandForced(
@@ -137,7 +137,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess_addGracePeriodFlag() throws Exception {
void testSuccess_addGracePeriodFlag() throws Exception {
runCommandForced(
"--add_grace_period=PT300S",
"--roid_suffix=Q9JYB4C",
@@ -147,27 +147,27 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess_roidSuffixWorks() throws Exception {
void testSuccess_roidSuffixWorks() throws Exception {
runCommandForced("--roid_suffix=RSUFFIX", "--dns_writers=VoidDnsWriter", "tld");
assertThat(Registry.get("tld").getRoidSuffix()).isEqualTo("RSUFFIX");
}
@Test
public void testSuccess_escrow() throws Exception {
void testSuccess_escrow() throws Exception {
runCommandForced(
"--escrow=true", "--roid_suffix=Q9JYB4C", "--dns_writers=VoidDnsWriter", "xn--q9jyb4c");
assertThat(Registry.get("xn--q9jyb4c").getEscrowEnabled()).isTrue();
}
@Test
public void testSuccess_noEscrow() throws Exception {
void testSuccess_noEscrow() throws Exception {
runCommandForced(
"--escrow=false", "--roid_suffix=Q9JYB4C", "--dns_writers=VoidDnsWriter", "xn--q9jyb4c");
assertThat(Registry.get("xn--q9jyb4c").getEscrowEnabled()).isFalse();
}
@Test
public void testSuccess_redemptionGracePeriodFlag() throws Exception {
void testSuccess_redemptionGracePeriodFlag() throws Exception {
runCommandForced(
"--redemption_grace_period=PT300S",
"--roid_suffix=Q9JYB4C",
@@ -178,7 +178,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess_pendingDeleteLengthFlag() throws Exception {
void testSuccess_pendingDeleteLengthFlag() throws Exception {
runCommandForced(
"--pending_delete_length=PT300S",
"--roid_suffix=Q9JYB4C",
@@ -188,7 +188,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess_automaticTransferLengthFlag() throws Exception {
void testSuccess_automaticTransferLengthFlag() throws Exception {
runCommandForced(
"--automatic_transfer_length=PT300S",
"--roid_suffix=Q9JYB4C",
@@ -199,7 +199,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess_createBillingCostFlag() throws Exception {
void testSuccess_createBillingCostFlag() throws Exception {
runCommandForced(
"--create_billing_cost=\"USD 42.42\"",
"--roid_suffix=Q9JYB4C",
@@ -209,7 +209,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess_restoreBillingCostFlag() throws Exception {
void testSuccess_restoreBillingCostFlag() throws Exception {
runCommandForced(
"--restore_billing_cost=\"USD 42.42\"",
"--roid_suffix=Q9JYB4C",
@@ -220,7 +220,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess_serverStatusChangeCostFlag() throws Exception {
void testSuccess_serverStatusChangeCostFlag() throws Exception {
runCommandForced(
"--server_status_change_cost=\"USD 42.42\"",
"--roid_suffix=Q9JYB4C",
@@ -231,7 +231,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess_nonUsdBillingCostFlag() throws Exception {
void testSuccess_nonUsdBillingCostFlag() throws Exception {
runCommandForced(
"--create_billing_cost=\"JPY 12345\"",
"--restore_billing_cost=\"JPY 67890\"",
@@ -247,7 +247,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess_multipartTld() throws Exception {
void testSuccess_multipartTld() throws Exception {
runCommandForced("co.uk", "--roid_suffix=COUK", "--dns_writers=VoidDnsWriter");
Registry registry = Registry.get("co.uk");
@@ -259,7 +259,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess_setReservedLists() throws Exception {
void testSuccess_setReservedLists() throws Exception {
runCommandForced(
"--reserved_lists=xn--q9jyb4c_abuse,common_abuse",
"--roid_suffix=Q9JYB4C",
@@ -270,7 +270,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testFailure_invalidAddGracePeriod() {
void testFailure_invalidAddGracePeriod() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -284,7 +284,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testFailure_invalidRedemptionGracePeriod() {
void testFailure_invalidRedemptionGracePeriod() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -298,7 +298,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testFailure_invalidPendingDeleteLength() {
void testFailure_invalidPendingDeleteLength() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -312,7 +312,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testFailure_invalidTldState() {
void testFailure_invalidTldState() {
ParameterException thrown =
assertThrows(
ParameterException.class,
@@ -326,7 +326,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testFailure_bothTldStateFlags() {
void testFailure_bothTldStateFlags() {
DateTime now = DateTime.now(UTC);
IllegalArgumentException thrown =
assertThrows(
@@ -345,7 +345,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testFailure_negativeInitialRenewBillingCost() {
void testFailure_negativeInitialRenewBillingCost() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -359,7 +359,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testFailure_invalidEapCurrency() {
void testFailure_invalidEapCurrency() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -373,7 +373,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testFailure_noTldName() {
void testFailure_noTldName() {
ParameterException thrown = assertThrows(ParameterException.class, this::runCommandForced);
assertThat(thrown)
.hasMessageThat()
@@ -381,7 +381,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testFailure_noDnsWriter() {
void testFailure_noDnsWriter() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -390,7 +390,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testFailure_alreadyExists() {
void testFailure_alreadyExists() {
createTld("xn--q9jyb4c");
IllegalStateException thrown =
assertThrows(
@@ -402,7 +402,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testFailure_tldStartsWithDigit() {
void testFailure_tldStartsWithDigit() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -411,7 +411,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess_setAllowedRegistrants() throws Exception {
void testSuccess_setAllowedRegistrants() throws Exception {
runCommandForced(
"--allowed_registrants=alice,bob",
"--roid_suffix=Q9JYB4C",
@@ -422,7 +422,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess_setAllowedNameservers() throws Exception {
void testSuccess_setAllowedNameservers() throws Exception {
runCommandForced(
"--allowed_nameservers=ns1.example.com,ns2.example.com",
"--roid_suffix=Q9JYB4C",
@@ -433,22 +433,22 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess_setCommonReservedListOnTld() throws Exception {
void testSuccess_setCommonReservedListOnTld() throws Exception {
runSuccessfulReservedListsTest("common_abuse");
}
@Test
public void testSuccess_setTldSpecificReservedListOnTld() throws Exception {
void testSuccess_setTldSpecificReservedListOnTld() throws Exception {
runSuccessfulReservedListsTest("xn--q9jyb4c_abuse");
}
@Test
public void testSuccess_setCommonReservedListAndTldSpecificReservedListOnTld() throws Exception {
void testSuccess_setCommonReservedListAndTldSpecificReservedListOnTld() throws Exception {
runSuccessfulReservedListsTest("common_abuse,xn--q9jyb4c_abuse");
}
@Test
public void testFailure_setReservedListFromOtherTld() {
void testFailure_setReservedListFromOtherTld() {
runFailureReservedListsTest(
"tld_banned",
IllegalArgumentException.class,
@@ -456,12 +456,12 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess_setReservedListFromOtherTld_withOverride() throws Exception {
void testSuccess_setReservedListFromOtherTld_withOverride() throws Exception {
runReservedListsTestOverride("tld_banned");
}
@Test
public void testFailure_setCommonAndReservedListFromOtherTld() {
void testFailure_setCommonAndReservedListFromOtherTld() {
runFailureReservedListsTest(
"common_abuse,tld_banned",
IllegalArgumentException.class,
@@ -469,7 +469,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess_setCommonAndReservedListFromOtherTld_withOverride() throws Exception {
void testSuccess_setCommonAndReservedListFromOtherTld_withOverride() throws Exception {
runReservedListsTestOverride("common_abuse,tld_banned");
String errMsg =
"Error overridden: The reserved list(s) tld_banned "
@@ -478,7 +478,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testFailure_setMultipleReservedListsFromOtherTld() {
void testFailure_setMultipleReservedListsFromOtherTld() {
runFailureReservedListsTest(
"tld_banned,soy_expurgated",
IllegalArgumentException.class,
@@ -486,12 +486,12 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess_setMultipleReservedListsFromOtherTld_withOverride() throws Exception {
void testSuccess_setMultipleReservedListsFromOtherTld_withOverride() throws Exception {
runReservedListsTestOverride("tld_banned,soy_expurgated");
}
@Test
public void testFailure_setNonExistentReservedLists() {
void testFailure_setNonExistentReservedLists() {
runFailureReservedListsTest(
"xn--q9jyb4c_asdf,common_asdsdgh",
IllegalArgumentException.class,
@@ -499,7 +499,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess_setPremiumList() throws Exception {
void testSuccess_setPremiumList() throws Exception {
runCommandForced(
"--premium_list=xn--q9jyb4c",
"--roid_suffix=Q9JYB4C",
@@ -509,7 +509,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess_setDriveFolderIdToValue() throws Exception {
void testSuccess_setDriveFolderIdToValue() throws Exception {
runCommandForced(
"--drive_folder_id=madmax2030",
"--roid_suffix=Q9JYB4C",
@@ -519,7 +519,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testSuccess_setDriveFolderIdToNull() throws Exception {
void testSuccess_setDriveFolderIdToNull() throws Exception {
runCommandForced(
"--drive_folder_id=null",
"--roid_suffix=Q9JYB4C",
@@ -529,7 +529,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testFailure_setPremiumListThatDoesntExist() {
void testFailure_setPremiumListThatDoesntExist() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -543,7 +543,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
}
@Test
public void testFailure_specifiedDnsWriters_dontExist() {
void testFailure_specifiedDnsWriters_dontExist() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -29,19 +29,22 @@ import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableMap;
import com.google.common.net.MediaType;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
/** Unit tests for {@link CurlCommand}. */
public class CurlCommandTest extends CommandTestCase<CurlCommand> {
class CurlCommandTest extends CommandTestCase<CurlCommand> {
@Mock private AppEngineConnection connection;
@Mock private AppEngineConnection connectionForService;
@Before
public void init() {
@BeforeEach
void beforeEach() {
command.setConnection(connection);
when(connection.withService(any())).thenReturn(connectionForService);
}
@@ -49,7 +52,7 @@ public class CurlCommandTest extends CommandTestCase<CurlCommand> {
@Captor ArgumentCaptor<ImmutableMap<String, String>> urlParamCaptor;
@Test
public void testGetInvocation() throws Exception {
void testGetInvocation() throws Exception {
runCommand("--path=/foo/bar?a=1&b=2", "--service=TOOLS");
verify(connection).withService(TOOLS);
verifyNoMoreInteractions(connection);
@@ -58,7 +61,7 @@ public class CurlCommandTest extends CommandTestCase<CurlCommand> {
}
@Test
public void testExplicitGetInvocation() throws Exception {
void testExplicitGetInvocation() throws Exception {
runCommand("--path=/foo/bar?a=1&b=2", "--request=GET", "--service=BACKEND");
verify(connection).withService(BACKEND);
verifyNoMoreInteractions(connection);
@@ -67,7 +70,7 @@ public class CurlCommandTest extends CommandTestCase<CurlCommand> {
}
@Test
public void testPostInvocation() throws Exception {
void testPostInvocation() throws Exception {
runCommand("--path=/foo/bar?a=1&b=2", "--data=some data", "--service=DEFAULT");
verify(connection).withService(DEFAULT);
verifyNoMoreInteractions(connection);
@@ -80,7 +83,7 @@ public class CurlCommandTest extends CommandTestCase<CurlCommand> {
}
@Test
public void testPostInvocation_withContentType() throws Exception {
void testPostInvocation_withContentType() throws Exception {
runCommand(
"--path=/foo/bar?a=1&b=2",
"--data=some data",
@@ -97,7 +100,8 @@ public class CurlCommandTest extends CommandTestCase<CurlCommand> {
}
@Test
public void testPostInvocation_badContentType() throws Exception {
@MockitoSettings(strictness = Strictness.LENIENT)
void testPostInvocation_badContentType() throws Exception {
assertThrows(
IllegalArgumentException.class,
() ->
@@ -111,7 +115,7 @@ public class CurlCommandTest extends CommandTestCase<CurlCommand> {
}
@Test
public void testMultiDataPost() throws Exception {
void testMultiDataPost() throws Exception {
runCommand(
"--path=/foo/bar?a=1&b=2", "--data=first=100", "-d", "second=200", "--service=PUBAPI");
verify(connection).withService(PUBAPI);
@@ -125,7 +129,7 @@ public class CurlCommandTest extends CommandTestCase<CurlCommand> {
}
@Test
public void testDataDoesntSplit() throws Exception {
void testDataDoesntSplit() throws Exception {
runCommand(
"--path=/foo/bar?a=1&b=2", "--data=one,two", "--service=PUBAPI");
verify(connection).withService(PUBAPI);
@@ -139,7 +143,7 @@ public class CurlCommandTest extends CommandTestCase<CurlCommand> {
}
@Test
public void testExplicitPostInvocation() throws Exception {
void testExplicitPostInvocation() throws Exception {
runCommand("--path=/foo/bar?a=1&b=2", "--request=POST", "--service=TOOLS");
verify(connection).withService(TOOLS);
verifyNoMoreInteractions(connection);
@@ -152,7 +156,8 @@ public class CurlCommandTest extends CommandTestCase<CurlCommand> {
}
@Test
public void testGetWithBody() throws Exception {
@MockitoSettings(strictness = Strictness.LENIENT)
void testGetWithBody() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -27,12 +27,11 @@ import google.registry.model.domain.token.AllocationToken.TokenType;
import google.registry.model.reporting.HistoryEntry;
import java.util.Collection;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link DeleteAllocationTokensCommand}. */
public class DeleteAllocationTokensCommandTest
extends CommandTestCase<DeleteAllocationTokensCommand> {
class DeleteAllocationTokensCommandTest extends CommandTestCase<DeleteAllocationTokensCommand> {
private AllocationToken preRed1;
private AllocationToken preRed2;
@@ -41,8 +40,8 @@ public class DeleteAllocationTokensCommandTest
private AllocationToken othrRed;
private AllocationToken othrNot;
@Before
public void init() {
@BeforeEach
void beforeEach() {
createTlds("foo", "bar");
preRed1 = persistToken("prefix12345AA", null, true);
preRed2 = persistToken("prefixgh8907a", null, true);
@@ -53,7 +52,7 @@ public class DeleteAllocationTokensCommandTest
}
@Test
public void test_deleteOnlyUnredeemedTokensWithPrefix() throws Exception {
void test_deleteOnlyUnredeemedTokensWithPrefix() throws Exception {
runCommandForced("--prefix", "prefix");
assertThat(reloadTokens(preNot1, preNot2)).isEmpty();
assertThat(reloadTokens(preRed1, preRed2, othrRed, othrNot))
@@ -61,7 +60,7 @@ public class DeleteAllocationTokensCommandTest
}
@Test
public void test_deleteSingleAllocationToken() throws Exception {
void test_deleteSingleAllocationToken() throws Exception {
runCommandForced("--prefix", "asdgfho7HASDS");
assertThat(reloadTokens(othrNot)).isEmpty();
assertThat(reloadTokens(preRed1, preRed2, preNot1, preNot2, othrRed))
@@ -69,7 +68,7 @@ public class DeleteAllocationTokensCommandTest
}
@Test
public void test_deleteParticularTokens() throws Exception {
void test_deleteParticularTokens() throws Exception {
runCommandForced("--tokens", "prefix2978204,asdgfho7HASDS");
assertThat(reloadTokens(preNot1, othrNot)).isEmpty();
assertThat(reloadTokens(preRed1, preRed2, preNot2, othrRed))
@@ -77,14 +76,14 @@ public class DeleteAllocationTokensCommandTest
}
@Test
public void test_deleteTokensWithNonExistentPrefix_doesNothing() throws Exception {
void test_deleteTokensWithNonExistentPrefix_doesNothing() throws Exception {
runCommandForced("--prefix", "nonexistent");
assertThat(reloadTokens(preRed1, preRed2, preNot1, preNot2, othrRed, othrNot))
.containsExactly(preRed1, preRed2, preNot1, preNot2, othrRed, othrNot);
}
@Test
public void test_dryRun_deletesNothing() throws Exception {
void test_dryRun_deletesNothing() throws Exception {
runCommandForced("--prefix", "prefix", "--dry_run");
assertThat(reloadTokens(preRed1, preRed2, preNot1, preNot2, othrRed, othrNot))
.containsExactly(preRed1, preRed2, preNot1, preNot2, othrRed, othrNot);
@@ -92,7 +91,7 @@ public class DeleteAllocationTokensCommandTest
}
@Test
public void test_defaultOptions_doesntDeletePerDomainTokens() throws Exception {
void test_defaultOptions_doesntDeletePerDomainTokens() throws Exception {
AllocationToken preDom1 = persistToken("prefixasdfg897as", "foo.bar", false);
AllocationToken preDom2 = persistToken("prefix98HAZXadbn", "foo.bar", true);
runCommandForced("--prefix", "prefix");
@@ -102,7 +101,7 @@ public class DeleteAllocationTokensCommandTest
}
@Test
public void test_withDomains_doesDeletePerDomainTokens() throws Exception {
void test_withDomains_doesDeletePerDomainTokens() throws Exception {
AllocationToken preDom1 = persistToken("prefixasdfg897as", "foo.bar", false);
AllocationToken preDom2 = persistToken("prefix98HAZXadbn", "foo.bar", true);
runCommandForced("--prefix", "prefix", "--with_domains");
@@ -112,7 +111,7 @@ public class DeleteAllocationTokensCommandTest
}
@Test
public void testSkipUnlimitedUseTokens() throws Exception {
void testSkipUnlimitedUseTokens() throws Exception {
AllocationToken unlimitedUseToken =
persistResource(
new AllocationToken.Builder()
@@ -124,7 +123,7 @@ public class DeleteAllocationTokensCommandTest
}
@Test
public void test_batching() throws Exception {
void test_batching() throws Exception {
for (int i = 0; i < 50; i++) {
persistToken(String.format("batch%2d", i), null, i % 2 == 0);
}
@@ -134,7 +133,7 @@ public class DeleteAllocationTokensCommandTest
}
@Test
public void test_prefixIsRequired() {
void test_prefixIsRequired() {
IllegalArgumentException thrown =
assertThrows(IllegalArgumentException.class, this::runCommandForced);
assertThat(thrown)
@@ -143,7 +142,7 @@ public class DeleteAllocationTokensCommandTest
}
@Test
public void testFailure_bothPrefixAndTokens() {
void testFailure_bothPrefixAndTokens() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@@ -154,7 +153,7 @@ public class DeleteAllocationTokensCommandTest
}
@Test
public void testFailure_emptyPrefix() {
void testFailure_emptyPrefix() {
IllegalArgumentException thrown =
assertThrows(IllegalArgumentException.class, () -> runCommandForced("--prefix", ""));
assertThat(thrown).hasMessageThat().isEqualTo("Provided prefix should not be blank");
@@ -17,39 +17,39 @@ package google.registry.tools;
import static org.junit.Assert.assertThrows;
import com.beust.jcommander.ParameterException;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link DeleteDomainCommand}. */
public class DeleteDomainCommandTest extends EppToolCommandTestCase<DeleteDomainCommand> {
class DeleteDomainCommandTest extends EppToolCommandTestCase<DeleteDomainCommand> {
@Test
public void testSuccess() throws Exception {
void testSuccess() throws Exception {
runCommand("--client=NewRegistrar", "--domain_name=example.tld", "--force", "--reason=Test");
eppVerifier.verifySent("domain_delete.xml");
}
@Test
public void testSuccess_multipleWordReason() throws Exception {
void testSuccess_multipleWordReason() throws Exception {
runCommandForced(
"--client=NewRegistrar", "--domain_name=example.tld", "--reason=\"Test test\"");
eppVerifier.verifySent("domain_delete_multiple_word_reason.xml");
}
@Test
public void testSuccess_immediately() throws Exception {
void testSuccess_immediately() throws Exception {
runCommandForced(
"--client=NewRegistrar", "--domain_name=example.tld", "--immediately", "--reason=Test");
eppVerifier.expectSuperuser().verifySent("domain_delete_immediately.xml");
}
@Test
public void testSuccess_requestedByRegistrarFalse() throws Exception {
void testSuccess_requestedByRegistrarFalse() throws Exception {
runCommandForced("--client=NewRegistrar", "--domain_name=example.tld", "--reason=Test");
eppVerifier.verifySent("domain_delete.xml");
}
@Test
public void testSuccess_requestedByRegistrarTrue() throws Exception {
void testSuccess_requestedByRegistrarTrue() throws Exception {
runCommandForced(
"--client=NewRegistrar",
"--domain_name=example.tld",
@@ -59,28 +59,28 @@ public class DeleteDomainCommandTest extends EppToolCommandTestCase<DeleteDomain
}
@Test
public void testFailure_noReason() {
void testFailure_noReason() {
assertThrows(
ParameterException.class,
() -> runCommand("--client=NewRegistrar", "--domain_name=example.tld", "--force"));
}
@Test
public void testFailure_missingClientId() {
void testFailure_missingClientId() {
assertThrows(
ParameterException.class,
() -> runCommand("--domain_name=example.tld", "--force", "--reason=Test"));
}
@Test
public void testFailure_missingDomainName() {
void testFailure_missingDomainName() {
assertThrows(
ParameterException.class,
() -> runCommand("--client=NewRegistrar", "--force", "--reason=Test"));
}
@Test
public void testFailure_unknownFlag() {
void testFailure_unknownFlag() {
assertThrows(
ParameterException.class,
() ->
@@ -93,7 +93,7 @@ public class DeleteDomainCommandTest extends EppToolCommandTestCase<DeleteDomain
}
@Test
public void testFailure_mainParameter() {
void testFailure_mainParameter() {
assertThrows(
ParameterException.class,
() ->
@@ -17,26 +17,26 @@ package google.registry.tools;
import static org.junit.Assert.assertThrows;
import com.beust.jcommander.ParameterException;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link DeleteHostCommand}. */
public class DeleteHostCommandTest extends EppToolCommandTestCase<DeleteHostCommand> {
class DeleteHostCommandTest extends EppToolCommandTestCase<DeleteHostCommand> {
@Test
public void testSuccess() throws Exception {
void testSuccess() throws Exception {
runCommand("--client=NewRegistrar", "--host=ns1.example.tld", "--force", "--reason=Test");
eppVerifier.verifySent("host_delete.xml");
}
@Test
public void testSuccess_multipleWordReason() throws Exception {
void testSuccess_multipleWordReason() throws Exception {
runCommand(
"--client=NewRegistrar", "--host=ns1.example.tld", "--force", "--reason=\"Test test\"");
eppVerifier.verifySent("host_delete_multiple_word_reason.xml");
}
@Test
public void testSuccess_requestedByRegistrarFalse() throws Exception {
void testSuccess_requestedByRegistrarFalse() throws Exception {
runCommand(
"--client=NewRegistrar",
"--host=ns1.example.tld",
@@ -47,7 +47,7 @@ public class DeleteHostCommandTest extends EppToolCommandTestCase<DeleteHostComm
}
@Test
public void testSuccess_requestedByRegistrarTrue() throws Exception {
void testSuccess_requestedByRegistrarTrue() throws Exception {
runCommand(
"--client=NewRegistrar",
"--host=ns1.example.tld",
@@ -58,28 +58,28 @@ public class DeleteHostCommandTest extends EppToolCommandTestCase<DeleteHostComm
}
@Test
public void testFailure_noReason() {
void testFailure_noReason() {
assertThrows(
ParameterException.class,
() -> runCommand("--client=NewRegistrar", "--host=ns1.example.tld", "--force"));
}
@Test
public void testFailure_missingClientId() {
void testFailure_missingClientId() {
assertThrows(
ParameterException.class,
() -> runCommand("--host=ns1.example.tld", "--force", "--reason=Test"));
}
@Test
public void testFailure_missingHostName() {
void testFailure_missingHostName() {
assertThrows(
ParameterException.class,
() -> runCommand("--client=NewRegistrar", "--force", "--reason=Test"));
}
@Test
public void testFailure_unknownFlag() {
void testFailure_unknownFlag() {
assertThrows(
ParameterException.class,
() ->
@@ -92,7 +92,7 @@ public class DeleteHostCommandTest extends EppToolCommandTestCase<DeleteHostComm
}
@Test
public void testFailure_mainParameter() {
void testFailure_mainParameter() {
assertThrows(
ParameterException.class,
() ->
@@ -26,13 +26,13 @@ import static org.junit.Assert.assertThrows;
import google.registry.model.registry.Registry;
import google.registry.model.registry.label.PremiumList;
import google.registry.model.registry.label.PremiumList.PremiumListEntry;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link DeletePremiumListCommand}. */
public class DeletePremiumListCommandTest extends CommandTestCase<DeletePremiumListCommand> {
class DeletePremiumListCommandTest extends CommandTestCase<DeletePremiumListCommand> {
@Test
public void testSuccess() throws Exception {
void testSuccess() throws Exception {
PremiumList premiumList = persistPremiumList("xn--q9jyb4c", "blah,USD 100");
assertThat(loadPremiumListEntries(premiumList)).hasSize(1);
runCommand("--force", "--name=xn--q9jyb4c");
@@ -47,7 +47,7 @@ public class DeletePremiumListCommandTest extends CommandTestCase<DeletePremiumL
}
@Test
public void testFailure_whenPremiumListDoesNotExist() {
void testFailure_whenPremiumListDoesNotExist() {
IllegalArgumentException thrown =
assertThrows(IllegalArgumentException.class, () -> runCommandForced("--name=foo"));
assertThat(thrown)
@@ -56,7 +56,7 @@ public class DeletePremiumListCommandTest extends CommandTestCase<DeletePremiumL
}
@Test
public void testFailure_whenPremiumListIsInUse() {
void testFailure_whenPremiumListIsInUse() {
PremiumList premiumList = persistPremiumList("xn--q9jyb4c", "blah,USD 100");
createTld("xn--q9jyb4c");
persistResource(Registry.get("xn--q9jyb4c").asBuilder().setPremiumList(premiumList).build());
@@ -23,28 +23,28 @@ import static org.junit.Assert.assertThrows;
import google.registry.model.registry.Registry;
import google.registry.model.registry.label.ReservedList;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link DeleteReservedListCommand}. */
public class DeleteReservedListCommandTest extends CommandTestCase<DeleteReservedListCommand> {
class DeleteReservedListCommandTest extends CommandTestCase<DeleteReservedListCommand> {
ReservedList reservedList;
private ReservedList reservedList;
@Before
public void init() {
@BeforeEach
void beforeEach() {
reservedList = persistReservedList("common", "blah,FULLY_BLOCKED");
}
@Test
public void testSuccess() throws Exception {
void testSuccess() throws Exception {
assertThat(reservedList.getReservedListEntries()).hasSize(1);
runCommandForced("--name=common");
assertThat(ReservedList.get("common")).isEmpty();
}
@Test
public void testFailure_whenReservedListDoesNotExist() {
void testFailure_whenReservedListDoesNotExist() {
String expectedError =
"Cannot delete the reserved list doesntExistReservedList because it doesn't exist.";
IllegalArgumentException thrown =
@@ -55,7 +55,7 @@ public class DeleteReservedListCommandTest extends CommandTestCase<DeleteReserve
}
@Test
public void testFailure_whenReservedListIsInUse() {
void testFailure_whenReservedListIsInUse() {
createTld("xn--q9jyb4c");
persistResource(Registry.get("xn--q9jyb4c").asBuilder().setReservedLists(reservedList).build());
IllegalArgumentException thrown =
@@ -28,17 +28,17 @@ import google.registry.model.registry.Registry;
import google.registry.model.registry.Registry.RegistryNotFoundException;
import google.registry.model.registry.Registry.TldType;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link DeleteTldCommand}. */
public class DeleteTldCommandTest extends CommandTestCase<DeleteTldCommand> {
class DeleteTldCommandTest extends CommandTestCase<DeleteTldCommand> {
private static final String TLD_REAL = "tldreal";
private static final String TLD_TEST = "tldtest";
@Before
public void setUp() {
@BeforeEach
void beforeEach() {
persistResource(
newRegistry(
TLD_REAL,
@@ -54,7 +54,7 @@ public class DeleteTldCommandTest extends CommandTestCase<DeleteTldCommand> {
}
@Test
public void testSuccess_otherTldUnaffected() throws Exception {
void testSuccess_otherTldUnaffected() throws Exception {
runCommandForced("--tld=" + TLD_TEST);
Registry.get(TLD_REAL);
@@ -62,24 +62,24 @@ public class DeleteTldCommandTest extends CommandTestCase<DeleteTldCommand> {
}
@Test
public void testFailure_whenTldDoesNotExist() {
void testFailure_whenTldDoesNotExist() {
assertThrows(RegistryNotFoundException.class, () -> runCommandForced("--tld=nonexistenttld"));
}
@Test
public void testFailure_whenTldIsReal() {
void testFailure_whenTldIsReal() {
assertThrows(IllegalStateException.class, () -> runCommandForced("--tld=" + TLD_REAL));
}
@Test
public void testFailure_whenDomainsArePresent() {
void testFailure_whenDomainsArePresent() {
persistDeletedDomain("domain." + TLD_TEST, DateTime.parse("2000-01-01TZ"));
assertThrows(IllegalStateException.class, () -> runCommandForced("--tld=" + TLD_TEST));
}
@Test
public void testFailure_whenRegistrarLinksToTld() {
void testFailure_whenRegistrarLinksToTld() {
allowRegistrarAccess("TheRegistrar", TLD_TEST);
assertThrows(IllegalStateException.class, () -> runCommandForced("--tld=" + TLD_TEST));
@@ -33,6 +33,7 @@ import static org.joda.time.Duration.standardHours;
import static org.joda.time.Duration.standardSeconds;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableList;
import google.registry.batch.AsyncTaskEnqueuerTest;
@@ -57,28 +58,20 @@ import java.util.Set;
import java.util.stream.Collectors;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
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 google.registry.tools.DomainLockUtils}. */
@RunWith(JUnit4.class)
public final class DomainLockUtilsTest {
private static final String DOMAIN_NAME = "example.tld";
private static final String POC_ID = "marla.singer@example.com";
private final FakeClock clock = new FakeClock(DateTime.now(DateTimeZone.UTC));
private final DomainLockUtils domainLockUtils =
new DomainLockUtils(
new DeterministicStringGenerator(Alphabets.BASE_58),
"adminreg",
AsyncTaskEnqueuerTest.createForTesting(
mock(AppEngineServiceUtils.class), clock, standardSeconds(90)));
private DomainLockUtils domainLockUtils;
@Rule
@RegisterExtension
public final AppEngineRule appEngineRule =
AppEngineRule.builder()
.withDatastoreAndCloudSql()
@@ -89,15 +82,24 @@ public final class DomainLockUtilsTest {
private DomainBase domain;
@Before
public void setup() {
@BeforeEach
void setup() {
createTlds("tld", "net");
HostResource host = persistActiveHost("ns1.example.net");
domain = persistResource(newDomainBase(DOMAIN_NAME, host));
AppEngineServiceUtils appEngineServiceUtils = mock(AppEngineServiceUtils.class);
when(appEngineServiceUtils.getServiceHostname("backend")).thenReturn("backend.hostname.fake");
domainLockUtils =
new DomainLockUtils(
new DeterministicStringGenerator(Alphabets.BASE_58),
"adminreg",
AsyncTaskEnqueuerTest.createForTesting(
appEngineServiceUtils, clock, standardSeconds(90)));
}
@Test
public void testSuccess_createLock() {
void testSuccess_createLock() {
RegistryLock lock =
domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
assertNoDomainChanges();
@@ -105,7 +107,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testSuccess_createUnlock() {
void testSuccess_createUnlock() {
domainLockUtils.administrativelyApplyLock(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
RegistryLock lock =
domainLockUtils.saveNewRegistryUnlockRequest(
@@ -114,7 +116,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testSuccess_createUnlock_adminUnlockingAdmin() {
void testSuccess_createUnlock_adminUnlockingAdmin() {
domainLockUtils.administrativelyApplyLock(DOMAIN_NAME, "TheRegistrar", null, true);
RegistryLock lock =
domainLockUtils.saveNewRegistryUnlockRequest(
@@ -123,7 +125,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testSuccess_createLock_previousLockExpired() {
void testSuccess_createLock_previousLockExpired() {
domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
clock.advanceBy(standardDays(1));
RegistryLock lock =
@@ -133,7 +135,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testSuccess_createUnlock_previousUnlockRequestExpired() {
void testSuccess_createUnlock_previousUnlockRequestExpired() {
domainLockUtils.administrativelyApplyLock(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
domainLockUtils.saveNewRegistryUnlockRequest(
DOMAIN_NAME, "TheRegistrar", false, Optional.empty());
@@ -146,7 +148,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testSuccess_applyLockDomain() {
void testSuccess_applyLockDomain() {
RegistryLock lock =
domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), false);
@@ -154,7 +156,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testSuccess_applyUnlockDomain() {
void testSuccess_applyUnlockDomain() {
domainLockUtils.administrativelyApplyLock(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
RegistryLock unlock =
domainLockUtils.saveNewRegistryUnlockRequest(
@@ -164,7 +166,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testSuccess_applyAdminLock_onlyHistoryEntry() {
void testSuccess_applyAdminLock_onlyHistoryEntry() {
RegistryLock lock =
domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", null, true);
domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), true);
@@ -172,7 +174,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testSuccess_applyAdminUnlock_onlyHistoryEntry() {
void testSuccess_applyAdminUnlock_onlyHistoryEntry() {
RegistryLock lock =
domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", null, true);
domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), true);
@@ -184,20 +186,20 @@ public final class DomainLockUtilsTest {
}
@Test
public void testSuccess_administrativelyLock_nonAdmin() {
void testSuccess_administrativelyLock_nonAdmin() {
domainLockUtils.administrativelyApplyLock(
DOMAIN_NAME, "TheRegistrar", "Marla.Singer@crr.com", false);
verifyProperlyLockedDomain(false);
}
@Test
public void testSuccess_administrativelyLock_admin() {
void testSuccess_administrativelyLock_admin() {
domainLockUtils.administrativelyApplyLock(DOMAIN_NAME, "TheRegistrar", null, true);
verifyProperlyLockedDomain(true);
}
@Test
public void testSuccess_administrativelyUnlock_nonAdmin() {
void testSuccess_administrativelyUnlock_nonAdmin() {
RegistryLock lock =
domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), false);
@@ -207,7 +209,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testSuccess_administrativelyUnlock_admin() {
void testSuccess_administrativelyUnlock_admin() {
RegistryLock lock =
domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", null, true);
domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), true);
@@ -217,7 +219,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testSuccess_regularLock_relockSet() {
void testSuccess_regularLock_relockSet() {
domainLockUtils.administrativelyApplyLock(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
RegistryLock oldLock =
domainLockUtils.administrativelyApplyUnlock(
@@ -231,7 +233,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testSuccess_administrativelyLock_relockSet() {
void testSuccess_administrativelyLock_relockSet() {
domainLockUtils.administrativelyApplyLock(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
RegistryLock oldLock =
domainLockUtils.administrativelyApplyUnlock(
@@ -244,7 +246,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testSuccess_createUnlock_relockDuration() {
void testSuccess_createUnlock_relockDuration() {
domainLockUtils.administrativelyApplyLock(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
RegistryLock lock =
domainLockUtils.saveNewRegistryUnlockRequest(
@@ -253,7 +255,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testSuccess_unlock_relockSubmitted() {
void testSuccess_unlock_relockSubmitted() {
domainLockUtils.administrativelyApplyLock(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
RegistryLock lock =
domainLockUtils.saveNewRegistryUnlockRequest(
@@ -264,6 +266,7 @@ public final class DomainLockUtilsTest {
new TaskMatcher()
.url(RelockDomainAction.PATH)
.method("POST")
.header("Host", "backend.hostname.fake")
.param(
RelockDomainAction.OLD_UNLOCK_REVISION_ID_PARAM,
String.valueOf(lock.getRevisionId()))
@@ -273,7 +276,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testFailure_createUnlock_alreadyPendingUnlock() {
void testFailure_createUnlock_alreadyPendingUnlock() {
RegistryLock lock =
domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), false);
@@ -291,7 +294,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testFailure_createUnlock_nonAdminUnlockingAdmin() {
void testFailure_createUnlock_nonAdminUnlockingAdmin() {
RegistryLock lock =
domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", null, true);
domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), true);
@@ -306,7 +309,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testFailure_createLock_unknownDomain() {
void testFailure_createLock_unknownDomain() {
assertThat(
assertThrows(
IllegalArgumentException.class,
@@ -318,7 +321,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testFailure_createLock_alreadyPendingLock() {
void testFailure_createLock_alreadyPendingLock() {
domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
assertThat(
assertThrows(
@@ -331,7 +334,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testFailure_createLock_alreadyLocked() {
void testFailure_createLock_alreadyLocked() {
persistResource(domain.asBuilder().setStatusValues(REGISTRY_LOCK_STATUSES).build());
assertThat(
assertThrows(
@@ -344,7 +347,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testFailure_createUnlock_alreadyUnlocked() {
void testFailure_createUnlock_alreadyUnlocked() {
assertThat(
assertThrows(
IllegalArgumentException.class,
@@ -356,7 +359,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testFailure_applyLock_alreadyApplied() {
void testFailure_applyLock_alreadyApplied() {
RegistryLock lock =
domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), false);
@@ -371,7 +374,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testFailure_applyLock_expired() {
void testFailure_applyLock_expired() {
RegistryLock lock =
domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
clock.advanceBy(standardDays(1));
@@ -385,7 +388,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testFailure_applyLock_nonAdmin_applyAdminLock() {
void testFailure_applyLock_nonAdmin_applyAdminLock() {
RegistryLock lock =
domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", null, true);
assertThat(
@@ -398,7 +401,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testFailure_applyUnlock_alreadyUnlocked() {
void testFailure_applyUnlock_alreadyUnlocked() {
RegistryLock lock =
domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), false);
@@ -417,7 +420,7 @@ public final class DomainLockUtilsTest {
}
@Test
public void testFailure_applyLock_alreadyLocked() {
void testFailure_applyLock_alreadyLocked() {
RegistryLock lock =
domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
String verificationCode = lock.getVerificationCode();
@@ -17,23 +17,17 @@ package google.registry.tools;
import static com.google.common.truth.Truth.assertThat;
import java.io.File;
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.Test;
@RunWith(JUnit4.class)
public class DumpGoldenSchemaCommandTest extends CommandTestCase<DumpGoldenSchemaCommand> {
/** Unit tests for {@link google.registry.tools.DumpGoldenSchemaCommand}. */
class DumpGoldenSchemaCommandTest extends CommandTestCase<DumpGoldenSchemaCommand> {
@Rule public TemporaryFolder tmp = new TemporaryFolder();
public DumpGoldenSchemaCommandTest() {}
DumpGoldenSchemaCommandTest() {}
@Test
public void testSchemaGeneration() throws Exception {
runCommand(
"--output=" + tmp.getRoot() + File.separatorChar + "golden.sql", "--start_postgresql");
assertThat(new File(tmp.getRoot(), "golden.sql").length()).isGreaterThan(1);
void testSchemaGeneration() throws Exception {
File schemaFile = tmpDir.resolve("golden.sql").toFile();
runCommand("--output=" + schemaFile.toString(), "--start_postgresql");
assertThat(schemaFile.length()).isGreaterThan(1);
}
}

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