Upgrade converters/TMCH/RDAP to JUnit 5 (#703)

Also renames some existing Rules to Extensions (and removes JUnit 4 features
from them entirely if no longer being used).
This commit is contained in:
Ben McIlwain 2020-07-21 18:48:41 -04:00 committed by GitHub
parent f5186f8476
commit 9a5ba249db
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
96 changed files with 1374 additions and 1507 deletions

View file

@ -46,7 +46,7 @@ import google.registry.model.registry.Registry;
import google.registry.model.registry.Registry.TldType; import google.registry.model.registry.Registry.TldType;
import google.registry.model.reporting.HistoryEntry; import google.registry.model.reporting.HistoryEntry;
import google.registry.testing.FakeResponse; import google.registry.testing.FakeResponse;
import google.registry.testing.SystemPropertyRule; import google.registry.testing.SystemPropertyExtension;
import google.registry.testing.mapreduce.MapreduceTestCase; import google.registry.testing.mapreduce.MapreduceTestCase;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
@ -61,7 +61,8 @@ class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDataActio
private static final DateTime DELETION_TIME = DateTime.parse("2010-01-01T00:00:00.000Z"); private static final DateTime DELETION_TIME = DateTime.parse("2010-01-01T00:00:00.000Z");
@RegisterExtension final SystemPropertyRule systemPropertyRule = new SystemPropertyRule(); @RegisterExtension
final SystemPropertyExtension systemPropertyExtension = new SystemPropertyExtension();
@BeforeEach @BeforeEach
void beforeEach() { void beforeEach() {
@ -92,7 +93,7 @@ class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDataActio
action.isDryRun = false; action.isDryRun = false;
action.tlds = ImmutableSet.of(); action.tlds = ImmutableSet.of();
action.registryAdminClientId = "TheRegistrar"; action.registryAdminClientId = "TheRegistrar";
RegistryEnvironment.SANDBOX.setup(systemPropertyRule); RegistryEnvironment.SANDBOX.setup(systemPropertyExtension);
} }
private void runMapreduce() throws Exception { private void runMapreduce() throws Exception {
@ -154,7 +155,7 @@ class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDataActio
@Test @Test
void testFail_givenNonDotTestTldOnProd() { void testFail_givenNonDotTestTldOnProd() {
action.tlds = ImmutableSet.of("example"); action.tlds = ImmutableSet.of("example");
RegistryEnvironment.PRODUCTION.setup(systemPropertyRule); RegistryEnvironment.PRODUCTION.setup(systemPropertyExtension);
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows(IllegalArgumentException.class, this::runMapreduce); assertThrows(IllegalArgumentException.class, this::runMapreduce);
assertThat(thrown) assertThat(thrown)

View file

@ -44,12 +44,10 @@ import org.junit.Test;
import org.junit.experimental.categories.Category; import org.junit.experimental.categories.Category;
import org.junit.rules.RuleChain; import org.junit.rules.RuleChain;
import org.junit.rules.TemporaryFolder; import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit test for {@link Transforms#writeToSql}. */ /** Unit test for {@link Transforms#writeToSql}. */
@RunWith(JUnit4.class)
public class WriteToSqlTest implements Serializable { public class WriteToSqlTest implements Serializable {
private static final DateTime START_TIME = DateTime.parse("2000-01-01T00:00:00.0Z"); private static final DateTime START_TIME = DateTime.parse("2000-01-01T00:00:00.0Z");
private final FakeClock fakeClock = new FakeClock(START_TIME); private final FakeClock fakeClock = new FakeClock(START_TIME);

View file

@ -17,7 +17,7 @@ package google.registry.keyring.api;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import google.registry.testing.BouncyCastleProviderRule; import google.registry.testing.BouncyCastleProviderExtension;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPException;
@ -35,7 +35,8 @@ import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link KeySerializer}. */ /** Unit tests for {@link KeySerializer}. */
class KeySerializerTest { class KeySerializerTest {
@RegisterExtension final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule(); @RegisterExtension
final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
/** /**
* An Armored representation of a pgp secret key. * An Armored representation of a pgp secret key.

View file

@ -22,7 +22,7 @@ import google.registry.keyring.api.KeySerializer;
import google.registry.model.server.KmsSecret; import google.registry.model.server.KmsSecret;
import google.registry.model.server.KmsSecretRevision; import google.registry.model.server.KmsSecretRevision;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import google.registry.testing.BouncyCastleProviderRule; import google.registry.testing.BouncyCastleProviderExtension;
import org.bouncycastle.openpgp.PGPKeyPair; import org.bouncycastle.openpgp.PGPKeyPair;
import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPPublicKey;
@ -33,7 +33,8 @@ import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link KmsKeyring}. */ /** Unit tests for {@link KmsKeyring}. */
class KmsKeyringTest { class KmsKeyringTest {
@RegisterExtension final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule(); @RegisterExtension
final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
@RegisterExtension @RegisterExtension
final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();

View file

@ -23,7 +23,7 @@ import google.registry.keyring.api.KeySerializer;
import google.registry.model.server.KmsSecret; import google.registry.model.server.KmsSecret;
import google.registry.model.server.KmsSecretRevision; import google.registry.model.server.KmsSecretRevision;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import google.registry.testing.BouncyCastleProviderRule; import google.registry.testing.BouncyCastleProviderExtension;
import java.io.IOException; import java.io.IOException;
import org.bouncycastle.openpgp.PGPKeyPair; import org.bouncycastle.openpgp.PGPKeyPair;
import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPPublicKey;
@ -37,7 +37,8 @@ public class KmsUpdaterTest {
@RegisterExtension @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@RegisterExtension public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule(); @RegisterExtension
public final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
private KmsUpdater updater; private KmsUpdater updater;

View file

@ -24,7 +24,7 @@ import static google.registry.testing.DatastoreHelper.persistResource;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import google.registry.model.contact.ContactResource; import google.registry.model.contact.ContactResource;
import google.registry.model.host.HostResource; import google.registry.model.host.HostResource;
import google.registry.testing.TestCacheRule; import google.registry.testing.TestCacheExtension;
import org.joda.time.Duration; import org.joda.time.Duration;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.extension.RegisterExtension;
@ -33,8 +33,8 @@ import org.junit.jupiter.api.extension.RegisterExtension;
public class EppResourceTest extends EntityTestCase { public class EppResourceTest extends EntityTestCase {
@RegisterExtension @RegisterExtension
public final TestCacheRule testCacheRule = public final TestCacheExtension testCacheExtension =
new TestCacheRule.Builder().withEppResourceCache(Duration.standardDays(1)).build(); new TestCacheExtension.Builder().withEppResourceCache(Duration.standardDays(1)).build();
@Test @Test
void test_loadCached_ignoresContactChange() { void test_loadCached_ignoresContactChange() {

View file

@ -31,7 +31,7 @@ import google.registry.model.EntityTestCase;
import google.registry.model.contact.ContactResource; import google.registry.model.contact.ContactResource;
import google.registry.model.host.HostResource; import google.registry.model.host.HostResource;
import google.registry.model.index.ForeignKeyIndex.ForeignKeyHostIndex; import google.registry.model.index.ForeignKeyIndex.ForeignKeyHostIndex;
import google.registry.testing.TestCacheRule; import google.registry.testing.TestCacheExtension;
import org.joda.time.Duration; import org.joda.time.Duration;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -41,8 +41,8 @@ import org.junit.jupiter.api.extension.RegisterExtension;
public class ForeignKeyIndexTest extends EntityTestCase { public class ForeignKeyIndexTest extends EntityTestCase {
@RegisterExtension @RegisterExtension
public final TestCacheRule testCacheRule = public final TestCacheExtension testCacheExtension =
new TestCacheRule.Builder().withForeignIndexKeyCache(Duration.standardDays(1)).build(); new TestCacheExtension.Builder().withForeignIndexKeyCache(Duration.standardDays(1)).build();
@BeforeEach @BeforeEach
void setUp() { void setUp() {

View file

@ -48,7 +48,7 @@ import google.registry.model.registry.Registry;
import google.registry.model.registry.label.PremiumList.PremiumListEntry; import google.registry.model.registry.label.PremiumList.PremiumListEntry;
import google.registry.model.registry.label.PremiumList.PremiumListRevision; import google.registry.model.registry.label.PremiumList.PremiumListRevision;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import google.registry.testing.TestCacheRule; import google.registry.testing.TestCacheExtension;
import java.util.Map; import java.util.Map;
import org.joda.money.Money; import org.joda.money.Money;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
@ -63,8 +63,8 @@ public class PremiumListUtilsTest {
// Set long persist times on caches so they can be tested (cache times default to 0 in tests). // Set long persist times on caches so they can be tested (cache times default to 0 in tests).
@RegisterExtension @RegisterExtension
public final TestCacheRule testCacheRule = public final TestCacheExtension testCacheExtension =
new TestCacheRule.Builder() new TestCacheExtension.Builder()
.withPremiumListsCache(standardDays(1)) .withPremiumListsCache(standardDays(1))
.withPremiumListEntriesCache(standardDays(1)) .withPremiumListEntriesCache(standardDays(1))
.build(); .build();

View file

@ -21,7 +21,7 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import javax.persistence.Embeddable; import javax.persistence.Embeddable;
import javax.persistence.Embedded; import javax.persistence.Embedded;
@ -36,21 +36,18 @@ import javax.persistence.PrePersist;
import javax.persistence.PreRemove; import javax.persistence.PreRemove;
import javax.persistence.PreUpdate; import javax.persistence.PreUpdate;
import javax.persistence.Transient; import javax.persistence.Transient;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link EntityCallbacksListener}. */ /** Unit tests for {@link EntityCallbacksListener}. */
@RunWith(JUnit4.class) class EntityCallbacksListenerTest {
public class EntityCallbacksListenerTest {
@Rule @RegisterExtension
public final JpaUnitTestRule jpaRule = public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule(); new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule();
@Test @Test
public void verifyAllCallbacks_executedExpectedTimes() { void verifyAllCallbacks_executedExpectedTimes() {
TestEntity testPersist = new TestEntity(); TestEntity testPersist = new TestEntity();
jpaTm().transact(() -> jpaTm().saveNew(testPersist)); jpaTm().transact(() -> jpaTm().saveNew(testPersist));
checkAll(testPersist, 1, 0, 0, 0); checkAll(testPersist, 1, 0, 0, 0);
@ -84,7 +81,7 @@ public class EntityCallbacksListenerTest {
} }
@Test @Test
public void verifyAllManagedEntities_haveNoMethodWithEmbedded() { void verifyAllManagedEntities_haveNoMethodWithEmbedded() {
ImmutableSet<Class> violations = ImmutableSet<Class> violations =
PersistenceXmlUtility.getManagedClasses().stream() PersistenceXmlUtility.getManagedClasses().stream()
.filter(clazz -> clazz.isAnnotationPresent(Entity.class)) .filter(clazz -> clazz.isAnnotationPresent(Entity.class))
@ -98,7 +95,7 @@ public class EntityCallbacksListenerTest {
} }
@Test @Test
public void verifyHasMethodAnnotatedWithEmbedded_work() { void verifyHasMethodAnnotatedWithEmbedded_work() {
assertThat(hasMethodAnnotatedWithEmbedded(ViolationEntity.class)).isTrue(); assertThat(hasMethodAnnotatedWithEmbedded(ViolationEntity.class)).isTrue();
} }

View file

@ -24,7 +24,7 @@ import google.registry.model.ImmutableObject;
import google.registry.model.common.TimedTransitionProperty; import google.registry.model.common.TimedTransitionProperty;
import google.registry.model.registry.Registry.BillingCostTransition; import google.registry.model.registry.Registry.BillingCostTransition;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import org.joda.money.Money; import org.joda.money.Money;
@ -36,7 +36,7 @@ import org.junit.jupiter.api.extension.RegisterExtension;
public class BillingCostTransitionConverterTest { public class BillingCostTransitionConverterTest {
@RegisterExtension @RegisterExtension
public final JpaUnitTestRule jpa = public final JpaUnitTestExtension jpa =
new JpaTestRules.Builder() new JpaTestRules.Builder()
.withInitScript("sql/flyway/V14__load_extension_for_hstore.sql") .withInitScript("sql/flyway/V14__load_extension_for_hstore.sql")
.withEntityClass(TestEntity.class) .withEntityClass(TestEntity.class)

View file

@ -22,25 +22,22 @@ import com.google.common.collect.ImmutableSet;
import com.google.common.hash.BloomFilter; import com.google.common.hash.BloomFilter;
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import google.registry.schema.replay.EntityTest.EntityForTesting; import google.registry.schema.replay.EntityTest.EntityForTesting;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link BloomFilterConverter}. */ /** Unit tests for {@link BloomFilterConverter}. */
@RunWith(JUnit4.class) class BloomFilterConverterTest {
public class BloomFilterConverterTest {
@Rule @RegisterExtension
public final JpaUnitTestRule jpaRule = public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule(); new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule();
@Test @Test
public void roundTripConversion_returnsSameBloomFilter() { void roundTripConversion_returnsSameBloomFilter() {
BloomFilter<String> bloomFilter = BloomFilter.create(stringFunnel(US_ASCII), 3); BloomFilter<String> bloomFilter = BloomFilter.create(stringFunnel(US_ASCII), 3);
ImmutableSet.of("foo", "bar", "baz").forEach(bloomFilter::put); ImmutableSet.of("foo", "bar", "baz").forEach(bloomFilter::put);
TestEntity entity = new TestEntity(bloomFilter); TestEntity entity = new TestEntity(bloomFilter);

View file

@ -20,25 +20,23 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import google.registry.util.CidrAddressBlock; import google.registry.util.CidrAddressBlock;
import java.util.List; import java.util.List;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link CidrAddressBlockListConverter}. */ /** Unit tests for {@link CidrAddressBlockListConverter}. */
@RunWith(JUnit4.class)
public class CidrAddressBlockListConverterTest { public class CidrAddressBlockListConverterTest {
@Rule
public final JpaUnitTestRule jpaRule = @RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule(); new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule();
@Test @Test
public void roundTripConversion_returnsSameCidrAddressBlock() { void roundTripConversion_returnsSameCidrAddressBlock() {
List<CidrAddressBlock> addresses = List<CidrAddressBlock> addresses =
ImmutableList.of( ImmutableList.of(
CidrAddressBlock.create("0.0.0.0/32"), CidrAddressBlock.create("0.0.0.0/32"),

View file

@ -19,32 +19,29 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import google.registry.model.CreateAutoTimestamp; import google.registry.model.CreateAutoTimestamp;
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import google.registry.schema.replay.EntityTest.EntityForTesting; import google.registry.schema.replay.EntityTest.EntityForTesting;
import google.registry.testing.FakeClock; import google.registry.testing.FakeClock;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link CreateAutoTimestampConverter}. */ /** Unit tests for {@link CreateAutoTimestampConverter}. */
@RunWith(JUnit4.class)
public class CreateAutoTimestampConverterTest { public class CreateAutoTimestampConverterTest {
private final FakeClock fakeClock = new FakeClock(); private final FakeClock fakeClock = new FakeClock();
@Rule @RegisterExtension
public final JpaUnitTestRule jpaRule = public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder() new JpaTestRules.Builder()
.withClock(fakeClock) .withClock(fakeClock)
.withEntityClass(TestEntity.class) .withEntityClass(TestEntity.class)
.buildUnitTestRule(); .buildUnitTestRule();
@Test @Test
public void testTypeConversion() { void testTypeConversion() {
CreateAutoTimestamp ts = CreateAutoTimestamp.create(DateTime.parse("2019-09-9T11:39:00Z")); CreateAutoTimestamp ts = CreateAutoTimestamp.create(DateTime.parse("2019-09-9T11:39:00Z"));
TestEntity ent = new TestEntity("myinst", ts); TestEntity ent = new TestEntity("myinst", ts);
@ -55,7 +52,7 @@ public class CreateAutoTimestampConverterTest {
} }
@Test @Test
public void testAutoInitialization() { void testAutoInitialization() {
CreateAutoTimestamp ts = CreateAutoTimestamp.create(null); CreateAutoTimestamp ts = CreateAutoTimestamp.create(null);
TestEntity ent = new TestEntity("autoinit", ts); TestEntity ent = new TestEntity("autoinit", ts);

View file

@ -21,28 +21,26 @@ import com.google.common.collect.ImmutableMap;
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.model.registrar.Registrar.BillingAccountEntry; import google.registry.model.registrar.Registrar.BillingAccountEntry;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import java.util.Map; import java.util.Map;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import org.joda.money.CurrencyUnit; import org.joda.money.CurrencyUnit;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link CurrencyToBillingConverter}. */ /** Unit tests for {@link CurrencyToBillingConverter}. */
@RunWith(JUnit4.class)
public class CurrencyToBillingConverterTest { public class CurrencyToBillingConverterTest {
@Rule
public final JpaUnitTestRule jpaRule = @RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder() new JpaTestRules.Builder()
.withInitScript("sql/flyway/V14__load_extension_for_hstore.sql") .withInitScript("sql/flyway/V14__load_extension_for_hstore.sql")
.withEntityClass(TestEntity.class) .withEntityClass(TestEntity.class)
.buildUnitTestRule(); .buildUnitTestRule();
@Test @Test
public void roundTripConversion_returnsSameCurrencyToBillingMap() { void roundTripConversion_returnsSameCurrencyToBillingMap() {
ImmutableMap<CurrencyUnit, BillingAccountEntry> currencyToBilling = ImmutableMap<CurrencyUnit, BillingAccountEntry> currencyToBilling =
ImmutableMap.of( ImmutableMap.of(
CurrencyUnit.of("USD"), CurrencyUnit.of("USD"),

View file

@ -20,27 +20,24 @@ import static org.junit.Assert.assertThrows;
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import google.registry.schema.replay.EntityTest.EntityForTesting; import google.registry.schema.replay.EntityTest.EntityForTesting;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.PersistenceException; import javax.persistence.PersistenceException;
import org.joda.money.CurrencyUnit; import org.joda.money.CurrencyUnit;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link CurrencyUnitConverter}. */ /** Unit tests for {@link CurrencyUnitConverter}. */
@RunWith(JUnit4.class)
public class CurrencyUnitConverterTest { public class CurrencyUnitConverterTest {
@Rule @RegisterExtension
public final JpaUnitTestRule jpaRule = public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule(); new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule();
@Test @Test
public void roundTripConversion() { void roundTripConversion() {
TestEntity entity = new TestEntity(CurrencyUnit.EUR); TestEntity entity = new TestEntity(CurrencyUnit.EUR);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(entity)); jpaTm().transact(() -> jpaTm().getEntityManager().persist(entity));
assertThat( assertThat(
@ -59,7 +56,7 @@ public class CurrencyUnitConverterTest {
} }
@Test @Test
public void invalidCurrency() { void invalidCurrency() {
jpaTm() jpaTm()
.transact( .transact(
() -> () ->

View file

@ -19,46 +19,43 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import java.sql.Timestamp; import java.sql.Timestamp;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat; import org.joda.time.format.ISODateTimeFormat;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link DateTimeConverter}. */ /** Unit tests for {@link DateTimeConverter}. */
@RunWith(JUnit4.class)
public class DateTimeConverterTest { public class DateTimeConverterTest {
@Rule @RegisterExtension
public final JpaUnitTestRule jpaRule = public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule(); new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule();
private final DateTimeConverter converter = new DateTimeConverter(); private final DateTimeConverter converter = new DateTimeConverter();
@Test @Test
public void convertToDatabaseColumn_returnsNullIfInputIsNull() { void convertToDatabaseColumn_returnsNullIfInputIsNull() {
assertThat(converter.convertToDatabaseColumn(null)).isNull(); assertThat(converter.convertToDatabaseColumn(null)).isNull();
} }
@Test @Test
public void convertToDatabaseColumn_convertsCorrectly() { void convertToDatabaseColumn_convertsCorrectly() {
DateTime dateTime = DateTime.parse("2019-09-01T01:01:01"); DateTime dateTime = DateTime.parse("2019-09-01T01:01:01");
assertThat(converter.convertToDatabaseColumn(dateTime).getTime()) assertThat(converter.convertToDatabaseColumn(dateTime).getTime())
.isEqualTo(dateTime.getMillis()); .isEqualTo(dateTime.getMillis());
} }
@Test @Test
public void convertToEntityAttribute_returnsNullIfInputIsNull() { void convertToEntityAttribute_returnsNullIfInputIsNull() {
assertThat(converter.convertToEntityAttribute(null)).isNull(); assertThat(converter.convertToEntityAttribute(null)).isNull();
} }
@Test @Test
public void convertToEntityAttribute_convertsCorrectly() { void convertToEntityAttribute_convertsCorrectly() {
DateTime dateTime = DateTime.parse("2019-09-01T01:01:01Z"); DateTime dateTime = DateTime.parse("2019-09-01T01:01:01Z");
long millis = dateTime.getMillis(); long millis = dateTime.getMillis();
assertThat(converter.convertToEntityAttribute(new Timestamp(millis))).isEqualTo(dateTime); assertThat(converter.convertToEntityAttribute(new Timestamp(millis))).isEqualTo(dateTime);
@ -69,7 +66,7 @@ public class DateTimeConverterTest {
} }
@Test @Test
public void converter_generatesTimestampWithNormalizedZone() { void converter_generatesTimestampWithNormalizedZone() {
DateTime dt = parseDateTime("2019-09-01T01:01:01Z"); DateTime dt = parseDateTime("2019-09-01T01:01:01Z");
TestEntity entity = new TestEntity("normalized_utc_time", dt); TestEntity entity = new TestEntity("normalized_utc_time", dt);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(entity)); jpaTm().transact(() -> jpaTm().getEntityManager().persist(entity));
@ -81,7 +78,7 @@ public class DateTimeConverterTest {
} }
@Test @Test
public void converter_convertsNonUtcZoneCorrectly() { void converter_convertsNonUtcZoneCorrectly() {
DateTime dt = parseDateTime("2019-09-01T01:01:01-05:00"); DateTime dt = parseDateTime("2019-09-01T01:01:01-05:00");
TestEntity entity = new TestEntity("new_york_time", dt); TestEntity entity = new TestEntity("new_york_time", dt);

View file

@ -19,35 +19,32 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import google.registry.schema.replay.EntityTest.EntityForTesting; import google.registry.schema.replay.EntityTest.EntityForTesting;
import java.math.BigInteger; import java.math.BigInteger;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import org.joda.time.Duration; import org.joda.time.Duration;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link DurationConverter}. */ /** Unit tests for {@link DurationConverter}. */
@RunWith(JUnit4.class)
public class DurationConverterTest { public class DurationConverterTest {
@Rule @RegisterExtension
public final JpaUnitTestRule jpaRule = public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule(); new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule();
private final DurationConverter converter = new DurationConverter(); private final DurationConverter converter = new DurationConverter();
@Test @Test
public void testNulls() { void testNulls() {
assertThat(converter.convertToDatabaseColumn(null)).isNull(); assertThat(converter.convertToDatabaseColumn(null)).isNull();
assertThat(converter.convertToEntityAttribute(null)).isNull(); assertThat(converter.convertToEntityAttribute(null)).isNull();
} }
@Test @Test
public void testRoundTrip() { void testRoundTrip() {
TestEntity entity = new TestEntity(Duration.standardDays(6)); TestEntity entity = new TestEntity(Duration.standardDays(6));
jpaTm().transact(() -> jpaTm().getEntityManager().persist(entity)); jpaTm().transact(() -> jpaTm().getEntityManager().persist(entity));
assertThat( assertThat(

View file

@ -42,7 +42,7 @@ public class InetAddressSetConverterTest {
.build(); .build();
@Test @Test
public void roundTripConversion_returnsSameAddresses() { void roundTripConversion_returnsSameAddresses() {
verifySaveAndLoad( verifySaveAndLoad(
ImmutableSet.of( ImmutableSet.of(
InetAddresses.forString("0.0.0.0"), InetAddresses.forString("0.0.0.0"),
@ -52,12 +52,12 @@ public class InetAddressSetConverterTest {
} }
@Test @Test
public void roundTrip_emptySet() { void roundTrip_emptySet() {
verifySaveAndLoad(ImmutableSet.of()); verifySaveAndLoad(ImmutableSet.of());
} }
@Test @Test
public void roundTrip_null() { void roundTrip_null() {
verifySaveAndLoad(null); verifySaveAndLoad(null);
} }

View file

@ -19,7 +19,7 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import google.registry.schema.replay.EntityTest.EntityForTesting; import google.registry.schema.replay.EntityTest.EntityForTesting;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Arrays; import java.util.Arrays;
@ -38,10 +38,8 @@ import javax.persistence.MapKeyColumn;
import javax.persistence.PostLoad; import javax.persistence.PostLoad;
import org.joda.money.CurrencyUnit; import org.joda.money.CurrencyUnit;
import org.joda.money.Money; import org.joda.money.Money;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** /**
* Unit tests for embeddable {@link Money}. * Unit tests for embeddable {@link Money}.
@ -61,16 +59,16 @@ import org.junit.runners.JUnit4;
* appropriate for the currency. This is espcially necessary for currencies like JPY where the scale * appropriate for the currency. This is espcially necessary for currencies like JPY where the scale
* is 0, which is different from the default scale that {@link BigDecimal} is persisted in database. * is 0, which is different from the default scale that {@link BigDecimal} is persisted in database.
*/ */
@RunWith(JUnit4.class)
public class JodaMoneyConverterTest { public class JodaMoneyConverterTest {
@Rule
public final JpaUnitTestRule jpaRule = @RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder() new JpaTestRules.Builder()
.withEntityClass(TestEntity.class, ComplexTestEntity.class) .withEntityClass(TestEntity.class, ComplexTestEntity.class)
.buildUnitTestRule(); .buildUnitTestRule();
@Test @Test
public void roundTripConversion() { void roundTripConversion() {
Money money = Money.of(CurrencyUnit.USD, 100); Money money = Money.of(CurrencyUnit.USD, 100);
TestEntity entity = new TestEntity(money); TestEntity entity = new TestEntity(money);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(entity)); jpaTm().transact(() -> jpaTm().getEntityManager().persist(entity));
@ -94,7 +92,7 @@ public class JodaMoneyConverterTest {
} }
@Test @Test
public void roundTripConversionWithComplexEntity() { void roundTripConversionWithComplexEntity() {
Money myMoney = Money.of(CurrencyUnit.USD, 100); Money myMoney = Money.of(CurrencyUnit.USD, 100);
Money yourMoney = Money.of(CurrencyUnit.GBP, 80); Money yourMoney = Money.of(CurrencyUnit.GBP, 80);
ImmutableMap<String, Money> moneyMap = ImmutableMap<String, Money> moneyMap =

View file

@ -20,7 +20,7 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.persistence.VKey; import google.registry.persistence.VKey;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import google.registry.schema.replay.EntityTest; import google.registry.schema.replay.EntityTest;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
@ -33,7 +33,7 @@ import org.junit.jupiter.api.extension.RegisterExtension;
public class LocalDateConverterTest { public class LocalDateConverterTest {
@RegisterExtension @RegisterExtension
public final JpaUnitTestRule jpaRule = public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder() new JpaTestRules.Builder()
.withEntityClass(LocalDateConverterTestEntity.class) .withEntityClass(LocalDateConverterTestEntity.class)
.buildUnitTestRule(); .buildUnitTestRule();
@ -41,13 +41,13 @@ public class LocalDateConverterTest {
private final LocalDate exampleDate = LocalDate.parse("2020-06-10", ISODateTimeFormat.date()); private final LocalDate exampleDate = LocalDate.parse("2020-06-10", ISODateTimeFormat.date());
@Test @Test
public void testNullInput() { void testNullInput() {
LocalDateConverterTestEntity retrievedEntity = persistAndLoadTestEntity(null); LocalDateConverterTestEntity retrievedEntity = persistAndLoadTestEntity(null);
assertThat(retrievedEntity.date).isNull(); assertThat(retrievedEntity.date).isNull();
} }
@Test @Test
public void testSaveAndLoad_success() { void testSaveAndLoad_success() {
LocalDateConverterTestEntity retrievedEntity = persistAndLoadTestEntity(exampleDate); LocalDateConverterTestEntity retrievedEntity = persistAndLoadTestEntity(exampleDate);
assertThat(retrievedEntity.date).isEqualTo(exampleDate); assertThat(retrievedEntity.date).isEqualTo(exampleDate);
} }

View file

@ -20,26 +20,23 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import google.registry.persistence.VKey; import google.registry.persistence.VKey;
import google.registry.persistence.WithLongVKey; import google.registry.persistence.WithLongVKey;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Test SQL persistence of VKey. */ /** Test SQL persistence of VKey. */
@RunWith(JUnit4.class)
public class LongVKeyConverterTest { public class LongVKeyConverterTest {
@Rule @RegisterExtension
public final JpaUnitTestRule jpaRule = public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder() new JpaTestRules.Builder()
.withEntityClass(TestEntity.class, VKeyConverter_LongType.class) .withEntityClass(TestEntity.class, VKeyConverter_LongType.class)
.buildUnitTestRule(); .buildUnitTestRule();
@Test @Test
public void testRoundTrip() { void testRoundTrip() {
TestEntity original = new TestEntity(VKey.createSql(TestEntity.class, 10L)); TestEntity original = new TestEntity(VKey.createSql(TestEntity.class, 10L));
jpaTm().transact(() -> jpaTm().getEntityManager().persist(original)); jpaTm().transact(() -> jpaTm().getEntityManager().persist(original));

View file

@ -20,24 +20,22 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import google.registry.model.eppcommon.StatusValue; import google.registry.model.eppcommon.StatusValue;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import java.util.Set; import java.util.Set;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link StatusValueSetConverter}. */ /** Unit tests for {@link StatusValueSetConverter}. */
@RunWith(JUnit4.class)
public class StatusValueSetConverterTest { public class StatusValueSetConverterTest {
@Rule
public final JpaUnitTestRule jpaRule = @RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule(); new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule();
@Test @Test
public void testRoundTrip() { void testRoundTrip() {
Set<StatusValue> enums = ImmutableSet.of(StatusValue.INACTIVE, StatusValue.PENDING_DELETE); Set<StatusValue> enums = ImmutableSet.of(StatusValue.INACTIVE, StatusValue.PENDING_DELETE);
TestEntity obj = new TestEntity("foo", enums); TestEntity obj = new TestEntity("foo", enums);

View file

@ -21,25 +21,23 @@ import static org.junit.Assert.assertThrows;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import java.util.List; import java.util.List;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.NoResultException; import javax.persistence.NoResultException;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link StringListConverter}. */ /** Unit tests for {@link StringListConverter}. */
@RunWith(JUnit4.class)
public class StringListConverterTest { public class StringListConverterTest {
@Rule
public final JpaUnitTestRule jpaRule = @RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule(); new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule();
@Test @Test
public void roundTripConversion_returnsSameStringList() { void roundTripConversion_returnsSameStringList() {
List<String> tlds = ImmutableList.of("app", "dev", "how"); List<String> tlds = ImmutableList.of("app", "dev", "how");
TestEntity testEntity = new TestEntity(tlds); TestEntity testEntity = new TestEntity(tlds);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity)); jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
@ -49,7 +47,7 @@ public class StringListConverterTest {
} }
@Test @Test
public void testMerge_succeeds() { void testMerge_succeeds() {
List<String> tlds = ImmutableList.of("app", "dev", "how"); List<String> tlds = ImmutableList.of("app", "dev", "how");
TestEntity testEntity = new TestEntity(tlds); TestEntity testEntity = new TestEntity(tlds);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity)); jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
@ -63,7 +61,7 @@ public class StringListConverterTest {
} }
@Test @Test
public void testNullValue_writesAndReadsNullSuccessfully() { void testNullValue_writesAndReadsNullSuccessfully() {
TestEntity testEntity = new TestEntity(null); TestEntity testEntity = new TestEntity(null);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity)); jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
TestEntity persisted = TestEntity persisted =
@ -72,7 +70,7 @@ public class StringListConverterTest {
} }
@Test @Test
public void testEmptyCollection_writesAndReadsEmptyCollectionSuccessfully() { void testEmptyCollection_writesAndReadsEmptyCollectionSuccessfully() {
TestEntity testEntity = new TestEntity(ImmutableList.of()); TestEntity testEntity = new TestEntity(ImmutableList.of());
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity)); jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
TestEntity persisted = TestEntity persisted =
@ -81,7 +79,7 @@ public class StringListConverterTest {
} }
@Test @Test
public void testNativeQuery_succeeds() throws Exception { void testNativeQuery_succeeds() throws Exception {
executeNativeQuery("INSERT INTO \"TestEntity\" (name, tlds) VALUES ('id', '{app, dev}')"); executeNativeQuery("INSERT INTO \"TestEntity\" (name, tlds) VALUES ('id', '{app, dev}')");
assertThat( assertThat(

View file

@ -22,21 +22,20 @@ import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import java.util.Map; import java.util.Map;
import javax.persistence.Converter; import javax.persistence.Converter;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.NoResultException; import javax.persistence.NoResultException;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link StringMapConverterBase}. */ /** Unit tests for {@link StringMapConverterBase}. */
@RunWith(JUnit4.class)
public class StringMapConverterBaseTest { public class StringMapConverterBaseTest {
@Rule
public final JpaTestRules.JpaUnitTestRule jpaRule = @RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder() new JpaTestRules.Builder()
.withInitScript("sql/flyway/V14__load_extension_for_hstore.sql") .withInitScript("sql/flyway/V14__load_extension_for_hstore.sql")
.withEntityClass(TestStringMapConverter.class, TestEntity.class) .withEntityClass(TestStringMapConverter.class, TestEntity.class)
@ -49,7 +48,7 @@ public class StringMapConverterBaseTest {
new Key("key3"), new Value("value3")); new Key("key3"), new Value("value3"));
@Test @Test
public void roundTripConversion_returnsSameMap() { void roundTripConversion_returnsSameMap() {
TestEntity testEntity = new TestEntity(MAP); TestEntity testEntity = new TestEntity(MAP);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity)); jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
TestEntity persisted = TestEntity persisted =
@ -58,7 +57,7 @@ public class StringMapConverterBaseTest {
} }
@Test @Test
public void testUpdateColumn_succeeds() { void testUpdateColumn_succeeds() {
TestEntity testEntity = new TestEntity(MAP); TestEntity testEntity = new TestEntity(MAP);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity)); jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
TestEntity persisted = TestEntity persisted =
@ -72,7 +71,7 @@ public class StringMapConverterBaseTest {
} }
@Test @Test
public void testNullValue_writesAndReadsNullSuccessfully() { void testNullValue_writesAndReadsNullSuccessfully() {
TestEntity testEntity = new TestEntity(null); TestEntity testEntity = new TestEntity(null);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity)); jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
TestEntity persisted = TestEntity persisted =
@ -81,7 +80,7 @@ public class StringMapConverterBaseTest {
} }
@Test @Test
public void testEmptyMap_writesAndReadsEmptyCollectionSuccessfully() { void testEmptyMap_writesAndReadsEmptyCollectionSuccessfully() {
TestEntity testEntity = new TestEntity(ImmutableMap.of()); TestEntity testEntity = new TestEntity(ImmutableMap.of());
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity)); jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
TestEntity persisted = TestEntity persisted =
@ -90,7 +89,7 @@ public class StringMapConverterBaseTest {
} }
@Test @Test
public void testNativeQuery_succeeds() { void testNativeQuery_succeeds() {
executeNativeQuery( executeNativeQuery(
"INSERT INTO \"TestEntity\" (name, map) VALUES ('id', 'key1=>value1, key2=>value2')"); "INSERT INTO \"TestEntity\" (name, map) VALUES ('id', 'key1=>value1, key2=>value2')");

View file

@ -20,24 +20,22 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import java.util.Set; import java.util.Set;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link StringSetConverter}. */ /** Unit tests for {@link StringSetConverter}. */
@RunWith(JUnit4.class)
public class StringSetConverterTest { public class StringSetConverterTest {
@Rule
public final JpaUnitTestRule jpaRule = @RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule(); new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule();
@Test @Test
public void roundTripConversion_returnsSameStringList() { void roundTripConversion_returnsSameStringList() {
Set<String> tlds = ImmutableSet.of("app", "dev", "how"); Set<String> tlds = ImmutableSet.of("app", "dev", "how");
TestEntity testEntity = new TestEntity(tlds); TestEntity testEntity = new TestEntity(tlds);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity)); jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
@ -47,7 +45,7 @@ public class StringSetConverterTest {
} }
@Test @Test
public void testNullValue_writesAndReadsNullSuccessfully() { void testNullValue_writesAndReadsNullSuccessfully() {
TestEntity testEntity = new TestEntity(null); TestEntity testEntity = new TestEntity(null);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity)); jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
TestEntity persisted = TestEntity persisted =
@ -56,7 +54,7 @@ public class StringSetConverterTest {
} }
@Test @Test
public void testEmptyCollection_writesAndReadsEmptyCollectionSuccessfully() { void testEmptyCollection_writesAndReadsEmptyCollectionSuccessfully() {
TestEntity testEntity = new TestEntity(ImmutableSet.of()); TestEntity testEntity = new TestEntity(ImmutableSet.of());
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity)); jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
TestEntity persisted = TestEntity persisted =

View file

@ -20,28 +20,23 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import google.registry.persistence.VKey; import google.registry.persistence.VKey;
import google.registry.persistence.WithStringVKey; import google.registry.persistence.WithStringVKey;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Test SQL persistence of VKey. */ /** Test SQL persistence of VKey. */
@RunWith(JUnit4.class)
public class StringVKeyConverterTest { public class StringVKeyConverterTest {
@Rule @RegisterExtension
public final JpaUnitTestRule jpaRule = public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder() new JpaTestRules.Builder()
.withEntityClass(TestEntity.class, VKeyConverter_StringType.class) .withEntityClass(TestEntity.class, VKeyConverter_StringType.class)
.buildUnitTestRule(); .buildUnitTestRule();
public StringVKeyConverterTest() {}
@Test @Test
public void testRoundTrip() { void testRoundTrip() {
TestEntity original = TestEntity original =
new TestEntity("TheRealSpartacus", VKey.createSql(TestEntity.class, "ImSpartacus!")); new TestEntity("TheRealSpartacus", VKey.createSql(TestEntity.class, "ImSpartacus!"));
jpaTm().transact(() -> jpaTm().getEntityManager().persist(original)); jpaTm().transact(() -> jpaTm().getEntityManager().persist(original));

View file

@ -20,26 +20,23 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.model.registrar.Registrar.State; import google.registry.model.registrar.Registrar.State;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.EnumType; import javax.persistence.EnumType;
import javax.persistence.Enumerated; import javax.persistence.Enumerated;
import javax.persistence.Id; import javax.persistence.Id;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link Enumerated} annotation. */ /** Unit tests for {@link Enumerated} annotation. */
@RunWith(JUnit4.class)
public class StringValueEnumeratedTest { public class StringValueEnumeratedTest {
@Rule @RegisterExtension
public final JpaUnitTestRule jpaRule = public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule(); new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule();
@Test @Test
public void roundTripConversion_returnsSameEnum() { void roundTripConversion_returnsSameEnum() {
TestEntity testEntity = new TestEntity(State.ACTIVE); TestEntity testEntity = new TestEntity(State.ACTIVE);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity)); jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
TestEntity persisted = TestEntity persisted =
@ -48,7 +45,7 @@ public class StringValueEnumeratedTest {
} }
@Test @Test
public void testNativeQuery_succeeds() { void testNativeQuery_succeeds() {
TestEntity testEntity = new TestEntity(State.DISABLED); TestEntity testEntity = new TestEntity(State.DISABLED);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity)); jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));

View file

@ -25,7 +25,7 @@ import google.registry.model.ImmutableObject;
import google.registry.model.common.TimedTransitionProperty; import google.registry.model.common.TimedTransitionProperty;
import google.registry.model.common.TimedTransitionProperty.TimedTransition; import google.registry.model.common.TimedTransitionProperty.TimedTransition;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import java.util.Map; import java.util.Map;
import javax.persistence.Converter; import javax.persistence.Converter;
import javax.persistence.Entity; import javax.persistence.Entity;
@ -36,10 +36,10 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link TimedTransitionPropertyConverterBase}. */ /** Unit tests for {@link TimedTransitionPropertyConverterBase}. */
public class TimedTransitionPropertyConverterBaseTest { class TimedTransitionPropertyConverterBaseTest {
@RegisterExtension @RegisterExtension
public final JpaUnitTestRule jpa = public final JpaUnitTestExtension jpa =
new JpaTestRules.Builder() new JpaTestRules.Builder()
.withInitScript("sql/flyway/V14__load_extension_for_hstore.sql") .withInitScript("sql/flyway/V14__load_extension_for_hstore.sql")
.withEntityClass(TestTimedTransitionPropertyConverter.class, TestEntity.class) .withEntityClass(TestTimedTransitionPropertyConverter.class, TestEntity.class)

View file

@ -24,7 +24,7 @@ import google.registry.model.common.TimedTransitionProperty;
import google.registry.model.registry.Registry.TldState; import google.registry.model.registry.Registry.TldState;
import google.registry.model.registry.Registry.TldStateTransition; import google.registry.model.registry.Registry.TldStateTransition;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import org.joda.time.DateTime; import org.joda.time.DateTime;
@ -32,10 +32,10 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link TldStateTransitionConverter}. */ /** Unit tests for {@link TldStateTransitionConverter}. */
public class TldStateTransitionConverterTest { class TldStateTransitionConverterTest {
@RegisterExtension @RegisterExtension
public final JpaUnitTestRule jpa = public final JpaUnitTestExtension jpa =
new JpaTestRules.Builder() new JpaTestRules.Builder()
.withInitScript("sql/flyway/V14__load_extension_for_hstore.sql") .withInitScript("sql/flyway/V14__load_extension_for_hstore.sql")
.withEntityClass(TestEntity.class) .withEntityClass(TestEntity.class)

View file

@ -19,31 +19,28 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.model.UpdateAutoTimestamp; import google.registry.model.UpdateAutoTimestamp;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import google.registry.schema.replay.EntityTest.EntityForTesting; import google.registry.schema.replay.EntityTest.EntityForTesting;
import google.registry.testing.FakeClock; import google.registry.testing.FakeClock;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link UpdateAutoTimestampConverter}. */ /** Unit tests for {@link UpdateAutoTimestampConverter}. */
@RunWith(JUnit4.class)
public class UpdateAutoTimestampConverterTest { public class UpdateAutoTimestampConverterTest {
private final FakeClock fakeClock = new FakeClock(); private final FakeClock fakeClock = new FakeClock();
@Rule @RegisterExtension
public final JpaUnitTestRule jpaRule = public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder() new JpaTestRules.Builder()
.withClock(fakeClock) .withClock(fakeClock)
.withEntityClass(TestEntity.class) .withEntityClass(TestEntity.class)
.buildUnitTestRule(); .buildUnitTestRule();
@Test @Test
public void testTypeConversion() { void testTypeConversion() {
TestEntity ent = new TestEntity("myinst", null); TestEntity ent = new TestEntity("myinst", null);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(ent)); jpaTm().transact(() -> jpaTm().getEntityManager().persist(ent));
@ -56,7 +53,7 @@ public class UpdateAutoTimestampConverterTest {
} }
@Test @Test
public void testTimeChangesOnSubsequentTransactions() { void testTimeChangesOnSubsequentTransactions() {
TestEntity ent1 = new TestEntity("myinst1", null); TestEntity ent1 = new TestEntity("myinst1", null);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(ent1)); jpaTm().transact(() -> jpaTm().getEntityManager().persist(ent1));

View file

@ -19,46 +19,43 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.time.Instant; import java.time.Instant;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link ZonedDateTimeConverter}. */ /** Unit tests for {@link ZonedDateTimeConverter}. */
@RunWith(JUnit4.class)
public class ZonedDateTimeConverterTest { public class ZonedDateTimeConverterTest {
@Rule @RegisterExtension
public final JpaUnitTestRule jpaRule = public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule(); new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule();
private final ZonedDateTimeConverter converter = new ZonedDateTimeConverter(); private final ZonedDateTimeConverter converter = new ZonedDateTimeConverter();
@Test @Test
public void convertToDatabaseColumn_returnsNullIfInputIsNull() { void convertToDatabaseColumn_returnsNullIfInputIsNull() {
assertThat(converter.convertToDatabaseColumn(null)).isNull(); assertThat(converter.convertToDatabaseColumn(null)).isNull();
} }
@Test @Test
public void convertToDatabaseColumn_convertsCorrectly() { void convertToDatabaseColumn_convertsCorrectly() {
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2019-09-01T01:01:01Z"); ZonedDateTime zonedDateTime = ZonedDateTime.parse("2019-09-01T01:01:01Z");
assertThat(converter.convertToDatabaseColumn(zonedDateTime).toInstant()) assertThat(converter.convertToDatabaseColumn(zonedDateTime).toInstant())
.isEqualTo(zonedDateTime.toInstant()); .isEqualTo(zonedDateTime.toInstant());
} }
@Test @Test
public void convertToEntityAttribute_returnsNullIfInputIsNull() { void convertToEntityAttribute_returnsNullIfInputIsNull() {
assertThat(converter.convertToEntityAttribute(null)).isNull(); assertThat(converter.convertToEntityAttribute(null)).isNull();
} }
@Test @Test
public void convertToEntityAttribute_convertsCorrectly() { void convertToEntityAttribute_convertsCorrectly() {
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2019-09-01T01:01:01Z"); ZonedDateTime zonedDateTime = ZonedDateTime.parse("2019-09-01T01:01:01Z");
Instant instant = zonedDateTime.toInstant(); Instant instant = zonedDateTime.toInstant();
assertThat(converter.convertToEntityAttribute(Timestamp.from(instant))) assertThat(converter.convertToEntityAttribute(Timestamp.from(instant)))
@ -66,7 +63,7 @@ public class ZonedDateTimeConverterTest {
} }
@Test @Test
public void converter_generatesTimestampWithNormalizedZone() { void converter_generatesTimestampWithNormalizedZone() {
ZonedDateTime zdt = ZonedDateTime.parse("2019-09-01T01:01:01Z"); ZonedDateTime zdt = ZonedDateTime.parse("2019-09-01T01:01:01Z");
TestEntity entity = new TestEntity("normalized_utc_time", zdt); TestEntity entity = new TestEntity("normalized_utc_time", zdt);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(entity)); jpaTm().transact(() -> jpaTm().getEntityManager().persist(entity));
@ -78,7 +75,7 @@ public class ZonedDateTimeConverterTest {
} }
@Test @Test
public void converter_convertsNonNormalizedZoneCorrectly() { void converter_convertsNonNormalizedZoneCorrectly() {
ZonedDateTime zdt = ZonedDateTime.parse("2019-09-01T01:01:01Z[UTC]"); ZonedDateTime zdt = ZonedDateTime.parse("2019-09-01T01:01:01Z[UTC]");
TestEntity entity = new TestEntity("non_normalized_utc_time", zdt); TestEntity entity = new TestEntity("non_normalized_utc_time", zdt);
@ -91,7 +88,7 @@ public class ZonedDateTimeConverterTest {
} }
@Test @Test
public void converter_convertsNonUtcZoneCorrectly() { void converter_convertsNonUtcZoneCorrectly() {
ZonedDateTime zdt = ZonedDateTime.parse("2019-09-01T01:01:01+05:00"); ZonedDateTime zdt = ZonedDateTime.parse("2019-09-01T01:01:01+05:00");
TestEntity entity = new TestEntity("new_york_time", zdt); TestEntity entity = new TestEntity("new_york_time", zdt);

View file

@ -43,6 +43,7 @@ import org.junit.runners.model.Statement;
* JpaTransactionManager} instances. * JpaTransactionManager} instances.
*/ */
public class JpaTestRules { public class JpaTestRules {
private static final String GOLDEN_SCHEMA_SQL_PATH = "sql/schema/nomulus.golden.sql"; private static final String GOLDEN_SCHEMA_SQL_PATH = "sql/schema/nomulus.golden.sql";
/** /**
@ -50,7 +51,6 @@ public class JpaTestRules {
* with the Nomulus Cloud SQL schema. * with the Nomulus Cloud SQL schema.
*/ */
public static class JpaIntegrationTestRule extends JpaTransactionManagerRule { public static class JpaIntegrationTestRule extends JpaTransactionManagerRule {
private JpaIntegrationTestRule( private JpaIntegrationTestRule(
Clock clock, Clock clock,
ImmutableList<Class> extraEntityClasses, ImmutableList<Class> extraEntityClasses,
@ -59,14 +59,15 @@ public class JpaTestRules {
} }
} }
private static final AssertionError EXCEPTION_OF_DISAPPROVAL =
new AssertionError("ಠ_ಠ Why are you writing new tests in JUnit 4?? ಠ_ಠ");
/** /**
* Junit rule for unit tests with JPA framework, when the underlying database is populated by the * JUnit extension for unit tests with JPA framework, when the underlying database is populated by
* optional init script (which must not be the Nomulus Cloud SQL schema). This rule can also be * the optional init script (which must not be the Nomulus Cloud SQL schema).
* used as am extension for JUnit5 tests.
*/ */
public static class JpaUnitTestRule extends JpaTransactionManagerRule public static class JpaUnitTestExtension extends JpaTransactionManagerRule {
implements BeforeEachCallback, AfterEachCallback { private JpaUnitTestExtension(
private JpaUnitTestRule(
Clock clock, Clock clock,
Optional<String> initScriptPath, Optional<String> initScriptPath,
ImmutableList<Class> extraEntityClasses, ImmutableList<Class> extraEntityClasses,
@ -75,13 +76,13 @@ public class JpaTestRules {
} }
@Override @Override
public void beforeEach(ExtensionContext context) throws Exception { public void before() {
this.before(); throw EXCEPTION_OF_DISAPPROVAL;
} }
@Override @Override
public void afterEach(ExtensionContext context) throws Exception { public void after() {
this.after(); throw EXCEPTION_OF_DISAPPROVAL;
} }
} }
@ -157,7 +158,7 @@ public class JpaTestRules {
* Sets the SQL script to be used to initialize the database. If not set, * Sets the SQL script to be used to initialize the database. If not set,
* sql/schema/nomulus.golden.sql will be used. * sql/schema/nomulus.golden.sql will be used.
* *
* <p>The {@code initScript} is only accepted when building {@link JpaUnitTestRule}. * <p>The {@code initScript} is only accepted when building {@link JpaUnitTestExtension}.
*/ */
public Builder withInitScript(String initScript) { public Builder withInitScript(String initScript) {
this.initScript = initScript; this.initScript = initScript;
@ -219,13 +220,14 @@ public class JpaTestRules {
} }
/** /**
* Builds a {@link JpaUnitTestRule} instance that can also be used as an extension for JUnit5. * Builds a {@link JpaUnitTestExtension} instance that can also be used as an extension for
* JUnit5.
*/ */
public JpaUnitTestRule buildUnitTestRule() { public JpaUnitTestExtension buildUnitTestRule() {
checkState( checkState(
!Objects.equals(GOLDEN_SCHEMA_SQL_PATH, initScript), !Objects.equals(GOLDEN_SCHEMA_SQL_PATH, initScript),
"Unit tests must not depend on the Nomulus schema."); "Unit tests must not depend on the Nomulus schema.");
return new JpaUnitTestRule( return new JpaUnitTestExtension(
clock == null ? new FakeClock(DateTime.now(UTC)) : clock, clock == null ? new FakeClock(DateTime.now(UTC)) : clock,
Optional.ofNullable(initScript), Optional.ofNullable(initScript),
ImmutableList.copyOf(extraEntityClasses), ImmutableList.copyOf(extraEntityClasses),

View file

@ -18,7 +18,7 @@ import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
@ -28,23 +28,24 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit test for {@link JpaTestRules.Builder#withSqlLogging()}. */ /** Unit test for {@link JpaTestRules.Builder#withSqlLogging()}. */
public class JpaTestRulesSqlLoggingTest { class JpaTestRulesSqlLoggingTest {
// Entity under test: configured to log SQL statements to Stdout. // Entity under test: configured to log SQL statements to Stdout.
@RegisterExtension @RegisterExtension
JpaUnitTestRule jpaRule = new JpaTestRules.Builder().withSqlLogging().buildUnitTestRule(); JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withSqlLogging().buildUnitTestRule();
private PrintStream orgStdout; private PrintStream orgStdout;
private ByteArrayOutputStream stdoutBuffer; private ByteArrayOutputStream stdoutBuffer;
@BeforeEach @BeforeEach
public void beforeEach() { void beforeEach() {
orgStdout = System.out; orgStdout = System.out;
System.setOut(new PrintStream(stdoutBuffer = new ByteArrayOutputStream())); System.setOut(new PrintStream(stdoutBuffer = new ByteArrayOutputStream()));
} }
@AfterEach @AfterEach
public void afterEach() { void afterEach() {
System.setOut(orgStdout); System.setOut(orgStdout);
} }

View file

@ -22,7 +22,7 @@ import static org.junit.Assert.assertThrows;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.persistence.VKey; import google.registry.persistence.VKey;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import google.registry.testing.FakeClock; import google.registry.testing.FakeClock;
import java.io.Serializable; import java.io.Serializable;
import java.math.BigInteger; import java.math.BigInteger;
@ -32,10 +32,8 @@ import javax.persistence.EntityManager;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.IdClass; import javax.persistence.IdClass;
import javax.persistence.RollbackException; import javax.persistence.RollbackException;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** /**
* Unit tests for SQL only APIs defined in {@link JpaTransactionManagerImpl}. Note that the tests * Unit tests for SQL only APIs defined in {@link JpaTransactionManagerImpl}. Note that the tests
@ -44,8 +42,7 @@ import org.junit.runners.JUnit4;
* <p>TODO(shicong): Remove duplicate tests that covered by TransactionManagerTest by refactoring * <p>TODO(shicong): Remove duplicate tests that covered by TransactionManagerTest by refactoring
* the test schema. * the test schema.
*/ */
@RunWith(JUnit4.class) class JpaTransactionManagerImplTest {
public class JpaTransactionManagerImplTest {
private final FakeClock fakeClock = new FakeClock(); private final FakeClock fakeClock = new FakeClock();
private final TestEntity theEntity = new TestEntity("theEntity", "foo"); private final TestEntity theEntity = new TestEntity("theEntity", "foo");
@ -60,8 +57,8 @@ public class JpaTransactionManagerImplTest {
new TestEntity("entity2", "bar"), new TestEntity("entity2", "bar"),
new TestEntity("entity3", "qux")); new TestEntity("entity3", "qux"));
@Rule @RegisterExtension
public final JpaUnitTestRule jpaRule = final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder() new JpaTestRules.Builder()
.withInitScript(fileClassPath(getClass(), "test_schema.sql")) .withInitScript(fileClassPath(getClass(), "test_schema.sql"))
.withClock(fakeClock) .withClock(fakeClock)
@ -69,7 +66,7 @@ public class JpaTransactionManagerImplTest {
.buildUnitTestRule(); .buildUnitTestRule();
@Test @Test
public void transact_succeeds() { void transact_succeeds() {
assertPersonEmpty(); assertPersonEmpty();
assertCompanyEmpty(); assertCompanyEmpty();
jpaTm() jpaTm()
@ -87,7 +84,7 @@ public class JpaTransactionManagerImplTest {
} }
@Test @Test
public void transact_hasNoEffectWithPartialSuccess() { void transact_hasNoEffectWithPartialSuccess() {
assertPersonEmpty(); assertPersonEmpty();
assertCompanyEmpty(); assertCompanyEmpty();
assertThrows( assertThrows(
@ -105,7 +102,7 @@ public class JpaTransactionManagerImplTest {
} }
@Test @Test
public void transact_reusesExistingTransaction() { void transact_reusesExistingTransaction() {
assertPersonEmpty(); assertPersonEmpty();
assertCompanyEmpty(); assertCompanyEmpty();
jpaTm() jpaTm()
@ -126,7 +123,7 @@ public class JpaTransactionManagerImplTest {
} }
@Test @Test
public void saveNew_succeeds() { void saveNew_succeeds() {
assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse(); assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse();
jpaTm().transact(() -> jpaTm().saveNew(theEntity)); jpaTm().transact(() -> jpaTm().saveNew(theEntity));
assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isTrue(); assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isTrue();
@ -134,7 +131,7 @@ public class JpaTransactionManagerImplTest {
} }
@Test @Test
public void saveNew_throwsExceptionIfEntityExists() { void saveNew_throwsExceptionIfEntityExists() {
assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse(); assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse();
jpaTm().transact(() -> jpaTm().saveNew(theEntity)); jpaTm().transact(() -> jpaTm().saveNew(theEntity));
assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isTrue(); assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isTrue();
@ -143,7 +140,7 @@ public class JpaTransactionManagerImplTest {
} }
@Test @Test
public void createCompoundIdEntity_succeeds() { void createCompoundIdEntity_succeeds() {
assertThat(jpaTm().transact(() -> jpaTm().checkExists(compoundIdEntity))).isFalse(); assertThat(jpaTm().transact(() -> jpaTm().checkExists(compoundIdEntity))).isFalse();
jpaTm().transact(() -> jpaTm().saveNew(compoundIdEntity)); jpaTm().transact(() -> jpaTm().saveNew(compoundIdEntity));
assertThat(jpaTm().transact(() -> jpaTm().checkExists(compoundIdEntity))).isTrue(); assertThat(jpaTm().transact(() -> jpaTm().checkExists(compoundIdEntity))).isTrue();
@ -152,7 +149,7 @@ public class JpaTransactionManagerImplTest {
} }
@Test @Test
public void saveAllNew_succeeds() { void saveAllNew_succeeds() {
moreEntities.forEach( moreEntities.forEach(
entity -> assertThat(jpaTm().transact(() -> jpaTm().checkExists(entity))).isFalse()); entity -> assertThat(jpaTm().transact(() -> jpaTm().checkExists(entity))).isFalse());
jpaTm().transact(() -> jpaTm().saveAllNew(moreEntities)); jpaTm().transact(() -> jpaTm().saveAllNew(moreEntities));
@ -163,7 +160,7 @@ public class JpaTransactionManagerImplTest {
} }
@Test @Test
public void saveAllNew_rollsBackWhenFailure() { void saveAllNew_rollsBackWhenFailure() {
moreEntities.forEach( moreEntities.forEach(
entity -> assertThat(jpaTm().transact(() -> jpaTm().checkExists(entity))).isFalse()); entity -> assertThat(jpaTm().transact(() -> jpaTm().checkExists(entity))).isFalse());
jpaTm().transact(() -> jpaTm().saveNew(moreEntities.get(0))); jpaTm().transact(() -> jpaTm().saveNew(moreEntities.get(0)));
@ -175,7 +172,7 @@ public class JpaTransactionManagerImplTest {
} }
@Test @Test
public void saveNewOrUpdate_persistsNewEntity() { void saveNewOrUpdate_persistsNewEntity() {
assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse(); assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse();
jpaTm().transact(() -> jpaTm().saveNewOrUpdate(theEntity)); jpaTm().transact(() -> jpaTm().saveNewOrUpdate(theEntity));
assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isTrue(); assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isTrue();
@ -183,7 +180,7 @@ public class JpaTransactionManagerImplTest {
} }
@Test @Test
public void saveNewOrUpdate_updatesExistingEntity() { void saveNewOrUpdate_updatesExistingEntity() {
jpaTm().transact(() -> jpaTm().saveNew(theEntity)); jpaTm().transact(() -> jpaTm().saveNew(theEntity));
TestEntity persisted = jpaTm().transact(() -> jpaTm().load(theEntityKey)); TestEntity persisted = jpaTm().transact(() -> jpaTm().load(theEntityKey));
assertThat(persisted.data).isEqualTo("foo"); assertThat(persisted.data).isEqualTo("foo");
@ -194,7 +191,7 @@ public class JpaTransactionManagerImplTest {
} }
@Test @Test
public void saveNewOrUpdateAll_succeeds() { void saveNewOrUpdateAll_succeeds() {
moreEntities.forEach( moreEntities.forEach(
entity -> assertThat(jpaTm().transact(() -> jpaTm().checkExists(entity))).isFalse()); entity -> assertThat(jpaTm().transact(() -> jpaTm().checkExists(entity))).isFalse());
jpaTm().transact(() -> jpaTm().saveNewOrUpdateAll(moreEntities)); jpaTm().transact(() -> jpaTm().saveNewOrUpdateAll(moreEntities));
@ -205,7 +202,7 @@ public class JpaTransactionManagerImplTest {
} }
@Test @Test
public void update_succeeds() { void update_succeeds() {
jpaTm().transact(() -> jpaTm().saveNew(theEntity)); jpaTm().transact(() -> jpaTm().saveNew(theEntity));
TestEntity persisted = TestEntity persisted =
jpaTm().transact(() -> jpaTm().load(VKey.createSql(TestEntity.class, "theEntity"))); jpaTm().transact(() -> jpaTm().load(VKey.createSql(TestEntity.class, "theEntity")));
@ -217,7 +214,7 @@ public class JpaTransactionManagerImplTest {
} }
@Test @Test
public void updateCompoundIdEntity_succeeds() { void updateCompoundIdEntity_succeeds() {
jpaTm().transact(() -> jpaTm().saveNew(compoundIdEntity)); jpaTm().transact(() -> jpaTm().saveNew(compoundIdEntity));
TestCompoundIdEntity persisted = jpaTm().transact(() -> jpaTm().load(compoundIdEntityKey)); TestCompoundIdEntity persisted = jpaTm().transact(() -> jpaTm().load(compoundIdEntityKey));
assertThat(persisted.data).isEqualTo("foo"); assertThat(persisted.data).isEqualTo("foo");
@ -228,7 +225,7 @@ public class JpaTransactionManagerImplTest {
} }
@Test @Test
public void update_throwsExceptionWhenEntityDoesNotExist() { void update_throwsExceptionWhenEntityDoesNotExist() {
assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse(); assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse();
assertThrows( assertThrows(
IllegalArgumentException.class, () -> jpaTm().transact(() -> jpaTm().update(theEntity))); IllegalArgumentException.class, () -> jpaTm().transact(() -> jpaTm().update(theEntity)));
@ -236,7 +233,7 @@ public class JpaTransactionManagerImplTest {
} }
@Test @Test
public void updateAll_succeeds() { void updateAll_succeeds() {
jpaTm().transact(() -> jpaTm().saveAllNew(moreEntities)); jpaTm().transact(() -> jpaTm().saveAllNew(moreEntities));
ImmutableList<TestEntity> updated = ImmutableList<TestEntity> updated =
ImmutableList.of( ImmutableList.of(
@ -249,7 +246,7 @@ public class JpaTransactionManagerImplTest {
} }
@Test @Test
public void updateAll_rollsBackWhenFailure() { void updateAll_rollsBackWhenFailure() {
jpaTm().transact(() -> jpaTm().saveAllNew(moreEntities)); jpaTm().transact(() -> jpaTm().saveAllNew(moreEntities));
ImmutableList<TestEntity> updated = ImmutableList<TestEntity> updated =
ImmutableList.of( ImmutableList.of(
@ -264,7 +261,7 @@ public class JpaTransactionManagerImplTest {
} }
@Test @Test
public void load_succeeds() { void load_succeeds() {
assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse(); assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse();
jpaTm().transact(() -> jpaTm().saveNew(theEntity)); jpaTm().transact(() -> jpaTm().saveNew(theEntity));
TestEntity persisted = jpaTm().transact(() -> jpaTm().load(theEntityKey)); TestEntity persisted = jpaTm().transact(() -> jpaTm().load(theEntityKey));
@ -273,14 +270,14 @@ public class JpaTransactionManagerImplTest {
} }
@Test @Test
public void load_throwsOnMissingElement() { void load_throwsOnMissingElement() {
assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse(); assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse();
assertThrows( assertThrows(
NoSuchElementException.class, () -> jpaTm().transact(() -> jpaTm().load(theEntityKey))); NoSuchElementException.class, () -> jpaTm().transact(() -> jpaTm().load(theEntityKey)));
} }
@Test @Test
public void maybeLoad_succeeds() { void maybeLoad_succeeds() {
assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse(); assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse();
jpaTm().transact(() -> jpaTm().saveNew(theEntity)); jpaTm().transact(() -> jpaTm().saveNew(theEntity));
TestEntity persisted = jpaTm().transact(() -> jpaTm().maybeLoad(theEntityKey).get()); TestEntity persisted = jpaTm().transact(() -> jpaTm().maybeLoad(theEntityKey).get());
@ -289,13 +286,13 @@ public class JpaTransactionManagerImplTest {
} }
@Test @Test
public void maybeLoad_nonExistentObject() { void maybeLoad_nonExistentObject() {
assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse(); assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse();
assertThat(jpaTm().transact(() -> jpaTm().maybeLoad(theEntityKey)).isPresent()).isFalse(); assertThat(jpaTm().transact(() -> jpaTm().maybeLoad(theEntityKey)).isPresent()).isFalse();
} }
@Test @Test
public void loadCompoundIdEntity_succeeds() { void loadCompoundIdEntity_succeeds() {
assertThat(jpaTm().transact(() -> jpaTm().checkExists(compoundIdEntity))).isFalse(); assertThat(jpaTm().transact(() -> jpaTm().checkExists(compoundIdEntity))).isFalse();
jpaTm().transact(() -> jpaTm().saveNew(compoundIdEntity)); jpaTm().transact(() -> jpaTm().saveNew(compoundIdEntity));
TestCompoundIdEntity persisted = jpaTm().transact(() -> jpaTm().load(compoundIdEntityKey)); TestCompoundIdEntity persisted = jpaTm().transact(() -> jpaTm().load(compoundIdEntityKey));
@ -305,14 +302,14 @@ public class JpaTransactionManagerImplTest {
} }
@Test @Test
public void loadAll_succeeds() { void loadAll_succeeds() {
jpaTm().transact(() -> jpaTm().saveAllNew(moreEntities)); jpaTm().transact(() -> jpaTm().saveAllNew(moreEntities));
ImmutableList<TestEntity> persisted = jpaTm().transact(() -> jpaTm().loadAll(TestEntity.class)); ImmutableList<TestEntity> persisted = jpaTm().transact(() -> jpaTm().loadAll(TestEntity.class));
assertThat(persisted).containsExactlyElementsIn(moreEntities); assertThat(persisted).containsExactlyElementsIn(moreEntities);
} }
@Test @Test
public void delete_succeeds() { void delete_succeeds() {
jpaTm().transact(() -> jpaTm().saveNew(theEntity)); jpaTm().transact(() -> jpaTm().saveNew(theEntity));
assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isTrue(); assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isTrue();
jpaTm().transact(() -> jpaTm().delete(theEntityKey)); jpaTm().transact(() -> jpaTm().delete(theEntityKey));
@ -320,14 +317,14 @@ public class JpaTransactionManagerImplTest {
} }
@Test @Test
public void delete_returnsZeroWhenNoEntity() { void delete_returnsZeroWhenNoEntity() {
assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse(); assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse();
jpaTm().transact(() -> jpaTm().delete(theEntityKey)); jpaTm().transact(() -> jpaTm().delete(theEntityKey));
assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse(); assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse();
} }
@Test @Test
public void deleteCompoundIdEntity_succeeds() { void deleteCompoundIdEntity_succeeds() {
jpaTm().transact(() -> jpaTm().saveNew(compoundIdEntity)); jpaTm().transact(() -> jpaTm().saveNew(compoundIdEntity));
assertThat(jpaTm().transact(() -> jpaTm().checkExists(compoundIdEntity))).isTrue(); assertThat(jpaTm().transact(() -> jpaTm().checkExists(compoundIdEntity))).isTrue();
jpaTm().transact(() -> jpaTm().delete(compoundIdEntityKey)); jpaTm().transact(() -> jpaTm().delete(compoundIdEntityKey));
@ -335,7 +332,7 @@ public class JpaTransactionManagerImplTest {
} }
@Test @Test
public void assertDelete_throwsExceptionWhenEntityNotDeleted() { void assertDelete_throwsExceptionWhenEntityNotDeleted() {
assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse(); assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse();
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,

View file

@ -31,6 +31,7 @@ import google.registry.persistence.HibernateSchemaExporter;
import google.registry.persistence.NomulusPostgreSql; import google.registry.persistence.NomulusPostgreSql;
import google.registry.persistence.PersistenceModule; import google.registry.persistence.PersistenceModule;
import google.registry.persistence.PersistenceXmlUtility; import google.registry.persistence.PersistenceXmlUtility;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import google.registry.util.Clock; import google.registry.util.Clock;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -55,6 +56,9 @@ import javax.persistence.EntityManagerFactory;
import org.hibernate.cfg.Environment; import org.hibernate.cfg.Environment;
import org.hibernate.jpa.boot.internal.ParsedPersistenceXmlDescriptor; import org.hibernate.jpa.boot.internal.ParsedPersistenceXmlDescriptor;
import org.hibernate.jpa.boot.spi.Bootstrap; import org.hibernate.jpa.boot.spi.Bootstrap;
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.junit.rules.ExternalResource;
import org.testcontainers.containers.JdbcDatabaseContainer; import org.testcontainers.containers.JdbcDatabaseContainer;
import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.containers.PostgreSQLContainer;
@ -63,14 +67,16 @@ import org.testcontainers.containers.PostgreSQLContainer;
* Base class of JUnit Rules to provision {@link JpaTransactionManagerImpl} backed by {@link * Base class of JUnit Rules to provision {@link JpaTransactionManagerImpl} backed by {@link
* PostgreSQLContainer}. This class is not for direct use. Use specialized subclasses, {@link * PostgreSQLContainer}. This class is not for direct use. Use specialized subclasses, {@link
* google.registry.persistence.transaction.JpaTestRules.JpaIntegrationTestRule} or {@link * google.registry.persistence.transaction.JpaTestRules.JpaIntegrationTestRule} or {@link
* JpaTestRules.JpaUnitTestRule} as befits the use case. * JpaUnitTestExtension} as befits the use case.
* *
* <p>This rule also replaces the {@link JpaTransactionManagerImpl} provided by {@link * <p>This rule also replaces the {@link JpaTransactionManagerImpl} provided by {@link
* TransactionManagerFactory} with the {@link JpaTransactionManagerImpl} generated by the rule * TransactionManagerFactory} with the {@link JpaTransactionManagerImpl} generated by the rule
* itself, so that all SQL queries will be sent to the database instance created by {@link * itself, so that all SQL queries will be sent to the database instance created by {@link
* PostgreSQLContainer} to achieve test purpose. * PostgreSQLContainer} to achieve test purpose.
*/ */
abstract class JpaTransactionManagerRule extends ExternalResource { abstract class JpaTransactionManagerRule extends ExternalResource
implements BeforeEachCallback, AfterEachCallback {
private static final String DB_CLEANUP_SQL_PATH = private static final String DB_CLEANUP_SQL_PATH =
"google/registry/persistence/transaction/cleanup_database.sql"; "google/registry/persistence/transaction/cleanup_database.sql";
private static final String POSTGRES_DB_NAME = "postgres"; private static final String POSTGRES_DB_NAME = "postgres";
@ -191,7 +197,7 @@ abstract class JpaTransactionManagerRule extends ExternalResource {
} }
@Override @Override
public void before() throws Exception { public void beforeEach(ExtensionContext context) throws Exception {
if (entityHash == emfEntityHash) { if (entityHash == emfEntityHash) {
checkState(emf != null, "Missing EntityManagerFactory."); checkState(emf != null, "Missing EntityManagerFactory.");
resetTablesAndSequences(); resetTablesAndSequences();
@ -204,11 +210,21 @@ abstract class JpaTransactionManagerRule extends ExternalResource {
} }
@Override @Override
public void after() { public void afterEach(ExtensionContext context) {
TransactionManagerFactory.setJpaTm(Suppliers.ofInstance(cachedTm)); TransactionManagerFactory.setJpaTm(Suppliers.ofInstance(cachedTm));
cachedTm = null; cachedTm = null;
} }
@Override
public void before() throws Exception {
beforeEach(null);
}
@Override
public void after() {
afterEach(null);
}
public String getDatabaseUrl() { public String getDatabaseUrl() {
return database.getJdbcUrl(); return database.getJdbcUrl();
} }

View file

@ -19,29 +19,26 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertThrows;
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import google.registry.schema.tmch.ClaimsList; import google.registry.schema.tmch.ClaimsList;
import java.util.List; import java.util.List;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.PersistenceException; import javax.persistence.PersistenceException;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** JUnit test for {@link JpaTransactionManagerRule}, with {@link JpaUnitTestRule} as proxy. */ /** JUnit test for {@link JpaTransactionManagerRule}, with {@link JpaUnitTestExtension} as proxy. */
@RunWith(JUnit4.class)
public class JpaTransactionManagerRuleTest { public class JpaTransactionManagerRuleTest {
@Rule @RegisterExtension
public final JpaUnitTestRule jpaRule = public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder() new JpaTestRules.Builder()
.withEntityClass(ClaimsList.class, TestEntity.class) .withEntityClass(ClaimsList.class, TestEntity.class)
.buildUnitTestRule(); .buildUnitTestRule();
@Test @Test
public void verifiesRuleWorks() { void verifiesRuleWorks() {
assertThrows( assertThrows(
PersistenceException.class, PersistenceException.class,
() -> () ->
@ -65,7 +62,7 @@ public class JpaTransactionManagerRuleTest {
} }
@Test @Test
public void testExtraParameters() { void testExtraParameters() {
// This test verifies that 1) withEntityClass() has registered TestEntity and 2) The table // This test verifies that 1) withEntityClass() has registered TestEntity and 2) The table
// has been created, implying withProperty(HBM2DDL_AUTO, "update") worked. // has been created, implying withProperty(HBM2DDL_AUTO, "update") worked.
TestEntity original = new TestEntity("key", "value"); TestEntity original = new TestEntity("key", "value");

View file

@ -33,33 +33,29 @@ import google.registry.testing.FakeClock;
import google.registry.util.Clock; import google.registry.util.Clock;
import org.joda.money.Money; import org.joda.money.Money;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link PricingEngineProxy}. */ /** Tests for {@link PricingEngineProxy}. */
@RunWith(JUnit4.class)
public class PricingEngineProxyTest { public class PricingEngineProxyTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
private Clock clock; private Clock clock;
@Before @BeforeEach
public void before() { void beforeEach() {
PremiumList premiumList = persistPremiumList( PremiumList premiumList =
"rich,USD 100", persistPremiumList("rich,USD 100", "richer,USD 999", "fraction,USD 20.50");
"richer,USD 999",
"fraction,USD 20.50");
createTld("moka"); createTld("moka");
persistResource(Registry.get("moka").asBuilder().setPremiumList(premiumList).build()); persistResource(Registry.get("moka").asBuilder().setPremiumList(premiumList).build());
clock = new FakeClock(DateTime.parse("2016-03-17T12:01:00Z")); clock = new FakeClock(DateTime.parse("2016-03-17T12:01:00Z"));
} }
@Test @Test
public void test_getDomainCreateCost_multipleYears() { void test_getDomainCreateCost_multipleYears() {
assertThat(getDomainCreateCost("espresso.moka", clock.nowUtc(), 1)) assertThat(getDomainCreateCost("espresso.moka", clock.nowUtc(), 1))
.isEqualTo(Money.parse("USD 13")); .isEqualTo(Money.parse("USD 13"));
assertThat(getDomainCreateCost("espresso.moka", clock.nowUtc(), 5)) assertThat(getDomainCreateCost("espresso.moka", clock.nowUtc(), 5))
@ -71,7 +67,7 @@ public class PricingEngineProxyTest {
} }
@Test @Test
public void test_getDomainRenewCost_multipleYears() { void test_getDomainRenewCost_multipleYears() {
assertThat(getDomainRenewCost("espresso.moka", clock.nowUtc(), 1)) assertThat(getDomainRenewCost("espresso.moka", clock.nowUtc(), 1))
.isEqualTo(Money.parse("USD 11")); .isEqualTo(Money.parse("USD 11"));
assertThat(getDomainRenewCost("espresso.moka", clock.nowUtc(), 5)) assertThat(getDomainRenewCost("espresso.moka", clock.nowUtc(), 5))
@ -83,7 +79,7 @@ public class PricingEngineProxyTest {
} }
@Test @Test
public void testIsPremiumDomain() { void testIsPremiumDomain() {
createTld("example"); createTld("example");
assertThat(isDomainPremium("poor.example", clock.nowUtc())).isFalse(); assertThat(isDomainPremium("poor.example", clock.nowUtc())).isFalse();
assertThat(isDomainPremium("rich.example", clock.nowUtc())).isTrue(); assertThat(isDomainPremium("rich.example", clock.nowUtc())).isTrue();
@ -91,14 +87,12 @@ public class PricingEngineProxyTest {
} }
@Test @Test
public void testGetDomainCreateCost() { void testGetDomainCreateCost() {
// The example tld has a premium price for "rich". // The example tld has a premium price for "rich".
createTld("example"); createTld("example");
// The default value of 17 is set in createTld(). // The default value of 17 is set in createTld().
assertThat(getDomainCreateCost("poor.example", clock.nowUtc(), 1)) assertThat(getDomainCreateCost("poor.example", clock.nowUtc(), 1)).isEqualTo(Money.of(USD, 13));
.isEqualTo(Money.of(USD, 13)); assertThat(getDomainCreateCost("poor.example", clock.nowUtc(), 2)).isEqualTo(Money.of(USD, 26));
assertThat(getDomainCreateCost("poor.example", clock.nowUtc(), 2))
.isEqualTo(Money.of(USD, 26));
assertThat(getDomainCreateCost("rich.example", clock.nowUtc(), 1)) assertThat(getDomainCreateCost("rich.example", clock.nowUtc(), 1))
.isEqualTo(Money.of(USD, 100)); .isEqualTo(Money.of(USD, 100));
assertThat(getDomainCreateCost("rich.example", clock.nowUtc(), 2)) assertThat(getDomainCreateCost("rich.example", clock.nowUtc(), 2))
@ -106,7 +100,7 @@ public class PricingEngineProxyTest {
} }
@Test @Test
public void testGetDomainRenewCost() { void testGetDomainRenewCost() {
// The example tld has a premium price for "rich". // The example tld has a premium price for "rich".
createTld("example"); createTld("example");
persistResource( persistResource(
@ -116,32 +110,20 @@ public class PricingEngineProxyTest {
ImmutableSortedMap.of( ImmutableSortedMap.of(
START_OF_TIME, Money.of(USD, 8), clock.nowUtc(), Money.of(USD, 10))) START_OF_TIME, Money.of(USD, 8), clock.nowUtc(), Money.of(USD, 10)))
.build()); .build());
assertThat(getDomainRenewCost("poor.example", START_OF_TIME, 1)) assertThat(getDomainRenewCost("poor.example", START_OF_TIME, 1)).isEqualTo(Money.of(USD, 8));
.isEqualTo(Money.of(USD, 8)); assertThat(getDomainRenewCost("poor.example", START_OF_TIME, 2)).isEqualTo(Money.of(USD, 16));
assertThat(getDomainRenewCost("poor.example", START_OF_TIME, 2)) assertThat(getDomainRenewCost("poor.example", clock.nowUtc(), 1)).isEqualTo(Money.of(USD, 10));
.isEqualTo(Money.of(USD, 16)); assertThat(getDomainRenewCost("poor.example", clock.nowUtc(), 2)).isEqualTo(Money.of(USD, 20));
assertThat(getDomainRenewCost("poor.example", clock.nowUtc(), 1)) assertThat(getDomainRenewCost("rich.example", START_OF_TIME, 1)).isEqualTo(Money.of(USD, 100));
.isEqualTo(Money.of(USD, 10)); assertThat(getDomainRenewCost("rich.example", START_OF_TIME, 2)).isEqualTo(Money.of(USD, 200));
assertThat(getDomainRenewCost("poor.example", clock.nowUtc(), 2)) assertThat(getDomainRenewCost("rich.example", clock.nowUtc(), 1)).isEqualTo(Money.of(USD, 100));
.isEqualTo(Money.of(USD, 20)); assertThat(getDomainRenewCost("rich.example", clock.nowUtc(), 2)).isEqualTo(Money.of(USD, 200));
assertThat(getDomainRenewCost("rich.example", START_OF_TIME, 1))
.isEqualTo(Money.of(USD, 100));
assertThat(getDomainRenewCost("rich.example", START_OF_TIME, 2))
.isEqualTo(Money.of(USD, 200));
assertThat(getDomainRenewCost("rich.example", clock.nowUtc(), 1))
.isEqualTo(Money.of(USD, 100));
assertThat(getDomainRenewCost("rich.example", clock.nowUtc(), 2))
.isEqualTo(Money.of(USD, 200));
} }
@Test @Test
public void testFailure_cantLoadPricingEngine() { void testFailure_cantLoadPricingEngine() {
createTld("example"); createTld("example");
persistResource( persistResource(Registry.get("example").asBuilder().setPremiumPricingEngine("fake").build());
Registry.get("example")
.asBuilder()
.setPremiumPricingEngine("fake")
.build());
IllegalStateException thrown = IllegalStateException thrown =
assertThrows( assertThrows(
IllegalStateException.class, IllegalStateException.class,

View file

@ -26,12 +26,10 @@ import google.registry.rdap.AbstractJsonableObject.JsonableException;
import google.registry.rdap.AbstractJsonableObject.RestrictJsonNames; import google.registry.rdap.AbstractJsonableObject.RestrictJsonNames;
import java.util.Optional; import java.util.Optional;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) /** Unit tests for {@link AbstractJsonableObject}. */
public final class AbstractJsonableObjectTest { final class AbstractJsonableObjectTest {
private final Gson gson = new Gson(); private final Gson gson = new Gson();
@ -40,7 +38,7 @@ public final class AbstractJsonableObjectTest {
} }
@Test @Test
public void testPrimitives() { void testPrimitives() {
Jsonable jsonable = new AbstractJsonableObject() { Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement String myString = "Hello, world!"; @JsonableElement String myString = "Hello, world!";
@JsonableElement int myInt = 42; @JsonableElement int myInt = 42;
@ -53,9 +51,8 @@ public final class AbstractJsonableObjectTest {
"{'myBoolean':false,'myDouble':3.14,'myInt':42,'myString':'Hello, world!'}")); "{'myBoolean':false,'myDouble':3.14,'myInt':42,'myString':'Hello, world!'}"));
} }
@Test @Test
public void testDateTime() { void testDateTime() {
Jsonable jsonable = new AbstractJsonableObject() { Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement DateTime dateTime = DateTime.parse("2019-01-02T13:53Z"); @JsonableElement DateTime dateTime = DateTime.parse("2019-01-02T13:53Z");
}; };
@ -63,7 +60,7 @@ public final class AbstractJsonableObjectTest {
} }
@Test @Test
public void testRenaming() { void testRenaming() {
Jsonable jsonable = new AbstractJsonableObject() { Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement("newName") String myString = "Hello, world!"; @JsonableElement("newName") String myString = "Hello, world!";
}; };
@ -71,7 +68,7 @@ public final class AbstractJsonableObjectTest {
} }
@Test @Test
public void testDuplicateNames_fails() { void testDuplicateNames_fails() {
Jsonable jsonable = new AbstractJsonableObject() { Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement String myString = "A"; @JsonableElement String myString = "A";
@JsonableElement("myString") String anotherString = "B"; @JsonableElement("myString") String anotherString = "B";
@ -81,7 +78,7 @@ public final class AbstractJsonableObjectTest {
} }
@Test @Test
public void testMethod() { void testMethod() {
Jsonable jsonable = Jsonable jsonable =
new AbstractJsonableObject() { new AbstractJsonableObject() {
@JsonableElement String myString() { @JsonableElement String myString() {
@ -92,7 +89,7 @@ public final class AbstractJsonableObjectTest {
} }
@Test @Test
public void testMethodWithArguments_fails() { void testMethodWithArguments_fails() {
Jsonable jsonable = Jsonable jsonable =
new AbstractJsonableObject() { new AbstractJsonableObject() {
@JsonableElement String myString(String in) { @JsonableElement String myString(String in) {
@ -103,9 +100,8 @@ public final class AbstractJsonableObjectTest {
.hasMessageThat().contains("must have no arguments"); .hasMessageThat().contains("must have no arguments");
} }
@Test @Test
public void testRecursive() { void testRecursive() {
Jsonable myJsonableObject = new AbstractJsonableObject() { Jsonable myJsonableObject = new AbstractJsonableObject() {
@JsonableElement double myDouble = 3.14; @JsonableElement double myDouble = 3.14;
@JsonableElement boolean myBoolean = false; @JsonableElement boolean myBoolean = false;
@ -124,7 +120,7 @@ public final class AbstractJsonableObjectTest {
} }
@Test @Test
public void testList() { void testList() {
Jsonable jsonable = new AbstractJsonableObject() { Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement @JsonableElement
ImmutableList<String> myList = ImmutableList.of("my", "immutable", "list"); ImmutableList<String> myList = ImmutableList.of("my", "immutable", "list");
@ -133,7 +129,7 @@ public final class AbstractJsonableObjectTest {
} }
@Test @Test
public void testMultipleLists() { void testMultipleLists() {
Jsonable jsonable = new AbstractJsonableObject() { Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement @JsonableElement
ImmutableList<String> myList = ImmutableList.of("my", "immutable", "list"); ImmutableList<String> myList = ImmutableList.of("my", "immutable", "list");
@ -145,7 +141,7 @@ public final class AbstractJsonableObjectTest {
} }
@Test @Test
public void testListElements() { void testListElements() {
Jsonable jsonable = new AbstractJsonableObject() { Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement @JsonableElement
ImmutableList<String> myList = ImmutableList.of("my", "immutable", "list"); ImmutableList<String> myList = ImmutableList.of("my", "immutable", "list");
@ -159,7 +155,7 @@ public final class AbstractJsonableObjectTest {
} }
@Test @Test
public void testListElementsWithoutList() { void testListElementsWithoutList() {
Jsonable jsonable = new AbstractJsonableObject() { Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement("myList[]") @JsonableElement("myList[]")
Integer myListMeaningOfLife = 42; Integer myListMeaningOfLife = 42;
@ -170,7 +166,7 @@ public final class AbstractJsonableObjectTest {
} }
@Test @Test
public void testListOptionalElements() { void testListOptionalElements() {
Jsonable jsonable = new AbstractJsonableObject() { Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement @JsonableElement
ImmutableList<String> myList = ImmutableList.of("my", "immutable", "list"); ImmutableList<String> myList = ImmutableList.of("my", "immutable", "list");
@ -183,7 +179,7 @@ public final class AbstractJsonableObjectTest {
} }
@Test @Test
public void testList_sameNameAsElement_failes() { void testList_sameNameAsElement_failes() {
Jsonable jsonable = new AbstractJsonableObject() { Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement("myList") @JsonableElement("myList")
String myString = "A"; String myString = "A";
@ -211,7 +207,7 @@ public final class AbstractJsonableObjectTest {
} }
@Test @Test
public void testRestricted_withAllowedNames() { void testRestricted_withAllowedNames() {
Jsonable jsonable = new AbstractJsonableObject() { Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement @JsonableElement
JsonableWithNameRestrictions allowed = new JsonableWithNameRestrictions(); JsonableWithNameRestrictions allowed = new JsonableWithNameRestrictions();
@ -225,7 +221,7 @@ public final class AbstractJsonableObjectTest {
} }
@Test @Test
public void testRestricted_withWrongName_failes() { void testRestricted_withWrongName_failes() {
Jsonable jsonable = new AbstractJsonableObject() { Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement @JsonableElement
JsonableWithNameRestrictions wrong = new JsonableWithNameRestrictions(); JsonableWithNameRestrictions wrong = new JsonableWithNameRestrictions();
@ -236,7 +232,7 @@ public final class AbstractJsonableObjectTest {
} }
@Test @Test
public void testRestricted_withNoNamesAllowed_fails() { void testRestricted_withNoNamesAllowed_fails() {
Jsonable jsonable = new AbstractJsonableObject() { Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement @JsonableElement
JsonableWithNoAllowedNames wrong = new JsonableWithNoAllowedNames(); JsonableWithNoAllowedNames wrong = new JsonableWithNoAllowedNames();
@ -252,14 +248,14 @@ public final class AbstractJsonableObjectTest {
} }
@Test @Test
public void testRestricted_withNoNamesAllowed_canBeOutermost() { void testRestricted_withNoNamesAllowed_canBeOutermost() {
Jsonable jsonable = new JsonableObjectWithNoAllowedNames(); Jsonable jsonable = new JsonableObjectWithNoAllowedNames();
assertThat(jsonable.toJson()) assertThat(jsonable.toJson())
.isEqualTo(createJson("{'key':'value'}")); .isEqualTo(createJson("{'key':'value'}"));
} }
@Test @Test
public void testRestricted_withNoNamesAllowed_canBeMerged() { void testRestricted_withNoNamesAllowed_canBeMerged() {
Jsonable jsonable = new AbstractJsonableObject() { Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement("*") final Jsonable inner = new JsonableObjectWithNoAllowedNames(); @JsonableElement("*") final Jsonable inner = new JsonableObjectWithNoAllowedNames();
@JsonableElement final String otherKey = "otherValue"; @JsonableElement final String otherKey = "otherValue";
@ -283,7 +279,7 @@ public final class AbstractJsonableObjectTest {
} }
@Test @Test
public void testInheritingStaticMembers_works() { void testInheritingStaticMembers_works() {
Jsonable jsonable = new InheritedWithStatic(); Jsonable jsonable = new InheritedWithStatic();
assertThat(jsonable.toJson()) assertThat(jsonable.toJson())
.isEqualTo(createJson("{'messages':['message 1','more messages','message 2']}")); .isEqualTo(createJson("{'messages':['message 1','more messages','message 2']}"));
@ -317,7 +313,7 @@ public final class AbstractJsonableObjectTest {
} }
@Test @Test
public void testOverriding_works() { void testOverriding_works() {
Jsonable jsonable = new InheritedOverriding(); Jsonable jsonable = new InheritedOverriding();
assertThat(jsonable.toJson()) assertThat(jsonable.toJson())
.isEqualTo( .isEqualTo(
@ -330,7 +326,7 @@ public final class AbstractJsonableObjectTest {
} }
@Test @Test
public void testMerge_works() { void testMerge_works() {
Jsonable jsonable = new AbstractJsonableObject() { Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement String key = "value"; @JsonableElement String key = "value";
@JsonableElement("*") Object subObject = new AbstractJsonableObject() { @JsonableElement("*") Object subObject = new AbstractJsonableObject() {
@ -342,7 +338,7 @@ public final class AbstractJsonableObjectTest {
} }
@Test @Test
public void testMerge_joinsArrays_works() { void testMerge_joinsArrays_works() {
Jsonable jsonable = new AbstractJsonableObject() { Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement("lst[]") String a = "value"; @JsonableElement("lst[]") String a = "value";
@JsonableElement("*") Object subObject = new AbstractJsonableObject() { @JsonableElement("*") Object subObject = new AbstractJsonableObject() {
@ -354,7 +350,7 @@ public final class AbstractJsonableObjectTest {
} }
@Test @Test
public void testMerge_multiLayer_works() { void testMerge_multiLayer_works() {
Jsonable jsonable = new AbstractJsonableObject() { Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement String key = "value"; @JsonableElement String key = "value";

View file

@ -32,16 +32,13 @@ import google.registry.rdap.RdapSearchResults.IncompletenessWarningType;
import google.registry.request.Action; import google.registry.request.Action;
import google.registry.request.auth.Auth; import google.registry.request.auth.Auth;
import java.util.Optional; import java.util.Optional;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RdapActionBase}. */ /** Unit tests for {@link RdapActionBase}. */
@RunWith(JUnit4.class) class RdapActionBaseTest extends RdapActionBaseTestCase<RdapActionBaseTest.RdapTestAction> {
public class RdapActionBaseTest extends RdapActionBaseTestCase<RdapActionBaseTest.RdapTestAction> {
public RdapActionBaseTest() { RdapActionBaseTest() {
super(RdapTestAction.class); super(RdapTestAction.class);
} }
@ -72,13 +69,13 @@ public class RdapActionBaseTest extends RdapActionBaseTestCase<RdapActionBaseTes
} }
} }
@Before @BeforeEach
public void setUp() { void beforeEach() {
createTld("thing"); createTld("thing");
} }
@Test @Test
public void testIllegalValue_showsReadableTypeName() { void testIllegalValue_showsReadableTypeName() {
assertThat(generateActualJson("IllegalArgumentException")).isEqualTo(generateExpectedJsonError( assertThat(generateActualJson("IllegalArgumentException")).isEqualTo(generateExpectedJsonError(
"Not a valid human-readable string", "Not a valid human-readable string",
400)); 400));
@ -86,45 +83,45 @@ public class RdapActionBaseTest extends RdapActionBaseTestCase<RdapActionBaseTes
} }
@Test @Test
public void testRuntimeException_returns500Error() { void testRuntimeException_returns500Error() {
assertThat(generateActualJson("RuntimeException")) assertThat(generateActualJson("RuntimeException"))
.isEqualTo(generateExpectedJsonError("An error was encountered", 500)); .isEqualTo(generateExpectedJsonError("An error was encountered", 500));
assertThat(response.getStatus()).isEqualTo(500); assertThat(response.getStatus()).isEqualTo(500);
} }
@Test @Test
public void testValidName_works() { void testValidName_works() {
assertThat(generateActualJson("no.thing")).isEqualTo(loadJsonFile("rdapjson_toplevel.json")); assertThat(generateActualJson("no.thing")).isEqualTo(loadJsonFile("rdapjson_toplevel.json"));
assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getStatus()).isEqualTo(200);
} }
@Test @Test
public void testContentType_rdapjson_utf8() { void testContentType_rdapjson_utf8() {
generateActualJson("no.thing"); generateActualJson("no.thing");
assertThat(response.getContentType().toString()) assertThat(response.getContentType().toString())
.isEqualTo("application/rdap+json; charset=utf-8"); .isEqualTo("application/rdap+json; charset=utf-8");
} }
@Test @Test
public void testHeadRequest_returnsNoContent() { void testHeadRequest_returnsNoContent() {
assertThat(generateHeadPayload("no.thing")).isEmpty(); assertThat(generateHeadPayload("no.thing")).isEmpty();
assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getStatus()).isEqualTo(200);
} }
@Test @Test
public void testHeadRequestIllegalValue_returnsNoContent() { void testHeadRequestIllegalValue_returnsNoContent() {
assertThat(generateHeadPayload("IllegalArgumentException")).isEmpty(); assertThat(generateHeadPayload("IllegalArgumentException")).isEmpty();
assertThat(response.getStatus()).isEqualTo(400); assertThat(response.getStatus()).isEqualTo(400);
} }
@Test @Test
public void testRdapServer_allowsAllCrossOriginRequests() { void testRdapServer_allowsAllCrossOriginRequests() {
generateActualJson("no.thing"); generateActualJson("no.thing");
assertThat(response.getHeaders().get(ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("*"); assertThat(response.getHeaders().get(ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("*");
} }
@Test @Test
public void testMetrics_onSuccess() { void testMetrics_onSuccess() {
generateActualJson("no.thing"); generateActualJson("no.thing");
verify(rdapMetrics) verify(rdapMetrics)
.updateMetrics( .updateMetrics(
@ -143,7 +140,7 @@ public class RdapActionBaseTest extends RdapActionBaseTestCase<RdapActionBaseTes
} }
@Test @Test
public void testMetrics_onError() { void testMetrics_onError() {
generateActualJson("IllegalArgumentException"); generateActualJson("IllegalArgumentException");
verify(rdapMetrics) verify(rdapMetrics)
.updateMetrics( .updateMetrics(
@ -162,7 +159,7 @@ public class RdapActionBaseTest extends RdapActionBaseTestCase<RdapActionBaseTes
} }
@Test @Test
public void testUnformatted() { void testUnformatted() {
action.requestPath = actionPath + "no.thing"; action.requestPath = actionPath + "no.thing";
action.requestMethod = GET; action.requestMethod = GET;
action.run(); action.run();
@ -172,7 +169,7 @@ public class RdapActionBaseTest extends RdapActionBaseTestCase<RdapActionBaseTes
} }
@Test @Test
public void testFormatted() { void testFormatted() {
action.requestPath = actionPath + "no.thing?formatOutput=true"; action.requestPath = actionPath + "no.thing?formatOutput=true";
action.requestMethod = GET; action.requestMethod = GET;
action.formatOutputParam = Optional.of(true); action.formatOutputParam = Optional.of(true);

View file

@ -39,17 +39,16 @@ import google.registry.util.TypeUtils;
import java.util.HashMap; import java.util.HashMap;
import java.util.Optional; import java.util.Optional;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.extension.RegisterExtension;
/** Common unit test code for actions inheriting {@link RdapActionBase}. */ /** Common unit test code for actions inheriting {@link RdapActionBase}. */
public abstract class RdapActionBaseTestCase<A extends RdapActionBase> { abstract class RdapActionBaseTestCase<A extends RdapActionBase> {
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Rule @RegisterExtension public final InjectRule inject = new InjectRule();
public final InjectRule inject = new InjectRule();
protected static final AuthResult AUTH_RESULT = protected static final AuthResult AUTH_RESULT =
AuthResult.create( AuthResult.create(
@ -63,21 +62,21 @@ public abstract class RdapActionBaseTestCase<A extends RdapActionBase> {
protected FakeResponse response = new FakeResponse(); protected FakeResponse response = new FakeResponse();
protected final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01TZ")); protected final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01TZ"));
protected final RdapMetrics rdapMetrics = mock(RdapMetrics.class); final RdapMetrics rdapMetrics = mock(RdapMetrics.class);
protected RdapAuthorization.Role metricRole = PUBLIC; RdapAuthorization.Role metricRole = PUBLIC;
protected A action; protected A action;
protected final String actionPath; final String actionPath;
protected final Class<A> rdapActionClass; private final Class<A> rdapActionClass;
protected RdapActionBaseTestCase(Class<A> rdapActionClass) { RdapActionBaseTestCase(Class<A> rdapActionClass) {
this.rdapActionClass = rdapActionClass; this.rdapActionClass = rdapActionClass;
this.actionPath = Actions.getPathForAction(rdapActionClass); this.actionPath = Actions.getPathForAction(rdapActionClass);
} }
@Before @BeforeEach
public void baseSetUp() { public void beforeEachRdapActionBaseTestCase() {
inject.setStaticField(Ofy.class, "clock", clock); inject.setStaticField(Ofy.class, "clock", clock);
action = TypeUtils.instantiate(rdapActionClass); action = TypeUtils.instantiate(rdapActionClass);
action.includeDeletedParam = Optional.empty(); action.includeDeletedParam = Optional.empty();
@ -101,29 +100,27 @@ public abstract class RdapActionBaseTestCase<A extends RdapActionBase> {
metricRole = PUBLIC; metricRole = PUBLIC;
} }
protected void loginAsAdmin() { void loginAsAdmin() {
action.rdapAuthorization = RdapAuthorization.ADMINISTRATOR_AUTHORIZATION; action.rdapAuthorization = RdapAuthorization.ADMINISTRATOR_AUTHORIZATION;
action.rdapJsonFormatter.rdapAuthorization = action.rdapAuthorization; action.rdapJsonFormatter.rdapAuthorization = action.rdapAuthorization;
metricRole = ADMINISTRATOR; metricRole = ADMINISTRATOR;
} }
protected JsonObject generateActualJson(String domainName) { JsonObject generateActualJson(String domainName) {
action.requestPath = actionPath + domainName; action.requestPath = actionPath + domainName;
action.requestMethod = GET; action.requestMethod = GET;
action.run(); action.run();
return RdapTestHelper.parseJsonObject(response.getPayload()); return RdapTestHelper.parseJsonObject(response.getPayload());
} }
protected String generateHeadPayload(String domainName) { String generateHeadPayload(String domainName) {
action.requestPath = actionPath + domainName; action.requestPath = actionPath + domainName;
action.requestMethod = HEAD; action.requestMethod = HEAD;
action.run(); action.run();
return response.getPayload(); return response.getPayload();
} }
protected JsonObject generateExpectedJsonError( JsonObject generateExpectedJsonError(String description, int code) {
String description,
int code) {
String title; String title;
switch (code) { switch (code) {
case 404: case 404:
@ -147,12 +144,15 @@ public abstract class RdapActionBaseTestCase<A extends RdapActionBase> {
} }
return RdapTestHelper.loadJsonFile( return RdapTestHelper.loadJsonFile(
"rdap_error.json", "rdap_error.json",
"DESCRIPTION", description, "DESCRIPTION",
"TITLE", title, description,
"CODE", String.valueOf(code)); "TITLE",
title,
"CODE",
String.valueOf(code));
} }
protected static JsonFileBuilder jsonFileBuilder() { static JsonFileBuilder jsonFileBuilder() {
return new JsonFileBuilder(); return new JsonFileBuilder();
} }
@ -173,7 +173,7 @@ public abstract class RdapActionBaseTestCase<A extends RdapActionBase> {
return put(String.format("%s%d", key, index), value); return put(String.format("%s%d", key, index), value);
} }
public JsonFileBuilder putNext(String key, String value, String... moreKeyValues) { JsonFileBuilder putNext(String key, String value, String... moreKeyValues) {
checkArgument(moreKeyValues.length % 2 == 0); checkArgument(moreKeyValues.length % 2 == 0);
int index = putNextAndReturnIndex(key, value); int index = putNextAndReturnIndex(key, value);
for (int i = 0; i < moreKeyValues.length; i += 2) { for (int i = 0; i < moreKeyValues.length; i += 2) {
@ -182,29 +182,29 @@ public abstract class RdapActionBaseTestCase<A extends RdapActionBase> {
return this; return this;
} }
public JsonFileBuilder addDomain(String name, String handle) { JsonFileBuilder addDomain(String name, String handle) {
return putNext( return putNext(
"DOMAIN_PUNYCODE_NAME_", Idn.toASCII(name), "DOMAIN_PUNYCODE_NAME_", Idn.toASCII(name),
"DOMAIN_UNICODE_NAME_", name, "DOMAIN_UNICODE_NAME_", name,
"DOMAIN_HANDLE_", handle); "DOMAIN_HANDLE_", handle);
} }
public JsonFileBuilder addNameserver(String name, String handle) { JsonFileBuilder addNameserver(String name, String handle) {
return putNext( return putNext(
"NAMESERVER_NAME_", Idn.toASCII(name), "NAMESERVER_NAME_", Idn.toASCII(name),
"NAMESERVER_UNICODE_NAME_", name, "NAMESERVER_UNICODE_NAME_", name,
"NAMESERVER_HANDLE_", handle); "NAMESERVER_HANDLE_", handle);
} }
public JsonFileBuilder addRegistrar(String fullName) { JsonFileBuilder addRegistrar(String fullName) {
return putNext("REGISTRAR_FULL_NAME_", fullName); return putNext("REGISTRAR_FULL_NAME_", fullName);
} }
public JsonFileBuilder addContact(String handle) { JsonFileBuilder addContact(String handle) {
return putNext("CONTACT_HANDLE_", handle); return putNext("CONTACT_HANDLE_", handle);
} }
public JsonFileBuilder setNextQuery(String nextQuery) { JsonFileBuilder setNextQuery(String nextQuery) {
return put("NEXT_QUERY", nextQuery); return put("NEXT_QUERY", nextQuery);
} }

View file

@ -30,12 +30,10 @@ import google.registry.rdap.RdapDataStructures.RdapConformance;
import google.registry.rdap.RdapDataStructures.RdapStatus; import google.registry.rdap.RdapDataStructures.RdapStatus;
import google.registry.rdap.RdapDataStructures.Remark; import google.registry.rdap.RdapDataStructures.Remark;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) /** Unit tests for {@link RdapDataStructures}. */
public final class RdapDataStructuresTest { final class RdapDataStructuresTest {
private void assertRestrictedNames(Object object, String... names) { private void assertRestrictedNames(Object object, String... names) {
assertThat(AbstractJsonableObject.getNameRestriction(object.getClass()).get()) assertThat(AbstractJsonableObject.getNameRestriction(object.getClass()).get())
@ -43,7 +41,7 @@ public final class RdapDataStructuresTest {
} }
@Test @Test
public void testRdapConformance() { void testRdapConformance() {
assertThat(RdapConformance.INSTANCE.toJson()) assertThat(RdapConformance.INSTANCE.toJson())
.isEqualTo(createJson( .isEqualTo(createJson(
"[", "[",
@ -54,7 +52,7 @@ public final class RdapDataStructuresTest {
} }
@Test @Test
public void testLink() { void testLink() {
Link link = Link link =
Link.builder() Link.builder()
.setHref("myHref") .setHref("myHref")
@ -68,7 +66,7 @@ public final class RdapDataStructuresTest {
} }
@Test @Test
public void testNotice() { void testNotice() {
Notice notice = Notice.builder() Notice notice = Notice.builder()
.setDescription("AAA", "BBB") .setDescription("AAA", "BBB")
.setTitle("myTitle") .setTitle("myTitle")
@ -88,7 +86,7 @@ public final class RdapDataStructuresTest {
} }
@Test @Test
public void testRemark() { void testRemark() {
Remark remark = Remark.builder() Remark remark = Remark.builder()
.setDescription("AAA", "BBB") .setDescription("AAA", "BBB")
.setTitle("myTitle") .setTitle("myTitle")
@ -108,13 +106,13 @@ public final class RdapDataStructuresTest {
} }
@Test @Test
public void testLanguage() { void testLanguage() {
assertThat(LanguageIdentifier.EN.toJson()).isEqualTo(createJson("'en'")); assertThat(LanguageIdentifier.EN.toJson()).isEqualTo(createJson("'en'"));
assertRestrictedNames(LanguageIdentifier.EN, "lang"); assertRestrictedNames(LanguageIdentifier.EN, "lang");
} }
@Test @Test
public void testEvent() { void testEvent() {
Event event = Event event =
Event.builder() Event.builder()
.setEventAction(EventAction.REGISTRATION) .setEventAction(EventAction.REGISTRATION)
@ -135,7 +133,7 @@ public final class RdapDataStructuresTest {
} }
@Test @Test
public void testEventWithoutActor() { void testEventWithoutActor() {
EventWithoutActor event = EventWithoutActor event =
EventWithoutActor.builder() EventWithoutActor.builder()
.setEventAction(EventAction.REGISTRATION) .setEventAction(EventAction.REGISTRATION)
@ -154,20 +152,20 @@ public final class RdapDataStructuresTest {
} }
@Test @Test
public void testRdapStatus() { void testRdapStatus() {
assertThat(RdapStatus.ACTIVE.toJson()).isEqualTo(createJson("'active'")); assertThat(RdapStatus.ACTIVE.toJson()).isEqualTo(createJson("'active'"));
assertRestrictedNames(RdapStatus.ACTIVE, "status[]"); assertRestrictedNames(RdapStatus.ACTIVE, "status[]");
} }
@Test @Test
public void testPort43() { void testPort43() {
Port43WhoisServer port43 = Port43WhoisServer.create("myServer"); Port43WhoisServer port43 = Port43WhoisServer.create("myServer");
assertThat(port43.toJson()).isEqualTo(createJson("'myServer'")); assertThat(port43.toJson()).isEqualTo(createJson("'myServer'"));
assertRestrictedNames(port43, "port43"); assertRestrictedNames(port43, "port43");
} }
@Test @Test
public void testPublicId() { void testPublicId() {
PublicId publicId = PublicId.create(PublicId.Type.IANA_REGISTRAR_ID, "myId"); PublicId publicId = PublicId.create(PublicId.Type.IANA_REGISTRAR_ID, "myId");
assertThat(publicId.toJson()) assertThat(publicId.toJson())
.isEqualTo(createJson("{'identifier':'myId','type':'IANA Registrar ID'}")); .isEqualTo(createJson("{'identifier':'myId','type':'IANA Registrar ID'}"));
@ -175,7 +173,7 @@ public final class RdapDataStructuresTest {
} }
@Test @Test
public void testObjectClassName() { void testObjectClassName() {
assertThat(ObjectClassName.DOMAIN.toJson()).isEqualTo(createJson("'domain'")); assertThat(ObjectClassName.DOMAIN.toJson()).isEqualTo(createJson("'domain'"));
assertRestrictedNames(ObjectClassName.DOMAIN, "objectClassName"); assertRestrictedNames(ObjectClassName.DOMAIN, "objectClassName");
} }

View file

@ -41,22 +41,19 @@ import google.registry.rdap.RdapMetrics.WildcardType;
import google.registry.rdap.RdapSearchResults.IncompletenessWarningType; import google.registry.rdap.RdapSearchResults.IncompletenessWarningType;
import google.registry.request.Action; import google.registry.request.Action;
import java.util.Optional; import java.util.Optional;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RdapDomainAction}. */ /** Unit tests for {@link RdapDomainAction}. */
@RunWith(JUnit4.class) class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainAction> {
public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainAction> {
public RdapDomainActionTest() { RdapDomainActionTest() {
super(RdapDomainAction.class); super(RdapDomainAction.class);
} }
@Before @BeforeEach
public void setUp() { void beforeEach() {
// lol // lol
createTld("lol"); createTld("lol");
Registrar registrarLol = persistResource(makeRegistrar( Registrar registrarLol = persistResource(makeRegistrar(
@ -246,7 +243,7 @@ public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainActio
} }
@Test @Test
public void testInvalidDomain_returns400() { void testInvalidDomain_returns400() {
assertThat(generateActualJson("invalid/domain/name")) assertThat(generateActualJson("invalid/domain/name"))
.isEqualTo( .isEqualTo(
generateExpectedJsonError( generateExpectedJsonError(
@ -257,7 +254,7 @@ public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainActio
} }
@Test @Test
public void testUnknownDomain_returns400() { void testUnknownDomain_returns400() {
assertThat(generateActualJson("missingdomain.com")) assertThat(generateActualJson("missingdomain.com"))
.isEqualTo( .isEqualTo(
generateExpectedJsonError( generateExpectedJsonError(
@ -268,45 +265,45 @@ public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainActio
} }
@Test @Test
public void testValidDomain_works() { void testValidDomain_works() {
login("evilregistrar"); login("evilregistrar");
assertProperResponseForCatLol("cat.lol", "rdap_domain.json"); assertProperResponseForCatLol("cat.lol", "rdap_domain.json");
} }
@Test @Test
public void testValidDomain_asAdministrator_works() { void testValidDomain_asAdministrator_works() {
loginAsAdmin(); loginAsAdmin();
assertProperResponseForCatLol("cat.lol", "rdap_domain.json"); assertProperResponseForCatLol("cat.lol", "rdap_domain.json");
} }
@Test @Test
public void testValidDomain_notLoggedIn_noContacts() { void testValidDomain_notLoggedIn_noContacts() {
assertProperResponseForCatLol("cat.lol", "rdap_domain_no_contacts_with_remark.json"); assertProperResponseForCatLol("cat.lol", "rdap_domain_no_contacts_with_remark.json");
} }
@Test @Test
public void testValidDomain_loggedInAsOtherRegistrar_noContacts() { void testValidDomain_loggedInAsOtherRegistrar_noContacts() {
login("idnregistrar"); login("idnregistrar");
assertProperResponseForCatLol("cat.lol", "rdap_domain_no_contacts_with_remark.json"); assertProperResponseForCatLol("cat.lol", "rdap_domain_no_contacts_with_remark.json");
} }
@Test @Test
public void testUpperCase_ignored() { void testUpperCase_ignored() {
assertProperResponseForCatLol("CaT.lOl", "rdap_domain_no_contacts_with_remark.json"); assertProperResponseForCatLol("CaT.lOl", "rdap_domain_no_contacts_with_remark.json");
} }
@Test @Test
public void testTrailingDot_ignored() { void testTrailingDot_ignored() {
assertProperResponseForCatLol("cat.lol.", "rdap_domain_no_contacts_with_remark.json"); assertProperResponseForCatLol("cat.lol.", "rdap_domain_no_contacts_with_remark.json");
} }
@Test @Test
public void testQueryParameter_ignored() { void testQueryParameter_ignored() {
assertProperResponseForCatLol("cat.lol?key=value", "rdap_domain_no_contacts_with_remark.json"); assertProperResponseForCatLol("cat.lol?key=value", "rdap_domain_no_contacts_with_remark.json");
} }
@Test @Test
public void testIdnDomain_works() { void testIdnDomain_works() {
login("idnregistrar"); login("idnregistrar");
assertThat(generateActualJson("cat.みんな")) assertThat(generateActualJson("cat.みんな"))
.isEqualTo( .isEqualTo(
@ -324,7 +321,7 @@ public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainActio
} }
@Test @Test
public void testIdnDomainWithPercentEncoding_works() { void testIdnDomainWithPercentEncoding_works() {
login("idnregistrar"); login("idnregistrar");
assertThat(generateActualJson("cat.%E3%81%BF%E3%82%93%E3%81%AA")) assertThat(generateActualJson("cat.%E3%81%BF%E3%82%93%E3%81%AA"))
.isEqualTo( .isEqualTo(
@ -342,7 +339,7 @@ public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainActio
} }
@Test @Test
public void testPunycodeDomain_works() { void testPunycodeDomain_works() {
login("idnregistrar"); login("idnregistrar");
assertThat(generateActualJson("cat.xn--q9jyb4c")) assertThat(generateActualJson("cat.xn--q9jyb4c"))
.isEqualTo( .isEqualTo(
@ -360,7 +357,7 @@ public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainActio
} }
@Test @Test
public void testMultilevelDomain_works() { void testMultilevelDomain_works() {
login("1tldregistrar"); login("1tldregistrar");
assertThat(generateActualJson("cat.1.tld")) assertThat(generateActualJson("cat.1.tld"))
.isEqualTo( .isEqualTo(
@ -378,37 +375,37 @@ public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainActio
} }
// todo (b/27378695): reenable or delete this test // todo (b/27378695): reenable or delete this test
@Ignore @Disabled
@Test @Test
public void testDomainInTestTld_notFound() { void testDomainInTestTld_notFound() {
persistResource(Registry.get("lol").asBuilder().setTldType(Registry.TldType.TEST).build()); persistResource(Registry.get("lol").asBuilder().setTldType(Registry.TldType.TEST).build());
generateActualJson("cat.lol"); generateActualJson("cat.lol");
assertThat(response.getStatus()).isEqualTo(404); assertThat(response.getStatus()).isEqualTo(404);
} }
@Test @Test
public void testDeletedDomain_notFound() { void testDeletedDomain_notFound() {
assertThat(generateActualJson("dodo.lol")) assertThat(generateActualJson("dodo.lol"))
.isEqualTo(generateExpectedJsonError("dodo.lol not found", 404)); .isEqualTo(generateExpectedJsonError("dodo.lol not found", 404));
assertThat(response.getStatus()).isEqualTo(404); assertThat(response.getStatus()).isEqualTo(404);
} }
@Test @Test
public void testDeletedDomain_notFound_includeDeletedSetFalse() { void testDeletedDomain_notFound_includeDeletedSetFalse() {
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
generateActualJson("dodo.lol"); generateActualJson("dodo.lol");
assertThat(response.getStatus()).isEqualTo(404); assertThat(response.getStatus()).isEqualTo(404);
} }
@Test @Test
public void testDeletedDomain_notFound_notLoggedIn() { void testDeletedDomain_notFound_notLoggedIn() {
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
generateActualJson("dodo.lol"); generateActualJson("dodo.lol");
assertThat(response.getStatus()).isEqualTo(404); assertThat(response.getStatus()).isEqualTo(404);
} }
@Test @Test
public void testDeletedDomain_notFound_loggedInAsDifferentRegistrar() { void testDeletedDomain_notFound_loggedInAsDifferentRegistrar() {
login("1tldregistrar"); login("1tldregistrar");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
generateActualJson("dodo.lol"); generateActualJson("dodo.lol");
@ -416,7 +413,7 @@ public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainActio
} }
@Test @Test
public void testDeletedDomain_works_loggedInAsCorrectRegistrar() { void testDeletedDomain_works_loggedInAsCorrectRegistrar() {
login("evilregistrar"); login("evilregistrar");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
assertThat(generateActualJson("dodo.lol")) assertThat(generateActualJson("dodo.lol"))
@ -435,7 +432,7 @@ public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainActio
} }
@Test @Test
public void testDeletedDomain_works_loggedInAsAdmin() { void testDeletedDomain_works_loggedInAsAdmin() {
loginAsAdmin(); loginAsAdmin();
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
assertThat(generateActualJson("dodo.lol")) assertThat(generateActualJson("dodo.lol"))
@ -454,7 +451,7 @@ public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainActio
} }
@Test @Test
public void testMetrics() { void testMetrics() {
generateActualJson("cat.lol"); generateActualJson("cat.lol");
verify(rdapMetrics) verify(rdapMetrics)
.updateMetrics( .updateMetrics(

View file

@ -53,17 +53,14 @@ import google.registry.testing.FakeResponse;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.util.HashMap; import java.util.HashMap;
import java.util.Optional; import java.util.Optional;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RdapDomainSearchAction}. */ /** Unit tests for {@link RdapDomainSearchAction}. */
@RunWith(JUnit4.class) class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDomainSearchAction> {
public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDomainSearchAction> {
public RdapDomainSearchActionTest() { RdapDomainSearchActionTest() {
super(RdapDomainSearchAction.class); super(RdapDomainSearchAction.class);
} }
@ -140,8 +137,8 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
return host; return host;
} }
@Before @BeforeEach
public void setUp() { void beforeEach() {
RdapDomainSearchAction.maxNameserversInFirstStage = 40; RdapDomainSearchAction.maxNameserversInFirstStage = 40;
// lol // lol
@ -646,7 +643,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testInvalidPath_rejected() { void testInvalidPath_rejected() {
action.requestPath = actionPath + "/path"; action.requestPath = actionPath + "/path";
action.run(); action.run();
assertThat(response.getStatus()).isEqualTo(400); assertThat(response.getStatus()).isEqualTo(400);
@ -654,7 +651,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testInvalidRequest_rejected() { void testInvalidRequest_rejected() {
assertThat(generateActualJson(RequestType.NONE, null)) assertThat(generateActualJson(RequestType.NONE, null))
.isEqualTo( .isEqualTo(
generateExpectedJsonError( generateExpectedJsonError(
@ -664,7 +661,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testInvalidWildcard_rejected() { void testInvalidWildcard_rejected() {
assertThat(generateActualJson(RequestType.NAME, "exam*ple")) assertThat(generateActualJson(RequestType.NAME, "exam*ple"))
.isEqualTo( .isEqualTo(
generateExpectedJsonError( generateExpectedJsonError(
@ -676,7 +673,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testMultipleWildcards_rejected() { void testMultipleWildcards_rejected() {
assertThat(generateActualJson(RequestType.NAME, "*.*")) assertThat(generateActualJson(RequestType.NAME, "*.*"))
.isEqualTo( .isEqualTo(
generateExpectedJsonError( generateExpectedJsonError(
@ -688,7 +685,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNoCharactersToMatch_rejected() { void testNoCharactersToMatch_rejected() {
rememberWildcardType("*"); rememberWildcardType("*");
assertThat(generateActualJson(RequestType.NAME, "*")) assertThat(generateActualJson(RequestType.NAME, "*"))
.isEqualTo( .isEqualTo(
@ -701,7 +698,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testFewerThanTwoCharactersToMatch_rejected() { void testFewerThanTwoCharactersToMatch_rejected() {
rememberWildcardType("a*"); rememberWildcardType("a*");
assertThat(generateActualJson(RequestType.NAME, "a*")) assertThat(generateActualJson(RequestType.NAME, "a*"))
.isEqualTo( .isEqualTo(
@ -714,21 +711,21 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_found() { void testDomainMatch_found() {
login("evilregistrar"); login("evilregistrar");
runSuccessfulTestWithCatLol(RequestType.NAME, "cat.lol", "rdap_domain.json"); runSuccessfulTestWithCatLol(RequestType.NAME, "cat.lol", "rdap_domain.json");
verifyMetrics(SearchType.BY_DOMAIN_NAME, Optional.of(1L)); verifyMetrics(SearchType.BY_DOMAIN_NAME, Optional.of(1L));
} }
@Test @Test
public void testDomainMatch_foundWithUpperCase() { void testDomainMatch_foundWithUpperCase() {
login("evilregistrar"); login("evilregistrar");
runSuccessfulTestWithCatLol(RequestType.NAME, "CaT.lOl", "rdap_domain.json"); runSuccessfulTestWithCatLol(RequestType.NAME, "CaT.lOl", "rdap_domain.json");
verifyMetrics(SearchType.BY_DOMAIN_NAME, Optional.of(1L)); verifyMetrics(SearchType.BY_DOMAIN_NAME, Optional.of(1L));
} }
@Test @Test
public void testDomainMatch_found_sameRegistrarRequested() { void testDomainMatch_found_sameRegistrarRequested() {
login("evilregistrar"); login("evilregistrar");
action.registrarParam = Optional.of("evilregistrar"); action.registrarParam = Optional.of("evilregistrar");
runSuccessfulTestWithCatLol(RequestType.NAME, "cat.lol", "rdap_domain.json"); runSuccessfulTestWithCatLol(RequestType.NAME, "cat.lol", "rdap_domain.json");
@ -736,21 +733,21 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_notFound_differentRegistrarRequested() { void testDomainMatch_notFound_differentRegistrarRequested() {
action.registrarParam = Optional.of("otherregistrar"); action.registrarParam = Optional.of("otherregistrar");
runNotFoundTest(RequestType.NAME, "cat.lol", "No domains found"); runNotFoundTest(RequestType.NAME, "cat.lol", "No domains found");
verifyErrorMetrics(SearchType.BY_DOMAIN_NAME); verifyErrorMetrics(SearchType.BY_DOMAIN_NAME);
} }
@Test @Test
public void testDomainMatch_found_asAdministrator() { void testDomainMatch_found_asAdministrator() {
loginAsAdmin(); loginAsAdmin();
runSuccessfulTestWithCatLol(RequestType.NAME, "cat.lol", "rdap_domain.json"); runSuccessfulTestWithCatLol(RequestType.NAME, "cat.lol", "rdap_domain.json");
verifyMetrics(SearchType.BY_DOMAIN_NAME, Optional.of(1L)); verifyMetrics(SearchType.BY_DOMAIN_NAME, Optional.of(1L));
} }
@Test @Test
public void testDomainMatch_found_loggedInAsOtherRegistrar() { void testDomainMatch_found_loggedInAsOtherRegistrar() {
login("otherregistrar"); login("otherregistrar");
runSuccessfulTestWithCatLol( runSuccessfulTestWithCatLol(
RequestType.NAME, "cat.lol", "rdap_domain_no_contacts_with_remark.json"); RequestType.NAME, "cat.lol", "rdap_domain_no_contacts_with_remark.json");
@ -761,21 +758,21 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
* This test is flaky because IDN.toASCII may or may not remove the trailing dot of its own * This test is flaky because IDN.toASCII may or may not remove the trailing dot of its own
* accord. If it does, the test will pass. * accord. If it does, the test will pass.
*/ */
@Ignore @Disabled
@Test @Test
public void testDomainMatchWithTrailingDot_notFound() { void testDomainMatchWithTrailingDot_notFound() {
runNotFoundTest(RequestType.NAME, "cat.lol.", "No domains found"); runNotFoundTest(RequestType.NAME, "cat.lol.", "No domains found");
} }
@Test @Test
public void testDomainMatch_cat2_lol_found() { void testDomainMatch_cat2_lol_found() {
login("evilregistrar"); login("evilregistrar");
runSuccessfulTestWithCat2Lol(RequestType.NAME, "cat2.lol", "rdap_domain_cat2.json"); runSuccessfulTestWithCat2Lol(RequestType.NAME, "cat2.lol", "rdap_domain_cat2.json");
verifyMetrics(SearchType.BY_DOMAIN_NAME, Optional.of(1L)); verifyMetrics(SearchType.BY_DOMAIN_NAME, Optional.of(1L));
} }
@Test @Test
public void testDomainMatch_cat_example_found() { void testDomainMatch_cat_example_found() {
login("evilregistrar"); login("evilregistrar");
runSuccessfulTest( runSuccessfulTest(
RequestType.NAME, RequestType.NAME,
@ -790,7 +787,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_cat_idn_unicode_found() { void testDomainMatch_cat_idn_unicode_found() {
runSuccessfulTest( runSuccessfulTest(
RequestType.NAME, RequestType.NAME,
"cat.みんな", "cat.みんな",
@ -806,7 +803,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_cat_idn_punycode_found() { void testDomainMatch_cat_idn_punycode_found() {
runSuccessfulTest( runSuccessfulTest(
RequestType.NAME, RequestType.NAME,
"cat.xn--q9jyb4c", "cat.xn--q9jyb4c",
@ -820,7 +817,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_cat_1_test_found() { void testDomainMatch_cat_1_test_found() {
runSuccessfulTest( runSuccessfulTest(
RequestType.NAME, RequestType.NAME,
"cat.1.test", "cat.1.test",
@ -834,7 +831,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_castar_1_test_found() { void testDomainMatch_castar_1_test_found() {
runSuccessfulTest( runSuccessfulTest(
RequestType.NAME, RequestType.NAME,
"ca*.1.test", "ca*.1.test",
@ -848,13 +845,13 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_castar_test_notFound() { void testDomainMatch_castar_test_notFound() {
runNotFoundTest(RequestType.NAME, "ca*.test", "No domains found"); runNotFoundTest(RequestType.NAME, "ca*.test", "No domains found");
verifyErrorMetrics(SearchType.BY_DOMAIN_NAME); verifyErrorMetrics(SearchType.BY_DOMAIN_NAME);
} }
@Test @Test
public void testDomainMatch_catstar_lol_found() { void testDomainMatch_catstar_lol_found() {
rememberWildcardType("cat*.lol"); rememberWildcardType("cat*.lol");
assertThat(generateActualJson(RequestType.NAME, "cat*.lol")) assertThat(generateActualJson(RequestType.NAME, "cat*.lol"))
.isEqualTo(generateExpectedJsonForTwoDomainsCatStarReply()); .isEqualTo(generateExpectedJsonForTwoDomainsCatStarReply());
@ -863,7 +860,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_cstar_lol_found() { void testDomainMatch_cstar_lol_found() {
rememberWildcardType("c*.lol"); rememberWildcardType("c*.lol");
assertThat(generateActualJson(RequestType.NAME, "c*.lol")) assertThat(generateActualJson(RequestType.NAME, "c*.lol"))
.isEqualTo(generateExpectedJsonForTwoDomainsCatStarReply()); .isEqualTo(generateExpectedJsonForTwoDomainsCatStarReply());
@ -872,13 +869,13 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_qstar_lol_notFound() { void testDomainMatch_qstar_lol_notFound() {
runNotFoundTest(RequestType.NAME, "q*.lol", "No domains found"); runNotFoundTest(RequestType.NAME, "q*.lol", "No domains found");
verifyErrorMetrics(SearchType.BY_DOMAIN_NAME); verifyErrorMetrics(SearchType.BY_DOMAIN_NAME);
} }
@Test @Test
public void testDomainMatch_star_lol_found() { void testDomainMatch_star_lol_found() {
rememberWildcardType("*.lol"); rememberWildcardType("*.lol");
assertThat(generateActualJson(RequestType.NAME, "*.lol")) assertThat(generateActualJson(RequestType.NAME, "*.lol"))
.isEqualTo(generateExpectedJsonForTwoDomainsCatStarReply()); .isEqualTo(generateExpectedJsonForTwoDomainsCatStarReply());
@ -887,7 +884,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_star_lol_found_sameRegistrarRequested() { void testDomainMatch_star_lol_found_sameRegistrarRequested() {
action.registrarParam = Optional.of("evilregistrar"); action.registrarParam = Optional.of("evilregistrar");
rememberWildcardType("*.lol"); rememberWildcardType("*.lol");
assertThat(generateActualJson(RequestType.NAME, "*.lol")) assertThat(generateActualJson(RequestType.NAME, "*.lol"))
@ -897,7 +894,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_star_lol_notFound_differentRegistrarRequested() { void testDomainMatch_star_lol_notFound_differentRegistrarRequested() {
action.registrarParam = Optional.of("otherregistrar"); action.registrarParam = Optional.of("otherregistrar");
rememberWildcardType("*.lol"); rememberWildcardType("*.lol");
runNotFoundTest(RequestType.NAME, "*.lol", "No domains found"); runNotFoundTest(RequestType.NAME, "*.lol", "No domains found");
@ -905,7 +902,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_cat_star_found() { void testDomainMatch_cat_star_found() {
rememberWildcardType("cat.*"); rememberWildcardType("cat.*");
assertThat(generateActualJson(RequestType.NAME, "cat.*")) assertThat(generateActualJson(RequestType.NAME, "cat.*"))
.isEqualTo( .isEqualTo(
@ -920,7 +917,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_cat_star_foundOne_sameRegistrarRequested() { void testDomainMatch_cat_star_foundOne_sameRegistrarRequested() {
login("evilregistrar"); login("evilregistrar");
action.registrarParam = Optional.of("evilregistrar"); action.registrarParam = Optional.of("evilregistrar");
runSuccessfulTestWithCatLol(RequestType.NAME, "cat.*", "rdap_domain.json"); runSuccessfulTestWithCatLol(RequestType.NAME, "cat.*", "rdap_domain.json");
@ -928,21 +925,21 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_cat_star_notFound_differentRegistrarRequested() { void testDomainMatch_cat_star_notFound_differentRegistrarRequested() {
action.registrarParam = Optional.of("otherregistrar"); action.registrarParam = Optional.of("otherregistrar");
runNotFoundTest(RequestType.NAME, "cat.*", "No domains found"); runNotFoundTest(RequestType.NAME, "cat.*", "No domains found");
verifyErrorMetrics(SearchType.BY_DOMAIN_NAME); verifyErrorMetrics(SearchType.BY_DOMAIN_NAME);
} }
@Test @Test
public void testDomainMatch_cat_lstar_found() { void testDomainMatch_cat_lstar_found() {
login("evilregistrar"); login("evilregistrar");
runSuccessfulTestWithCatLol(RequestType.NAME, "cat.l*", "rdap_domain.json"); runSuccessfulTestWithCatLol(RequestType.NAME, "cat.l*", "rdap_domain.json");
verifyMetrics(SearchType.BY_DOMAIN_NAME, Optional.of(1L)); verifyMetrics(SearchType.BY_DOMAIN_NAME, Optional.of(1L));
} }
@Test @Test
public void testDomainMatch_catstar_found() { void testDomainMatch_catstar_found() {
rememberWildcardType("cat*"); rememberWildcardType("cat*");
assertThat(generateActualJson(RequestType.NAME, "cat*")) assertThat(generateActualJson(RequestType.NAME, "cat*"))
.isEqualTo( .isEqualTo(
@ -958,7 +955,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatchWithWildcardAndEmptySuffix_fails() { void testDomainMatchWithWildcardAndEmptySuffix_fails() {
// Unfortunately, we can't be sure which error is going to be returned. The version of // Unfortunately, we can't be sure which error is going to be returned. The version of
// IDN.toASCII used in Eclipse drops a trailing dot, if any. But the version linked in by // IDN.toASCII used in Eclipse drops a trailing dot, if any. But the version linked in by
// Blaze throws an error in that situation. So just check that it returns an error. // Blaze throws an error in that situation. So just check that it returns an error.
@ -968,20 +965,20 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_dog_notFound() { void testDomainMatch_dog_notFound() {
runNotFoundTest(RequestType.NAME, "dog*", "No domains found"); runNotFoundTest(RequestType.NAME, "dog*", "No domains found");
verifyErrorMetrics(SearchType.BY_DOMAIN_NAME); verifyErrorMetrics(SearchType.BY_DOMAIN_NAME);
} }
@Test @Test
public void testDomainMatchDeletedDomain_notFound() { void testDomainMatchDeletedDomain_notFound() {
persistDomainAsDeleted(domainCatLol, clock.nowUtc().minusDays(1)); persistDomainAsDeleted(domainCatLol, clock.nowUtc().minusDays(1));
runNotFoundTest(RequestType.NAME, "cat.lol", "No domains found"); runNotFoundTest(RequestType.NAME, "cat.lol", "No domains found");
verifyErrorMetrics(SearchType.BY_DOMAIN_NAME); verifyErrorMetrics(SearchType.BY_DOMAIN_NAME);
} }
@Test @Test
public void testDomainMatchDeletedDomain_notFound_deletedNotRequested() { void testDomainMatchDeletedDomain_notFound_deletedNotRequested() {
login("evilregistrar"); login("evilregistrar");
persistDomainAsDeleted(domainCatLol, clock.nowUtc().minusDays(1)); persistDomainAsDeleted(domainCatLol, clock.nowUtc().minusDays(1));
runNotFoundTest(RequestType.NAME, "cat.lol", "No domains found"); runNotFoundTest(RequestType.NAME, "cat.lol", "No domains found");
@ -989,7 +986,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatchDeletedDomain_found_loggedInAsSameRegistrar() { void testDomainMatchDeletedDomain_found_loggedInAsSameRegistrar() {
login("evilregistrar"); login("evilregistrar");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
deleteCatLol(); deleteCatLol();
@ -998,7 +995,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatchDeletedDomain_notFound_loggedInAsOtherRegistrar() { void testDomainMatchDeletedDomain_notFound_loggedInAsOtherRegistrar() {
login("otherregistrar"); login("otherregistrar");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
persistDomainAsDeleted(domainCatLol, clock.nowUtc().minusDays(1)); persistDomainAsDeleted(domainCatLol, clock.nowUtc().minusDays(1));
@ -1007,7 +1004,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatchDeletedDomain_found_loggedInAsAdmin() { void testDomainMatchDeletedDomain_found_loggedInAsAdmin() {
loginAsAdmin(); loginAsAdmin();
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
deleteCatLol(); deleteCatLol();
@ -1016,14 +1013,14 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatchDeletedDomainWithWildcard_notFound() { void testDomainMatchDeletedDomainWithWildcard_notFound() {
persistDomainAsDeleted(domainCatLol, clock.nowUtc().minusDays(1)); persistDomainAsDeleted(domainCatLol, clock.nowUtc().minusDays(1));
runNotFoundTest(RequestType.NAME, "cat.lo*", "No domains found"); runNotFoundTest(RequestType.NAME, "cat.lo*", "No domains found");
verifyErrorMetrics(SearchType.BY_DOMAIN_NAME, Optional.of(1L), 404); verifyErrorMetrics(SearchType.BY_DOMAIN_NAME, Optional.of(1L), 404);
} }
@Test @Test
public void testDomainMatchDeletedDomainsWithWildcardAndTld_notFound() { void testDomainMatchDeletedDomainsWithWildcardAndTld_notFound() {
persistDomainAsDeleted(domainCatLol, clock.nowUtc().minusDays(1)); persistDomainAsDeleted(domainCatLol, clock.nowUtc().minusDays(1));
persistDomainAsDeleted(domainCatLol2, clock.nowUtc().minusDays(1)); persistDomainAsDeleted(domainCatLol2, clock.nowUtc().minusDays(1));
runNotFoundTest(RequestType.NAME, "cat*.lol", "No domains found"); runNotFoundTest(RequestType.NAME, "cat*.lol", "No domains found");
@ -1031,16 +1028,16 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
// TODO(b/27378695): reenable or delete this test // TODO(b/27378695): reenable or delete this test
@Ignore @Disabled
@Test @Test
public void testDomainMatchDomainInTestTld_notFound() { void testDomainMatchDomainInTestTld_notFound() {
persistResource(Registry.get("lol").asBuilder().setTldType(Registry.TldType.TEST).build()); persistResource(Registry.get("lol").asBuilder().setTldType(Registry.TldType.TEST).build());
runNotFoundTest(RequestType.NAME, "cat.lol", "No domains found"); runNotFoundTest(RequestType.NAME, "cat.lol", "No domains found");
verifyErrorMetrics(SearchType.BY_DOMAIN_NAME); verifyErrorMetrics(SearchType.BY_DOMAIN_NAME);
} }
@Test @Test
public void testDomainMatch_manyDeletedDomains_fullResultSet() { void testDomainMatch_manyDeletedDomains_fullResultSet() {
// There are enough domains to fill a full result set; deleted domains are ignored. // There are enough domains to fill a full result set; deleted domains are ignored.
createManyDomainsAndHosts(4, 4, 2); createManyDomainsAndHosts(4, 4, 2);
rememberWildcardType("domain*.lol"); rememberWildcardType("domain*.lol");
@ -1051,7 +1048,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_manyDeletedDomains_partialResultSetDueToInsufficientDomains() { void testDomainMatch_manyDeletedDomains_partialResultSetDueToInsufficientDomains() {
// There are not enough domains to fill a full result set. // There are not enough domains to fill a full result set.
createManyDomainsAndHosts(3, 20, 2); createManyDomainsAndHosts(3, 20, 2);
rememberWildcardType("domain*.lol"); rememberWildcardType("domain*.lol");
@ -1062,7 +1059,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_manyDeletedDomains_partialResultSetDueToFetchingLimit() { void testDomainMatch_manyDeletedDomains_partialResultSetDueToFetchingLimit() {
// This is not exactly desired behavior, but expected: There are enough domains to fill a full // This is not exactly desired behavior, but expected: There are enough domains to fill a full
// result set, but there are so many deleted domains that we run out of patience before we work // result set, but there are so many deleted domains that we run out of patience before we work
// our way through all of them. // our way through all of them.
@ -1084,7 +1081,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_nontruncatedResultsSet() { void testDomainMatch_nontruncatedResultsSet() {
createManyDomainsAndHosts(4, 1, 2); createManyDomainsAndHosts(4, 1, 2);
runSuccessfulTestWithFourDomains( runSuccessfulTestWithFourDomains(
RequestType.NAME, RequestType.NAME,
@ -1098,7 +1095,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_truncatedResultsSet() { void testDomainMatch_truncatedResultsSet() {
createManyDomainsAndHosts(5, 1, 2); createManyDomainsAndHosts(5, 1, 2);
runSuccessfulTestWithFourDomains( runSuccessfulTestWithFourDomains(
RequestType.NAME, RequestType.NAME,
@ -1113,7 +1110,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_tldSearchOrderedProperly() { void testDomainMatch_tldSearchOrderedProperly() {
createManyDomainsAndHosts(4, 1, 2); createManyDomainsAndHosts(4, 1, 2);
rememberWildcardType("*.lol"); rememberWildcardType("*.lol");
assertThat(generateActualJson(RequestType.NAME, "*.lol")) assertThat(generateActualJson(RequestType.NAME, "*.lol"))
@ -1129,7 +1126,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_reallyTruncatedResultsSet() { void testDomainMatch_reallyTruncatedResultsSet() {
// Don't use 10 or more domains for this test, because domain10.lol will come before // Don't use 10 or more domains for this test, because domain10.lol will come before
// domain2.lol, and you'll get the wrong domains in the result set. // domain2.lol, and you'll get the wrong domains in the result set.
createManyDomainsAndHosts(9, 1, 2); createManyDomainsAndHosts(9, 1, 2);
@ -1146,7 +1143,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_truncatedResultsAfterMultipleChunks() { void testDomainMatch_truncatedResultsAfterMultipleChunks() {
createManyDomainsAndHosts(5, 6, 2); createManyDomainsAndHosts(5, 6, 2);
rememberWildcardType("domain*.lol"); rememberWildcardType("domain*.lol");
assertThat(generateActualJson(RequestType.NAME, "domain*.lol")) assertThat(generateActualJson(RequestType.NAME, "domain*.lol"))
@ -1163,7 +1160,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_cursorNavigationWithInitialString() throws Exception { void testDomainMatch_cursorNavigationWithInitialString() throws Exception {
createManyDomainsAndHosts(11, 1, 2); createManyDomainsAndHosts(11, 1, 2);
checkCursorNavigation( checkCursorNavigation(
RequestType.NAME, RequestType.NAME,
@ -1183,7 +1180,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testDomainMatch_cursorNavigationWithTldSuffix() throws Exception { void testDomainMatch_cursorNavigationWithTldSuffix() throws Exception {
createManyDomainsAndHosts(11, 1, 2); createManyDomainsAndHosts(11, 1, 2);
checkCursorNavigation( checkCursorNavigation(
RequestType.NAME, RequestType.NAME,
@ -1205,7 +1202,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatch_foundMultiple() { void testNameserverMatch_foundMultiple() {
rememberWildcardType("ns1.cat.lol"); rememberWildcardType("ns1.cat.lol");
assertThat(generateActualJson(RequestType.NS_LDH_NAME, "ns1.cat.lol")) assertThat(generateActualJson(RequestType.NS_LDH_NAME, "ns1.cat.lol"))
.isEqualTo(generateExpectedJsonForTwoDomainsNsReply()); .isEqualTo(generateExpectedJsonForTwoDomainsNsReply());
@ -1214,7 +1211,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatch_foundMultiple_sameRegistrarRequested() { void testNameserverMatch_foundMultiple_sameRegistrarRequested() {
action.registrarParam = Optional.of("TheRegistrar"); action.registrarParam = Optional.of("TheRegistrar");
rememberWildcardType("ns1.cat.lol"); rememberWildcardType("ns1.cat.lol");
assertThat(generateActualJson(RequestType.NS_LDH_NAME, "ns1.cat.lol")) assertThat(generateActualJson(RequestType.NS_LDH_NAME, "ns1.cat.lol"))
@ -1224,21 +1221,21 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatch_notFound_differentRegistrarRequested() { void testNameserverMatch_notFound_differentRegistrarRequested() {
action.registrarParam = Optional.of("otherregistrar"); action.registrarParam = Optional.of("otherregistrar");
runNotFoundTest(RequestType.NS_LDH_NAME, "ns1.cat.lol", "No matching nameservers found"); runNotFoundTest(RequestType.NS_LDH_NAME, "ns1.cat.lol", "No matching nameservers found");
verifyErrorMetrics(SearchType.BY_NAMESERVER_NAME, Optional.empty(), Optional.of(0L), 404); verifyErrorMetrics(SearchType.BY_NAMESERVER_NAME, Optional.empty(), Optional.of(0L), 404);
} }
@Test @Test
public void testNameserverMatchWithWildcard_found() { void testNameserverMatchWithWildcard_found() {
login("evilregistrar"); login("evilregistrar");
runSuccessfulTestWithCatLol(RequestType.NS_LDH_NAME, "ns2.cat.l*", "rdap_domain.json"); runSuccessfulTestWithCatLol(RequestType.NS_LDH_NAME, "ns2.cat.l*", "rdap_domain.json");
verifyMetrics(SearchType.BY_NAMESERVER_NAME, 1, 1); verifyMetrics(SearchType.BY_NAMESERVER_NAME, 1, 1);
} }
@Test @Test
public void testNameserverMatchWithWildcard_found_sameRegistrarRequested() { void testNameserverMatchWithWildcard_found_sameRegistrarRequested() {
login("evilregistrar"); login("evilregistrar");
action.registrarParam = Optional.of("TheRegistrar"); action.registrarParam = Optional.of("TheRegistrar");
runSuccessfulTestWithCatLol(RequestType.NS_LDH_NAME, "ns2.cat.l*", "rdap_domain.json"); runSuccessfulTestWithCatLol(RequestType.NS_LDH_NAME, "ns2.cat.l*", "rdap_domain.json");
@ -1246,20 +1243,20 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatchWithWildcard_notFound_differentRegistrarRequested() { void testNameserverMatchWithWildcard_notFound_differentRegistrarRequested() {
action.registrarParam = Optional.of("otherregistrar"); action.registrarParam = Optional.of("otherregistrar");
runNotFoundTest(RequestType.NS_LDH_NAME, "ns2.cat.l*", "No matching nameservers found"); runNotFoundTest(RequestType.NS_LDH_NAME, "ns2.cat.l*", "No matching nameservers found");
verifyErrorMetrics(SearchType.BY_NAMESERVER_NAME, Optional.empty(), Optional.of(0L), 404); verifyErrorMetrics(SearchType.BY_NAMESERVER_NAME, Optional.empty(), Optional.of(0L), 404);
} }
@Test @Test
public void testNameserverMatchWithWildcardAndDomainSuffix_notFound() { void testNameserverMatchWithWildcardAndDomainSuffix_notFound() {
runNotFoundTest(RequestType.NS_LDH_NAME, "ns5*.cat.lol", "No matching nameservers found"); runNotFoundTest(RequestType.NS_LDH_NAME, "ns5*.cat.lol", "No matching nameservers found");
verifyErrorMetrics(SearchType.BY_NAMESERVER_NAME, Optional.empty(), Optional.of(0L), 404); verifyErrorMetrics(SearchType.BY_NAMESERVER_NAME, Optional.empty(), Optional.of(0L), 404);
} }
@Test @Test
public void testNameserverMatchWithNoPrefixAndDomainSuffix_found() { void testNameserverMatchWithNoPrefixAndDomainSuffix_found() {
rememberWildcardType("*.cat.lol"); rememberWildcardType("*.cat.lol");
assertThat(generateActualJson(RequestType.NS_LDH_NAME, "*.cat.lol")) assertThat(generateActualJson(RequestType.NS_LDH_NAME, "*.cat.lol"))
.isEqualTo(generateExpectedJsonForTwoDomainsNsReply()); .isEqualTo(generateExpectedJsonForTwoDomainsNsReply());
@ -1268,7 +1265,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatchWithOneCharacterPrefixAndDomainSuffix_found() { void testNameserverMatchWithOneCharacterPrefixAndDomainSuffix_found() {
rememberWildcardType("n*.cat.lol"); rememberWildcardType("n*.cat.lol");
assertThat(generateActualJson(RequestType.NS_LDH_NAME, "n*.cat.lol")) assertThat(generateActualJson(RequestType.NS_LDH_NAME, "n*.cat.lol"))
.isEqualTo(generateExpectedJsonForTwoDomainsNsReply()); .isEqualTo(generateExpectedJsonForTwoDomainsNsReply());
@ -1277,8 +1274,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void void testNameserverMatchWithOneCharacterPrefixAndDomainSuffix_found_sameRegistrarRequested() {
testNameserverMatchWithOneCharacterPrefixAndDomainSuffix_found_sameRegistrarRequested() {
action.registrarParam = Optional.of("TheRegistrar"); action.registrarParam = Optional.of("TheRegistrar");
rememberWildcardType("n*.cat.lol"); rememberWildcardType("n*.cat.lol");
assertThat(generateActualJson(RequestType.NS_LDH_NAME, "n*.cat.lol")) assertThat(generateActualJson(RequestType.NS_LDH_NAME, "n*.cat.lol"))
@ -1288,14 +1284,14 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatchWithPrefixAndDomainSuffix_notFound_differentRegistrarRequested() { void testNameserverMatchWithPrefixAndDomainSuffix_notFound_differentRegistrarRequested() {
action.registrarParam = Optional.of("otherregistrar"); action.registrarParam = Optional.of("otherregistrar");
runNotFoundTest(RequestType.NS_LDH_NAME, "n*.cat.lol", "No matching nameservers found"); runNotFoundTest(RequestType.NS_LDH_NAME, "n*.cat.lol", "No matching nameservers found");
verifyErrorMetrics(SearchType.BY_NAMESERVER_NAME, Optional.empty(), Optional.of(0L), 404); verifyErrorMetrics(SearchType.BY_NAMESERVER_NAME, Optional.empty(), Optional.of(0L), 404);
} }
@Test @Test
public void testNameserverMatchWithTwoCharacterPrefixAndDomainSuffix_found() { void testNameserverMatchWithTwoCharacterPrefixAndDomainSuffix_found() {
rememberWildcardType("ns*.cat.lol"); rememberWildcardType("ns*.cat.lol");
assertThat(generateActualJson(RequestType.NS_LDH_NAME, "ns*.cat.lol")) assertThat(generateActualJson(RequestType.NS_LDH_NAME, "ns*.cat.lol"))
.isEqualTo(generateExpectedJsonForTwoDomainsNsReply()); .isEqualTo(generateExpectedJsonForTwoDomainsNsReply());
@ -1304,7 +1300,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatchWithWildcardAndEmptySuffix_unprocessable() { void testNameserverMatchWithWildcardAndEmptySuffix_unprocessable() {
rememberWildcardTypeInvalid(); rememberWildcardTypeInvalid();
generateActualJson(RequestType.NS_LDH_NAME, "ns*."); generateActualJson(RequestType.NS_LDH_NAME, "ns*.");
assertThat(response.getStatus()).isEqualTo(422); assertThat(response.getStatus()).isEqualTo(422);
@ -1312,7 +1308,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatchWithWildcardAndInvalidSuffix_unprocessable() { void testNameserverMatchWithWildcardAndInvalidSuffix_unprocessable() {
rememberWildcardType("ns*.google.com"); rememberWildcardType("ns*.google.com");
generateActualJson(RequestType.NS_LDH_NAME, "ns*.google.com"); generateActualJson(RequestType.NS_LDH_NAME, "ns*.google.com");
assertThat(response.getStatus()).isEqualTo(422); assertThat(response.getStatus()).isEqualTo(422);
@ -1320,21 +1316,21 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatch_ns2_cat_lol_found() { void testNameserverMatch_ns2_cat_lol_found() {
login("evilregistrar"); login("evilregistrar");
runSuccessfulTestWithCatLol(RequestType.NS_LDH_NAME, "ns2.cat.lol", "rdap_domain.json"); runSuccessfulTestWithCatLol(RequestType.NS_LDH_NAME, "ns2.cat.lol", "rdap_domain.json");
verifyMetrics(SearchType.BY_NAMESERVER_NAME, 1, 1); verifyMetrics(SearchType.BY_NAMESERVER_NAME, 1, 1);
} }
@Test @Test
public void testNameserverMatch_ns2_dog_lol_found() { void testNameserverMatch_ns2_dog_lol_found() {
login("evilregistrar"); login("evilregistrar");
runSuccessfulTestWithCat2Lol(RequestType.NS_LDH_NAME, "ns2.dog.lol", "rdap_domain_cat2.json"); runSuccessfulTestWithCat2Lol(RequestType.NS_LDH_NAME, "ns2.dog.lol", "rdap_domain_cat2.json");
verifyMetrics(SearchType.BY_NAMESERVER_NAME, 1, 1); verifyMetrics(SearchType.BY_NAMESERVER_NAME, 1, 1);
} }
@Test @Test
public void testNameserverMatch_ns1_cat_idn_unicode_badRequest() { void testNameserverMatch_ns1_cat_idn_unicode_badRequest() {
// nsLdhName must use punycode. // nsLdhName must use punycode.
metricWildcardType = WildcardType.INVALID; metricWildcardType = WildcardType.INVALID;
metricPrefixLength = 0; metricPrefixLength = 0;
@ -1344,7 +1340,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatch_ns1_cat_idn_punycode_found() { void testNameserverMatch_ns1_cat_idn_punycode_found() {
runSuccessfulTest( runSuccessfulTest(
RequestType.NS_LDH_NAME, RequestType.NS_LDH_NAME,
"ns1.cat.xn--q9jyb4c", "ns1.cat.xn--q9jyb4c",
@ -1358,7 +1354,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatch_ns1_cat_1_test_found() { void testNameserverMatch_ns1_cat_1_test_found() {
runSuccessfulTest( runSuccessfulTest(
RequestType.NS_LDH_NAME, RequestType.NS_LDH_NAME,
"ns1.cat.1.test", "ns1.cat.1.test",
@ -1372,7 +1368,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatch_nsstar_cat_1_test_found() { void testNameserverMatch_nsstar_cat_1_test_found() {
runSuccessfulTest( runSuccessfulTest(
RequestType.NS_LDH_NAME, RequestType.NS_LDH_NAME,
"ns*.cat.1.test", "ns*.cat.1.test",
@ -1386,7 +1382,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatch_nsstar_test_unprocessable() { void testNameserverMatch_nsstar_test_unprocessable() {
rememberWildcardType("ns*.1.test"); rememberWildcardType("ns*.1.test");
generateActualJson(RequestType.NS_LDH_NAME, "ns*.1.test"); generateActualJson(RequestType.NS_LDH_NAME, "ns*.1.test");
assertThat(response.getStatus()).isEqualTo(422); assertThat(response.getStatus()).isEqualTo(422);
@ -1394,21 +1390,21 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatchMissing_notFound() { void testNameserverMatchMissing_notFound() {
runNotFoundTest(RequestType.NS_LDH_NAME, "ns1.missing.com", "No matching nameservers found"); runNotFoundTest(RequestType.NS_LDH_NAME, "ns1.missing.com", "No matching nameservers found");
verifyErrorMetrics(SearchType.BY_NAMESERVER_NAME, Optional.empty(), Optional.of(0L), 404); verifyErrorMetrics(SearchType.BY_NAMESERVER_NAME, Optional.empty(), Optional.of(0L), 404);
} }
// TODO(b/27378695): reenable or delete this test // TODO(b/27378695): reenable or delete this test
@Ignore @Disabled
@Test @Test
public void testNameserverMatchDomainsInTestTld_notFound() { void testNameserverMatchDomainsInTestTld_notFound() {
persistResource(Registry.get("lol").asBuilder().setTldType(Registry.TldType.TEST).build()); persistResource(Registry.get("lol").asBuilder().setTldType(Registry.TldType.TEST).build());
runNotFoundTest(RequestType.NS_LDH_NAME, "ns2.cat.lol", "No matching nameservers found"); runNotFoundTest(RequestType.NS_LDH_NAME, "ns2.cat.lol", "No matching nameservers found");
} }
@Test @Test
public void testNameserverMatchDeletedDomain_notFound() { void testNameserverMatchDeletedDomain_notFound() {
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
deleteCatLol(); deleteCatLol();
runNotFoundTest(RequestType.NS_LDH_NAME, "ns2.cat.lol", "No domains found"); runNotFoundTest(RequestType.NS_LDH_NAME, "ns2.cat.lol", "No domains found");
@ -1416,7 +1412,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatchDeletedDomain_found_loggedInAsSameRegistrar() { void testNameserverMatchDeletedDomain_found_loggedInAsSameRegistrar() {
login("evilregistrar"); login("evilregistrar");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
deleteCatLol(); deleteCatLol();
@ -1425,7 +1421,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatchDeletedDomain_notFound_loggedInAsOtherRegistrar() { void testNameserverMatchDeletedDomain_notFound_loggedInAsOtherRegistrar() {
login("otherregistrar"); login("otherregistrar");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
persistDomainAsDeleted(domainCatLol, clock.nowUtc().minusDays(1)); persistDomainAsDeleted(domainCatLol, clock.nowUtc().minusDays(1));
@ -1434,7 +1430,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatchDeletedDomain_found_loggedInAsAdmin() { void testNameserverMatchDeletedDomain_found_loggedInAsAdmin() {
loginAsAdmin(); loginAsAdmin();
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
deleteCatLol(); deleteCatLol();
@ -1443,7 +1439,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatchOneDeletedDomain_foundTheOther() { void testNameserverMatchOneDeletedDomain_foundTheOther() {
login("evilregistrar"); login("evilregistrar");
persistDomainAsDeleted(domainCatExample, clock.nowUtc().minusDays(1)); persistDomainAsDeleted(domainCatExample, clock.nowUtc().minusDays(1));
runSuccessfulTestWithCatLol(RequestType.NS_LDH_NAME, "ns1.cat.lol", "rdap_domain.json"); runSuccessfulTestWithCatLol(RequestType.NS_LDH_NAME, "ns1.cat.lol", "rdap_domain.json");
@ -1451,7 +1447,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatchTwoDeletedDomains_notFound() { void testNameserverMatchTwoDeletedDomains_notFound() {
persistDomainAsDeleted(domainCatLol, clock.nowUtc().minusDays(1)); persistDomainAsDeleted(domainCatLol, clock.nowUtc().minusDays(1));
persistDomainAsDeleted(domainCatExample, clock.nowUtc().minusDays(1)); persistDomainAsDeleted(domainCatExample, clock.nowUtc().minusDays(1));
runNotFoundTest(RequestType.NS_LDH_NAME, "ns1.cat.lol", "No domains found"); runNotFoundTest(RequestType.NS_LDH_NAME, "ns1.cat.lol", "No domains found");
@ -1459,28 +1455,28 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatchDeletedNameserver_notFound() { void testNameserverMatchDeletedNameserver_notFound() {
persistResource(hostNs1CatLol.asBuilder().setDeletionTime(clock.nowUtc().minusDays(1)).build()); persistResource(hostNs1CatLol.asBuilder().setDeletionTime(clock.nowUtc().minusDays(1)).build());
runNotFoundTest(RequestType.NS_LDH_NAME, "ns1.cat.lol", "No matching nameservers found"); runNotFoundTest(RequestType.NS_LDH_NAME, "ns1.cat.lol", "No matching nameservers found");
verifyErrorMetrics(SearchType.BY_NAMESERVER_NAME, Optional.empty(), Optional.of(0L), 404); verifyErrorMetrics(SearchType.BY_NAMESERVER_NAME, Optional.empty(), Optional.of(0L), 404);
} }
@Test @Test
public void testNameserverMatchDeletedNameserverWithWildcard_notFound() { void testNameserverMatchDeletedNameserverWithWildcard_notFound() {
persistResource(hostNs1CatLol.asBuilder().setDeletionTime(clock.nowUtc().minusDays(1)).build()); persistResource(hostNs1CatLol.asBuilder().setDeletionTime(clock.nowUtc().minusDays(1)).build());
runNotFoundTest(RequestType.NS_LDH_NAME, "ns1.cat.l*", "No matching nameservers found"); runNotFoundTest(RequestType.NS_LDH_NAME, "ns1.cat.l*", "No matching nameservers found");
verifyErrorMetrics(SearchType.BY_NAMESERVER_NAME, Optional.empty(), Optional.of(0L), 404); verifyErrorMetrics(SearchType.BY_NAMESERVER_NAME, Optional.empty(), Optional.of(0L), 404);
} }
@Test @Test
public void testNameserverMatchDeletedNameserverWithWildcardAndSuffix_notFound() { void testNameserverMatchDeletedNameserverWithWildcardAndSuffix_notFound() {
persistResource(hostNs1CatLol.asBuilder().setDeletionTime(clock.nowUtc().minusDays(1)).build()); persistResource(hostNs1CatLol.asBuilder().setDeletionTime(clock.nowUtc().minusDays(1)).build());
runNotFoundTest(RequestType.NS_LDH_NAME, "ns1*.cat.lol", "No matching nameservers found"); runNotFoundTest(RequestType.NS_LDH_NAME, "ns1*.cat.lol", "No matching nameservers found");
verifyErrorMetrics(SearchType.BY_NAMESERVER_NAME, Optional.empty(), Optional.of(0L), 404); verifyErrorMetrics(SearchType.BY_NAMESERVER_NAME, Optional.empty(), Optional.of(0L), 404);
} }
@Test @Test
public void testNameserverMatchManyNameserversForTheSameDomains() { void testNameserverMatchManyNameserversForTheSameDomains() {
// 40 nameservers for each of 3 domains; we should get back all three undeleted domains, because // 40 nameservers for each of 3 domains; we should get back all three undeleted domains, because
// each one references the nameserver. // each one references the nameserver.
createManyDomainsAndHosts(3, 1, 40); createManyDomainsAndHosts(3, 1, 40);
@ -1492,7 +1488,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatchManyNameserversForTheSameDomainsWithWildcard() { void testNameserverMatchManyNameserversForTheSameDomainsWithWildcard() {
// Same as above, except with a wildcard (that still only finds one nameserver). // Same as above, except with a wildcard (that still only finds one nameserver).
createManyDomainsAndHosts(3, 1, 40); createManyDomainsAndHosts(3, 1, 40);
rememberWildcardType("ns1.domain1.l*"); rememberWildcardType("ns1.domain1.l*");
@ -1503,7 +1499,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatchManyNameserversForTheSameDomainsWithSuffix() { void testNameserverMatchManyNameserversForTheSameDomainsWithSuffix() {
// Same as above, except that we find all 39 nameservers because of the wildcard. But we // Same as above, except that we find all 39 nameservers because of the wildcard. But we
// should still only return 3 domains, because we merge duplicate domains together in a set. // should still only return 3 domains, because we merge duplicate domains together in a set.
// Since we fetch domains by nameserver in batches of 30 nameservers, we need to make sure to // Since we fetch domains by nameserver in batches of 30 nameservers, we need to make sure to
@ -1517,7 +1513,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatch_nontruncatedResultsSet() { void testNameserverMatch_nontruncatedResultsSet() {
createManyDomainsAndHosts(4, 1, 2); createManyDomainsAndHosts(4, 1, 2);
runSuccessfulTestWithFourDomains( runSuccessfulTestWithFourDomains(
RequestType.NS_LDH_NAME, RequestType.NS_LDH_NAME,
@ -1531,7 +1527,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatch_truncatedResultsSet() { void testNameserverMatch_truncatedResultsSet() {
createManyDomainsAndHosts(5, 1, 2); createManyDomainsAndHosts(5, 1, 2);
runSuccessfulTestWithFourDomains( runSuccessfulTestWithFourDomains(
RequestType.NS_LDH_NAME, RequestType.NS_LDH_NAME,
@ -1550,7 +1546,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatch_reallyTruncatedResultsSet() { void testNameserverMatch_reallyTruncatedResultsSet() {
createManyDomainsAndHosts(9, 1, 2); createManyDomainsAndHosts(9, 1, 2);
runSuccessfulTestWithFourDomains( runSuccessfulTestWithFourDomains(
RequestType.NS_LDH_NAME, RequestType.NS_LDH_NAME,
@ -1569,7 +1565,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatch_duplicatesNotTruncated() { void testNameserverMatch_duplicatesNotTruncated() {
// 36 nameservers for each of 4 domains; these should translate into two fetches, which should // 36 nameservers for each of 4 domains; these should translate into two fetches, which should
// not trigger the truncation warning because all the domains will be duplicates. // not trigger the truncation warning because all the domains will be duplicates.
createManyDomainsAndHosts(4, 1, 36); createManyDomainsAndHosts(4, 1, 36);
@ -1587,7 +1583,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatch_incompleteResultsSet() { void testNameserverMatch_incompleteResultsSet() {
createManyDomainsAndHosts(2, 1, 41); createManyDomainsAndHosts(2, 1, 41);
rememberWildcardType("ns*.domain1.lol"); rememberWildcardType("ns*.domain1.lol");
assertThat(generateActualJson(RequestType.NS_LDH_NAME, "ns*.domain1.lol")) assertThat(generateActualJson(RequestType.NS_LDH_NAME, "ns*.domain1.lol"))
@ -1605,7 +1601,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testNameserverMatch_cursorNavigation() throws Exception { void testNameserverMatch_cursorNavigation() throws Exception {
createManyDomainsAndHosts(8, 1, 2); createManyDomainsAndHosts(8, 1, 2);
checkCursorNavigation( checkCursorNavigation(
RequestType.NS_LDH_NAME, RequestType.NS_LDH_NAME,
@ -1622,7 +1618,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testAddressMatchV4Address_invalidAddress() { void testAddressMatchV4Address_invalidAddress() {
rememberWildcardType("1.2.3.4.5.6.7.8.9"); rememberWildcardType("1.2.3.4.5.6.7.8.9");
generateActualJson(RequestType.NS_IP, "1.2.3.4.5.6.7.8.9"); generateActualJson(RequestType.NS_IP, "1.2.3.4.5.6.7.8.9");
assertThat(response.getStatus()).isEqualTo(400); assertThat(response.getStatus()).isEqualTo(400);
@ -1630,7 +1626,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testAddressMatchV4Address_foundMultiple() { void testAddressMatchV4Address_foundMultiple() {
rememberWildcardType("1.2.3.4"); rememberWildcardType("1.2.3.4");
assertThat(generateActualJson(RequestType.NS_IP, "1.2.3.4")) assertThat(generateActualJson(RequestType.NS_IP, "1.2.3.4"))
.isEqualTo(generateExpectedJsonForTwoDomainsNsReply()); .isEqualTo(generateExpectedJsonForTwoDomainsNsReply());
@ -1639,7 +1635,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testAddressMatchV4Address_foundMultiple_sameRegistrarRequested() { void testAddressMatchV4Address_foundMultiple_sameRegistrarRequested() {
action.registrarParam = Optional.of("TheRegistrar"); action.registrarParam = Optional.of("TheRegistrar");
rememberWildcardType("1.2.3.4"); rememberWildcardType("1.2.3.4");
assertThat(generateActualJson(RequestType.NS_IP, "1.2.3.4")) assertThat(generateActualJson(RequestType.NS_IP, "1.2.3.4"))
@ -1649,14 +1645,14 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testAddressMatchV4Address_notFound_differentRegistrarRequested() { void testAddressMatchV4Address_notFound_differentRegistrarRequested() {
action.registrarParam = Optional.of("otherregistrar"); action.registrarParam = Optional.of("otherregistrar");
runNotFoundTest(RequestType.NS_IP, "1.2.3.4", "No domains found"); runNotFoundTest(RequestType.NS_IP, "1.2.3.4", "No domains found");
verifyErrorMetrics(SearchType.BY_NAMESERVER_ADDRESS, Optional.empty(), Optional.of(0L), 404); verifyErrorMetrics(SearchType.BY_NAMESERVER_ADDRESS, Optional.empty(), Optional.of(0L), 404);
} }
@Test @Test
public void testAddressMatchV6Address_foundOne() { void testAddressMatchV6Address_foundOne() {
runSuccessfulTestWithCatLol( runSuccessfulTestWithCatLol(
RequestType.NS_IP, RequestType.NS_IP,
"bad:f00d:cafe:0:0:0:15:beef", "bad:f00d:cafe:0:0:0:15:beef",
@ -1665,15 +1661,15 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testAddressMatchLocalhost_notFound() { void testAddressMatchLocalhost_notFound() {
runNotFoundTest(RequestType.NS_IP, "127.0.0.1", "No domains found"); runNotFoundTest(RequestType.NS_IP, "127.0.0.1", "No domains found");
verifyErrorMetrics(SearchType.BY_NAMESERVER_ADDRESS, Optional.empty(), Optional.of(0L), 404); verifyErrorMetrics(SearchType.BY_NAMESERVER_ADDRESS, Optional.empty(), Optional.of(0L), 404);
} }
// TODO(b/27378695): reenable or delete this test // TODO(b/27378695): reenable or delete this test
@Ignore @Disabled
@Test @Test
public void testAddressMatchDomainsInTestTld_notFound() { void testAddressMatchDomainsInTestTld_notFound() {
persistResource(Registry.get("lol").asBuilder().setTldType(Registry.TldType.TEST).build()); persistResource(Registry.get("lol").asBuilder().setTldType(Registry.TldType.TEST).build());
persistResource(Registry.get("example").asBuilder().setTldType(Registry.TldType.TEST).build()); persistResource(Registry.get("example").asBuilder().setTldType(Registry.TldType.TEST).build());
runNotFoundTest(RequestType.NS_IP, "127.0.0.1", "No matching nameservers found"); runNotFoundTest(RequestType.NS_IP, "127.0.0.1", "No matching nameservers found");
@ -1681,7 +1677,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testAddressMatchDeletedDomain_notFound() { void testAddressMatchDeletedDomain_notFound() {
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
deleteCatLol(); deleteCatLol();
runNotFoundTest(RequestType.NS_IP, "bad:f00d:cafe:0:0:0:15:beef", "No domains found"); runNotFoundTest(RequestType.NS_IP, "bad:f00d:cafe:0:0:0:15:beef", "No domains found");
@ -1689,7 +1685,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testAddressMatchDeletedDomain_found_loggedInAsSameRegistrar() { void testAddressMatchDeletedDomain_found_loggedInAsSameRegistrar() {
login("evilregistrar"); login("evilregistrar");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
deleteCatLol(); deleteCatLol();
@ -1699,7 +1695,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testAddressMatchDeletedDomain_notFound_loggedInAsOtherRegistrar() { void testAddressMatchDeletedDomain_notFound_loggedInAsOtherRegistrar() {
login("otherregistrar"); login("otherregistrar");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
persistDomainAsDeleted(domainCatLol, clock.nowUtc().minusDays(1)); persistDomainAsDeleted(domainCatLol, clock.nowUtc().minusDays(1));
@ -1708,7 +1704,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testAddressMatchDeletedDomain_found_loggedInAsAdmin() { void testAddressMatchDeletedDomain_found_loggedInAsAdmin() {
loginAsAdmin(); loginAsAdmin();
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
deleteCatLol(); deleteCatLol();
@ -1718,7 +1714,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testAddressMatchOneDeletedDomain_foundTheOther() { void testAddressMatchOneDeletedDomain_foundTheOther() {
login("evilregistrar"); login("evilregistrar");
persistDomainAsDeleted(domainCatExample, clock.nowUtc().minusDays(1)); persistDomainAsDeleted(domainCatExample, clock.nowUtc().minusDays(1));
rememberWildcardType("1.2.3.4"); rememberWildcardType("1.2.3.4");
@ -1739,7 +1735,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testAddressMatchTwoDeletedDomains_notFound() { void testAddressMatchTwoDeletedDomains_notFound() {
persistDomainAsDeleted(domainCatLol, clock.nowUtc().minusDays(1)); persistDomainAsDeleted(domainCatLol, clock.nowUtc().minusDays(1));
persistDomainAsDeleted(domainCatExample, clock.nowUtc().minusDays(1)); persistDomainAsDeleted(domainCatExample, clock.nowUtc().minusDays(1));
runNotFoundTest(RequestType.NS_IP, "1.2.3.4", "No domains found"); runNotFoundTest(RequestType.NS_IP, "1.2.3.4", "No domains found");
@ -1747,14 +1743,14 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testAddressMatchDeletedNameserver_notFound() { void testAddressMatchDeletedNameserver_notFound() {
persistResource(hostNs1CatLol.asBuilder().setDeletionTime(clock.nowUtc().minusDays(1)).build()); persistResource(hostNs1CatLol.asBuilder().setDeletionTime(clock.nowUtc().minusDays(1)).build());
runNotFoundTest(RequestType.NS_IP, "1.2.3.4", "No domains found"); runNotFoundTest(RequestType.NS_IP, "1.2.3.4", "No domains found");
verifyErrorMetrics(SearchType.BY_NAMESERVER_ADDRESS, Optional.empty(), Optional.of(0L), 404); verifyErrorMetrics(SearchType.BY_NAMESERVER_ADDRESS, Optional.empty(), Optional.of(0L), 404);
} }
@Test @Test
public void testAddressMatch_nontruncatedResultsSet() { void testAddressMatch_nontruncatedResultsSet() {
createManyDomainsAndHosts(4, 1, 2); createManyDomainsAndHosts(4, 1, 2);
runSuccessfulTestWithFourDomains( runSuccessfulTestWithFourDomains(
RequestType.NS_IP, RequestType.NS_IP,
@ -1768,7 +1764,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testAddressMatch_truncatedResultsSet() { void testAddressMatch_truncatedResultsSet() {
createManyDomainsAndHosts(5, 1, 2); createManyDomainsAndHosts(5, 1, 2);
runSuccessfulTestWithFourDomains( runSuccessfulTestWithFourDomains(
RequestType.NS_IP, RequestType.NS_IP,
@ -1787,7 +1783,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testAddressMatch_reallyTruncatedResultsSet() { void testAddressMatch_reallyTruncatedResultsSet() {
createManyDomainsAndHosts(9, 1, 2); createManyDomainsAndHosts(9, 1, 2);
runSuccessfulTestWithFourDomains( runSuccessfulTestWithFourDomains(
RequestType.NS_IP, RequestType.NS_IP,
@ -1806,7 +1802,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDom
} }
@Test @Test
public void testAddressMatch_cursorNavigation() throws Exception { void testAddressMatch_cursorNavigation() throws Exception {
createManyDomainsAndHosts(7, 1, 2); createManyDomainsAndHosts(7, 1, 2);
checkCursorNavigation( checkCursorNavigation(
RequestType.NS_IP, RequestType.NS_IP,

View file

@ -40,16 +40,13 @@ import google.registry.rdap.RdapSearchResults.IncompletenessWarningType;
import google.registry.request.Action; import google.registry.request.Action;
import java.util.Optional; import java.util.Optional;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RdapEntityAction}. */ /** Unit tests for {@link RdapEntityAction}. */
@RunWith(JUnit4.class) class RdapEntityActionTest extends RdapActionBaseTestCase<RdapEntityAction> {
public class RdapEntityActionTest extends RdapActionBaseTestCase<RdapEntityAction> {
public RdapEntityActionTest() { RdapEntityActionTest() {
super(RdapEntityAction.class); super(RdapEntityAction.class);
} }
@ -60,8 +57,8 @@ public class RdapEntityActionTest extends RdapActionBaseTestCase<RdapEntityActio
private ContactResource disconnectedContact; private ContactResource disconnectedContact;
private ContactResource deletedContact; private ContactResource deletedContact;
@Before @BeforeEach
public void setUp() { void beforeEach() {
// lol // lol
createTld("lol"); createTld("lol");
registrarLol = persistResource(makeRegistrar( registrarLol = persistResource(makeRegistrar(
@ -191,35 +188,35 @@ public class RdapEntityActionTest extends RdapActionBaseTestCase<RdapEntityActio
} }
@Test @Test
public void testUnknownEntity_RoidPattern_notFound() { void testUnknownEntity_RoidPattern_notFound() {
runNotFoundTest("_MISSING-ENTITY_"); runNotFoundTest("_MISSING-ENTITY_");
} }
@Test @Test
public void testUnknownEntity_IanaPattern_notFound() { void testUnknownEntity_IanaPattern_notFound() {
runNotFoundTest("123"); runNotFoundTest("123");
} }
@Test @Test
public void testUnknownEntity_notRoidNotIana_notFound() { void testUnknownEntity_notRoidNotIana_notFound() {
// Since we allow search by registrar name, every string is a possible name // Since we allow search by registrar name, every string is a possible name
runNotFoundTest("some,random,string"); runNotFoundTest("some,random,string");
} }
@Test @Test
public void testValidRegistrantContact_works() { void testValidRegistrantContact_works() {
login("evilregistrar"); login("evilregistrar");
runSuccessfulHandleTest(registrant.getRepoId(), "rdap_associated_contact.json"); runSuccessfulHandleTest(registrant.getRepoId(), "rdap_associated_contact.json");
} }
@Test @Test
public void testValidRegistrantContact_found_asAdministrator() { void testValidRegistrantContact_found_asAdministrator() {
loginAsAdmin(); loginAsAdmin();
runSuccessfulHandleTest(registrant.getRepoId(), "rdap_associated_contact.json"); runSuccessfulHandleTest(registrant.getRepoId(), "rdap_associated_contact.json");
} }
@Test @Test
public void testValidRegistrantContact_found_notLoggedIn() { void testValidRegistrantContact_found_notLoggedIn() {
runSuccessfulHandleTest( runSuccessfulHandleTest(
registrant.getRepoId(), registrant.getRepoId(),
"(◕‿◕)", "(◕‿◕)",
@ -229,7 +226,7 @@ public class RdapEntityActionTest extends RdapActionBaseTestCase<RdapEntityActio
} }
@Test @Test
public void testValidRegistrantContact_found_loggedInAsOtherRegistrar() { void testValidRegistrantContact_found_loggedInAsOtherRegistrar() {
login("otherregistrar"); login("otherregistrar");
runSuccessfulHandleTest( runSuccessfulHandleTest(
registrant.getRepoId(), registrant.getRepoId(),
@ -240,49 +237,49 @@ public class RdapEntityActionTest extends RdapActionBaseTestCase<RdapEntityActio
} }
@Test @Test
public void testValidAdminContact_works() { void testValidAdminContact_works() {
login("evilregistrar"); login("evilregistrar");
runSuccessfulHandleTest(adminContact.getRepoId(), "rdap_associated_contact.json"); runSuccessfulHandleTest(adminContact.getRepoId(), "rdap_associated_contact.json");
} }
@Test @Test
public void testValidTechContact_works() { void testValidTechContact_works() {
login("evilregistrar"); login("evilregistrar");
runSuccessfulHandleTest(techContact.getRepoId(), "rdap_associated_contact.json"); runSuccessfulHandleTest(techContact.getRepoId(), "rdap_associated_contact.json");
} }
@Test @Test
public void testValidDisconnectedContact_works() { void testValidDisconnectedContact_works() {
login("evilregistrar"); login("evilregistrar");
runSuccessfulHandleTest(disconnectedContact.getRepoId(), "rdap_contact.json"); runSuccessfulHandleTest(disconnectedContact.getRepoId(), "rdap_contact.json");
} }
@Test @Test
public void testDeletedContact_notFound() { void testDeletedContact_notFound() {
runNotFoundTest(deletedContact.getRepoId()); runNotFoundTest(deletedContact.getRepoId());
} }
@Test @Test
public void testDeletedContact_notFound_includeDeletedSetFalse() { void testDeletedContact_notFound_includeDeletedSetFalse() {
action.includeDeletedParam = Optional.of(false); action.includeDeletedParam = Optional.of(false);
runNotFoundTest(deletedContact.getRepoId()); runNotFoundTest(deletedContact.getRepoId());
} }
@Test @Test
public void testDeletedContact_notFound_notLoggedIn() { void testDeletedContact_notFound_notLoggedIn() {
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
runNotFoundTest(deletedContact.getRepoId()); runNotFoundTest(deletedContact.getRepoId());
} }
@Test @Test
public void testDeletedContact_notFound_loggedInAsDifferentRegistrar() { void testDeletedContact_notFound_loggedInAsDifferentRegistrar() {
login("idnregistrar"); login("idnregistrar");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
runNotFoundTest(deletedContact.getRepoId()); runNotFoundTest(deletedContact.getRepoId());
} }
@Test @Test
public void testDeletedContact_found_loggedInAsCorrectRegistrar() { void testDeletedContact_found_loggedInAsCorrectRegistrar() {
login("evilregistrar"); login("evilregistrar");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
runSuccessfulHandleTest( runSuccessfulHandleTest(
@ -294,7 +291,7 @@ public class RdapEntityActionTest extends RdapActionBaseTestCase<RdapEntityActio
} }
@Test @Test
public void testDeletedContact_found_loggedInAsAdmin() { void testDeletedContact_found_loggedInAsAdmin() {
loginAsAdmin(); loginAsAdmin();
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
runSuccessfulHandleTest( runSuccessfulHandleTest(
@ -306,12 +303,12 @@ public class RdapEntityActionTest extends RdapActionBaseTestCase<RdapEntityActio
} }
@Test @Test
public void testRegistrar_found() { void testRegistrar_found() {
runSuccessfulHandleTest("101", "Yes Virginia <script>", "rdap_registrar.json"); runSuccessfulHandleTest("101", "Yes Virginia <script>", "rdap_registrar.json");
} }
@Test @Test
public void testRegistrarByName_found() { void testRegistrarByName_found() {
assertThat(generateActualJson("IDN%20Registrar")) assertThat(generateActualJson("IDN%20Registrar"))
.isEqualTo( .isEqualTo(
generateExpectedJsonWithTopLevelEntries( generateExpectedJsonWithTopLevelEntries(
@ -320,28 +317,28 @@ public class RdapEntityActionTest extends RdapActionBaseTestCase<RdapEntityActio
} }
@Test @Test
public void testRegistrar102_works() { void testRegistrar102_works() {
runSuccessfulHandleTest("102", "IDN Registrar", "rdap_registrar.json"); runSuccessfulHandleTest("102", "IDN Registrar", "rdap_registrar.json");
} }
@Test @Test
public void testRegistrar103_works() { void testRegistrar103_works() {
runSuccessfulHandleTest("103", "Multilevel Registrar", "rdap_registrar.json"); runSuccessfulHandleTest("103", "Multilevel Registrar", "rdap_registrar.json");
} }
@Test @Test
public void testRegistrar104_notFound() { void testRegistrar104_notFound() {
runNotFoundTest("104"); runNotFoundTest("104");
} }
@Test @Test
public void testRegistrar104_notFound_deletedFlagWhenNotLoggedIn() { void testRegistrar104_notFound_deletedFlagWhenNotLoggedIn() {
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
runNotFoundTest("104"); runNotFoundTest("104");
} }
@Test @Test
public void testRegistrar104_found_deletedFlagWhenLoggedIn() { void testRegistrar104_found_deletedFlagWhenLoggedIn() {
login("deletedregistrar"); login("deletedregistrar");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
runSuccessfulHandleTest( runSuccessfulHandleTest(
@ -349,14 +346,14 @@ public class RdapEntityActionTest extends RdapActionBaseTestCase<RdapEntityActio
} }
@Test @Test
public void testRegistrar104_notFound_deletedFlagWhenLoggedInAsOther() { void testRegistrar104_notFound_deletedFlagWhenLoggedInAsOther() {
login("1tldregistrar"); login("1tldregistrar");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
runNotFoundTest("104"); runNotFoundTest("104");
} }
@Test @Test
public void testRegistrar104_found_deletedFlagWhenLoggedInAsAdmin() { void testRegistrar104_found_deletedFlagWhenLoggedInAsAdmin() {
loginAsAdmin(); loginAsAdmin();
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
runSuccessfulHandleTest( runSuccessfulHandleTest(
@ -364,12 +361,12 @@ public class RdapEntityActionTest extends RdapActionBaseTestCase<RdapEntityActio
} }
@Test @Test
public void testRegistrar105_doesNotExist() { void testRegistrar105_doesNotExist() {
runNotFoundTest("105"); runNotFoundTest("105");
} }
@Test @Test
public void testQueryParameter_ignored() { void testQueryParameter_ignored() {
login("evilregistrar"); login("evilregistrar");
assertThat(generateActualJson(techContact.getRepoId() + "?key=value")).isEqualTo( assertThat(generateActualJson(techContact.getRepoId() + "?key=value")).isEqualTo(
generateExpectedJsonWithTopLevelEntries( generateExpectedJsonWithTopLevelEntries(
@ -378,7 +375,7 @@ public class RdapEntityActionTest extends RdapActionBaseTestCase<RdapEntityActio
} }
@Test @Test
public void testMetrics() { void testMetrics() {
generateActualJson(registrant.getRepoId()); generateActualJson(registrant.getRepoId());
verify(rdapMetrics) verify(rdapMetrics)
.updateMetrics( .updateMetrics(

View file

@ -47,16 +47,13 @@ import google.registry.testing.FakeResponse;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.util.Optional; import java.util.Optional;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RdapEntitySearchAction}. */ /** Unit tests for {@link RdapEntitySearchAction}. */
@RunWith(JUnit4.class) class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEntitySearchAction> {
public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEntitySearchAction> {
public RdapEntitySearchActionTest() { RdapEntitySearchActionTest() {
super(RdapEntitySearchAction.class); super(RdapEntitySearchAction.class);
} }
@ -105,8 +102,8 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
return parseJsonObject(response.getPayload()); return parseJsonObject(response.getPayload());
} }
@Before @BeforeEach
public void setUp() { void beforeEach() {
createTld("tld"); createTld("tld");
// deleted // deleted
@ -390,7 +387,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testInvalidPath_rejected() { void testInvalidPath_rejected() {
action.requestPath = actionPath + "/path"; action.requestPath = actionPath + "/path";
action.run(); action.run();
assertThat(response.getStatus()).isEqualTo(400); assertThat(response.getStatus()).isEqualTo(400);
@ -398,7 +395,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testInvalidRequest_rejected() { void testInvalidRequest_rejected() {
action.run(); action.run();
assertThat(parseJsonObject(response.getPayload())) assertThat(parseJsonObject(response.getPayload()))
.isEqualTo( .isEqualTo(
@ -409,7 +406,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatch_suffixRejected() { void testNameMatch_suffixRejected() {
assertThat(generateActualJsonWithFullName("exam*ple")) assertThat(generateActualJsonWithFullName("exam*ple"))
.isEqualTo( .isEqualTo(
generateExpectedJsonError( generateExpectedJsonError(
@ -421,7 +418,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testHandleMatch_suffixRejected() { void testHandleMatch_suffixRejected() {
assertThat(generateActualJsonWithHandle("exam*ple")) assertThat(generateActualJsonWithHandle("exam*ple"))
.isEqualTo( .isEqualTo(
generateExpectedJsonError( generateExpectedJsonError(
@ -433,7 +430,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testMultipleWildcards_rejected() { void testMultipleWildcards_rejected() {
assertThat(generateActualJsonWithHandle("*.*")) assertThat(generateActualJsonWithHandle("*.*"))
.isEqualTo( .isEqualTo(
generateExpectedJsonError( generateExpectedJsonError(
@ -445,7 +442,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNoCharactersToMatch_rejected() { void testNoCharactersToMatch_rejected() {
rememberWildcardType("*"); rememberWildcardType("*");
assertThat(generateActualJsonWithHandle("*")) assertThat(generateActualJsonWithHandle("*"))
.isEqualTo( .isEqualTo(
@ -457,7 +454,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testFewerThanTwoCharactersToMatch_rejected() { void testFewerThanTwoCharactersToMatch_rejected() {
rememberWildcardType("a*"); rememberWildcardType("a*");
assertThat(generateActualJsonWithHandle("a*")) assertThat(generateActualJsonWithHandle("a*"))
.isEqualTo( .isEqualTo(
@ -469,7 +466,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testInvalidSubtype_rejected() { void testInvalidSubtype_rejected() {
action.subtypeParam = Optional.of("Space Aliens"); action.subtypeParam = Optional.of("Space Aliens");
assertThat(generateActualJsonWithFullName("Blinky (赤ベイ)")) assertThat(generateActualJsonWithFullName("Blinky (赤ベイ)"))
.isEqualTo( .isEqualTo(
@ -482,14 +479,14 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchContact_found() { void testNameMatchContact_found() {
login("2-RegistrarTest"); login("2-RegistrarTest");
runSuccessfulNameTestWithBlinky("Blinky (赤ベイ)", "rdap_contact.json"); runSuccessfulNameTestWithBlinky("Blinky (赤ベイ)", "rdap_contact.json");
verifyMetrics(1); verifyMetrics(1);
} }
@Test @Test
public void testNameMatchContact_found_subtypeAll() { void testNameMatchContact_found_subtypeAll() {
login("2-RegistrarTest"); login("2-RegistrarTest");
action.subtypeParam = Optional.of("aLl"); action.subtypeParam = Optional.of("aLl");
runSuccessfulNameTestWithBlinky("Blinky (赤ベイ)", "rdap_contact.json"); runSuccessfulNameTestWithBlinky("Blinky (赤ベイ)", "rdap_contact.json");
@ -497,7 +494,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchContact_found_subtypeContacts() { void testNameMatchContact_found_subtypeContacts() {
login("2-RegistrarTest"); login("2-RegistrarTest");
action.subtypeParam = Optional.of("cONTACTS"); action.subtypeParam = Optional.of("cONTACTS");
runSuccessfulNameTestWithBlinky("Blinky (赤ベイ)", "rdap_contact.json"); runSuccessfulNameTestWithBlinky("Blinky (赤ベイ)", "rdap_contact.json");
@ -505,7 +502,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchContact_notFound_subtypeRegistrars() { void testNameMatchContact_notFound_subtypeRegistrars() {
login("2-RegistrarTest"); login("2-RegistrarTest");
action.subtypeParam = Optional.of("Registrars"); action.subtypeParam = Optional.of("Registrars");
runNotFoundNameTest("Blinky (赤ベイ)"); runNotFoundNameTest("Blinky (赤ベイ)");
@ -513,7 +510,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchContact_found_specifyingSameRegistrar() { void testNameMatchContact_found_specifyingSameRegistrar() {
login("2-RegistrarTest"); login("2-RegistrarTest");
action.registrarParam = Optional.of("2-RegistrarTest"); action.registrarParam = Optional.of("2-RegistrarTest");
runSuccessfulNameTestWithBlinky("Blinky (赤ベイ)", "rdap_contact.json"); runSuccessfulNameTestWithBlinky("Blinky (赤ベイ)", "rdap_contact.json");
@ -521,7 +518,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchContact_notFound_specifyingOtherRegistrar() { void testNameMatchContact_notFound_specifyingOtherRegistrar() {
login("2-RegistrarTest"); login("2-RegistrarTest");
action.registrarParam = Optional.of("2-RegistrarInact"); action.registrarParam = Optional.of("2-RegistrarInact");
runNotFoundNameTest("Blinky (赤ベイ)"); runNotFoundNameTest("Blinky (赤ベイ)");
@ -529,7 +526,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchContact_found_asAdministrator() { void testNameMatchContact_found_asAdministrator() {
loginAsAdmin(); loginAsAdmin();
rememberWildcardType("Blinky (赤ベイ)"); rememberWildcardType("Blinky (赤ベイ)");
runSuccessfulNameTestWithBlinky("Blinky (赤ベイ)", "rdap_contact.json"); runSuccessfulNameTestWithBlinky("Blinky (赤ベイ)", "rdap_contact.json");
@ -537,27 +534,27 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchContact_notFound_notLoggedIn() { void testNameMatchContact_notFound_notLoggedIn() {
runNotFoundNameTest("Blinky (赤ベイ)"); runNotFoundNameTest("Blinky (赤ベイ)");
verifyErrorMetrics(0); verifyErrorMetrics(0);
} }
@Test @Test
public void testNameMatchContact_notFound_loggedInAsOtherRegistrar() { void testNameMatchContact_notFound_loggedInAsOtherRegistrar() {
login("2-Registrar"); login("2-Registrar");
runNotFoundNameTest("Blinky (赤ベイ)"); runNotFoundNameTest("Blinky (赤ベイ)");
verifyErrorMetrics(0); verifyErrorMetrics(0);
} }
@Test @Test
public void testNameMatchContact_found_wildcard() { void testNameMatchContact_found_wildcard() {
login("2-RegistrarTest"); login("2-RegistrarTest");
runSuccessfulNameTestWithBlinky("Blinky*", "rdap_contact.json"); runSuccessfulNameTestWithBlinky("Blinky*", "rdap_contact.json");
verifyMetrics(1); verifyMetrics(1);
} }
@Test @Test
public void testNameMatchContact_found_wildcardSpecifyingSameRegistrar() { void testNameMatchContact_found_wildcardSpecifyingSameRegistrar() {
login("2-RegistrarTest"); login("2-RegistrarTest");
action.registrarParam = Optional.of("2-RegistrarTest"); action.registrarParam = Optional.of("2-RegistrarTest");
runSuccessfulNameTestWithBlinky("Blinky*", "rdap_contact.json"); runSuccessfulNameTestWithBlinky("Blinky*", "rdap_contact.json");
@ -565,7 +562,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchContact_notFound_wildcardSpecifyingOtherRegistrar() { void testNameMatchContact_notFound_wildcardSpecifyingOtherRegistrar() {
login("2-RegistrarTest"); login("2-RegistrarTest");
action.registrarParam = Optional.of("2-RegistrarInact"); action.registrarParam = Optional.of("2-RegistrarInact");
runNotFoundNameTest("Blinky*"); runNotFoundNameTest("Blinky*");
@ -573,7 +570,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchContact_found_wildcardBoth() { void testNameMatchContact_found_wildcardBoth() {
login("2-RegistrarTest"); login("2-RegistrarTest");
rememberWildcardType("Blin*"); rememberWildcardType("Blin*");
assertThat(generateActualJsonWithFullName("Blin*")) assertThat(generateActualJsonWithFullName("Blin*"))
@ -583,14 +580,14 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchContact_notFound_deleted() { void testNameMatchContact_notFound_deleted() {
login("2-RegistrarTest"); login("2-RegistrarTest");
runNotFoundNameTest("Cl*"); runNotFoundNameTest("Cl*");
verifyErrorMetrics(0); verifyErrorMetrics(0);
} }
@Test @Test
public void testNameMatchContact_notFound_deletedWhenLoggedInAsOtherRegistrar() { void testNameMatchContact_notFound_deletedWhenLoggedInAsOtherRegistrar() {
login("2-RegistrarTest"); login("2-RegistrarTest");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
runNotFoundNameTest("Cl*"); runNotFoundNameTest("Cl*");
@ -598,7 +595,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchContact_notFound_deletedWhenLoggedInAsSameRegistrar() { void testNameMatchContact_notFound_deletedWhenLoggedInAsSameRegistrar() {
login("2-Registrar"); login("2-Registrar");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
runNotFoundNameTest("Cl*"); runNotFoundNameTest("Cl*");
@ -606,7 +603,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchContact_notFound_deletedWhenLoggedInAsAdmin() { void testNameMatchContact_notFound_deletedWhenLoggedInAsAdmin() {
loginAsAdmin(); loginAsAdmin();
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
runNotFoundNameTest("Cl*"); runNotFoundNameTest("Cl*");
@ -614,7 +611,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchRegistrar_found() { void testNameMatchRegistrar_found() {
login("2-RegistrarTest"); login("2-RegistrarTest");
runSuccessfulNameTest( runSuccessfulNameTest(
"Yes Virginia <script>", "20", "Yes Virginia <script>", "rdap_registrar.json"); "Yes Virginia <script>", "20", "Yes Virginia <script>", "rdap_registrar.json");
@ -622,7 +619,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchRegistrar_found_subtypeAll() { void testNameMatchRegistrar_found_subtypeAll() {
login("2-RegistrarTest"); login("2-RegistrarTest");
action.subtypeParam = Optional.of("all"); action.subtypeParam = Optional.of("all");
runSuccessfulNameTest( runSuccessfulNameTest(
@ -631,7 +628,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchRegistrar_found_subtypeRegistrars() { void testNameMatchRegistrar_found_subtypeRegistrars() {
login("2-RegistrarTest"); login("2-RegistrarTest");
action.subtypeParam = Optional.of("REGISTRARS"); action.subtypeParam = Optional.of("REGISTRARS");
runSuccessfulNameTest( runSuccessfulNameTest(
@ -640,7 +637,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchRegistrar_notFound_subtypeContacts() { void testNameMatchRegistrar_notFound_subtypeContacts() {
login("2-RegistrarTest"); login("2-RegistrarTest");
action.subtypeParam = Optional.of("contacts"); action.subtypeParam = Optional.of("contacts");
runNotFoundNameTest("Yes Virginia <script>"); runNotFoundNameTest("Yes Virginia <script>");
@ -648,7 +645,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchRegistrar_found_specifyingSameRegistrar() { void testNameMatchRegistrar_found_specifyingSameRegistrar() {
action.registrarParam = Optional.of("2-Registrar"); action.registrarParam = Optional.of("2-Registrar");
runSuccessfulNameTest( runSuccessfulNameTest(
"Yes Virginia <script>", "20", "Yes Virginia <script>", "rdap_registrar.json"); "Yes Virginia <script>", "20", "Yes Virginia <script>", "rdap_registrar.json");
@ -656,14 +653,14 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchRegistrar_notFound_specifyingDifferentRegistrar() { void testNameMatchRegistrar_notFound_specifyingDifferentRegistrar() {
action.registrarParam = Optional.of("2-RegistrarTest"); action.registrarParam = Optional.of("2-RegistrarTest");
runNotFoundNameTest("Yes Virginia <script>"); runNotFoundNameTest("Yes Virginia <script>");
verifyErrorMetrics(0); verifyErrorMetrics(0);
} }
@Test @Test
public void testNameMatchContacts_nonTruncated() { void testNameMatchContacts_nonTruncated() {
login("2-RegistrarTest"); login("2-RegistrarTest");
createManyContactsAndRegistrars(4, 0, registrarTest); createManyContactsAndRegistrars(4, 0, registrarTest);
rememberWildcardType("Entity *"); rememberWildcardType("Entity *");
@ -674,7 +671,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchContacts_truncated() { void testNameMatchContacts_truncated() {
login("2-RegistrarTest"); login("2-RegistrarTest");
createManyContactsAndRegistrars(5, 0, registrarTest); createManyContactsAndRegistrars(5, 0, registrarTest);
rememberWildcardType("Entity *"); rememberWildcardType("Entity *");
@ -687,7 +684,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchContacts_reallyTruncated() { void testNameMatchContacts_reallyTruncated() {
login("2-RegistrarTest"); login("2-RegistrarTest");
createManyContactsAndRegistrars(9, 0, registrarTest); createManyContactsAndRegistrars(9, 0, registrarTest);
rememberWildcardType("Entity *"); rememberWildcardType("Entity *");
@ -701,7 +698,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchContacts_cursorNavigation() throws Exception { void testNameMatchContacts_cursorNavigation() throws Exception {
login("2-RegistrarTest"); login("2-RegistrarTest");
createManyContactsAndRegistrars(9, 0, registrarTest); createManyContactsAndRegistrars(9, 0, registrarTest);
checkCursorNavigation( checkCursorNavigation(
@ -720,7 +717,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchRegistrars_nonTruncated() { void testNameMatchRegistrars_nonTruncated() {
createManyContactsAndRegistrars(0, 4, registrarTest); createManyContactsAndRegistrars(0, 4, registrarTest);
rememberWildcardType("Entity *"); rememberWildcardType("Entity *");
assertThat(generateActualJsonWithFullName("Entity *")) assertThat(generateActualJsonWithFullName("Entity *"))
@ -730,7 +727,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchRegistrars_truncated() { void testNameMatchRegistrars_truncated() {
createManyContactsAndRegistrars(0, 5, registrarTest); createManyContactsAndRegistrars(0, 5, registrarTest);
rememberWildcardType("Entity *"); rememberWildcardType("Entity *");
assertThat(generateActualJsonWithFullName("Entity *")) assertThat(generateActualJsonWithFullName("Entity *"))
@ -742,7 +739,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchRegistrars_reallyTruncated() { void testNameMatchRegistrars_reallyTruncated() {
createManyContactsAndRegistrars(0, 9, registrarTest); createManyContactsAndRegistrars(0, 9, registrarTest);
rememberWildcardType("Entity *"); rememberWildcardType("Entity *");
assertThat(generateActualJsonWithFullName("Entity *")) assertThat(generateActualJsonWithFullName("Entity *"))
@ -754,7 +751,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchRegistrars_cursorNavigation() throws Exception { void testNameMatchRegistrars_cursorNavigation() throws Exception {
createManyContactsAndRegistrars(0, 13, registrarTest); createManyContactsAndRegistrars(0, 13, registrarTest);
checkCursorNavigation( checkCursorNavigation(
QueryType.FULL_NAME, QueryType.FULL_NAME,
@ -776,7 +773,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchRegistrars_cursorNavigationThroughAll() throws Exception { void testNameMatchRegistrars_cursorNavigationThroughAll() throws Exception {
createManyContactsAndRegistrars(0, 13, registrarTest); createManyContactsAndRegistrars(0, 13, registrarTest);
action.subtypeParam = Optional.of("registrars"); action.subtypeParam = Optional.of("registrars");
checkCursorNavigation( checkCursorNavigation(
@ -802,7 +799,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchMix_truncated() { void testNameMatchMix_truncated() {
login("2-RegistrarTest"); login("2-RegistrarTest");
createManyContactsAndRegistrars(3, 3, registrarTest); createManyContactsAndRegistrars(3, 3, registrarTest);
rememberWildcardType("Entity *"); rememberWildcardType("Entity *");
@ -815,7 +812,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchMix_cursorNavigation() throws Exception { void testNameMatchMix_cursorNavigation() throws Exception {
login("2-RegistrarTest"); login("2-RegistrarTest");
createManyContactsAndRegistrars(3, 3, registrarTest); createManyContactsAndRegistrars(3, 3, registrarTest);
checkCursorNavigation( checkCursorNavigation(
@ -831,7 +828,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchMix_subtypeContacts() { void testNameMatchMix_subtypeContacts() {
login("2-RegistrarTest"); login("2-RegistrarTest");
action.subtypeParam = Optional.of("contacts"); action.subtypeParam = Optional.of("contacts");
createManyContactsAndRegistrars(4, 4, registrarTest); createManyContactsAndRegistrars(4, 4, registrarTest);
@ -843,7 +840,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchMix_subtypeRegistrars() { void testNameMatchMix_subtypeRegistrars() {
login("2-RegistrarTest"); login("2-RegistrarTest");
action.subtypeParam = Optional.of("registrars"); action.subtypeParam = Optional.of("registrars");
createManyContactsAndRegistrars(1, 1, registrarTest); createManyContactsAndRegistrars(1, 1, registrarTest);
@ -853,13 +850,13 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchRegistrar_notFound_inactive() { void testNameMatchRegistrar_notFound_inactive() {
runNotFoundNameTest("No Way"); runNotFoundNameTest("No Way");
verifyErrorMetrics(0); verifyErrorMetrics(0);
} }
@Test @Test
public void testNameMatchRegistrar_notFound_inactiveAsDifferentRegistrar() { void testNameMatchRegistrar_notFound_inactiveAsDifferentRegistrar() {
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
login("2-Registrar"); login("2-Registrar");
runNotFoundNameTest("No Way"); runNotFoundNameTest("No Way");
@ -867,7 +864,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchRegistrar_found_inactiveAsSameRegistrar() { void testNameMatchRegistrar_found_inactiveAsSameRegistrar() {
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
login("2-RegistrarInact"); login("2-RegistrarInact");
runSuccessfulNameTest("No Way", "21", "No Way", "inactive", null, "rdap_registrar.json"); runSuccessfulNameTest("No Way", "21", "No Way", "inactive", null, "rdap_registrar.json");
@ -875,7 +872,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchRegistrar_found_inactiveAsAdmin() { void testNameMatchRegistrar_found_inactiveAsAdmin() {
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
loginAsAdmin(); loginAsAdmin();
runSuccessfulNameTest("No Way", "21", "No Way", "inactive", null, "rdap_registrar.json"); runSuccessfulNameTest("No Way", "21", "No Way", "inactive", null, "rdap_registrar.json");
@ -883,13 +880,13 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchRegistrar_notFound_test() { void testNameMatchRegistrar_notFound_test() {
runNotFoundNameTest("Da Test Registrar"); runNotFoundNameTest("Da Test Registrar");
verifyErrorMetrics(0); verifyErrorMetrics(0);
} }
@Test @Test
public void testNameMatchRegistrar_notFound_testAsDifferentRegistrar() { void testNameMatchRegistrar_notFound_testAsDifferentRegistrar() {
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
login("2-Registrar"); login("2-Registrar");
runNotFoundNameTest("Da Test Registrar"); runNotFoundNameTest("Da Test Registrar");
@ -897,7 +894,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchRegistrar_found_testAsSameRegistrar() { void testNameMatchRegistrar_found_testAsSameRegistrar() {
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
login("2-RegistrarTest"); login("2-RegistrarTest");
runSuccessfulNameTest( runSuccessfulNameTest(
@ -906,7 +903,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testNameMatchRegistrar_found_testAsAdmin() { void testNameMatchRegistrar_found_testAsAdmin() {
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
loginAsAdmin(); loginAsAdmin();
runSuccessfulNameTest( runSuccessfulNameTest(
@ -915,14 +912,14 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testHandleMatchContact_found() { void testHandleMatchContact_found() {
login("2-RegistrarTest"); login("2-RegistrarTest");
runSuccessfulHandleTestWithBlinky("2-ROID", "rdap_contact.json"); runSuccessfulHandleTestWithBlinky("2-ROID", "rdap_contact.json");
verifyMetrics(1); verifyMetrics(1);
} }
@Test @Test
public void testHandleMatchContact_found_subtypeAll() { void testHandleMatchContact_found_subtypeAll() {
login("2-RegistrarTest"); login("2-RegistrarTest");
action.subtypeParam = Optional.of("all"); action.subtypeParam = Optional.of("all");
runSuccessfulHandleTestWithBlinky("2-ROID", "rdap_contact.json"); runSuccessfulHandleTestWithBlinky("2-ROID", "rdap_contact.json");
@ -930,7 +927,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testHandleMatchContact_found_subtypeContacts() { void testHandleMatchContact_found_subtypeContacts() {
login("2-RegistrarTest"); login("2-RegistrarTest");
action.subtypeParam = Optional.of("contacts"); action.subtypeParam = Optional.of("contacts");
runSuccessfulHandleTestWithBlinky("2-ROID", "rdap_contact.json"); runSuccessfulHandleTestWithBlinky("2-ROID", "rdap_contact.json");
@ -938,7 +935,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testHandleMatchContact_notFound_subtypeRegistrars() { void testHandleMatchContact_notFound_subtypeRegistrars() {
login("2-RegistrarTest"); login("2-RegistrarTest");
action.subtypeParam = Optional.of("reGistrars"); action.subtypeParam = Optional.of("reGistrars");
runNotFoundHandleTest("2-ROID"); runNotFoundHandleTest("2-ROID");
@ -946,28 +943,28 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testHandleMatchContact_found_specifyingSameRegistrar() { void testHandleMatchContact_found_specifyingSameRegistrar() {
action.registrarParam = Optional.of("2-RegistrarTest"); action.registrarParam = Optional.of("2-RegistrarTest");
runSuccessfulHandleTestWithBlinky("2-ROID", "rdap_contact_no_personal_data_with_remark.json"); runSuccessfulHandleTestWithBlinky("2-ROID", "rdap_contact_no_personal_data_with_remark.json");
verifyMetrics(1); verifyMetrics(1);
} }
@Test @Test
public void testHandleMatchContact_notFound_specifyingDifferentRegistrar() { void testHandleMatchContact_notFound_specifyingDifferentRegistrar() {
action.registrarParam = Optional.of("2-Registrar"); action.registrarParam = Optional.of("2-Registrar");
runNotFoundHandleTest("2-ROID"); runNotFoundHandleTest("2-ROID");
verifyErrorMetrics(0); verifyErrorMetrics(0);
} }
@Test @Test
public void testHandleMatchContact_notFound_deleted() { void testHandleMatchContact_notFound_deleted() {
login("2-RegistrarTest"); login("2-RegistrarTest");
runNotFoundHandleTest("6-ROID"); runNotFoundHandleTest("6-ROID");
verifyErrorMetrics(0); verifyErrorMetrics(0);
} }
@Test @Test
public void testHandleMatchContact_notFound_deletedWhenLoggedInAsOtherRegistrar() { void testHandleMatchContact_notFound_deletedWhenLoggedInAsOtherRegistrar() {
login("2-RegistrarTest"); login("2-RegistrarTest");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
runNotFoundHandleTest("6-ROID"); runNotFoundHandleTest("6-ROID");
@ -975,7 +972,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testHandleMatchContact_found_deletedWhenLoggedInAsSameRegistrar() { void testHandleMatchContact_found_deletedWhenLoggedInAsSameRegistrar() {
login("2-Registrar"); login("2-Registrar");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
runSuccessfulHandleTest( runSuccessfulHandleTest(
@ -989,7 +986,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testHandleMatchContact_found_deletedWhenLoggedInAsAdmin() { void testHandleMatchContact_found_deletedWhenLoggedInAsAdmin() {
loginAsAdmin(); loginAsAdmin();
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
runSuccessfulHandleTest( runSuccessfulHandleTest(
@ -1003,14 +1000,14 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testHandleMatchContact_notFound_deletedWildcard() { void testHandleMatchContact_notFound_deletedWildcard() {
login("2-RegistrarTest"); login("2-RegistrarTest");
runNotFoundHandleTest("6-ROI*"); runNotFoundHandleTest("6-ROI*");
verifyErrorMetrics(0); verifyErrorMetrics(0);
} }
@Test @Test
public void testHandleMatchContact_notFound_deletedWildcardWhenLoggedInAsOtherRegistrar() { void testHandleMatchContact_notFound_deletedWildcardWhenLoggedInAsOtherRegistrar() {
login("2-RegistrarTest"); login("2-RegistrarTest");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
runNotFoundHandleTest("6-ROI*"); runNotFoundHandleTest("6-ROI*");
@ -1018,7 +1015,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testHandleMatchContact_found_deletedWildcardWhenLoggedInAsSameRegistrar() { void testHandleMatchContact_found_deletedWildcardWhenLoggedInAsSameRegistrar() {
login("2-Registrar"); login("2-Registrar");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
runSuccessfulHandleTest( runSuccessfulHandleTest(
@ -1032,7 +1029,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testHandleMatchContact_found_deletedWildcardWhenLoggedInAsAdmin() { void testHandleMatchContact_found_deletedWildcardWhenLoggedInAsAdmin() {
loginAsAdmin(); loginAsAdmin();
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
runSuccessfulHandleTest( runSuccessfulHandleTest(
@ -1046,48 +1043,48 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testHandleMatchRegistrar_found() { void testHandleMatchRegistrar_found() {
runSuccessfulHandleTest("20", "20", "Yes Virginia <script>", "rdap_registrar.json"); runSuccessfulHandleTest("20", "20", "Yes Virginia <script>", "rdap_registrar.json");
verifyMetrics(0); verifyMetrics(0);
} }
@Test @Test
public void testHandleMatchRegistrar_found_subtypeAll() { void testHandleMatchRegistrar_found_subtypeAll() {
action.subtypeParam = Optional.of("all"); action.subtypeParam = Optional.of("all");
runSuccessfulHandleTest("20", "20", "Yes Virginia <script>", "rdap_registrar.json"); runSuccessfulHandleTest("20", "20", "Yes Virginia <script>", "rdap_registrar.json");
verifyMetrics(0); verifyMetrics(0);
} }
@Test @Test
public void testHandleMatchRegistrar_found_subtypeRegistrars() { void testHandleMatchRegistrar_found_subtypeRegistrars() {
action.subtypeParam = Optional.of("registrars"); action.subtypeParam = Optional.of("registrars");
runSuccessfulHandleTest("20", "20", "Yes Virginia <script>", "rdap_registrar.json"); runSuccessfulHandleTest("20", "20", "Yes Virginia <script>", "rdap_registrar.json");
verifyMetrics(0); verifyMetrics(0);
} }
@Test @Test
public void testHandleMatchRegistrar_notFound_subtypeContacts() { void testHandleMatchRegistrar_notFound_subtypeContacts() {
action.subtypeParam = Optional.of("contacts"); action.subtypeParam = Optional.of("contacts");
runNotFoundHandleTest("20"); runNotFoundHandleTest("20");
verifyErrorMetrics(0); verifyErrorMetrics(0);
} }
@Test @Test
public void testHandleMatchRegistrar_found_specifyingSameRegistrar() { void testHandleMatchRegistrar_found_specifyingSameRegistrar() {
action.registrarParam = Optional.of("2-Registrar"); action.registrarParam = Optional.of("2-Registrar");
runSuccessfulHandleTest("20", "20", "Yes Virginia <script>", "rdap_registrar.json"); runSuccessfulHandleTest("20", "20", "Yes Virginia <script>", "rdap_registrar.json");
verifyMetrics(0); verifyMetrics(0);
} }
@Test @Test
public void testHandleMatchRegistrar_notFound_specifyingDifferentRegistrar() { void testHandleMatchRegistrar_notFound_specifyingDifferentRegistrar() {
action.registrarParam = Optional.of("2-RegistrarTest"); action.registrarParam = Optional.of("2-RegistrarTest");
runNotFoundHandleTest("20"); runNotFoundHandleTest("20");
verifyErrorMetrics(0); verifyErrorMetrics(0);
} }
@Test @Test
public void testHandleMatchContact_found_wildcardWithResultSetSizeOne() { void testHandleMatchContact_found_wildcardWithResultSetSizeOne() {
login("2-RegistrarTest"); login("2-RegistrarTest");
action.rdapResultSetMaxSize = 1; action.rdapResultSetMaxSize = 1;
runSuccessfulHandleTestWithBlinky("2-R*", "rdap_contact.json"); runSuccessfulHandleTestWithBlinky("2-R*", "rdap_contact.json");
@ -1095,14 +1092,14 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testHandleMatchContact_found_wildcard() { void testHandleMatchContact_found_wildcard() {
login("2-RegistrarTest"); login("2-RegistrarTest");
runSuccessfulHandleTestWithBlinky("2-RO*", "rdap_contact.json"); runSuccessfulHandleTestWithBlinky("2-RO*", "rdap_contact.json");
verifyMetrics(1); verifyMetrics(1);
} }
@Test @Test
public void testHandleMatchContact_found_wildcardSpecifyingSameRegistrar() { void testHandleMatchContact_found_wildcardSpecifyingSameRegistrar() {
action.registrarParam = Optional.of("2-RegistrarTest"); action.registrarParam = Optional.of("2-RegistrarTest");
login("2-RegistrarTest"); login("2-RegistrarTest");
runSuccessfulHandleTestWithBlinky("2-RO*", "rdap_contact.json"); runSuccessfulHandleTestWithBlinky("2-RO*", "rdap_contact.json");
@ -1110,7 +1107,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testHandleMatchContact_notFound_wildcardSpecifyingDifferentRegistrar() { void testHandleMatchContact_notFound_wildcardSpecifyingDifferentRegistrar() {
action.registrarParam = Optional.of("2-Registrar"); action.registrarParam = Optional.of("2-Registrar");
login("2-RegistrarTest"); login("2-RegistrarTest");
runNotFoundHandleTest("2-RO*"); runNotFoundHandleTest("2-RO*");
@ -1118,20 +1115,20 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testHandleMatchContact_found_deleted() { void testHandleMatchContact_found_deleted() {
login("2-RegistrarTest"); login("2-RegistrarTest");
runSuccessfulHandleTestWithBlinky("2-RO*", "rdap_contact.json"); runSuccessfulHandleTestWithBlinky("2-RO*", "rdap_contact.json");
verifyMetrics(1); verifyMetrics(1);
} }
@Test @Test
public void testHandleMatchContact_notFound_wildcard() { void testHandleMatchContact_notFound_wildcard() {
runNotFoundHandleTest("20*"); runNotFoundHandleTest("20*");
verifyErrorMetrics(0); verifyErrorMetrics(0);
} }
@Test @Test
public void testHandleMatchContact_cursorNavigationWithFullLastPage() throws Exception { void testHandleMatchContact_cursorNavigationWithFullLastPage() throws Exception {
login("2-RegistrarTest"); login("2-RegistrarTest");
createManyContactsAndRegistrars(12, 0, registrarTest); createManyContactsAndRegistrars(12, 0, registrarTest);
checkCursorNavigation( checkCursorNavigation(
@ -1154,7 +1151,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testHandleMatchContact_cursorNavigationWithPartialLastPage() throws Exception { void testHandleMatchContact_cursorNavigationWithPartialLastPage() throws Exception {
login("2-RegistrarTest"); login("2-RegistrarTest");
createManyContactsAndRegistrars(13, 0, registrarTest); createManyContactsAndRegistrars(13, 0, registrarTest);
checkCursorNavigation( checkCursorNavigation(
@ -1178,13 +1175,13 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testHandleMatchRegistrar_notFound_wildcard() { void testHandleMatchRegistrar_notFound_wildcard() {
runNotFoundHandleTest("3test*"); runNotFoundHandleTest("3test*");
verifyErrorMetrics(0); verifyErrorMetrics(0);
} }
@Test @Test
public void testHandleMatchRegistrars_cursorNavigationThroughAll() throws Exception { void testHandleMatchRegistrars_cursorNavigationThroughAll() throws Exception {
createManyContactsAndRegistrars(0, 13, registrarTest); createManyContactsAndRegistrars(0, 13, registrarTest);
action.subtypeParam = Optional.of("registrars"); action.subtypeParam = Optional.of("registrars");
checkCursorNavigation( checkCursorNavigation(
@ -1210,7 +1207,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testHandleMatchMix_found_truncated() { void testHandleMatchMix_found_truncated() {
createManyContactsAndRegistrars(30, 0, registrarTest); createManyContactsAndRegistrars(30, 0, registrarTest);
rememberWildcardType("00*"); rememberWildcardType("00*");
JsonObject obj = generateActualJsonWithHandle("00*"); JsonObject obj = generateActualJsonWithHandle("00*");
@ -1220,13 +1217,13 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testHandleMatchRegistrar_notFound_inactive() { void testHandleMatchRegistrar_notFound_inactive() {
runNotFoundHandleTest("21"); runNotFoundHandleTest("21");
verifyErrorMetrics(0); verifyErrorMetrics(0);
} }
@Test @Test
public void testHandleMatchRegistrar_notFound_inactiveAsDifferentRegistrar() { void testHandleMatchRegistrar_notFound_inactiveAsDifferentRegistrar() {
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
login("2-Registrar"); login("2-Registrar");
runNotFoundHandleTest("21"); runNotFoundHandleTest("21");
@ -1234,7 +1231,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testHandleMatchRegistrar_found_inactiveAsSameRegistrar() { void testHandleMatchRegistrar_found_inactiveAsSameRegistrar() {
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
login("2-RegistrarInact"); login("2-RegistrarInact");
runSuccessfulHandleTest("21", "21", "No Way", "inactive", null, "rdap_registrar.json"); runSuccessfulHandleTest("21", "21", "No Way", "inactive", null, "rdap_registrar.json");
@ -1242,7 +1239,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEnt
} }
@Test @Test
public void testHandleMatchRegistrar_found_inactiveAsAdmin() { void testHandleMatchRegistrar_found_inactiveAsAdmin() {
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
loginAsAdmin(); loginAsAdmin();
runSuccessfulHandleTest("21", "21", "No Way", "inactive", null, "rdap_registrar.json"); runSuccessfulHandleTest("21", "21", "No Way", "inactive", null, "rdap_registrar.json");

View file

@ -23,55 +23,49 @@ import google.registry.rdap.RdapMetrics.SearchType;
import google.registry.rdap.RdapMetrics.WildcardType; import google.registry.rdap.RdapMetrics.WildcardType;
import google.registry.rdap.RdapSearchResults.IncompletenessWarningType; import google.registry.rdap.RdapSearchResults.IncompletenessWarningType;
import google.registry.request.Action; import google.registry.request.Action;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RdapHelpAction}. */ /** Unit tests for {@link RdapHelpAction}. */
@RunWith(JUnit4.class) class RdapHelpActionTest extends RdapActionBaseTestCase<RdapHelpAction> {
public class RdapHelpActionTest extends RdapActionBaseTestCase<RdapHelpAction> {
public RdapHelpActionTest() { RdapHelpActionTest() {
super(RdapHelpAction.class); super(RdapHelpAction.class);
} }
@Test @Test
public void testHelpActionMaliciousPath_notFound() { void testHelpActionMaliciousPath_notFound() {
assertThat(generateActualJson("../passwd")) assertThat(generateActualJson("../passwd"))
.isEqualTo(generateExpectedJsonError("no help found for ../passwd", 404)); .isEqualTo(generateExpectedJsonError("no help found for ../passwd", 404));
assertThat(response.getStatus()).isEqualTo(404); assertThat(response.getStatus()).isEqualTo(404);
} }
@Test @Test
public void testHelpActionUnknownPath_notFound() { void testHelpActionUnknownPath_notFound() {
assertThat(generateActualJson("hlarg")).isEqualTo( assertThat(generateActualJson("hlarg"))
generateExpectedJsonError("no help found for hlarg", 404)); .isEqualTo(generateExpectedJsonError("no help found for hlarg", 404));
assertThat(response.getStatus()).isEqualTo(404); assertThat(response.getStatus()).isEqualTo(404);
} }
@Test @Test
public void testHelpActionDefault_getsIndex() { void testHelpActionDefault_getsIndex() {
assertThat(generateActualJson("")) assertThat(generateActualJson("")).isEqualTo(loadJsonFile("rdap_help_index.json"));
.isEqualTo(loadJsonFile("rdap_help_index.json"));
assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getStatus()).isEqualTo(200);
} }
@Test @Test
public void testHelpActionSlash_getsIndex() { void testHelpActionSlash_getsIndex() {
assertThat(generateActualJson("/")) assertThat(generateActualJson("/")).isEqualTo(loadJsonFile("rdap_help_index.json"));
.isEqualTo(loadJsonFile("rdap_help_index.json"));
assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getStatus()).isEqualTo(200);
} }
@Test @Test
public void testHelpActionTos_works() { void testHelpActionTos_works() {
assertThat(generateActualJson("/tos")) assertThat(generateActualJson("/tos")).isEqualTo(loadJsonFile("rdap_help_tos.json"));
.isEqualTo(loadJsonFile("rdap_help_tos.json"));
assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getStatus()).isEqualTo(200);
} }
@Test @Test
public void testHelpActionMetrics() { void testHelpActionMetrics() {
generateActualJson("/tos"); generateActualJson("/tos");
verify(rdapMetrics) verify(rdapMetrics)
.updateMetrics( .updateMetrics(

View file

@ -50,20 +50,17 @@ import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock; import google.registry.testing.FakeClock;
import google.registry.testing.InjectRule; import google.registry.testing.InjectRule;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RdapJsonFormatter}. */ /** Unit tests for {@link RdapJsonFormatter}. */
@RunWith(JUnit4.class) class RdapJsonFormatterTest {
public class RdapJsonFormatterTest {
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Rule public final InjectRule inject = new InjectRule(); @RegisterExtension public final InjectRule inject = new InjectRule();
private final FakeClock clock = new FakeClock(DateTime.parse("1999-01-01T00:00:00Z")); private final FakeClock clock = new FakeClock(DateTime.parse("1999-01-01T00:00:00Z"));
@ -83,9 +80,8 @@ public class RdapJsonFormatterTest {
private ContactResource contactResourceTech; private ContactResource contactResourceTech;
private ContactResource contactResourceNotLinked; private ContactResource contactResourceNotLinked;
@BeforeEach
@Before void beforeEach() {
public void setUp() {
inject.setStaticField(Ofy.class, "clock", clock); inject.setStaticField(Ofy.class, "clock", clock);
rdapJsonFormatter = RdapTestHelper.getTestRdapJsonFormatter(clock); rdapJsonFormatter = RdapTestHelper.getTestRdapJsonFormatter(clock);
@ -259,7 +255,7 @@ public class RdapJsonFormatterTest {
clock.nowUtc().minusMonths(3))); clock.nowUtc().minusMonths(3)));
} }
public static ImmutableList<RegistrarContact> makeMoreRegistrarContacts(Registrar registrar) { static ImmutableList<RegistrarContact> makeMoreRegistrarContacts(Registrar registrar) {
return ImmutableList.of( return ImmutableList.of(
new RegistrarContact.Builder() new RegistrarContact.Builder()
.setParent(registrar) .setParent(registrar)
@ -306,41 +302,41 @@ public class RdapJsonFormatterTest {
} }
@Test @Test
public void testRegistrar() { void testRegistrar() {
assertThat(rdapJsonFormatter.createRdapRegistrarEntity(registrar, OutputDataType.FULL).toJson()) assertThat(rdapJsonFormatter.createRdapRegistrarEntity(registrar, OutputDataType.FULL).toJson())
.isEqualTo(loadJson("rdapjson_registrar.json")); .isEqualTo(loadJson("rdapjson_registrar.json"));
} }
@Test @Test
public void testRegistrar_summary() { void testRegistrar_summary() {
assertThat( assertThat(
rdapJsonFormatter.createRdapRegistrarEntity(registrar, OutputDataType.SUMMARY).toJson()) rdapJsonFormatter.createRdapRegistrarEntity(registrar, OutputDataType.SUMMARY).toJson())
.isEqualTo(loadJson("rdapjson_registrar_summary.json")); .isEqualTo(loadJson("rdapjson_registrar_summary.json"));
} }
@Test @Test
public void testHost_ipv4() { void testHost_ipv4() {
assertThat( assertThat(
rdapJsonFormatter.createRdapNameserver(hostResourceIpv4, OutputDataType.FULL).toJson()) rdapJsonFormatter.createRdapNameserver(hostResourceIpv4, OutputDataType.FULL).toJson())
.isEqualTo(loadJson("rdapjson_host_ipv4.json")); .isEqualTo(loadJson("rdapjson_host_ipv4.json"));
} }
@Test @Test
public void testHost_ipv6() { void testHost_ipv6() {
assertThat( assertThat(
rdapJsonFormatter.createRdapNameserver(hostResourceIpv6, OutputDataType.FULL).toJson()) rdapJsonFormatter.createRdapNameserver(hostResourceIpv6, OutputDataType.FULL).toJson())
.isEqualTo(loadJson("rdapjson_host_ipv6.json")); .isEqualTo(loadJson("rdapjson_host_ipv6.json"));
} }
@Test @Test
public void testHost_both() { void testHost_both() {
assertThat( assertThat(
rdapJsonFormatter.createRdapNameserver(hostResourceBoth, OutputDataType.FULL).toJson()) rdapJsonFormatter.createRdapNameserver(hostResourceBoth, OutputDataType.FULL).toJson())
.isEqualTo(loadJson("rdapjson_host_both.json")); .isEqualTo(loadJson("rdapjson_host_both.json"));
} }
@Test @Test
public void testHost_both_summary() { void testHost_both_summary() {
assertThat( assertThat(
rdapJsonFormatter rdapJsonFormatter
.createRdapNameserver(hostResourceBoth, OutputDataType.SUMMARY) .createRdapNameserver(hostResourceBoth, OutputDataType.SUMMARY)
@ -349,7 +345,7 @@ public class RdapJsonFormatterTest {
} }
@Test @Test
public void testHost_noAddresses() { void testHost_noAddresses() {
assertThat( assertThat(
rdapJsonFormatter rdapJsonFormatter
.createRdapNameserver(hostResourceNoAddresses, OutputDataType.FULL) .createRdapNameserver(hostResourceNoAddresses, OutputDataType.FULL)
@ -358,7 +354,7 @@ public class RdapJsonFormatterTest {
} }
@Test @Test
public void testHost_notLinked() { void testHost_notLinked() {
assertThat( assertThat(
rdapJsonFormatter rdapJsonFormatter
.createRdapNameserver(hostResourceNotLinked, OutputDataType.FULL) .createRdapNameserver(hostResourceNotLinked, OutputDataType.FULL)
@ -367,7 +363,7 @@ public class RdapJsonFormatterTest {
} }
@Test @Test
public void testHost_superordinateHasPendingTransfer() { void testHost_superordinateHasPendingTransfer() {
assertThat( assertThat(
rdapJsonFormatter rdapJsonFormatter
.createRdapNameserver(hostResourceSuperordinatePendingTransfer, OutputDataType.FULL) .createRdapNameserver(hostResourceSuperordinatePendingTransfer, OutputDataType.FULL)
@ -376,7 +372,7 @@ public class RdapJsonFormatterTest {
} }
@Test @Test
public void testRegistrant() { void testRegistrant() {
assertThat( assertThat(
rdapJsonFormatter rdapJsonFormatter
.createRdapContactEntity( .createRdapContactEntity(
@ -388,7 +384,7 @@ public class RdapJsonFormatterTest {
} }
@Test @Test
public void testRegistrant_summary() { void testRegistrant_summary() {
assertThat( assertThat(
rdapJsonFormatter rdapJsonFormatter
.createRdapContactEntity( .createRdapContactEntity(
@ -400,7 +396,7 @@ public class RdapJsonFormatterTest {
} }
@Test @Test
public void testRegistrant_loggedOut() { void testRegistrant_loggedOut() {
rdapJsonFormatter.rdapAuthorization = RdapAuthorization.PUBLIC_AUTHORIZATION; rdapJsonFormatter.rdapAuthorization = RdapAuthorization.PUBLIC_AUTHORIZATION;
assertThat( assertThat(
rdapJsonFormatter rdapJsonFormatter
@ -413,7 +409,7 @@ public class RdapJsonFormatterTest {
} }
@Test @Test
public void testRegistrant_baseHasNoTrailingSlash() { void testRegistrant_baseHasNoTrailingSlash() {
// First, make sure we have a trailing slash at the end by default! // First, make sure we have a trailing slash at the end by default!
// This test tries to change the default state, if the default doesn't have a /, then this test // This test tries to change the default state, if the default doesn't have a /, then this test
// doesn't help. // doesn't help.
@ -432,7 +428,7 @@ public class RdapJsonFormatterTest {
} }
@Test @Test
public void testAdmin() { void testAdmin() {
assertThat( assertThat(
rdapJsonFormatter rdapJsonFormatter
.createRdapContactEntity( .createRdapContactEntity(
@ -444,7 +440,7 @@ public class RdapJsonFormatterTest {
} }
@Test @Test
public void testTech() { void testTech() {
assertThat( assertThat(
rdapJsonFormatter rdapJsonFormatter
.createRdapContactEntity( .createRdapContactEntity(
@ -454,7 +450,7 @@ public class RdapJsonFormatterTest {
} }
@Test @Test
public void testRolelessContact() { void testRolelessContact() {
assertThat( assertThat(
rdapJsonFormatter rdapJsonFormatter
.createRdapContactEntity( .createRdapContactEntity(
@ -464,7 +460,7 @@ public class RdapJsonFormatterTest {
} }
@Test @Test
public void testUnlinkedContact() { void testUnlinkedContact() {
assertThat( assertThat(
rdapJsonFormatter rdapJsonFormatter
.createRdapContactEntity( .createRdapContactEntity(
@ -474,26 +470,26 @@ public class RdapJsonFormatterTest {
} }
@Test @Test
public void testDomain_full() { void testDomain_full() {
assertThat(rdapJsonFormatter.createRdapDomain(domainBaseFull, OutputDataType.FULL).toJson()) assertThat(rdapJsonFormatter.createRdapDomain(domainBaseFull, OutputDataType.FULL).toJson())
.isEqualTo(loadJson("rdapjson_domain_full.json")); .isEqualTo(loadJson("rdapjson_domain_full.json"));
} }
@Test @Test
public void testDomain_summary() { void testDomain_summary() {
assertThat(rdapJsonFormatter.createRdapDomain(domainBaseFull, OutputDataType.SUMMARY).toJson()) assertThat(rdapJsonFormatter.createRdapDomain(domainBaseFull, OutputDataType.SUMMARY).toJson())
.isEqualTo(loadJson("rdapjson_domain_summary.json")); .isEqualTo(loadJson("rdapjson_domain_summary.json"));
} }
@Test @Test
public void testDomain_logged_out() { void testDomain_logged_out() {
rdapJsonFormatter.rdapAuthorization = RdapAuthorization.PUBLIC_AUTHORIZATION; rdapJsonFormatter.rdapAuthorization = RdapAuthorization.PUBLIC_AUTHORIZATION;
assertThat(rdapJsonFormatter.createRdapDomain(domainBaseFull, OutputDataType.FULL).toJson()) assertThat(rdapJsonFormatter.createRdapDomain(domainBaseFull, OutputDataType.FULL).toJson())
.isEqualTo(loadJson("rdapjson_domain_logged_out.json")); .isEqualTo(loadJson("rdapjson_domain_logged_out.json"));
} }
@Test @Test
public void testDomain_noNameserversNoTransfersMultipleRoleContact() { void testDomain_noNameserversNoTransfersMultipleRoleContact() {
assertThat( assertThat(
rdapJsonFormatter rdapJsonFormatter
.createRdapDomain(domainBaseNoNameserversNoTransfers, OutputDataType.FULL) .createRdapDomain(domainBaseNoNameserversNoTransfers, OutputDataType.FULL)
@ -502,7 +498,7 @@ public class RdapJsonFormatterTest {
} }
@Test @Test
public void testError() { void testError() {
assertThat( assertThat(
RdapObjectClasses.ErrorResponse.create( RdapObjectClasses.ErrorResponse.create(
SC_BAD_REQUEST, "Invalid Domain Name", "Not a valid domain name") SC_BAD_REQUEST, "Invalid Domain Name", "Not a valid domain name")
@ -511,7 +507,7 @@ public class RdapJsonFormatterTest {
} }
@Test @Test
public void testTopLevel() { void testTopLevel() {
assertThat( assertThat(
TopLevelReplyObject.create( TopLevelReplyObject.create(
new ReplyPayloadBase(BoilerplateType.OTHER) { new ReplyPayloadBase(BoilerplateType.OTHER) {
@ -523,7 +519,7 @@ public class RdapJsonFormatterTest {
} }
@Test @Test
public void testTopLevel_domain() { void testTopLevel_domain() {
assertThat( assertThat(
TopLevelReplyObject.create( TopLevelReplyObject.create(
new ReplyPayloadBase(BoilerplateType.DOMAIN) { new ReplyPayloadBase(BoilerplateType.DOMAIN) {

View file

@ -23,19 +23,16 @@ import google.registry.rdap.RdapMetrics.SearchType;
import google.registry.rdap.RdapMetrics.WildcardType; import google.registry.rdap.RdapMetrics.WildcardType;
import google.registry.rdap.RdapSearchResults.IncompletenessWarningType; import google.registry.rdap.RdapSearchResults.IncompletenessWarningType;
import google.registry.request.Action; import google.registry.request.Action;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RdapMetrics}. */ /** Unit tests for {@link RdapMetrics}. */
@RunWith(JUnit4.class) class RdapMetricsTest {
public class RdapMetricsTest {
private final RdapMetrics rdapMetrics = new RdapMetrics(); private final RdapMetrics rdapMetrics = new RdapMetrics();
@Before @BeforeEach
public void setUp() { void beforeEach() {
RdapMetrics.requests.reset(); RdapMetrics.requests.reset();
RdapMetrics.responses.reset(); RdapMetrics.responses.reset();
RdapMetrics.numberOfDomainsRetrieved.reset(); RdapMetrics.numberOfDomainsRetrieved.reset();
@ -58,7 +55,7 @@ public class RdapMetricsTest {
} }
@Test @Test
public void testPost() { void testPost() {
rdapMetrics.updateMetrics(getBuilder().setRequestMethod(Action.Method.POST).build()); rdapMetrics.updateMetrics(getBuilder().setRequestMethod(Action.Method.POST).build());
assertThat(RdapMetrics.requests) assertThat(RdapMetrics.requests)
.hasValueForLabels(1, "DOMAINS", "NO", "NO", "PUBLIC", "POST") .hasValueForLabels(1, "DOMAINS", "NO", "NO", "PUBLIC", "POST")
@ -67,7 +64,7 @@ public class RdapMetricsTest {
} }
@Test @Test
public void testHead() { void testHead() {
rdapMetrics.updateMetrics(getBuilder().setRequestMethod(Action.Method.HEAD).build()); rdapMetrics.updateMetrics(getBuilder().setRequestMethod(Action.Method.HEAD).build());
assertThat(RdapMetrics.requests) assertThat(RdapMetrics.requests)
.hasValueForLabels(1, "DOMAINS", "NO", "NO", "PUBLIC", "HEAD") .hasValueForLabels(1, "DOMAINS", "NO", "NO", "PUBLIC", "HEAD")
@ -76,7 +73,7 @@ public class RdapMetricsTest {
} }
@Test @Test
public void testPrefixLength_cappedAt5() { void testPrefixLength_cappedAt5() {
rdapMetrics.updateMetrics( rdapMetrics.updateMetrics(
getBuilder().setPrefixLength(6).setNumDomainsRetrieved(1).build()); getBuilder().setPrefixLength(6).setNumDomainsRetrieved(1).build());
assertThat(RdapMetrics.numberOfDomainsRetrieved) assertThat(RdapMetrics.numberOfDomainsRetrieved)
@ -86,7 +83,7 @@ public class RdapMetricsTest {
} }
@Test @Test
public void testIncludeDeleted() { void testIncludeDeleted() {
rdapMetrics.updateMetrics(getBuilder().setIncludeDeleted(true).build()); rdapMetrics.updateMetrics(getBuilder().setIncludeDeleted(true).build());
assertThat(RdapMetrics.requests) assertThat(RdapMetrics.requests)
.hasValueForLabels(1, "DOMAINS", "YES", "NO", "PUBLIC", "GET") .hasValueForLabels(1, "DOMAINS", "YES", "NO", "PUBLIC", "GET")
@ -95,7 +92,7 @@ public class RdapMetricsTest {
} }
@Test @Test
public void testDesiredRegistrar() { void testDesiredRegistrar() {
rdapMetrics.updateMetrics(getBuilder().setRegistrarSpecified(true).build()); rdapMetrics.updateMetrics(getBuilder().setRegistrarSpecified(true).build());
assertThat(RdapMetrics.requests) assertThat(RdapMetrics.requests)
.hasValueForLabels(1, "DOMAINS", "NO", "YES", "PUBLIC", "GET") .hasValueForLabels(1, "DOMAINS", "NO", "YES", "PUBLIC", "GET")
@ -104,7 +101,7 @@ public class RdapMetricsTest {
} }
@Test @Test
public void testCompleteResultSet() { void testCompleteResultSet() {
rdapMetrics.updateMetrics( rdapMetrics.updateMetrics(
getBuilder() getBuilder()
.setIncompletenessWarningType(IncompletenessWarningType.COMPLETE) .setIncompletenessWarningType(IncompletenessWarningType.COMPLETE)
@ -116,7 +113,7 @@ public class RdapMetricsTest {
} }
@Test @Test
public void testTruncatedResultSet() { void testTruncatedResultSet() {
rdapMetrics.updateMetrics( rdapMetrics.updateMetrics(
getBuilder() getBuilder()
.setIncompletenessWarningType(IncompletenessWarningType.TRUNCATED) .setIncompletenessWarningType(IncompletenessWarningType.TRUNCATED)
@ -128,7 +125,7 @@ public class RdapMetricsTest {
} }
@Test @Test
public void testPossiblyIncompleteResultSet() { void testPossiblyIncompleteResultSet() {
rdapMetrics.updateMetrics( rdapMetrics.updateMetrics(
getBuilder() getBuilder()
.setIncompletenessWarningType(IncompletenessWarningType.MIGHT_BE_INCOMPLETE) .setIncompletenessWarningType(IncompletenessWarningType.MIGHT_BE_INCOMPLETE)
@ -140,7 +137,7 @@ public class RdapMetricsTest {
} }
@Test @Test
public void testPublicRole() { void testPublicRole() {
rdapMetrics.updateMetrics(getBuilder().setRole(RdapAuthorization.Role.PUBLIC).build()); rdapMetrics.updateMetrics(getBuilder().setRole(RdapAuthorization.Role.PUBLIC).build());
assertThat(RdapMetrics.requests) assertThat(RdapMetrics.requests)
.hasValueForLabels(1, "DOMAINS", "NO", "NO", "PUBLIC", "GET") .hasValueForLabels(1, "DOMAINS", "NO", "NO", "PUBLIC", "GET")
@ -149,7 +146,7 @@ public class RdapMetricsTest {
} }
@Test @Test
public void testRegistrarRole() { void testRegistrarRole() {
rdapMetrics.updateMetrics(getBuilder().setRole(RdapAuthorization.Role.REGISTRAR).build()); rdapMetrics.updateMetrics(getBuilder().setRole(RdapAuthorization.Role.REGISTRAR).build());
assertThat(RdapMetrics.requests) assertThat(RdapMetrics.requests)
.hasValueForLabels(1, "DOMAINS", "NO", "NO", "REGISTRAR", "GET") .hasValueForLabels(1, "DOMAINS", "NO", "NO", "REGISTRAR", "GET")
@ -158,7 +155,7 @@ public class RdapMetricsTest {
} }
@Test @Test
public void testAdminRole() { void testAdminRole() {
rdapMetrics.updateMetrics(getBuilder().setRole(RdapAuthorization.Role.ADMINISTRATOR).build()); rdapMetrics.updateMetrics(getBuilder().setRole(RdapAuthorization.Role.ADMINISTRATOR).build());
assertThat(RdapMetrics.requests) assertThat(RdapMetrics.requests)
.hasValueForLabels(1, "DOMAINS", "NO", "NO", "ADMINISTRATOR", "GET") .hasValueForLabels(1, "DOMAINS", "NO", "NO", "ADMINISTRATOR", "GET")
@ -168,7 +165,7 @@ public class RdapMetricsTest {
/** Tests what would happen in a domain search for "cat.lol" which found that domain. */ /** Tests what would happen in a domain search for "cat.lol" which found that domain. */
@Test @Test
public void testSimpleDomainSearch() { void testSimpleDomainSearch() {
rdapMetrics.updateMetrics( rdapMetrics.updateMetrics(
getBuilder() getBuilder()
.setSearchType(SearchType.BY_DOMAIN_NAME) .setSearchType(SearchType.BY_DOMAIN_NAME)
@ -199,7 +196,7 @@ public class RdapMetricsTest {
* deleted domains, which found 10 matching hosts, then looked for domains and found 5 matches. * deleted domains, which found 10 matching hosts, then looked for domains and found 5 matches.
*/ */
@Test @Test
public void testDomainSearchByNameserverWithWildcardAndDeleted() { void testDomainSearchByNameserverWithWildcardAndDeleted() {
rdapMetrics.updateMetrics( rdapMetrics.updateMetrics(
getBuilder() getBuilder()
.setSearchType(SearchType.BY_NAMESERVER_NAME) .setSearchType(SearchType.BY_NAMESERVER_NAME)
@ -233,7 +230,7 @@ public class RdapMetricsTest {
/** Tests what would happen in a nameserver search for "*.cat.lol", which found no matches. */ /** Tests what would happen in a nameserver search for "*.cat.lol", which found no matches. */
@Test @Test
public void testNoNameserversFound() { void testNoNameserversFound() {
rdapMetrics.updateMetrics( rdapMetrics.updateMetrics(
getBuilder() getBuilder()
.setEndpointType(EndpointType.NAMESERVERS) .setEndpointType(EndpointType.NAMESERVERS)
@ -262,7 +259,7 @@ public class RdapMetricsTest {
/** Tests what would happen in an entity search for "Mike*" which found 50 contacts. */ /** Tests what would happen in an entity search for "Mike*" which found 50 contacts. */
@Test @Test
public void testEntitySearchByNameWithWildcard() { void testEntitySearchByNameWithWildcard() {
rdapMetrics.updateMetrics( rdapMetrics.updateMetrics(
getBuilder() getBuilder()
.setEndpointType(EndpointType.ENTITIES) .setEndpointType(EndpointType.ENTITIES)

View file

@ -33,21 +33,18 @@ import google.registry.rdap.RdapSearchResults.IncompletenessWarningType;
import google.registry.request.Action; import google.registry.request.Action;
import java.util.Optional; import java.util.Optional;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RdapNameserverAction}. */ /** Unit tests for {@link RdapNameserverAction}. */
@RunWith(JUnit4.class) class RdapNameserverActionTest extends RdapActionBaseTestCase<RdapNameserverAction> {
public class RdapNameserverActionTest extends RdapActionBaseTestCase<RdapNameserverAction> {
public RdapNameserverActionTest() { RdapNameserverActionTest() {
super(RdapNameserverAction.class); super(RdapNameserverAction.class);
} }
@Before @BeforeEach
public void setUp() { void beforeEach() {
// normal // normal
createTld("lol"); createTld("lol");
makeAndPersistHostResource( makeAndPersistHostResource(
@ -105,7 +102,7 @@ public class RdapNameserverActionTest extends RdapActionBaseTestCase<RdapNameser
} }
@Test @Test
public void testInvalidNameserver_returns400() { void testInvalidNameserver_returns400() {
assertThat(generateActualJson("invalid/host/name")) assertThat(generateActualJson("invalid/host/name"))
.isEqualTo( .isEqualTo(
generateExpectedJsonError( generateExpectedJsonError(
@ -115,14 +112,14 @@ public class RdapNameserverActionTest extends RdapActionBaseTestCase<RdapNameser
} }
@Test @Test
public void testUnknownNameserver_returns404() { void testUnknownNameserver_returns404() {
assertThat(generateActualJson("ns1.missing.com")).isEqualTo( assertThat(generateActualJson("ns1.missing.com")).isEqualTo(
generateExpectedJsonError("ns1.missing.com not found", 404)); generateExpectedJsonError("ns1.missing.com not found", 404));
assertThat(response.getStatus()).isEqualTo(404); assertThat(response.getStatus()).isEqualTo(404);
} }
@Test @Test
public void testValidNameserver_works() { void testValidNameserver_works() {
assertThat(generateActualJson("ns1.cat.lol")) assertThat(generateActualJson("ns1.cat.lol"))
.isEqualTo(generateExpectedJsonWithTopLevelEntries( .isEqualTo(generateExpectedJsonWithTopLevelEntries(
"ns1.cat.lol", "ns1.cat.lol",
@ -136,7 +133,7 @@ public class RdapNameserverActionTest extends RdapActionBaseTestCase<RdapNameser
} }
@Test @Test
public void testTrailingDot_getsIgnored() { void testTrailingDot_getsIgnored() {
assertThat(generateActualJson("ns1.cat.lol.")) assertThat(generateActualJson("ns1.cat.lol."))
.isEqualTo(generateExpectedJsonWithTopLevelEntries( .isEqualTo(generateExpectedJsonWithTopLevelEntries(
"ns1.cat.lol", "ns1.cat.lol",
@ -150,7 +147,7 @@ public class RdapNameserverActionTest extends RdapActionBaseTestCase<RdapNameser
} }
@Test @Test
public void testUpperCase_getsCanonicalized() { void testUpperCase_getsCanonicalized() {
assertThat(generateActualJson("Ns1.CaT.lOl.")) assertThat(generateActualJson("Ns1.CaT.lOl."))
.isEqualTo(generateExpectedJsonWithTopLevelEntries( .isEqualTo(generateExpectedJsonWithTopLevelEntries(
"ns1.cat.lol", "ns1.cat.lol",
@ -164,7 +161,7 @@ public class RdapNameserverActionTest extends RdapActionBaseTestCase<RdapNameser
} }
@Test @Test
public void testQueryParameter_getsIgnored() { void testQueryParameter_getsIgnored() {
assertThat(generateActualJson("ns1.cat.lol?key=value")) assertThat(generateActualJson("ns1.cat.lol?key=value"))
.isEqualTo(generateExpectedJsonWithTopLevelEntries( .isEqualTo(generateExpectedJsonWithTopLevelEntries(
"ns1.cat.lol", "ns1.cat.lol",
@ -178,7 +175,7 @@ public class RdapNameserverActionTest extends RdapActionBaseTestCase<RdapNameser
} }
@Test @Test
public void testIdnNameserver_works() { void testIdnNameserver_works() {
assertThat(generateActualJson("ns1.cat.みんな")) assertThat(generateActualJson("ns1.cat.みんな"))
.isEqualTo(generateExpectedJsonWithTopLevelEntries( .isEqualTo(generateExpectedJsonWithTopLevelEntries(
"ns1.cat.みんな", "ns1.cat.みんな",
@ -193,7 +190,7 @@ public class RdapNameserverActionTest extends RdapActionBaseTestCase<RdapNameser
} }
@Test @Test
public void testPunycodeNameserver_works() { void testPunycodeNameserver_works() {
assertThat(generateActualJson("ns1.cat.xn--q9jyb4c")) assertThat(generateActualJson("ns1.cat.xn--q9jyb4c"))
.isEqualTo(generateExpectedJsonWithTopLevelEntries( .isEqualTo(generateExpectedJsonWithTopLevelEntries(
"ns1.cat.みんな", "ns1.cat.みんな",
@ -208,7 +205,7 @@ public class RdapNameserverActionTest extends RdapActionBaseTestCase<RdapNameser
} }
@Test @Test
public void testMultilevelNameserver_works() { void testMultilevelNameserver_works() {
assertThat(generateActualJson("ns1.domain.1.tld")) assertThat(generateActualJson("ns1.domain.1.tld"))
.isEqualTo(generateExpectedJsonWithTopLevelEntries( .isEqualTo(generateExpectedJsonWithTopLevelEntries(
"ns1.domain.1.tld", "ns1.domain.1.tld",
@ -222,7 +219,7 @@ public class RdapNameserverActionTest extends RdapActionBaseTestCase<RdapNameser
} }
@Test @Test
public void testExternalNameserver_works() { void testExternalNameserver_works() {
assertThat(generateActualJson("ns1.domain.external")) assertThat(generateActualJson("ns1.domain.external"))
.isEqualTo(generateExpectedJsonWithTopLevelEntries( .isEqualTo(generateExpectedJsonWithTopLevelEntries(
"ns1.domain.external", "ns1.domain.external",
@ -236,20 +233,20 @@ public class RdapNameserverActionTest extends RdapActionBaseTestCase<RdapNameser
} }
@Test @Test
public void testDeletedNameserver_notFound_includeDeletedNotSpecified() { void testDeletedNameserver_notFound_includeDeletedNotSpecified() {
generateActualJson("nsdeleted.cat.lol"); generateActualJson("nsdeleted.cat.lol");
assertThat(response.getStatus()).isEqualTo(404); assertThat(response.getStatus()).isEqualTo(404);
} }
@Test @Test
public void testDeletedNameserver_notFound_includeDeletedSetFalse() { void testDeletedNameserver_notFound_includeDeletedSetFalse() {
action.includeDeletedParam = Optional.of(false); action.includeDeletedParam = Optional.of(false);
generateActualJson("nsdeleted.cat.lol"); generateActualJson("nsdeleted.cat.lol");
assertThat(response.getStatus()).isEqualTo(404); assertThat(response.getStatus()).isEqualTo(404);
} }
@Test @Test
public void testDeletedNameserver_notFound_notLoggedIn() { void testDeletedNameserver_notFound_notLoggedIn() {
logout(); logout();
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
generateActualJson("nsdeleted.cat.lol"); generateActualJson("nsdeleted.cat.lol");
@ -257,7 +254,7 @@ public class RdapNameserverActionTest extends RdapActionBaseTestCase<RdapNameser
} }
@Test @Test
public void testDeletedNameserver_notFound_loggedInAsDifferentRegistrar() { void testDeletedNameserver_notFound_loggedInAsDifferentRegistrar() {
login("otherregistrar"); login("otherregistrar");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
generateActualJson("nsdeleted.cat.lol"); generateActualJson("nsdeleted.cat.lol");
@ -265,7 +262,7 @@ public class RdapNameserverActionTest extends RdapActionBaseTestCase<RdapNameser
} }
@Test @Test
public void testDeletedNameserver_found_loggedInAsCorrectRegistrar() { void testDeletedNameserver_found_loggedInAsCorrectRegistrar() {
login("TheRegistrar"); login("TheRegistrar");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
assertThat(generateActualJson("nsdeleted.cat.lol")) assertThat(generateActualJson("nsdeleted.cat.lol"))
@ -282,7 +279,7 @@ public class RdapNameserverActionTest extends RdapActionBaseTestCase<RdapNameser
} }
@Test @Test
public void testDeletedNameserver_found_loggedInAsAdmin() { void testDeletedNameserver_found_loggedInAsAdmin() {
loginAsAdmin(); loginAsAdmin();
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
assertThat(generateActualJson("nsdeleted.cat.lol")) assertThat(generateActualJson("nsdeleted.cat.lol"))
@ -299,7 +296,7 @@ public class RdapNameserverActionTest extends RdapActionBaseTestCase<RdapNameser
} }
@Test @Test
public void testMetrics() { void testMetrics() {
generateActualJson("ns1.cat.lol"); generateActualJson("ns1.cat.lol");
verify(rdapMetrics) verify(rdapMetrics)
.updateMetrics( .updateMetrics(

View file

@ -46,17 +46,13 @@ import google.registry.rdap.RdapSearchResults.IncompletenessWarningType;
import google.registry.testing.FakeResponse; import google.registry.testing.FakeResponse;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.util.Optional; import java.util.Optional;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RdapNameserverSearchAction}. */ /** Unit tests for {@link RdapNameserverSearchAction}. */
@RunWith(JUnit4.class) class RdapNameserverSearchActionTest extends RdapSearchActionTestCase<RdapNameserverSearchAction> {
public class RdapNameserverSearchActionTest
extends RdapSearchActionTestCase<RdapNameserverSearchAction> {
public RdapNameserverSearchActionTest() { RdapNameserverSearchActionTest() {
super(RdapNameserverSearchAction.class); super(RdapNameserverSearchAction.class);
} }
@ -102,8 +98,8 @@ public class RdapNameserverSearchActionTest
return parseJsonObject(response.getPayload()); return parseJsonObject(response.getPayload());
} }
@Before @BeforeEach
public void setUp() { void beforeEach() {
// cat.lol and cat2.lol // cat.lol and cat2.lol
createTld("lol"); createTld("lol");
Registrar registrar = Registrar registrar =
@ -236,7 +232,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testInvalidPath_rejected() { void testInvalidPath_rejected() {
action.requestPath = actionPath + "/path"; action.requestPath = actionPath + "/path";
action.run(); action.run();
assertThat(response.getStatus()).isEqualTo(400); assertThat(response.getStatus()).isEqualTo(400);
@ -244,7 +240,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testInvalidRequest_rejected() { void testInvalidRequest_rejected() {
action.run(); action.run();
assertThat(parseJsonObject(response.getPayload())) assertThat(parseJsonObject(response.getPayload()))
.isEqualTo(generateExpectedJsonError("You must specify either name=XXXX or ip=YYYY", 400)); .isEqualTo(generateExpectedJsonError("You must specify either name=XXXX or ip=YYYY", 400));
@ -253,7 +249,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testInvalidSuffix_rejected() { void testInvalidSuffix_rejected() {
assertThat(generateActualJsonWithName("exam*ple")) assertThat(generateActualJsonWithName("exam*ple"))
.isEqualTo( .isEqualTo(
generateExpectedJsonError( generateExpectedJsonError(
@ -266,7 +262,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNonexistentDomainSuffix_unprocessable() { void testNonexistentDomainSuffix_unprocessable() {
assertThat(generateActualJsonWithName("exam*.foo.bar")) assertThat(generateActualJsonWithName("exam*.foo.bar"))
.isEqualTo( .isEqualTo(
generateExpectedJsonError( generateExpectedJsonError(
@ -277,7 +273,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testMultipleWildcards_rejected() { void testMultipleWildcards_rejected() {
assertThat(generateActualJsonWithName("*.*")) assertThat(generateActualJsonWithName("*.*"))
.isEqualTo( .isEqualTo(
generateExpectedJsonError( generateExpectedJsonError(
@ -290,7 +286,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNoCharactersToMatch_rejected() { void testNoCharactersToMatch_rejected() {
assertThat(generateActualJsonWithName("*")) assertThat(generateActualJsonWithName("*"))
.isEqualTo( .isEqualTo(
generateExpectedJsonError("Initial search string must be at least 2 characters", 422)); generateExpectedJsonError("Initial search string must be at least 2 characters", 422));
@ -299,7 +295,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testFewerThanTwoCharactersToMatch_rejected() { void testFewerThanTwoCharactersToMatch_rejected() {
assertThat(generateActualJsonWithName("a*")) assertThat(generateActualJsonWithName("a*"))
.isEqualTo( .isEqualTo(
generateExpectedJsonError("Initial search string must be at least 2 characters", 422)); generateExpectedJsonError("Initial search string must be at least 2 characters", 422));
@ -308,7 +304,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatch_ns1_cat_lol_found() { void testNameMatch_ns1_cat_lol_found() {
assertThat(generateActualJsonWithName("ns1.cat.lol")) assertThat(generateActualJsonWithName("ns1.cat.lol"))
.isEqualTo( .isEqualTo(
generateExpectedJsonForNameserver( generateExpectedJsonForNameserver(
@ -318,7 +314,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatch_ns1_cat_lol_foundWithUpperCase() { void testNameMatch_ns1_cat_lol_foundWithUpperCase() {
assertThat(generateActualJsonWithName("Ns1.CaT.lOl")) assertThat(generateActualJsonWithName("Ns1.CaT.lOl"))
.isEqualTo( .isEqualTo(
generateExpectedJsonForNameserver( generateExpectedJsonForNameserver(
@ -328,7 +324,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatch_ns1_cat_lol_found_sameRegistrarRequested() { void testNameMatch_ns1_cat_lol_found_sameRegistrarRequested() {
action.registrarParam = Optional.of("TheRegistrar"); action.registrarParam = Optional.of("TheRegistrar");
generateActualJsonWithName("ns1.cat.lol"); generateActualJsonWithName("ns1.cat.lol");
assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getStatus()).isEqualTo(200);
@ -336,7 +332,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatch_ns1_cat_lol_notFound_differentRegistrarRequested() { void testNameMatch_ns1_cat_lol_notFound_differentRegistrarRequested() {
action.registrarParam = Optional.of("unicoderegistrar"); action.registrarParam = Optional.of("unicoderegistrar");
generateActualJsonWithName("ns1.cat.lol"); generateActualJsonWithName("ns1.cat.lol");
assertThat(response.getStatus()).isEqualTo(404); assertThat(response.getStatus()).isEqualTo(404);
@ -344,7 +340,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatch_ns2_cat_lol_found() { void testNameMatch_ns2_cat_lol_found() {
assertThat(generateActualJsonWithName("ns2.cat.lol")) assertThat(generateActualJsonWithName("ns2.cat.lol"))
.isEqualTo( .isEqualTo(
generateExpectedJsonForNameserver( generateExpectedJsonForNameserver(
@ -359,7 +355,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatch_ns1_cat2_lol_found() { void testNameMatch_ns1_cat2_lol_found() {
// ns1.cat2.lol has two IP addresses; just test that we are able to find it // ns1.cat2.lol has two IP addresses; just test that we are able to find it
generateActualJsonWithName("ns1.cat2.lol"); generateActualJsonWithName("ns1.cat2.lol");
assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getStatus()).isEqualTo(200);
@ -367,7 +363,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatch_ns1_cat_external_found() { void testNameMatch_ns1_cat_external_found() {
assertThat(generateActualJsonWithName("ns1.cat.external")) assertThat(generateActualJsonWithName("ns1.cat.external"))
.isEqualTo( .isEqualTo(
generateExpectedJsonForNameserver( generateExpectedJsonForNameserver(
@ -377,7 +373,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatch_ns1_cat_idn_unicode_found() { void testNameMatch_ns1_cat_idn_unicode_found() {
assertThat(generateActualJsonWithName("ns1.cat.みんな")) assertThat(generateActualJsonWithName("ns1.cat.みんな"))
.isEqualTo( .isEqualTo(
generateExpectedJsonForNameserver( generateExpectedJsonForNameserver(
@ -394,7 +390,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatch_ns1_cat_idn_punycode_found() { void testNameMatch_ns1_cat_idn_punycode_found() {
assertThat(generateActualJsonWithName("ns1.cat.xn--q9jyb4c")) assertThat(generateActualJsonWithName("ns1.cat.xn--q9jyb4c"))
.isEqualTo( .isEqualTo(
generateExpectedJsonForNameserver( generateExpectedJsonForNameserver(
@ -409,7 +405,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatch_ns1_cat_1_test_found() { void testNameMatch_ns1_cat_1_test_found() {
assertThat(generateActualJsonWithName("ns1.cat.1.test")) assertThat(generateActualJsonWithName("ns1.cat.1.test"))
.isEqualTo( .isEqualTo(
generateExpectedJsonForNameserver( generateExpectedJsonForNameserver(
@ -419,14 +415,14 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatch_nsstar_cat_lol_found() { void testNameMatch_nsstar_cat_lol_found() {
generateActualJsonWithName("ns*.cat.lol"); generateActualJsonWithName("ns*.cat.lol");
assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getStatus()).isEqualTo(200);
verifyMetrics(2); verifyMetrics(2);
} }
@Test @Test
public void testNameMatch_nsstar_cat_lol_found_sameRegistrarRequested() { void testNameMatch_nsstar_cat_lol_found_sameRegistrarRequested() {
action.registrarParam = Optional.of("TheRegistrar"); action.registrarParam = Optional.of("TheRegistrar");
generateActualJsonWithName("ns*.cat.lol"); generateActualJsonWithName("ns*.cat.lol");
assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getStatus()).isEqualTo(200);
@ -434,7 +430,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatch_nsstar_cat_lol_notFound_differentRegistrarRequested() { void testNameMatch_nsstar_cat_lol_notFound_differentRegistrarRequested() {
action.registrarParam = Optional.of("unicoderegistrar"); action.registrarParam = Optional.of("unicoderegistrar");
generateActualJsonWithName("ns*.cat.lol"); generateActualJsonWithName("ns*.cat.lol");
assertThat(response.getStatus()).isEqualTo(404); assertThat(response.getStatus()).isEqualTo(404);
@ -442,21 +438,21 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatch_nstar_cat_lol_found() { void testNameMatch_nstar_cat_lol_found() {
generateActualJsonWithName("n*.cat.lol"); generateActualJsonWithName("n*.cat.lol");
assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getStatus()).isEqualTo(200);
verifyMetrics(2); verifyMetrics(2);
} }
@Test @Test
public void testNameMatch_star_cat_lol_found() { void testNameMatch_star_cat_lol_found() {
generateActualJsonWithName("*.cat.lol"); generateActualJsonWithName("*.cat.lol");
assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getStatus()).isEqualTo(200);
verifyMetrics(2); verifyMetrics(2);
} }
@Test @Test
public void testNameMatch_star_cat_lol_found_sameRegistrarRequested() { void testNameMatch_star_cat_lol_found_sameRegistrarRequested() {
action.registrarParam = Optional.of("TheRegistrar"); action.registrarParam = Optional.of("TheRegistrar");
generateActualJsonWithName("*.cat.lol"); generateActualJsonWithName("*.cat.lol");
assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getStatus()).isEqualTo(200);
@ -464,7 +460,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatch_star_cat_lol_notFound_differentRegistrarRequested() { void testNameMatch_star_cat_lol_notFound_differentRegistrarRequested() {
action.registrarParam = Optional.of("unicoderegistrar"); action.registrarParam = Optional.of("unicoderegistrar");
generateActualJsonWithName("*.cat.lol"); generateActualJsonWithName("*.cat.lol");
assertThat(response.getStatus()).isEqualTo(404); assertThat(response.getStatus()).isEqualTo(404);
@ -472,35 +468,35 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatch_nsstar_found() { void testNameMatch_nsstar_found() {
generateActualJsonWithName("ns*"); generateActualJsonWithName("ns*");
assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getStatus()).isEqualTo(200);
verifyMetrics(5, IncompletenessWarningType.TRUNCATED); verifyMetrics(5, IncompletenessWarningType.TRUNCATED);
} }
@Test @Test
public void testNameMatch_ns1_cat_lstar_found() { void testNameMatch_ns1_cat_lstar_found() {
generateActualJsonWithName("ns1.cat.l*"); generateActualJsonWithName("ns1.cat.l*");
assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getStatus()).isEqualTo(200);
verifyMetrics(1); verifyMetrics(1);
} }
@Test @Test
public void testNameMatch_ns1_castar_found() { void testNameMatch_ns1_castar_found() {
generateActualJsonWithName("ns1.ca*"); generateActualJsonWithName("ns1.ca*");
assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getStatus()).isEqualTo(200);
verifyMetrics(5, IncompletenessWarningType.TRUNCATED); verifyMetrics(5, IncompletenessWarningType.TRUNCATED);
} }
@Test @Test
public void testNameMatch_dogstar_notFound() { void testNameMatch_dogstar_notFound() {
generateActualJsonWithName("dog*"); generateActualJsonWithName("dog*");
assertThat(response.getStatus()).isEqualTo(404); assertThat(response.getStatus()).isEqualTo(404);
verifyErrorMetrics(); verifyErrorMetrics();
} }
@Test @Test
public void testNameMatch_nontruncatedResultSet() { void testNameMatch_nontruncatedResultSet() {
createManyHosts(4); createManyHosts(4);
assertThat(generateActualJsonWithName("nsx*.cat.lol")) assertThat(generateActualJsonWithName("nsx*.cat.lol"))
.isEqualTo(loadJsonFile("rdap_nontruncated_hosts.json")); .isEqualTo(loadJsonFile("rdap_nontruncated_hosts.json"));
@ -509,7 +505,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatch_truncatedResultSet() { void testNameMatch_truncatedResultSet() {
createManyHosts(5); createManyHosts(5);
assertThat(generateActualJsonWithName("nsx*.cat.lol")) assertThat(generateActualJsonWithName("nsx*.cat.lol"))
.isEqualTo( .isEqualTo(
@ -520,7 +516,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatch_reallyTruncatedResultSet() { void testNameMatch_reallyTruncatedResultSet() {
createManyHosts(9); createManyHosts(9);
assertThat(generateActualJsonWithName("nsx*.cat.lol")) assertThat(generateActualJsonWithName("nsx*.cat.lol"))
.isEqualTo( .isEqualTo(
@ -532,7 +528,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatchDeletedHost_foundTheOtherHost() { void testNameMatchDeletedHost_foundTheOtherHost() {
persistResource(hostNs1CatLol.asBuilder().setDeletionTime(clock.nowUtc().minusDays(1)).build()); persistResource(hostNs1CatLol.asBuilder().setDeletionTime(clock.nowUtc().minusDays(1)).build());
assertThat(generateActualJsonWithName("ns*.cat.lol")) assertThat(generateActualJsonWithName("ns*.cat.lol"))
.isEqualTo( .isEqualTo(
@ -548,7 +544,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatchDeletedHost_notFound() { void testNameMatchDeletedHost_notFound() {
persistResource(hostNs1CatLol.asBuilder().setDeletionTime(clock.nowUtc().minusDays(1)).build()); persistResource(hostNs1CatLol.asBuilder().setDeletionTime(clock.nowUtc().minusDays(1)).build());
assertThat(generateActualJsonWithName("ns1.cat.lol")) assertThat(generateActualJsonWithName("ns1.cat.lol"))
.isEqualTo(generateExpectedJsonError("No nameservers found", 404)); .isEqualTo(generateExpectedJsonError("No nameservers found", 404));
@ -557,7 +553,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatchDeletedHostWithWildcard_notFound() { void testNameMatchDeletedHostWithWildcard_notFound() {
persistResource(hostNs1CatLol.asBuilder().setDeletionTime(clock.nowUtc().minusDays(1)).build()); persistResource(hostNs1CatLol.asBuilder().setDeletionTime(clock.nowUtc().minusDays(1)).build());
assertThat(generateActualJsonWithName("cat.lo*")) assertThat(generateActualJsonWithName("cat.lo*"))
.isEqualTo(generateExpectedJsonError("No nameservers found", 404)); .isEqualTo(generateExpectedJsonError("No nameservers found", 404));
@ -566,7 +562,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatchDeleted_notFound_includeDeletedNotSpecified() { void testNameMatchDeleted_notFound_includeDeletedNotSpecified() {
createDeletedHost(); createDeletedHost();
generateActualJsonWithName("nsdeleted.cat.lol"); generateActualJsonWithName("nsdeleted.cat.lol");
assertThat(response.getStatus()).isEqualTo(404); assertThat(response.getStatus()).isEqualTo(404);
@ -574,7 +570,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatchDeleted_notFound_notLoggedIn() { void testNameMatchDeleted_notFound_notLoggedIn() {
createDeletedHost(); createDeletedHost();
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
generateActualJsonWithName("nsdeleted.cat.lol"); generateActualJsonWithName("nsdeleted.cat.lol");
@ -583,7 +579,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatchDeleted_notFound_loggedInAsDifferentRegistrar() { void testNameMatchDeleted_notFound_loggedInAsDifferentRegistrar() {
createDeletedHost(); createDeletedHost();
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
login("unicoderegistrar"); login("unicoderegistrar");
@ -593,7 +589,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatchDeleted_found_loggedInAsCorrectRegistrar() { void testNameMatchDeleted_found_loggedInAsCorrectRegistrar() {
createDeletedHost(); createDeletedHost();
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
login("TheRegistrar"); login("TheRegistrar");
@ -603,7 +599,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatchDeleted_found_loggedInAsAdmin() { void testNameMatchDeleted_found_loggedInAsAdmin() {
createDeletedHost(); createDeletedHost();
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
loginAsAdmin(); loginAsAdmin();
@ -613,7 +609,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatchDeleted_found_loggedInAndRequestingSameRegistrar() { void testNameMatchDeleted_found_loggedInAndRequestingSameRegistrar() {
createDeletedHost(); createDeletedHost();
action.registrarParam = Optional.of("TheRegistrar"); action.registrarParam = Optional.of("TheRegistrar");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
@ -624,7 +620,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatchDeleted_notFound_loggedInButRequestingDifferentRegistrar() { void testNameMatchDeleted_notFound_loggedInButRequestingDifferentRegistrar() {
createDeletedHost(); createDeletedHost();
action.registrarParam = Optional.of("unicoderegistrar"); action.registrarParam = Optional.of("unicoderegistrar");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
@ -677,7 +673,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatch_cursorNavigationWithSuperordinateDomain() throws Exception { void testNameMatch_cursorNavigationWithSuperordinateDomain() throws Exception {
createManyHosts(9); createManyHosts(9);
checkCursorNavigation( checkCursorNavigation(
true, true,
@ -695,7 +691,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testNameMatch_cursorNavigationWithPrefix() throws Exception { void testNameMatch_cursorNavigationWithPrefix() throws Exception {
createManyHosts(9); createManyHosts(9);
checkCursorNavigation( checkCursorNavigation(
true, true,
@ -719,14 +715,14 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testAddressMatch_invalidAddress() { void testAddressMatch_invalidAddress() {
generateActualJsonWithIp("It is to laugh"); generateActualJsonWithIp("It is to laugh");
assertThat(response.getStatus()).isEqualTo(400); assertThat(response.getStatus()).isEqualTo(400);
verifyErrorMetrics(Optional.empty(), 400); verifyErrorMetrics(Optional.empty(), 400);
} }
@Test @Test
public void testAddressMatchV4Address_found() { void testAddressMatchV4Address_found() {
assertThat(generateActualJsonWithIp("1.2.3.4")) assertThat(generateActualJsonWithIp("1.2.3.4"))
.isEqualTo( .isEqualTo(
generateExpectedJsonForNameserver( generateExpectedJsonForNameserver(
@ -736,7 +732,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testAddressMatchV4Address_found_sameRegistrarRequested() { void testAddressMatchV4Address_found_sameRegistrarRequested() {
action.registrarParam = Optional.of("TheRegistrar"); action.registrarParam = Optional.of("TheRegistrar");
generateActualJsonWithIp("1.2.3.4"); generateActualJsonWithIp("1.2.3.4");
assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getStatus()).isEqualTo(200);
@ -744,7 +740,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testAddressMatchV4Address_notFound_differentRegistrarRequested() { void testAddressMatchV4Address_notFound_differentRegistrarRequested() {
action.registrarParam = Optional.of("unicoderegistrar"); action.registrarParam = Optional.of("unicoderegistrar");
generateActualJsonWithIp("1.2.3.4"); generateActualJsonWithIp("1.2.3.4");
assertThat(response.getStatus()).isEqualTo(404); assertThat(response.getStatus()).isEqualTo(404);
@ -752,7 +748,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testAddressMatchV6Address_foundMultiple() { void testAddressMatchV6Address_foundMultiple() {
assertThat(generateActualJsonWithIp("bad:f00d:cafe::15:beef")) assertThat(generateActualJsonWithIp("bad:f00d:cafe::15:beef"))
.isEqualTo(loadJsonFile("rdap_multiple_hosts.json")); .isEqualTo(loadJsonFile("rdap_multiple_hosts.json"));
assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getStatus()).isEqualTo(200);
@ -760,14 +756,14 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testAddressMatchLocalhost_notFound() { void testAddressMatchLocalhost_notFound() {
generateActualJsonWithIp("127.0.0.1"); generateActualJsonWithIp("127.0.0.1");
assertThat(response.getStatus()).isEqualTo(404); assertThat(response.getStatus()).isEqualTo(404);
verifyErrorMetrics(); verifyErrorMetrics();
} }
@Test @Test
public void testAddressMatchDeletedHost_notFound() { void testAddressMatchDeletedHost_notFound() {
persistResource(hostNs1CatLol.asBuilder().setDeletionTime(clock.nowUtc().minusDays(1)).build()); persistResource(hostNs1CatLol.asBuilder().setDeletionTime(clock.nowUtc().minusDays(1)).build());
assertThat(generateActualJsonWithIp("1.2.3.4")) assertThat(generateActualJsonWithIp("1.2.3.4"))
.isEqualTo(generateExpectedJsonError("No nameservers found", 404)); .isEqualTo(generateExpectedJsonError("No nameservers found", 404));
@ -776,7 +772,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testAddressMatch_nontruncatedResultSet() { void testAddressMatch_nontruncatedResultSet() {
createManyHosts(4); createManyHosts(4);
assertThat(generateActualJsonWithIp("5.5.5.1")) assertThat(generateActualJsonWithIp("5.5.5.1"))
.isEqualTo(loadJsonFile("rdap_nontruncated_hosts.json")); .isEqualTo(loadJsonFile("rdap_nontruncated_hosts.json"));
@ -785,7 +781,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testAddressMatch_truncatedResultSet() { void testAddressMatch_truncatedResultSet() {
createManyHosts(5); createManyHosts(5);
assertThat(generateActualJsonWithIp("5.5.5.1")) assertThat(generateActualJsonWithIp("5.5.5.1"))
.isEqualTo( .isEqualTo(
@ -796,7 +792,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testAddressMatch_reallyTruncatedResultSet() { void testAddressMatch_reallyTruncatedResultSet() {
createManyHosts(9); createManyHosts(9);
assertThat(generateActualJsonWithIp("5.5.5.1")) assertThat(generateActualJsonWithIp("5.5.5.1"))
.isEqualTo( .isEqualTo(
@ -809,7 +805,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testAddressMatchDeleted_notFound_includeDeletedNotSpecified() { void testAddressMatchDeleted_notFound_includeDeletedNotSpecified() {
createDeletedHost(); createDeletedHost();
generateActualJsonWithIp("4.3.2.1"); generateActualJsonWithIp("4.3.2.1");
assertThat(response.getStatus()).isEqualTo(404); assertThat(response.getStatus()).isEqualTo(404);
@ -817,7 +813,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testAddressMatchDeleted_notFound_notLoggedIn() { void testAddressMatchDeleted_notFound_notLoggedIn() {
createDeletedHost(); createDeletedHost();
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
generateActualJsonWithIp("4.3.2.1"); generateActualJsonWithIp("4.3.2.1");
@ -826,7 +822,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testAddressMatchDeleted_notFound_loggedInAsDifferentRegistrar() { void testAddressMatchDeleted_notFound_loggedInAsDifferentRegistrar() {
createDeletedHost(); createDeletedHost();
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
login("unicoderegistrar"); login("unicoderegistrar");
@ -836,7 +832,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testAddressMatchDeleted_found_loggedInAsCorrectRegistrar() { void testAddressMatchDeleted_found_loggedInAsCorrectRegistrar() {
createDeletedHost(); createDeletedHost();
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
login("TheRegistrar"); login("TheRegistrar");
@ -846,7 +842,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testAddressMatchDeleted_found_loggedInAsAdmin() { void testAddressMatchDeleted_found_loggedInAsAdmin() {
createDeletedHost(); createDeletedHost();
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
loginAsAdmin(); loginAsAdmin();
@ -856,7 +852,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testAddressMatchDeleted_found_loggedInAndRequestingSameRegisrar() { void testAddressMatchDeleted_found_loggedInAndRequestingSameRegisrar() {
createDeletedHost(); createDeletedHost();
action.registrarParam = Optional.of("TheRegistrar"); action.registrarParam = Optional.of("TheRegistrar");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
@ -867,7 +863,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testAddressMatchDeleted_notFound_loggedButRequestingDiffentRegistrar() { void testAddressMatchDeleted_notFound_loggedButRequestingDiffentRegistrar() {
createDeletedHost(); createDeletedHost();
action.registrarParam = Optional.of("unicoderegistrar"); action.registrarParam = Optional.of("unicoderegistrar");
action.includeDeletedParam = Optional.of(true); action.includeDeletedParam = Optional.of(true);
@ -878,7 +874,7 @@ public class RdapNameserverSearchActionTest
} }
@Test @Test
public void testAddressMatch_cursorNavigation() throws Exception { void testAddressMatch_cursorNavigation() throws Exception {
createManyHosts(9); createManyHosts(9);
checkCursorNavigation( checkCursorNavigation(
false, false,

View file

@ -24,13 +24,13 @@ import google.registry.rdap.RdapMetrics.WildcardType;
import google.registry.rdap.RdapSearchResults.IncompletenessWarningType; import google.registry.rdap.RdapSearchResults.IncompletenessWarningType;
import google.registry.request.Action; import google.registry.request.Action;
import java.util.Optional; import java.util.Optional;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
/** Common unit test code for actions inheriting {@link RdapSearchActionBase}. */ /** Common unit test code for actions inheriting {@link RdapSearchActionBase}. */
public abstract class RdapSearchActionTestCase<A extends RdapSearchActionBase> public abstract class RdapSearchActionTestCase<A extends RdapSearchActionBase>
extends RdapActionBaseTestCase<A> { extends RdapActionBaseTestCase<A> {
protected RdapSearchActionTestCase(Class<A> rdapActionClass) { RdapSearchActionTestCase(Class<A> rdapActionClass) {
super(rdapActionClass); super(rdapActionClass);
} }
@ -39,8 +39,8 @@ public abstract class RdapSearchActionTestCase<A extends RdapSearchActionBase>
int metricPrefixLength = 0; int metricPrefixLength = 0;
int metricStatusCode = SC_OK; int metricStatusCode = SC_OK;
@Before @BeforeEach
public void initRdapSearchActionTestCase() { public void beforeEachRdapSearchActionTestCase() {
action.parameterMap = ImmutableListMultimap.of(); action.parameterMap = ImmutableListMultimap.of();
action.cursorTokenParam = Optional.empty(); action.cursorTokenParam = Optional.empty();
action.registrarParam = Optional.empty(); action.registrarParam = Optional.empty();
@ -49,7 +49,7 @@ public abstract class RdapSearchActionTestCase<A extends RdapSearchActionBase>
action.requestPath = actionPath; action.requestPath = actionPath;
} }
void rememberWildcardType(WildcardType wildcardType, int prefixLength) { private void rememberWildcardType(WildcardType wildcardType, int prefixLength) {
metricWildcardType = wildcardType; metricWildcardType = wildcardType;
metricPrefixLength = prefixLength; metricPrefixLength = prefixLength;
} }

View file

@ -18,16 +18,13 @@ import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertThrows;
import google.registry.request.HttpException.UnprocessableEntityException; import google.registry.request.HttpException.UnprocessableEntityException;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RdapSearchPattern}. */ /** Unit tests for {@link RdapSearchPattern}. */
@RunWith(JUnit4.class) class RdapSearchPatternTest {
public class RdapSearchPatternTest {
@Test @Test
public void testNoWildcards_ok() { void testNoWildcards_ok() {
RdapSearchPattern rdapSearchPattern = RdapSearchPattern.createFromLdhDomainName("example.lol"); RdapSearchPattern rdapSearchPattern = RdapSearchPattern.createFromLdhDomainName("example.lol");
assertThat(rdapSearchPattern.getInitialString()).isEqualTo("example.lol"); assertThat(rdapSearchPattern.getInitialString()).isEqualTo("example.lol");
assertThat(rdapSearchPattern.getHasWildcard()).isFalse(); assertThat(rdapSearchPattern.getHasWildcard()).isFalse();
@ -35,7 +32,7 @@ public class RdapSearchPatternTest {
} }
@Test @Test
public void testWildcardNoTld_ok() { void testWildcardNoTld_ok() {
RdapSearchPattern rdapSearchPattern = RdapSearchPattern.createFromLdhDomainName("exam*"); RdapSearchPattern rdapSearchPattern = RdapSearchPattern.createFromLdhDomainName("exam*");
assertThat(rdapSearchPattern.getInitialString()).isEqualTo("exam"); assertThat(rdapSearchPattern.getInitialString()).isEqualTo("exam");
assertThat(rdapSearchPattern.getHasWildcard()).isTrue(); assertThat(rdapSearchPattern.getHasWildcard()).isTrue();
@ -43,7 +40,7 @@ public class RdapSearchPatternTest {
} }
@Test @Test
public void testWildcardTld_ok() { void testWildcardTld_ok() {
RdapSearchPattern rdapSearchPattern = RdapSearchPattern.createFromLdhDomainName("exam*.lol"); RdapSearchPattern rdapSearchPattern = RdapSearchPattern.createFromLdhDomainName("exam*.lol");
assertThat(rdapSearchPattern.getInitialString()).isEqualTo("exam"); assertThat(rdapSearchPattern.getInitialString()).isEqualTo("exam");
assertThat(rdapSearchPattern.getHasWildcard()).isTrue(); assertThat(rdapSearchPattern.getHasWildcard()).isTrue();
@ -51,7 +48,7 @@ public class RdapSearchPatternTest {
} }
@Test @Test
public void testWildcardAtStart_ok() { void testWildcardAtStart_ok() {
RdapSearchPattern rdapSearchPattern = RdapSearchPattern.createFromLdhDomainName("*.lol"); RdapSearchPattern rdapSearchPattern = RdapSearchPattern.createFromLdhDomainName("*.lol");
assertThat(rdapSearchPattern.getInitialString()).isEmpty(); assertThat(rdapSearchPattern.getInitialString()).isEmpty();
assertThat(rdapSearchPattern.getHasWildcard()).isTrue(); assertThat(rdapSearchPattern.getHasWildcard()).isTrue();
@ -59,7 +56,7 @@ public class RdapSearchPatternTest {
} }
@Test @Test
public void testWildcardOnly_ok() { void testWildcardOnly_ok() {
RdapSearchPattern rdapSearchPattern = RdapSearchPattern.createFromLdhDomainName("*"); RdapSearchPattern rdapSearchPattern = RdapSearchPattern.createFromLdhDomainName("*");
assertThat(rdapSearchPattern.getInitialString()).isEmpty(); assertThat(rdapSearchPattern.getInitialString()).isEmpty();
assertThat(rdapSearchPattern.getHasWildcard()).isTrue(); assertThat(rdapSearchPattern.getHasWildcard()).isTrue();
@ -67,28 +64,28 @@ public class RdapSearchPatternTest {
} }
@Test @Test
public void testMultipleWildcards_unprocessable() { void testMultipleWildcards_unprocessable() {
assertThrows( assertThrows(
UnprocessableEntityException.class, UnprocessableEntityException.class,
() -> RdapSearchPattern.createFromLdhDomainName("ex*am*.lol")); () -> RdapSearchPattern.createFromLdhDomainName("ex*am*.lol"));
} }
@Test @Test
public void testWildcardNotAtEnd_unprocessable() { void testWildcardNotAtEnd_unprocessable() {
assertThrows( assertThrows(
UnprocessableEntityException.class, UnprocessableEntityException.class,
() -> RdapSearchPattern.createFromLdhDomainName("ex*am")); () -> RdapSearchPattern.createFromLdhDomainName("ex*am"));
} }
@Test @Test
public void testWildcardNotAtEndWithTld_unprocessable() { void testWildcardNotAtEndWithTld_unprocessable() {
assertThrows( assertThrows(
UnprocessableEntityException.class, UnprocessableEntityException.class,
() -> RdapSearchPattern.createFromLdhDomainName("ex*am.lol")); () -> RdapSearchPattern.createFromLdhDomainName("ex*am.lol"));
} }
@Test @Test
public void testShortString_ok() { void testShortString_ok() {
RdapSearchPattern rdapSearchPattern = RdapSearchPattern.createFromLdhDomainName("e"); RdapSearchPattern rdapSearchPattern = RdapSearchPattern.createFromLdhDomainName("e");
assertThat(rdapSearchPattern.getInitialString()).isEqualTo("e"); assertThat(rdapSearchPattern.getInitialString()).isEqualTo("e");
assertThat(rdapSearchPattern.getHasWildcard()).isFalse(); assertThat(rdapSearchPattern.getHasWildcard()).isFalse();
@ -96,27 +93,27 @@ public class RdapSearchPatternTest {
} }
@Test @Test
public void testZeroLengthSuffix_unprocessable() { void testZeroLengthSuffix_unprocessable() {
assertThrows( assertThrows(
UnprocessableEntityException.class, UnprocessableEntityException.class,
() -> RdapSearchPattern.createFromLdhDomainName("exam*.")); () -> RdapSearchPattern.createFromLdhDomainName("exam*."));
} }
@Test @Test
public void testNextInitialString_alpha() { void testNextInitialString_alpha() {
RdapSearchPattern rdapSearchPattern = RdapSearchPattern.createFromLdhDomainName("exam*.lol"); RdapSearchPattern rdapSearchPattern = RdapSearchPattern.createFromLdhDomainName("exam*.lol");
assertThat(rdapSearchPattern.getNextInitialString()).isEqualTo("exan"); assertThat(rdapSearchPattern.getNextInitialString()).isEqualTo("exan");
} }
@Test @Test
public void testNextInitialString_unicode_translatedToPunycode() { void testNextInitialString_unicode_translatedToPunycode() {
RdapSearchPattern rdapSearchPattern = RdapSearchPattern rdapSearchPattern =
RdapSearchPattern.createFromLdhOrUnicodeDomainName("cat.みんな"); RdapSearchPattern.createFromLdhOrUnicodeDomainName("cat.みんな");
assertThat(rdapSearchPattern.getNextInitialString()).isEqualTo("cat.xn--q9jyb4d"); assertThat(rdapSearchPattern.getNextInitialString()).isEqualTo("cat.xn--q9jyb4d");
} }
@Test @Test
public void testUnicodeString_noWildcard() { void testUnicodeString_noWildcard() {
RdapSearchPattern rdapSearchPattern = RdapSearchPattern rdapSearchPattern =
RdapSearchPattern.createFromUnicodeString("unicode みんに string"); RdapSearchPattern.createFromUnicodeString("unicode みんに string");
assertThat(rdapSearchPattern.getInitialString()).isEqualTo("unicode みんに string"); assertThat(rdapSearchPattern.getInitialString()).isEqualTo("unicode みんに string");
@ -125,7 +122,7 @@ public class RdapSearchPatternTest {
} }
@Test @Test
public void testUnicodeString_withWildcard() { void testUnicodeString_withWildcard() {
RdapSearchPattern rdapSearchPattern = RdapSearchPattern rdapSearchPattern =
RdapSearchPattern.createFromUnicodeString("unicode みんに string*"); RdapSearchPattern.createFromUnicodeString("unicode みんに string*");
assertThat(rdapSearchPattern.getInitialString()).isEqualTo("unicode みんに string"); assertThat(rdapSearchPattern.getInitialString()).isEqualTo("unicode みんに string");
@ -134,7 +131,7 @@ public class RdapSearchPatternTest {
} }
@Test @Test
public void testUnicodeString_middleWildcard() { void testUnicodeString_middleWildcard() {
assertThrows( assertThrows(
UnprocessableEntityException.class, UnprocessableEntityException.class,
() -> RdapSearchPattern.createFromLdhDomainName("unicode みんに *string")); () -> RdapSearchPattern.createFromLdhDomainName("unicode みんに *string"));

View file

@ -32,7 +32,8 @@ import google.registry.util.Clock;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
public class RdapTestHelper { /** Test helper methods for RDAP tests. */
class RdapTestHelper {
private static final Gson GSON = private static final Gson GSON =
new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();

View file

@ -37,14 +37,11 @@ import google.registry.model.registry.Registry.TldType;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link UpdateRegistrarRdapBaseUrlsAction}. */ /** Unit tests for {@link UpdateRegistrarRdapBaseUrlsAction}. */
@RunWith(JUnit4.class)
public final class UpdateRegistrarRdapBaseUrlsActionTest { public final class UpdateRegistrarRdapBaseUrlsActionTest {
/** /**
@ -78,7 +75,7 @@ public final class UpdateRegistrarRdapBaseUrlsActionTest {
+ "]," + "],"
+ "\"version\":\"1.0\"}"; + "\"version\":\"1.0\"}";
@Rule @RegisterExtension
public AppEngineRule appEngineRule = public AppEngineRule appEngineRule =
new AppEngineRule.Builder().withDatastoreAndCloudSql().build(); new AppEngineRule.Builder().withDatastoreAndCloudSql().build();
@ -89,6 +86,7 @@ public final class UpdateRegistrarRdapBaseUrlsActionTest {
void addNextResponse(MockLowLevelHttpResponse response) { void addNextResponse(MockLowLevelHttpResponse response) {
simulatedResponses.add(response); simulatedResponses.add(response);
} }
List<MockLowLevelHttpRequest> getRequestsSent() { List<MockLowLevelHttpRequest> getRequestsSent() {
return requestsSent; return requestsSent;
} }
@ -106,8 +104,8 @@ public final class UpdateRegistrarRdapBaseUrlsActionTest {
private TestHttpTransport httpTransport; private TestHttpTransport httpTransport;
private UpdateRegistrarRdapBaseUrlsAction action; private UpdateRegistrarRdapBaseUrlsAction action;
@Before @BeforeEach
public void setUp() { void beforeEach() {
httpTransport = new TestHttpTransport(); httpTransport = new TestHttpTransport();
action = new UpdateRegistrarRdapBaseUrlsAction(); action = new UpdateRegistrarRdapBaseUrlsAction();
@ -148,22 +146,22 @@ public final class UpdateRegistrarRdapBaseUrlsActionTest {
String clientId, Long ianaId, Registrar.Type type, String... rdapBaseUrls) { String clientId, Long ianaId, Registrar.Type type, String... rdapBaseUrls) {
persistSimpleResource( persistSimpleResource(
new Registrar.Builder() new Registrar.Builder()
.setClientId(clientId) .setClientId(clientId)
.setRegistrarName(clientId) .setRegistrarName(clientId)
.setType(type) .setType(type)
.setIanaIdentifier(ianaId) .setIanaIdentifier(ianaId)
.setRdapBaseUrls(ImmutableSet.copyOf(rdapBaseUrls)) .setRdapBaseUrls(ImmutableSet.copyOf(rdapBaseUrls))
.setLocalizedAddress( .setLocalizedAddress(
new RegistrarAddress.Builder() new RegistrarAddress.Builder()
.setStreet(ImmutableList.of("123 fake st")) .setStreet(ImmutableList.of("123 fake st"))
.setCity("fakeCity") .setCity("fakeCity")
.setCountryCode("XX") .setCountryCode("XX")
.build()) .build())
.build()); .build());
} }
@Test @Test
public void testUnknownIana_cleared() { void testUnknownIana_cleared() {
// The IANA ID isn't in the JSON_LIST_REPLY // The IANA ID isn't in the JSON_LIST_REPLY
persistRegistrar("someRegistrar", 4123L, Registrar.Type.REAL, "http://rdap.example/blah"); persistRegistrar("someRegistrar", 4123L, Registrar.Type.REAL, "http://rdap.example/blah");
@ -175,7 +173,7 @@ public final class UpdateRegistrarRdapBaseUrlsActionTest {
} }
@Test @Test
public void testKnownIana_changed() { void testKnownIana_changed() {
// The IANA ID is in the JSON_LIST_REPLY // The IANA ID is in the JSON_LIST_REPLY
persistRegistrar("someRegistrar", 1448L, Registrar.Type.REAL, "http://rdap.example/blah"); persistRegistrar("someRegistrar", 1448L, Registrar.Type.REAL, "http://rdap.example/blah");
@ -188,7 +186,7 @@ public final class UpdateRegistrarRdapBaseUrlsActionTest {
} }
@Test @Test
public void testKnownIana_notReal_noChange() { void testKnownIana_notReal_noChange() {
// The IANA ID is in the JSON_LIST_REPLY // The IANA ID is in the JSON_LIST_REPLY
persistRegistrar("someRegistrar", 9999L, Registrar.Type.INTERNAL, "http://rdap.example/blah"); persistRegistrar("someRegistrar", 9999L, Registrar.Type.INTERNAL, "http://rdap.example/blah");
@ -201,7 +199,7 @@ public final class UpdateRegistrarRdapBaseUrlsActionTest {
} }
@Test @Test
public void testKnownIana_notReal_nullIANA_noChange() { void testKnownIana_notReal_nullIANA_noChange() {
persistRegistrar("someRegistrar", null, Registrar.Type.TEST, "http://rdap.example/blah"); persistRegistrar("someRegistrar", null, Registrar.Type.TEST, "http://rdap.example/blah");
action.run(); action.run();
@ -213,7 +211,7 @@ public final class UpdateRegistrarRdapBaseUrlsActionTest {
} }
@Test @Test
public void testKnownIana_multipleValues() { void testKnownIana_multipleValues() {
// The IANA ID is in the JSON_LIST_REPLY // The IANA ID is in the JSON_LIST_REPLY
persistRegistrar("registrar4000", 4000L, Registrar.Type.REAL, "http://rdap.example/blah"); persistRegistrar("registrar4000", 4000L, Registrar.Type.REAL, "http://rdap.example/blah");
persistRegistrar("registrar4001", 4001L, Registrar.Type.REAL, "http://rdap.example/blah"); persistRegistrar("registrar4001", 4001L, Registrar.Type.REAL, "http://rdap.example/blah");
@ -230,28 +228,31 @@ public final class UpdateRegistrarRdapBaseUrlsActionTest {
} }
@Test @Test
public void testNoTlds() { void testNoTlds() {
deleteTld("tld"); deleteTld("tld");
assertThat(assertThrows(IllegalArgumentException.class, action::run)).hasMessageThat() assertThat(assertThrows(IllegalArgumentException.class, action::run))
.hasMessageThat()
.isEqualTo("There must exist at least one REAL TLD."); .isEqualTo("There must exist at least one REAL TLD.");
} }
@Test @Test
public void testOnlyTestTlds() { void testOnlyTestTlds() {
persistResource(Registry.get("tld").asBuilder().setTldType(TldType.TEST).build()); persistResource(Registry.get("tld").asBuilder().setTldType(TldType.TEST).build());
assertThat(assertThrows(IllegalArgumentException.class, action::run)).hasMessageThat() assertThat(assertThrows(IllegalArgumentException.class, action::run))
.hasMessageThat()
.isEqualTo("There must exist at least one REAL TLD."); .isEqualTo("There must exist at least one REAL TLD.");
} }
@Test @Test
public void testSecondTldSucceeds() { void testSecondTldSucceeds() {
createTld("secondtld"); createTld("secondtld");
httpTransport = new TestHttpTransport(); httpTransport = new TestHttpTransport();
action.httpTransport = httpTransport; action.httpTransport = httpTransport;
// the first TLD request will return a bad cookie but the second will succeed // the first TLD request will return a bad cookie but the second will succeed
MockLowLevelHttpResponse badLoginResponse = new MockLowLevelHttpResponse(); MockLowLevelHttpResponse badLoginResponse = new MockLowLevelHttpResponse();
badLoginResponse.addHeader("Set-Cookie", badLoginResponse.addHeader(
"Set-Cookie",
"Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/mosapi/v1/app; Secure; HttpOnly"); "Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/mosapi/v1/app; Secure; HttpOnly");
httpTransport.addNextResponse(badLoginResponse); httpTransport.addNextResponse(badLoginResponse);
@ -261,25 +262,27 @@ public final class UpdateRegistrarRdapBaseUrlsActionTest {
} }
@Test @Test
public void testBothFail() { void testBothFail() {
createTld("secondtld"); createTld("secondtld");
httpTransport = new TestHttpTransport(); httpTransport = new TestHttpTransport();
action.httpTransport = httpTransport; action.httpTransport = httpTransport;
MockLowLevelHttpResponse badLoginResponse = new MockLowLevelHttpResponse(); MockLowLevelHttpResponse badLoginResponse = new MockLowLevelHttpResponse();
badLoginResponse.addHeader("Set-Cookie", badLoginResponse.addHeader(
"Set-Cookie",
"Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/mosapi/v1/app; Secure; HttpOnly"); "Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/mosapi/v1/app; Secure; HttpOnly");
// it should fail for both TLDs // it should fail for both TLDs
httpTransport.addNextResponse(badLoginResponse); httpTransport.addNextResponse(badLoginResponse);
httpTransport.addNextResponse(badLoginResponse); httpTransport.addNextResponse(badLoginResponse);
assertThat(assertThrows(RuntimeException.class, action::run)).hasMessageThat() assertThat(assertThrows(RuntimeException.class, action::run))
.hasMessageThat()
.isEqualTo("Error contacting MosAPI server. Tried TLDs [secondtld, tld]"); .isEqualTo("Error contacting MosAPI server. Tried TLDs [secondtld, tld]");
} }
@Test @Test
public void testFailureCause_ignoresLoginFailure() { void testFailureCause_ignoresLoginFailure() {
// Login failures aren't particularly interesting so we should log them, but the final // Login failures aren't particularly interesting so we should log them, but the final
// throwable should be some other failure if one existed // throwable should be some other failure if one existed
createTld("secondtld"); createTld("secondtld");

View file

@ -24,7 +24,7 @@ import static org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags.AES_128;
import com.google.common.flogger.FluentLogger; import com.google.common.flogger.FluentLogger;
import com.google.common.io.CharStreams; import com.google.common.io.CharStreams;
import google.registry.testing.BouncyCastleProviderRule; import google.registry.testing.BouncyCastleProviderExtension;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.InputStream; import java.io.InputStream;
@ -118,7 +118,8 @@ public class BouncyCastleTest {
private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final FluentLogger logger = FluentLogger.forEnclosingClass();
@RegisterExtension public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule(); @RegisterExtension
public final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
@Test @Test
void testCompressDecompress() throws Exception { void testCompressDecompress() throws Exception {

View file

@ -30,10 +30,10 @@ import com.google.common.io.Files;
import google.registry.gcs.GcsUtils; import google.registry.gcs.GcsUtils;
import google.registry.keyring.api.Keyring; import google.registry.keyring.api.Keyring;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import google.registry.testing.BouncyCastleProviderRule; import google.registry.testing.BouncyCastleProviderExtension;
import google.registry.testing.FakeKeyringModule; import google.registry.testing.FakeKeyringModule;
import google.registry.testing.GcsTestingUtils; import google.registry.testing.GcsTestingUtils;
import google.registry.testing.GpgSystemCommandRule; import google.registry.testing.GpgSystemCommandExtension;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -61,14 +61,15 @@ public class BrdaCopyActionTest {
private static final GcsFilename SIG_FILE = private static final GcsFilename SIG_FILE =
new GcsFilename("tub", "lol_2010-10-17_thin_S1_R0.sig"); new GcsFilename("tub", "lol_2010-10-17_thin_S1_R0.sig");
@RegisterExtension public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule(); @RegisterExtension
public final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
@RegisterExtension @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@RegisterExtension @RegisterExtension
public final GpgSystemCommandRule gpg = public final GpgSystemCommandExtension gpg =
new GpgSystemCommandRule( new GpgSystemCommandExtension(
RdeTestData.loadBytes("pgp-public-keyring.asc"), RdeTestData.loadBytes("pgp-public-keyring.asc"),
RdeTestData.loadBytes("pgp-private-keyring-escrow.asc")); RdeTestData.loadBytes("pgp-private-keyring-escrow.asc"));

View file

@ -24,9 +24,9 @@ import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.io.CharStreams; import com.google.common.io.CharStreams;
import google.registry.keyring.api.Keyring; import google.registry.keyring.api.Keyring;
import google.registry.testing.BouncyCastleProviderRule; import google.registry.testing.BouncyCastleProviderExtension;
import google.registry.testing.FakeKeyringModule; import google.registry.testing.FakeKeyringModule;
import google.registry.testing.GpgSystemCommandRule; import google.registry.testing.GpgSystemCommandExtension;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
@ -43,11 +43,12 @@ import org.junit.jupiter.params.provider.MethodSource;
/** GnuPG integration tests for {@link Ghostryde}. */ /** GnuPG integration tests for {@link Ghostryde}. */
class GhostrydeGpgIntegrationTest { class GhostrydeGpgIntegrationTest {
@RegisterExtension public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule(); @RegisterExtension
public final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
@RegisterExtension @RegisterExtension
public final GpgSystemCommandRule gpg = public final GpgSystemCommandExtension gpg =
new GpgSystemCommandRule( new GpgSystemCommandExtension(
RdeTestData.loadBytes("pgp-public-keyring.asc"), RdeTestData.loadBytes("pgp-public-keyring.asc"),
RdeTestData.loadBytes("pgp-private-keyring-registry.asc")); RdeTestData.loadBytes("pgp-private-keyring-registry.asc"));
@ -59,6 +60,7 @@ class GhostrydeGpgIntegrationTest {
"\0yolo", "\0yolo",
""); "");
@SuppressWarnings("unused")
static Stream<Arguments> provideTestCombinations() { static Stream<Arguments> provideTestCombinations() {
Stream.Builder<Arguments> stream = Stream.builder(); Stream.Builder<Arguments> stream = Stream.builder();
for (String command : COMMANDS) { for (String command : COMMANDS) {

View file

@ -27,7 +27,7 @@ import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.io.ByteStreams; import com.google.common.io.ByteStreams;
import google.registry.keyring.api.Keyring; import google.registry.keyring.api.Keyring;
import google.registry.testing.BouncyCastleProviderRule; import google.registry.testing.BouncyCastleProviderExtension;
import google.registry.testing.FakeKeyringModule; import google.registry.testing.FakeKeyringModule;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
@ -50,7 +50,8 @@ import org.junit.jupiter.params.provider.MethodSource;
@SuppressWarnings("resource") @SuppressWarnings("resource")
public class GhostrydeTest { public class GhostrydeTest {
@RegisterExtension public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule(); @RegisterExtension
public final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
private static final ImmutableList<String> CONTENTS = private static final ImmutableList<String> CONTENTS =
ImmutableList.of( ImmutableList.of(
@ -60,6 +61,7 @@ public class GhostrydeTest {
"\0yolo", "\0yolo",
""); "");
@SuppressWarnings("unused")
static Stream<Arguments> provideTestCombinations() { static Stream<Arguments> provideTestCombinations() {
return CONTENTS.stream().map(Arguments::of); return CONTENTS.stream().map(Arguments::of);
} }

View file

@ -50,7 +50,7 @@ import google.registry.model.registry.Registry;
import google.registry.request.HttpException.InternalServerErrorException; import google.registry.request.HttpException.InternalServerErrorException;
import google.registry.request.HttpException.NoContentException; import google.registry.request.HttpException.NoContentException;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import google.registry.testing.BouncyCastleProviderRule; import google.registry.testing.BouncyCastleProviderExtension;
import google.registry.testing.FakeClock; import google.registry.testing.FakeClock;
import google.registry.testing.FakeKeyringModule; import google.registry.testing.FakeKeyringModule;
import google.registry.testing.FakeResponse; import google.registry.testing.FakeResponse;
@ -76,7 +76,8 @@ public class RdeReportActionTest {
private static final ByteSource IIRDEA_BAD_XML = RdeTestData.loadBytes("iirdea_bad.xml"); private static final ByteSource IIRDEA_BAD_XML = RdeTestData.loadBytes("iirdea_bad.xml");
private static final ByteSource IIRDEA_GOOD_XML = RdeTestData.loadBytes("iirdea_good.xml"); private static final ByteSource IIRDEA_GOOD_XML = RdeTestData.loadBytes("iirdea_good.xml");
@RegisterExtension public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule(); @RegisterExtension
public final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
@RegisterExtension @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();

View file

@ -64,12 +64,12 @@ import google.registry.rde.JSchSshSession.JSchSshSessionFactory;
import google.registry.request.HttpException.NoContentException; import google.registry.request.HttpException.NoContentException;
import google.registry.request.RequestParameters; import google.registry.request.RequestParameters;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import google.registry.testing.BouncyCastleProviderRule; import google.registry.testing.BouncyCastleProviderExtension;
import google.registry.testing.FakeClock; import google.registry.testing.FakeClock;
import google.registry.testing.FakeKeyringModule; import google.registry.testing.FakeKeyringModule;
import google.registry.testing.FakeResponse; import google.registry.testing.FakeResponse;
import google.registry.testing.FakeSleeper; import google.registry.testing.FakeSleeper;
import google.registry.testing.GpgSystemCommandRule; import google.registry.testing.GpgSystemCommandExtension;
import google.registry.testing.Lazies; import google.registry.testing.Lazies;
import google.registry.testing.TaskQueueHelper.TaskMatcher; import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.testing.sftp.SftpServerRule; import google.registry.testing.sftp.SftpServerRule;
@ -116,11 +116,12 @@ public class RdeUploadActionTest {
@TempDir @TempDir
File folder; File folder;
@RegisterExtension public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule(); @RegisterExtension
public final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
@RegisterExtension @RegisterExtension
public final GpgSystemCommandRule gpg = public final GpgSystemCommandExtension gpg =
new GpgSystemCommandRule( new GpgSystemCommandExtension(
RdeTestData.loadBytes("pgp-public-keyring.asc"), RdeTestData.loadBytes("pgp-public-keyring.asc"),
RdeTestData.loadBytes("pgp-private-keyring-escrow.asc")); RdeTestData.loadBytes("pgp-private-keyring-escrow.asc"));

View file

@ -21,7 +21,7 @@ import static org.junit.Assert.assertThrows;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.io.ByteStreams; import com.google.common.io.ByteStreams;
import google.registry.testing.BouncyCastleProviderRule; import google.registry.testing.BouncyCastleProviderExtension;
import google.registry.testing.FakeKeyringModule; import google.registry.testing.FakeKeyringModule;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
@ -36,7 +36,8 @@ import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link RydeEncryption} */ /** Unit tests for {@link RydeEncryption} */
public final class RydeEncryptionTest { public final class RydeEncryptionTest {
@RegisterExtension public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule(); @RegisterExtension
public final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
@Test @Test
void testSuccess_oneReceiver_decryptWithCorrectKey() throws Exception { void testSuccess_oneReceiver_decryptWithCorrectKey() throws Exception {

View file

@ -25,9 +25,9 @@ import com.google.common.collect.ImmutableList;
import com.google.common.flogger.FluentLogger; import com.google.common.flogger.FluentLogger;
import com.google.common.io.CharStreams; import com.google.common.io.CharStreams;
import google.registry.keyring.api.Keyring; import google.registry.keyring.api.Keyring;
import google.registry.testing.BouncyCastleProviderRule; import google.registry.testing.BouncyCastleProviderExtension;
import google.registry.testing.FakeKeyringModule; import google.registry.testing.FakeKeyringModule;
import google.registry.testing.GpgSystemCommandRule; import google.registry.testing.GpgSystemCommandExtension;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
@ -49,11 +49,12 @@ public class RydeGpgIntegrationTest {
private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final FluentLogger logger = FluentLogger.forEnclosingClass();
@RegisterExtension public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule(); @RegisterExtension
public final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
@RegisterExtension @RegisterExtension
public final GpgSystemCommandRule gpg = public final GpgSystemCommandExtension gpg =
new GpgSystemCommandRule( new GpgSystemCommandExtension(
RdeTestData.loadBytes("pgp-public-keyring.asc"), RdeTestData.loadBytes("pgp-public-keyring.asc"),
RdeTestData.loadBytes("pgp-private-keyring-escrow.asc")); RdeTestData.loadBytes("pgp-private-keyring-escrow.asc"));

View file

@ -47,7 +47,7 @@ import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaIntegrationTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaIntegrationTestRule;
import google.registry.persistence.transaction.JpaTestRules.JpaIntegrationWithCoverageExtension; import google.registry.persistence.transaction.JpaTestRules.JpaIntegrationWithCoverageExtension;
import google.registry.persistence.transaction.JpaTestRules.JpaIntegrationWithCoverageRule; import google.registry.persistence.transaction.JpaTestRules.JpaIntegrationWithCoverageRule;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import google.registry.util.Clock; import google.registry.util.Clock;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.File; import java.io.File;
@ -110,18 +110,20 @@ public final class AppEngineRule extends ExternalResource
/** A rule-within-a-rule to provide a temporary folder for AppEngineRule's internal temp files. */ /** A rule-within-a-rule to provide a temporary folder for AppEngineRule's internal temp files. */
TemporaryFolder temporaryFolder = new TemporaryFolder(); TemporaryFolder temporaryFolder = new TemporaryFolder();
/** /**
* Sets up a SQL database when running on JUnit 5. This is for test classes that are not member of * Sets up a SQL database when running on JUnit 5. This is for test classes that are not member of
* the {@code SqlIntegrationTestSuite}. * the {@code SqlIntegrationTestSuite}.
*/ */
JpaIntegrationTestRule jpaIntegrationTestRule = null; private JpaIntegrationTestRule jpaIntegrationTestRule = null;
/** /**
* Sets up a SQL database when running on JUnit 5 and records the JPA entities tested by each test * Sets up a SQL database when running on JUnit 5 and records the JPA entities tested by each test
* class. This is for {@code SqlIntegrationTestSuite} members. * class. This is for {@code SqlIntegrationTestSuite} members.
*/ */
JpaIntegrationWithCoverageExtension jpaIntegrationWithCoverageExtension = null; private JpaIntegrationWithCoverageExtension jpaIntegrationWithCoverageExtension = null;
JpaUnitTestRule jpaUnitTestRule; private JpaUnitTestExtension jpaUnitTestRule;
private boolean withDatastore; private boolean withDatastore;
private boolean withoutCannedData; private boolean withoutCannedData;
@ -369,10 +371,10 @@ public final class AppEngineRule extends ExternalResource
builder builder
.withEntityClass(jpaTestEntities.toArray(new Class[jpaTestEntities.size()])) .withEntityClass(jpaTestEntities.toArray(new Class[jpaTestEntities.size()]))
.buildUnitTestRule(); .buildUnitTestRule();
jpaUnitTestRule.before(); jpaUnitTestRule.beforeEach(context);
} else { } else {
jpaIntegrationTestRule = builder.buildIntegrationTestRule(); jpaIntegrationTestRule = builder.buildIntegrationTestRule();
jpaIntegrationTestRule.before(); jpaIntegrationTestRule.beforeEach(context);
} }
} }
if (isWithDatastoreAndCloudSql()) { if (isWithDatastoreAndCloudSql()) {
@ -387,9 +389,9 @@ public final class AppEngineRule extends ExternalResource
if (enableJpaEntityCoverageCheck) { if (enableJpaEntityCoverageCheck) {
jpaIntegrationWithCoverageExtension.afterEach(context); jpaIntegrationWithCoverageExtension.afterEach(context);
} else if (withJpaUnitTest) { } else if (withJpaUnitTest) {
jpaUnitTestRule.after(); jpaUnitTestRule.afterEach(context);
} else { } else {
jpaIntegrationTestRule.after(); jpaIntegrationTestRule.afterEach(context);
} }
} }
after(); after();
@ -603,7 +605,7 @@ public final class AppEngineRule extends ExternalResource
} }
/** Create some fake registrars. */ /** Create some fake registrars. */
public static void loadInitialData() { private static void loadInitialData() {
persistSimpleResources( persistSimpleResources(
ImmutableList.of( ImmutableList.of(
makeRegistrar1(), makeRegistrar1(),

View file

@ -19,38 +19,26 @@ import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.rules.ExternalResource;
/** /**
* JUnit Rule for registering {@link BouncyCastleProvider} with Java Security. * JUnit extension for registering {@link BouncyCastleProvider} with Java Security.
* *
* <p>This rule is necessary in order to use the {@code "BC"} provider of cryptographic functions. * <p>This extension is necessary in order to use the {@code "BC"} provider of cryptographic
* Normally you would perform this registration in your {@code main()} function. * functions. Normally you would perform this registration in your {@code main()} function.
* *
* @see BouncyCastleProvider * @see BouncyCastleProvider
* @see org.junit.rules.ExternalResource * @see org.junit.jupiter.api.extension.Extension
* @see java.security.Security#addProvider(java.security.Provider) * @see java.security.Security#addProvider(java.security.Provider)
*/ */
public class BouncyCastleProviderRule extends ExternalResource public class BouncyCastleProviderExtension implements BeforeEachCallback, AfterEachCallback {
implements BeforeEachCallback, AfterEachCallback {
@Override @Override
public void beforeEach(ExtensionContext context) { public void beforeEach(ExtensionContext context) {
before();
}
@Override
public void afterEach(ExtensionContext context) {
after();
}
@Override
protected void before() {
Security.addProvider(new BouncyCastleProvider()); Security.addProvider(new BouncyCastleProvider());
} }
@Override @Override
protected void after() { public void afterEach(ExtensionContext context) {
Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME); Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
} }
} }

View file

@ -35,13 +35,13 @@ import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ExtensionContext;
/** /**
* GnuPG system command JUnit rule. * GnuPG system command JUnit extension.
* *
* <p>This rule creates a isolated environment for running the {@code gpg} command inside system * <p>This rule creates a isolated environment for running the {@code gpg} command inside system
* integration tests. It reduces a lot of the boilerplate of setting up the shell environment and * integration tests. It reduces a lot of the boilerplate of setting up the shell environment and
* importing your keyrings into a temporary config folder. * importing your keyrings into a temporary config folder.
*/ */
public final class GpgSystemCommandRule implements BeforeEachCallback, AfterEachCallback { public final class GpgSystemCommandExtension implements BeforeEachCallback, AfterEachCallback {
private static final File DEV_NULL = new File("/dev/null"); private static final File DEV_NULL = new File("/dev/null");
private static final String TEMP_FILE_PREFIX = "gpgtest"; private static final String TEMP_FILE_PREFIX = "gpgtest";
@ -53,8 +53,8 @@ public final class GpgSystemCommandRule implements BeforeEachCallback, AfterEach
private final ByteSource privateKeyring; private final ByteSource privateKeyring;
private final Runtime runtime = Runtime.getRuntime(); private final Runtime runtime = Runtime.getRuntime();
/** Constructs a new {@link GpgSystemCommandRule} instance. */ /** Constructs a new {@link GpgSystemCommandExtension} instance. */
public GpgSystemCommandRule(ByteSource publicKeyring, ByteSource privateKeyring) { public GpgSystemCommandExtension(ByteSource publicKeyring, ByteSource privateKeyring) {
this.publicKeyring = checkNotNull(publicKeyring, "publicKeyring"); this.publicKeyring = checkNotNull(publicKeyring, "publicKeyring");
this.privateKeyring = checkNotNull(privateKeyring, "privateKeyring"); this.privateKeyring = checkNotNull(privateKeyring, "privateKeyring");
} }

View file

@ -27,15 +27,14 @@ import javax.annotation.Nullable;
import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.rules.ExternalResource;
/** /**
* JUnit Rule for overriding the values Java system properties during tests. * JUnit extension for overriding the values Java system properties during tests.
* *
* <p>In most scenarios this class should be the last rule/extension to apply. In JUnit 5, apply * <p>In most scenarios this class should be the last rule/extension to apply. In JUnit 5, apply
* {@code @Order(value = Integer.MAX_VALUE)} to the extension. * {@code @Order(value = Integer.MAX_VALUE)} to the extension.
*/ */
public final class SystemPropertyRule extends ExternalResource public final class SystemPropertyExtension
implements SystemPropertySetter, BeforeEachCallback, AfterEachCallback { implements SystemPropertySetter, BeforeEachCallback, AfterEachCallback {
/** Class representing a system property key value pair. */ /** Class representing a system property key value pair. */
@ -72,7 +71,7 @@ public final class SystemPropertyRule extends ExternalResource
* @see java.lang.System#setProperty(String, String) * @see java.lang.System#setProperty(String, String)
*/ */
@Override @Override
public SystemPropertyRule setProperty(String key, @Nullable String value) { public SystemPropertyExtension setProperty(String key, @Nullable String value) {
originals.computeIfAbsent( originals.computeIfAbsent(
key, k -> new Property(k, Optional.ofNullable(System.getProperty(k)))); key, k -> new Property(k, Optional.ofNullable(System.getProperty(k))));
Property property = new Property(key, Optional.ofNullable(value)); Property property = new Property(key, Optional.ofNullable(value));
@ -85,7 +84,7 @@ public final class SystemPropertyRule extends ExternalResource
} }
@Override @Override
protected void before() { public void beforeEach(ExtensionContext context) {
checkState(!isRunning); checkState(!isRunning);
for (Property pending : pendings) { for (Property pending : pendings) {
pending.set(); pending.set();
@ -94,19 +93,9 @@ public final class SystemPropertyRule extends ExternalResource
} }
@Override @Override
protected void after() { public void afterEach(ExtensionContext context) {
for (Property original : originals.values()) { for (Property original : originals.values()) {
original.set(); original.set();
} }
} }
@Override
public void beforeEach(ExtensionContext context) {
before();
}
@Override
public void afterEach(ExtensionContext context) {
after();
}
} }

View file

@ -27,17 +27,16 @@ import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ExtensionContext;
/** /**
* Sets up caches with desired data expiry for testing and restores their default configurations * A JUnit extension that overloads cache expiry for tests.
* when tests complete.
* *
* <p>This rule is necessary because many caches in the system are singleton and referenced through * <p>This rule is necessary because many caches in the system are singleton and referenced through
* static fields. * static fields.
*/ */
public class TestCacheRule implements BeforeEachCallback, AfterEachCallback { public class TestCacheExtension implements BeforeEachCallback, AfterEachCallback {
private final ImmutableList<TestCacheHandler> cacheHandlers; private final ImmutableList<TestCacheHandler> cacheHandlers;
private TestCacheRule(ImmutableList<TestCacheHandler> cacheHandlers) { private TestCacheExtension(ImmutableList<TestCacheHandler> cacheHandlers) {
this.cacheHandlers = cacheHandlers; this.cacheHandlers = cacheHandlers;
} }
@ -51,7 +50,7 @@ public class TestCacheRule implements BeforeEachCallback, AfterEachCallback {
cacheHandlers.forEach(TestCacheHandler::after); cacheHandlers.forEach(TestCacheHandler::after);
} }
/** Builder for {@link TestCacheRule}. */ /** Builder for {@link TestCacheExtension}. */
public static class Builder { public static class Builder {
private final Map<String, TestCacheHandler> cacheHandlerMap = Maps.newHashMap(); private final Map<String, TestCacheHandler> cacheHandlerMap = Maps.newHashMap();
@ -83,8 +82,8 @@ public class TestCacheRule implements BeforeEachCallback, AfterEachCallback {
return this; return this;
} }
public TestCacheRule build() { public TestCacheExtension build() {
return new TestCacheRule(ImmutableList.copyOf(cacheHandlerMap.values())); return new TestCacheExtension(ImmutableList.copyOf(cacheHandlerMap.values()));
} }
} }

View file

@ -21,15 +21,12 @@ import com.google.common.collect.ImmutableList;
import google.registry.tmch.LordnLog.Result; import google.registry.tmch.LordnLog.Result;
import java.util.Map.Entry; import java.util.Map.Entry;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link LordnLog}. */ /** Unit tests for {@link LordnLog}. */
@RunWith(JUnit4.class) class LordnLogTest {
public class LordnLogTest {
public static final ImmutableList<String> EXAMPLE_FROM_RFC = private static final ImmutableList<String> EXAMPLE_FROM_RFC =
ImmutableList.of( ImmutableList.of(
"1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z," "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,"
+ "0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=," + "0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,"
@ -37,7 +34,7 @@ public class LordnLogTest {
"roid,result-code", "roid,result-code",
"SH8013-REP,2000"); "SH8013-REP,2000");
public static final ImmutableList<String> EXAMPLE_WITH_WARNINGS = private static final ImmutableList<String> EXAMPLE_WITH_WARNINGS =
ImmutableList.of( ImmutableList.of(
"1,2014-03-21T15:40:08.4Z,2014-03-21T15:35:28.0Z," "1,2014-03-21T15:40:08.4Z,2014-03-21T15:35:28.0Z,"
+ "0000000000000004799,accepted,warnings-present,2", + "0000000000000004799,accepted,warnings-present,2",
@ -46,7 +43,7 @@ public class LordnLogTest {
"1580e26-roid,3610"); "1580e26-roid,3610");
@Test @Test
public void testSuccess_parseFirstLine() { void testSuccess_parseFirstLine() {
LordnLog log = LordnLog.parse(EXAMPLE_FROM_RFC); LordnLog log = LordnLog.parse(EXAMPLE_FROM_RFC);
assertThat(log.getStatus()).isEqualTo(LordnLog.Status.ACCEPTED); assertThat(log.getStatus()).isEqualTo(LordnLog.Status.ACCEPTED);
assertThat(log.getLogCreation()).isEqualTo(DateTime.parse("2012-08-16T02:15:00.0Z")); assertThat(log.getLogCreation()).isEqualTo(DateTime.parse("2012-08-16T02:15:00.0Z"));
@ -57,7 +54,7 @@ public class LordnLogTest {
} }
@Test @Test
public void testSuccess_parseDnLines() { void testSuccess_parseDnLines() {
LordnLog log = LordnLog.parse(EXAMPLE_FROM_RFC); LordnLog log = LordnLog.parse(EXAMPLE_FROM_RFC);
Result result = log.getResult("SH8013-REP"); Result result = log.getResult("SH8013-REP");
assertThat(result).isNotNull(); assertThat(result).isNotNull();
@ -67,7 +64,7 @@ public class LordnLogTest {
} }
@Test @Test
public void testSuccess_iterate() { void testSuccess_iterate() {
for (Entry<String, Result> result : LordnLog.parse(EXAMPLE_FROM_RFC)) { for (Entry<String, Result> result : LordnLog.parse(EXAMPLE_FROM_RFC)) {
assertThat(result.getKey()).isEqualTo("SH8013-REP"); assertThat(result.getKey()).isEqualTo("SH8013-REP");
assertThat(result.getValue().getCode()).isEqualTo(2000); assertThat(result.getValue().getCode()).isEqualTo(2000);
@ -77,14 +74,14 @@ public class LordnLogTest {
} }
@Test @Test
public void testSuccess_noDnLines() { void testSuccess_noDnLines() {
LordnLog.parse(ImmutableList.of( LordnLog.parse(ImmutableList.of(
"1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,lolcat,accepted,no-warnings,0", "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,lolcat,accepted,no-warnings,0",
"roid,result-code")); "roid,result-code"));
} }
@Test @Test
public void testFailure_noDnLineMismatch() { void testFailure_noDnLineMismatch() {
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> () ->
@ -95,17 +92,17 @@ public class LordnLogTest {
} }
@Test @Test
public void testFailure_parseNull() { void testFailure_parseNull() {
assertThrows(NullPointerException.class, () -> LordnLog.parse(null)); assertThrows(NullPointerException.class, () -> LordnLog.parse(null));
} }
@Test @Test
public void testFailure_parseEmpty() { void testFailure_parseEmpty() {
assertThrows(Exception.class, () -> LordnLog.parse(ImmutableList.of())); assertThrows(Exception.class, () -> LordnLog.parse(ImmutableList.of()));
} }
@Test @Test
public void testFailure_parseMissingHeaderLine() { void testFailure_parseMissingHeaderLine() {
assertThrows( assertThrows(
Exception.class, Exception.class,
() -> () ->
@ -115,7 +112,7 @@ public class LordnLogTest {
} }
@Test @Test
public void testSuccess_toString() { void testSuccess_toString() {
assertThat(LordnLog.parse(EXAMPLE_WITH_WARNINGS).toString()).isEqualTo( assertThat(LordnLog.parse(EXAMPLE_WITH_WARNINGS).toString()).isEqualTo(
"LordnLog{" "LordnLog{"
+ "logId=0000000000000004799, " + "logId=0000000000000004799, "
@ -132,14 +129,14 @@ public class LordnLogTest {
} }
@Test @Test
public void testSuccess_resultToString() { void testSuccess_resultToString() {
assertThat( assertThat(
LordnLog.parse(EXAMPLE_FROM_RFC).iterator().next().toString()) LordnLog.parse(EXAMPLE_FROM_RFC).iterator().next().toString())
.isEqualTo("SH8013-REP=Result{code=2000, outcome=OK, description=OK}"); .isEqualTo("SH8013-REP=Result{code=2000, outcome=OK, description=OK}");
} }
@Test @Test
public void testSuccess_withWarnings() { void testSuccess_withWarnings() {
LordnLog log = LordnLog.parse(EXAMPLE_WITH_WARNINGS); LordnLog log = LordnLog.parse(EXAMPLE_WITH_WARNINGS);
assertThat(log.getStatus()).isEqualTo(LordnLog.Status.ACCEPTED); assertThat(log.getStatus()).isEqualTo(LordnLog.Status.ACCEPTED);
assertThat(log.getLogCreation()).isEqualTo(DateTime.parse("2014-03-21T15:40:08.4Z")); assertThat(log.getLogCreation()).isEqualTo(DateTime.parse("2014-03-21T15:40:08.4Z"));

View file

@ -34,27 +34,23 @@ import google.registry.testing.InjectRule;
import google.registry.testing.TaskQueueHelper.TaskMatcher; import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.util.Clock; import google.registry.util.Clock;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link LordnTaskUtils}. */ /** Unit tests for {@link LordnTaskUtils}. */
@RunWith(JUnit4.class)
public class LordnTaskUtilsTest { public class LordnTaskUtilsTest {
private static final Clock clock = new FakeClock(DateTime.parse("2010-05-01T10:11:12Z")); private static final Clock clock = new FakeClock(DateTime.parse("2010-05-01T10:11:12Z"));
@Rule @RegisterExtension
public final AppEngineRule appEngine = public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build(); AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@Rule @RegisterExtension public final InjectRule inject = new InjectRule();
public final InjectRule inject = new InjectRule();
@Before @BeforeEach
public void before() { void beforeEach() {
createTld("example"); createTld("example");
inject.setStaticField(Ofy.class, "clock", clock); inject.setStaticField(Ofy.class, "clock", clock);
} }
@ -68,7 +64,7 @@ public class LordnTaskUtilsTest {
} }
@Test @Test
public void test_enqueueDomainBaseTask_sunrise() { void test_enqueueDomainBaseTask_sunrise() {
persistDomainAndEnqueueLordn(newDomainBuilder().setRepoId("A-EXAMPLE").build()); persistDomainAndEnqueueLordn(newDomainBuilder().setRepoId("A-EXAMPLE").build());
String expectedPayload = String expectedPayload =
"A-EXAMPLE,fleece.example,smdzzzz,1,2010-05-01T10:11:12.000Z"; "A-EXAMPLE,fleece.example,smdzzzz,1,2010-05-01T10:11:12.000Z";
@ -77,7 +73,7 @@ public class LordnTaskUtilsTest {
} }
@Test @Test
public void test_enqueueDomainBaseTask_claims() { void test_enqueueDomainBaseTask_claims() {
DomainBase domain = DomainBase domain =
newDomainBuilder() newDomainBuilder()
.setRepoId("11-EXAMPLE") .setRepoId("11-EXAMPLE")
@ -93,7 +89,7 @@ public class LordnTaskUtilsTest {
} }
@Test @Test
public void test_oteRegistrarWithNullIanaId() { void test_oteRegistrarWithNullIanaId() {
tm() tm()
.transact( .transact(
() -> () ->
@ -112,7 +108,7 @@ public class LordnTaskUtilsTest {
} }
@Test @Test
public void test_enqueueDomainBaseTask_throwsExceptionOnInvalidRegistrar() { void test_enqueueDomainBaseTask_throwsExceptionOnInvalidRegistrar() {
DomainBase domain = DomainBase domain =
newDomainBuilder() newDomainBuilder()
.setRepoId("9000-EXAMPLE") .setRepoId("9000-EXAMPLE")
@ -126,7 +122,7 @@ public class LordnTaskUtilsTest {
} }
@Test @Test
public void test_enqueueDomainBaseTask_throwsNpeOnNullDomain() { void test_enqueueDomainBaseTask_throwsNpeOnNullDomain() {
assertThrows( assertThrows(
NullPointerException.class, NullPointerException.class,
() -> tm().transactNew(() -> LordnTaskUtils.enqueueDomainBaseTask(null))); () -> tm().transactNew(() -> LordnTaskUtils.enqueueDomainBaseTask(null)));

View file

@ -67,39 +67,40 @@ import java.security.SecureRandom;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Captor; import org.mockito.Captor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit; import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.MockitoRule; import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
/** Unit tests for {@link NordnUploadAction}. */ /** Unit tests for {@link NordnUploadAction}. */
@RunWith(JUnit4.class) @ExtendWith(MockitoExtension.class)
public class NordnUploadActionTest { class NordnUploadActionTest {
private static final String CLAIMS_CSV = "1,2010-05-01T10:11:12.000Z,1\n" private static final String CLAIMS_CSV =
+ "roid,domain-name,notice-id,registrar-id,registration-datetime,ack-datetime," "1,2010-05-01T10:11:12.000Z,1\n"
+ "application-datetime\n" + "roid,domain-name,notice-id,registrar-id,registration-datetime,ack-datetime,"
+ "2-TLD,claims-landrush1.tld,landrush1tcn,99999,2010-05-01T10:11:12.000Z," + "application-datetime\n"
+ "1969-12-31T23:00:00.000Z\n"; + "2-TLD,claims-landrush1.tld,landrush1tcn,99999,2010-05-01T10:11:12.000Z,"
+ "1969-12-31T23:00:00.000Z\n";
private static final String SUNRISE_CSV = "1,2010-05-01T10:11:12.000Z,1\n" private static final String SUNRISE_CSV =
+ "roid,domain-name,SMD-id,registrar-id,registration-datetime,application-datetime\n" "1,2010-05-01T10:11:12.000Z,1\n"
+ "2-TLD,sunrise1.tld,my-smdid,99999,2010-05-01T10:11:12.000Z\n"; + "roid,domain-name,SMD-id,registrar-id,registration-datetime,application-datetime\n"
+ "2-TLD,sunrise1.tld,my-smdid,99999,2010-05-01T10:11:12.000Z\n";
private static final String LOCATION_URL = "http://trololol"; private static final String LOCATION_URL = "http://trololol";
@Rule @RegisterExtension
public final AppEngineRule appEngine = public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build(); AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@Rule public final MockitoRule mocks = MockitoJUnit.rule(); @RegisterExtension public final InjectRule inject = new InjectRule();
@Rule public final InjectRule inject = new InjectRule();
@Mock private URLFetchService fetchService; @Mock private URLFetchService fetchService;
@Mock private HTTPResponse httpResponse; @Mock private HTTPResponse httpResponse;
@ -110,8 +111,8 @@ public class NordnUploadActionTest {
new LordnRequestInitializer(Optional.of("attack")); new LordnRequestInitializer(Optional.of("attack"));
private final NordnUploadAction action = new NordnUploadAction(); private final NordnUploadAction action = new NordnUploadAction();
@Before @BeforeEach
public void before() throws Exception { void beforeEach() throws Exception {
inject.setStaticField(Ofy.class, "clock", clock); inject.setStaticField(Ofy.class, "clock", clock);
when(fetchService.fetch(any(HTTPRequest.class))).thenReturn(httpResponse); when(fetchService.fetch(any(HTTPRequest.class))).thenReturn(httpResponse);
when(httpResponse.getContent()).thenReturn("Success".getBytes(US_ASCII)); when(httpResponse.getContent()).thenReturn("Success".getBytes(US_ASCII));
@ -132,8 +133,9 @@ public class NordnUploadActionTest {
action.retrier = new Retrier(new FakeSleeper(clock), 3); action.retrier = new Retrier(new FakeSleeper(clock), 3);
} }
@MockitoSettings(strictness = Strictness.LENIENT)
@Test @Test
public void test_convertTasksToCsv() { void test_convertTasksToCsv() {
List<TaskHandle> tasks = List<TaskHandle> tasks =
ImmutableList.of( ImmutableList.of(
makeTaskHandle("task1", "example", "csvLine1", "lordn-sunrise"), makeTaskHandle("task1", "example", "csvLine1", "lordn-sunrise"),
@ -143,22 +145,25 @@ public class NordnUploadActionTest {
.isEqualTo("1,2010-05-01T10:11:12.000Z,3\ncol1,col2\ncsvLine1\ncsvLine2\nending\n"); .isEqualTo("1,2010-05-01T10:11:12.000Z,3\ncol1,col2\ncsvLine1\ncsvLine2\nending\n");
} }
@MockitoSettings(strictness = Strictness.LENIENT)
@Test @Test
public void test_convertTasksToCsv_doesntFailOnEmptyTasks() { void test_convertTasksToCsv_doesntFailOnEmptyTasks() {
assertThat(NordnUploadAction.convertTasksToCsv(ImmutableList.of(), clock.nowUtc(), "col1,col2")) assertThat(NordnUploadAction.convertTasksToCsv(ImmutableList.of(), clock.nowUtc(), "col1,col2"))
.isEqualTo("1,2010-05-01T10:11:12.000Z,0\ncol1,col2\n"); .isEqualTo("1,2010-05-01T10:11:12.000Z,0\ncol1,col2\n");
} }
@MockitoSettings(strictness = Strictness.LENIENT)
@Test @Test
public void test_convertTasksToCsv_throwsNpeOnNullTasks() { void test_convertTasksToCsv_throwsNpeOnNullTasks() {
assertThrows( assertThrows(
NullPointerException.class, NullPointerException.class,
() -> NordnUploadAction.convertTasksToCsv(null, clock.nowUtc(), "header")); () -> NordnUploadAction.convertTasksToCsv(null, clock.nowUtc(), "header"));
} }
@MockitoSettings(strictness = Strictness.LENIENT)
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Test @Test
public void test_loadAllTasks_retryLogic_thirdTrysTheCharm() { void test_loadAllTasks_retryLogic_thirdTrysTheCharm() {
Queue queue = mock(Queue.class); Queue queue = mock(Queue.class);
TaskHandle task = new TaskHandle(TaskOptions.Builder.withTaskName("blah"), "blah"); TaskHandle task = new TaskHandle(TaskOptions.Builder.withTaskName("blah"), "blah");
when(queue.leaseTasks(any(LeaseOptions.class))) when(queue.leaseTasks(any(LeaseOptions.class)))
@ -168,8 +173,9 @@ public class NordnUploadActionTest {
assertThat(action.loadAllTasks(queue, "tld")).containsExactly(task); assertThat(action.loadAllTasks(queue, "tld")).containsExactly(task);
} }
@MockitoSettings(strictness = Strictness.LENIENT)
@Test @Test
public void test_loadAllTasks_retryLogic_allFailures() { void test_loadAllTasks_retryLogic_allFailures() {
Queue queue = mock(Queue.class); Queue queue = mock(Queue.class);
when(queue.leaseTasks(any(LeaseOptions.class))) when(queue.leaseTasks(any(LeaseOptions.class)))
.thenThrow(new TransientFailureException("some transient error")); .thenThrow(new TransientFailureException("some transient error"));
@ -179,7 +185,7 @@ public class NordnUploadActionTest {
} }
@Test @Test
public void testRun_claimsMode_appendsTldAndClaimsToRequestUrl() throws Exception { void testRun_claimsMode_appendsTldAndClaimsToRequestUrl() throws Exception {
persistClaimsModeDomain(); persistClaimsModeDomain();
action.run(); action.run();
assertThat(getCapturedHttpRequest().getURL()) assertThat(getCapturedHttpRequest().getURL())
@ -187,7 +193,7 @@ public class NordnUploadActionTest {
} }
@Test @Test
public void testRun_sunriseMode_appendsTldAndClaimsToRequestUrl() throws Exception { void testRun_sunriseMode_appendsTldAndClaimsToRequestUrl() throws Exception {
persistSunriseModeDomain(); persistSunriseModeDomain();
action.run(); action.run();
assertThat(getCapturedHttpRequest().getURL()) assertThat(getCapturedHttpRequest().getURL())
@ -195,7 +201,7 @@ public class NordnUploadActionTest {
} }
@Test @Test
public void testRun_usesMultipartContentType() throws Exception { void testRun_usesMultipartContentType() throws Exception {
persistClaimsModeDomain(); persistClaimsModeDomain();
action.run(); action.run();
assertThat(getHeaderFirst(getCapturedHttpRequest(), CONTENT_TYPE).get()) assertThat(getHeaderFirst(getCapturedHttpRequest(), CONTENT_TYPE).get())
@ -203,15 +209,15 @@ public class NordnUploadActionTest {
} }
@Test @Test
public void testRun_hasPassword_setsAuthorizationHeader() throws Exception { void testRun_hasPassword_setsAuthorizationHeader() throws Exception {
persistClaimsModeDomain(); persistClaimsModeDomain();
action.run(); action.run();
assertThat(getHeaderFirst(getCapturedHttpRequest(), AUTHORIZATION)) assertThat(getHeaderFirst(getCapturedHttpRequest(), AUTHORIZATION))
.hasValue("Basic bG9sY2F0OmF0dGFjaw=="); // echo -n lolcat:attack | base64 .hasValue("Basic bG9sY2F0OmF0dGFjaw=="); // echo -n lolcat:attack | base64
} }
@Test @Test
public void testRun_noPassword_doesntSendAuthorizationHeader() throws Exception { void testRun_noPassword_doesntSendAuthorizationHeader() throws Exception {
action.lordnRequestInitializer = new LordnRequestInitializer(Optional.empty()); action.lordnRequestInitializer = new LordnRequestInitializer(Optional.empty());
persistClaimsModeDomain(); persistClaimsModeDomain();
action.run(); action.run();
@ -219,31 +225,33 @@ public class NordnUploadActionTest {
} }
@Test @Test
public void testRun_claimsMode_payloadMatchesClaimsCsv() throws Exception { void testRun_claimsMode_payloadMatchesClaimsCsv() throws Exception {
persistClaimsModeDomain(); persistClaimsModeDomain();
action.run(); action.run();
assertThat(new String(getCapturedHttpRequest().getPayload(), UTF_8)).contains(CLAIMS_CSV); assertThat(new String(getCapturedHttpRequest().getPayload(), UTF_8)).contains(CLAIMS_CSV);
} }
@Test @Test
public void testRun_claimsMode_verifyTaskGetsEnqueuedWithClaimsCsv() { void testRun_claimsMode_verifyTaskGetsEnqueuedWithClaimsCsv() {
persistClaimsModeDomain(); persistClaimsModeDomain();
action.run(); action.run();
assertTasksEnqueued(NordnVerifyAction.QUEUE, new TaskMatcher() assertTasksEnqueued(
.url(NordnVerifyAction.PATH) NordnVerifyAction.QUEUE,
.header(NordnVerifyAction.URL_HEADER, LOCATION_URL) new TaskMatcher()
.header(CONTENT_TYPE, FORM_DATA.toString())); .url(NordnVerifyAction.PATH)
.header(NordnVerifyAction.URL_HEADER, LOCATION_URL)
.header(CONTENT_TYPE, FORM_DATA.toString()));
} }
@Test @Test
public void testRun_sunriseMode_payloadMatchesSunriseCsv() throws Exception { void testRun_sunriseMode_payloadMatchesSunriseCsv() throws Exception {
persistSunriseModeDomain(); persistSunriseModeDomain();
action.run(); action.run();
assertThat(new String(getCapturedHttpRequest().getPayload(), UTF_8)).contains(SUNRISE_CSV); assertThat(new String(getCapturedHttpRequest().getPayload(), UTF_8)).contains(SUNRISE_CSV);
} }
@Test @Test
public void test_noResponseContent_stillWorksNormally() throws Exception { void test_noResponseContent_stillWorksNormally() throws Exception {
// Returning null only affects logging. // Returning null only affects logging.
when(httpResponse.getContent()).thenReturn(null); when(httpResponse.getContent()).thenReturn(null);
persistSunriseModeDomain(); persistSunriseModeDomain();
@ -252,25 +260,29 @@ public class NordnUploadActionTest {
} }
@Test @Test
public void testRun_sunriseMode_verifyTaskGetsEnqueuedWithSunriseCsv() { void testRun_sunriseMode_verifyTaskGetsEnqueuedWithSunriseCsv() {
persistSunriseModeDomain(); persistSunriseModeDomain();
action.run(); action.run();
assertTasksEnqueued(NordnVerifyAction.QUEUE, new TaskMatcher() assertTasksEnqueued(
.url(NordnVerifyAction.PATH) NordnVerifyAction.QUEUE,
.header(NordnVerifyAction.URL_HEADER, LOCATION_URL) new TaskMatcher()
.header(CONTENT_TYPE, FORM_DATA.toString())); .url(NordnVerifyAction.PATH)
.header(NordnVerifyAction.URL_HEADER, LOCATION_URL)
.header(CONTENT_TYPE, FORM_DATA.toString()));
} }
@MockitoSettings(strictness = Strictness.LENIENT)
@Test @Test
public void testFailure_nullRegistryUser() { void testFailure_nullRegistryUser() {
persistClaimsModeDomain(); persistClaimsModeDomain();
persistResource(Registry.get("tld").asBuilder().setLordnUsername(null).build()); persistResource(Registry.get("tld").asBuilder().setLordnUsername(null).build());
VerifyException thrown = assertThrows(VerifyException.class, action::run); VerifyException thrown = assertThrows(VerifyException.class, action::run);
assertThat(thrown).hasMessageThat().contains("lordnUsername is not set for tld."); assertThat(thrown).hasMessageThat().contains("lordnUsername is not set for tld.");
} }
@MockitoSettings(strictness = Strictness.LENIENT)
@Test @Test
public void testFetchFailure() { void testFetchFailure() {
persistClaimsModeDomain(); persistClaimsModeDomain();
when(httpResponse.getResponseCode()).thenReturn(SC_INTERNAL_SERVER_ERROR); when(httpResponse.getResponseCode()).thenReturn(SC_INTERNAL_SERVER_ERROR);
assertThrows(UrlFetchException.class, action::run); assertThrows(UrlFetchException.class, action::run);

View file

@ -38,51 +38,49 @@ import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeResponse; import google.registry.testing.FakeResponse;
import java.net.URL; import java.net.URL;
import java.util.Optional; import java.util.Optional;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Captor; import org.mockito.Captor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit; import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.MockitoRule;
/** Unit tests for {@link NordnVerifyAction}. */ /** Unit tests for {@link NordnVerifyAction}. */
@RunWith(JUnit4.class) @ExtendWith(MockitoExtension.class)
public class NordnVerifyActionTest { class NordnVerifyActionTest {
private static final String LOG_ACCEPTED = "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z," private static final String LOG_ACCEPTED =
+ "0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,accepted,no-warnings,1\n" "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,"
+ "roid,result-code\n" + "0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,accepted,no-warnings,1\n"
+ "SH8013-REP,2000"; + "roid,result-code\n"
+ "SH8013-REP,2000";
private static final String LOG_REJECTED = "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z," private static final String LOG_REJECTED =
+ "0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,rejected,no-warnings,1\n" "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,"
+ "roid,result-code\n" + "0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,rejected,no-warnings,1\n"
+ "SH8013-REP,2001"; + "roid,result-code\n"
+ "SH8013-REP,2001";
private static final String LOG_WARNINGS = "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z," private static final String LOG_WARNINGS =
+ "0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,accepted,warnings-present,3\n" "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,accepted,warnings-present,3\n"
+ "roid,result-code\n" + "roid,result-code\n"
+ "SH8013-REP,2001\n" + "SH8013-REP,2001\n"
+ "lulz-roid,3609\n" + "lulz-roid,3609\n"
+ "sabokitty-roid,3610\n"; + "sabokitty-roid,3610\n";
private static final String LOG_ERRORS = "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z," private static final String LOG_ERRORS =
+ "0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,accepted,warnings-present,3\n" "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,accepted,warnings-present,3\n"
+ "roid,result-code\n" + "roid,result-code\n"
+ "SH8013-REP,2000\n" + "SH8013-REP,2000\n"
+ "lulz-roid,4601\n" + "lulz-roid,4601\n"
+ "bogpog,4611\n"; + "bogpog,4611\n";
@Rule @RegisterExtension
public final AppEngineRule appEngine = public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build(); AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@Mock private URLFetchService fetchService; @Mock private URLFetchService fetchService;
@Mock private HTTPResponse httpResponse; @Mock private HTTPResponse httpResponse;
@Captor private ArgumentCaptor<HTTPRequest> httpRequestCaptor; @Captor private ArgumentCaptor<HTTPRequest> httpRequestCaptor;
@ -92,8 +90,8 @@ public class NordnVerifyActionTest {
new LordnRequestInitializer(Optional.of("attack")); new LordnRequestInitializer(Optional.of("attack"));
private final NordnVerifyAction action = new NordnVerifyAction(); private final NordnVerifyAction action = new NordnVerifyAction();
@Before @BeforeEach
public void before() throws Exception { void beforeEach() throws Exception {
when(httpResponse.getResponseCode()).thenReturn(SC_OK); when(httpResponse.getResponseCode()).thenReturn(SC_OK);
when(httpResponse.getContent()).thenReturn(LOG_ACCEPTED.getBytes(UTF_8)); when(httpResponse.getContent()).thenReturn(LOG_ACCEPTED.getBytes(UTF_8));
when(fetchService.fetch(any(HTTPRequest.class))).thenReturn(httpResponse); when(fetchService.fetch(any(HTTPRequest.class))).thenReturn(httpResponse);
@ -112,54 +110,54 @@ public class NordnVerifyActionTest {
} }
@Test @Test
public void testSuccess_sendHttpRequest_urlIsCorrect() throws Exception { void testSuccess_sendHttpRequest_urlIsCorrect() throws Exception {
action.run(); action.run();
assertThat(getCapturedHttpRequest().getURL()).isEqualTo(new URL("http://127.0.0.1/blobio")); assertThat(getCapturedHttpRequest().getURL()).isEqualTo(new URL("http://127.0.0.1/blobio"));
} }
@Test @Test
public void testSuccess_hasLordnPassword_sendsAuthorizationHeader() throws Exception { void testSuccess_hasLordnPassword_sendsAuthorizationHeader() throws Exception {
action.run(); action.run();
assertThat(getHeaderFirst(getCapturedHttpRequest(), AUTHORIZATION)) assertThat(getHeaderFirst(getCapturedHttpRequest(), AUTHORIZATION))
.hasValue("Basic bG9sY2F0OmF0dGFjaw=="); // echo -n lolcat:attack | base64 .hasValue("Basic bG9sY2F0OmF0dGFjaw=="); // echo -n lolcat:attack | base64
} }
@Test @Test
public void testSuccess_noLordnPassword_doesntSetAuthorizationHeader() throws Exception { void testSuccess_noLordnPassword_doesntSetAuthorizationHeader() throws Exception {
action.lordnRequestInitializer = new LordnRequestInitializer(Optional.empty()); action.lordnRequestInitializer = new LordnRequestInitializer(Optional.empty());
action.run(); action.run();
assertThat(getHeaderFirst(getCapturedHttpRequest(), AUTHORIZATION)).isEmpty(); assertThat(getHeaderFirst(getCapturedHttpRequest(), AUTHORIZATION)).isEmpty();
} }
@Test @Test
public void successVerifyRejected() throws Exception { void successVerifyRejected() throws Exception {
when(httpResponse.getContent()).thenReturn(LOG_REJECTED.getBytes(UTF_8)); when(httpResponse.getContent()).thenReturn(LOG_REJECTED.getBytes(UTF_8));
LordnLog lastLog = action.verify(); LordnLog lastLog = action.verify();
assertThat(lastLog.getStatus()).isEqualTo(LordnLog.Status.REJECTED); assertThat(lastLog.getStatus()).isEqualTo(LordnLog.Status.REJECTED);
} }
@Test @Test
public void successVerifyWarnings() throws Exception { void successVerifyWarnings() throws Exception {
when(httpResponse.getContent()).thenReturn(LOG_WARNINGS.getBytes(UTF_8)); when(httpResponse.getContent()).thenReturn(LOG_WARNINGS.getBytes(UTF_8));
LordnLog lastLog = action.verify(); LordnLog lastLog = action.verify();
assertThat(lastLog.hasWarnings()).isTrue(); assertThat(lastLog.hasWarnings()).isTrue();
} }
@Test @Test
public void successVerifyErrors() throws Exception { void successVerifyErrors() throws Exception {
when(httpResponse.getContent()).thenReturn(LOG_ERRORS.getBytes(UTF_8)); when(httpResponse.getContent()).thenReturn(LOG_ERRORS.getBytes(UTF_8));
LordnLog lastLog = action.verify(); LordnLog lastLog = action.verify();
assertThat(lastLog.hasWarnings()).isTrue(); assertThat(lastLog.hasWarnings()).isTrue();
} }
@Test @Test
public void failureVerifyUnauthorized() { void failureVerifyUnauthorized() {
when(httpResponse.getResponseCode()).thenReturn(SC_UNAUTHORIZED); when(httpResponse.getResponseCode()).thenReturn(SC_UNAUTHORIZED);
assertThrows(Exception.class, action::run); assertThrows(Exception.class, action::run);
} }
@Test @Test
public void failureVerifyNotReady() { void failureVerifyNotReady() {
when(httpResponse.getResponseCode()).thenReturn(SC_NO_CONTENT); when(httpResponse.getResponseCode()).thenReturn(SC_NO_CONTENT);
ConflictException thrown = assertThrows(ConflictException.class, action::run); ConflictException thrown = assertThrows(ConflictException.class, action::run);
assertThat(thrown).hasMessageThat().contains("Not ready"); assertThat(thrown).hasMessageThat().contains("Not ready");

View file

@ -26,32 +26,28 @@ import google.registry.model.smd.SignedMarkRevocationList;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock; import google.registry.testing.FakeClock;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link SmdrlCsvParser}. */ /** Unit tests for {@link SmdrlCsvParser}. */
@RunWith(JUnit4.class) class SmdrlCsvParserTest {
public class SmdrlCsvParserTest {
@RegisterExtension public final AppEngineRule appEngine = AppEngineRule.builder().build();
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder()
.build();
private final FakeClock clock = new FakeClock(); private final FakeClock clock = new FakeClock();
private static final CharSource SMDRL_LATEST_CSV = private static final CharSource SMDRL_LATEST_CSV =
TmchTestData.loadBytes("smdrl-latest.csv").asCharSource(US_ASCII); TmchTestData.loadBytes("smdrl-latest.csv").asCharSource(US_ASCII);
@Test @Test
public void testParse() throws Exception { void testParse() throws Exception {
SignedMarkRevocationList smdrl = SmdrlCsvParser.parse(SMDRL_LATEST_CSV.readLines()); SignedMarkRevocationList smdrl = SmdrlCsvParser.parse(SMDRL_LATEST_CSV.readLines());
assertThat(smdrl.size()).isEqualTo(150); assertThat(smdrl.size()).isEqualTo(150);
assertThat(smdrl.getCreationTime()).isEqualTo(DateTime.parse("2013-11-24T23:30:04.3Z")); assertThat(smdrl.getCreationTime()).isEqualTo(DateTime.parse("2013-11-24T23:30:04.3Z"));
} }
@Test @Test
public void testFirstRow() throws Exception { void testFirstRow() throws Exception {
SignedMarkRevocationList smdrl = SmdrlCsvParser.parse(SMDRL_LATEST_CSV.readLines()); SignedMarkRevocationList smdrl = SmdrlCsvParser.parse(SMDRL_LATEST_CSV.readLines());
clock.setTo(DateTime.parse("2013-08-09T12:00:00.0Z")); clock.setTo(DateTime.parse("2013-08-09T12:00:00.0Z"));
assertThat(smdrl.isSmdRevoked("0000001681375789102250-65535", clock.nowUtc())).isTrue(); assertThat(smdrl.isSmdRevoked("0000001681375789102250-65535", clock.nowUtc())).isTrue();
@ -62,7 +58,7 @@ public class SmdrlCsvParserTest {
} }
@Test @Test
public void testLastRow() throws Exception { void testLastRow() throws Exception {
SignedMarkRevocationList smdrl = SmdrlCsvParser.parse(SMDRL_LATEST_CSV.readLines()); SignedMarkRevocationList smdrl = SmdrlCsvParser.parse(SMDRL_LATEST_CSV.readLines());
clock.setTo(DateTime.parse("2013-08-09T12:00:00.0Z")); clock.setTo(DateTime.parse("2013-08-09T12:00:00.0Z"));
assertThat(smdrl.isSmdRevoked("0000002211373633641407-65535", clock.nowUtc())).isTrue(); assertThat(smdrl.isSmdRevoked("0000002211373633641407-65535", clock.nowUtc())).isTrue();
@ -73,7 +69,7 @@ public class SmdrlCsvParserTest {
} }
@Test @Test
public void testRowWithDifferentDate() throws Exception { void testRowWithDifferentDate() throws Exception {
SignedMarkRevocationList smdrl = SmdrlCsvParser.parse(SMDRL_LATEST_CSV.readLines()); SignedMarkRevocationList smdrl = SmdrlCsvParser.parse(SMDRL_LATEST_CSV.readLines());
clock.setTo(DateTime.parse("2013-08-09T12:00:00.0Z")); clock.setTo(DateTime.parse("2013-08-09T12:00:00.0Z"));
assertThat(smdrl.isSmdRevoked("0000002101376042766438-65535", clock.nowUtc())).isFalse(); assertThat(smdrl.isSmdRevoked("0000002101376042766438-65535", clock.nowUtc())).isFalse();
@ -82,11 +78,13 @@ public class SmdrlCsvParserTest {
} }
@Test @Test
public void testOneRow() { void testOneRow() {
SignedMarkRevocationList smdrl = SmdrlCsvParser.parse(ImmutableList.of( SignedMarkRevocationList smdrl =
"1,2013-11-24T23:30:04.3Z", SmdrlCsvParser.parse(
"smd-id,insertion-datetime", ImmutableList.of(
"0000001681375789102250-65535,2013-08-09T12:00:00.0Z")); "1,2013-11-24T23:30:04.3Z",
"smd-id,insertion-datetime",
"0000001681375789102250-65535,2013-08-09T12:00:00.0Z"));
assertThat(smdrl.size()).isEqualTo(1); assertThat(smdrl.size()).isEqualTo(1);
assertThat(smdrl.getCreationTime()).isEqualTo(DateTime.parse("2013-11-24T23:30:04.3Z")); assertThat(smdrl.getCreationTime()).isEqualTo(DateTime.parse("2013-11-24T23:30:04.3Z"));
clock.setTo(DateTime.parse("2020-08-09T12:00:00.0Z")); clock.setTo(DateTime.parse("2020-08-09T12:00:00.0Z"));
@ -94,10 +92,10 @@ public class SmdrlCsvParserTest {
} }
@Test @Test
public void testEmpty() { void testEmpty() {
SignedMarkRevocationList smdrl = SmdrlCsvParser.parse(ImmutableList.of( SignedMarkRevocationList smdrl =
"1,2014-11-24T23:30:04.3Z", SmdrlCsvParser.parse(
"smd-id,insertion-datetime")); ImmutableList.of("1,2014-11-24T23:30:04.3Z", "smd-id,insertion-datetime"));
assertThat(smdrl.size()).isEqualTo(0); assertThat(smdrl.size()).isEqualTo(0);
assertThat(smdrl.getCreationTime()).isEqualTo(DateTime.parse("2014-11-24T23:30:04.3Z")); assertThat(smdrl.getCreationTime()).isEqualTo(DateTime.parse("2014-11-24T23:30:04.3Z"));
clock.setTo(DateTime.parse("2020-08-09T12:00:00.0Z")); clock.setTo(DateTime.parse("2020-08-09T12:00:00.0Z"));
@ -105,7 +103,7 @@ public class SmdrlCsvParserTest {
} }
@Test @Test
public void testFail_badVersion() { void testFail_badVersion() {
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
@ -119,7 +117,7 @@ public class SmdrlCsvParserTest {
} }
@Test @Test
public void testFail_badHeader() { void testFail_badHeader() {
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
@ -133,7 +131,7 @@ public class SmdrlCsvParserTest {
} }
@Test @Test
public void testFail_tooManyColumns() { void testFail_tooManyColumns() {
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,

View file

@ -22,30 +22,28 @@ import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse; import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService; import com.google.appengine.api.urlfetch.URLFetchService;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import google.registry.testing.BouncyCastleProviderRule; import google.registry.testing.BouncyCastleProviderExtension;
import google.registry.testing.FakeClock; import google.registry.testing.FakeClock;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Captor; import org.mockito.Captor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit; import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.MockitoRule;
/** Common code for unit tests of classes that extend {@link Marksdb}. */ /** Common code for unit tests of classes that extend {@link Marksdb}. */
@RunWith(JUnit4.class) @ExtendWith(MockitoExtension.class)
public abstract class TmchActionTestCase { abstract class TmchActionTestCase {
static final String MARKSDB_LOGIN_AND_PASSWORD = "lolcat:attack"; static final String MARKSDB_LOGIN_AND_PASSWORD = "lolcat:attack";
static final String MARKSDB_URL = "http://127.0.0.1/love"; static final String MARKSDB_URL = "http://127.0.0.1/love";
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Rule public final MockitoRule mocks = MockitoJUnit.rule(); @RegisterExtension
@Rule public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule(); public final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
@Mock URLFetchService fetchService; @Mock URLFetchService fetchService;
@Mock HTTPResponse httpResponse; @Mock HTTPResponse httpResponse;
@ -54,8 +52,8 @@ public abstract class TmchActionTestCase {
final FakeClock clock = new FakeClock(); final FakeClock clock = new FakeClock();
final Marksdb marksdb = new Marksdb(); final Marksdb marksdb = new Marksdb();
@Before @BeforeEach
public void commonBefore() throws Exception { public void beforeEachTmchActionTestCase() throws Exception {
marksdb.fetchService = fetchService; marksdb.fetchService = fetchService;
marksdb.tmchMarksdbUrl = MARKSDB_URL; marksdb.tmchMarksdbUrl = MARKSDB_URL;
marksdb.marksdbPublicKey = TmchData.loadPublicKey(TmchTestData.loadBytes("pubkey")); marksdb.marksdbPublicKey = TmchData.loadPublicKey(TmchTestData.loadBytes("pubkey"));

View file

@ -30,25 +30,22 @@ import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException; import java.security.cert.CertificateNotYetValidException;
import java.security.cert.CertificateRevokedException; import java.security.cert.CertificateRevokedException;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link TmchCertificateAuthority}. */ /** Unit tests for {@link TmchCertificateAuthority}. */
@RunWith(JUnit4.class) class TmchCertificateAuthorityTest {
public class TmchCertificateAuthorityTest {
public static final String GOOD_TEST_CERTIFICATE = loadFile("icann-tmch-test-good.crt"); private static final String GOOD_TEST_CERTIFICATE = loadFile("icann-tmch-test-good.crt");
public static final String REVOKED_TEST_CERTIFICATE = loadFile("icann-tmch-test-revoked.crt"); private static final String REVOKED_TEST_CERTIFICATE = loadFile("icann-tmch-test-revoked.crt");
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
private FakeClock clock = new FakeClock(DateTime.parse("2014-01-01T00:00:00Z")); private FakeClock clock = new FakeClock(DateTime.parse("2014-01-01T00:00:00Z"));
@Test @Test
public void testFailure_prodRootExpired() { void testFailure_prodRootExpired() {
TmchCertificateAuthority tmchCertificateAuthority = TmchCertificateAuthority tmchCertificateAuthority =
new TmchCertificateAuthority(PRODUCTION, clock); new TmchCertificateAuthority(PRODUCTION, clock);
clock.setTo(DateTime.parse("2024-01-01T00:00:00Z")); clock.setTo(DateTime.parse("2024-01-01T00:00:00Z"));
@ -59,7 +56,7 @@ public class TmchCertificateAuthorityTest {
} }
@Test @Test
public void testFailure_prodRootNotYetValid() { void testFailure_prodRootNotYetValid() {
TmchCertificateAuthority tmchCertificateAuthority = TmchCertificateAuthority tmchCertificateAuthority =
new TmchCertificateAuthority(PRODUCTION, clock); new TmchCertificateAuthority(PRODUCTION, clock);
clock.setTo(DateTime.parse("2000-01-01T00:00:00Z")); clock.setTo(DateTime.parse("2000-01-01T00:00:00Z"));
@ -70,7 +67,7 @@ public class TmchCertificateAuthorityTest {
} }
@Test @Test
public void testFailure_crlDoesntMatchCerts() { void testFailure_crlDoesntMatchCerts() {
// Use the prod cl, which won't match our test certificate. // Use the prod cl, which won't match our test certificate.
TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PILOT, clock); TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PILOT, clock);
TmchCrl.set( TmchCrl.set(
@ -83,13 +80,13 @@ public class TmchCertificateAuthorityTest {
} }
@Test @Test
public void testSuccess_verify() throws Exception { void testSuccess_verify() throws Exception {
TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PILOT, clock); TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PILOT, clock);
tmchCertificateAuthority.verify(loadCertificate(GOOD_TEST_CERTIFICATE)); tmchCertificateAuthority.verify(loadCertificate(GOOD_TEST_CERTIFICATE));
} }
@Test @Test
public void testFailure_verifySignatureDoesntMatch() { void testFailure_verifySignatureDoesntMatch() {
TmchCertificateAuthority tmchCertificateAuthority = TmchCertificateAuthority tmchCertificateAuthority =
new TmchCertificateAuthority(PRODUCTION, clock); new TmchCertificateAuthority(PRODUCTION, clock);
SignatureException e = SignatureException e =
@ -100,7 +97,7 @@ public class TmchCertificateAuthorityTest {
} }
@Test @Test
public void testFailure_verifyRevoked() { void testFailure_verifyRevoked() {
TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PILOT, clock); TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PILOT, clock);
CertificateRevokedException thrown = CertificateRevokedException thrown =
assertThrows( assertThrows(

View file

@ -28,10 +28,10 @@ import java.security.SignatureException;
import java.security.cert.CRLException; import java.security.cert.CRLException;
import java.security.cert.CertificateNotYetValidException; import java.security.cert.CertificateNotYetValidException;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** Unit tests for {@link TmchCrlAction}. */ /** Unit tests for {@link TmchCrlAction}. */
public class TmchCrlActionTest extends TmchActionTestCase { class TmchCrlActionTest extends TmchActionTestCase {
private TmchCrlAction newTmchCrlAction(TmchCaMode tmchCaMode) throws MalformedURLException { private TmchCrlAction newTmchCrlAction(TmchCaMode tmchCaMode) throws MalformedURLException {
TmchCrlAction action = new TmchCrlAction(); TmchCrlAction action = new TmchCrlAction();
@ -42,7 +42,7 @@ public class TmchCrlActionTest extends TmchActionTestCase {
} }
@Test @Test
public void testSuccess() throws Exception { void testSuccess() throws Exception {
clock.setTo(DateTime.parse("2013-07-24TZ")); clock.setTo(DateTime.parse("2013-07-24TZ"));
when(httpResponse.getContent()).thenReturn( when(httpResponse.getContent()).thenReturn(
readResourceBytes(TmchCertificateAuthority.class, "icann-tmch.crl").read()); readResourceBytes(TmchCertificateAuthority.class, "icann-tmch.crl").read());
@ -53,7 +53,7 @@ public class TmchCrlActionTest extends TmchActionTestCase {
} }
@Test @Test
public void testFailure_crlTooOld() throws Exception { void testFailure_crlTooOld() throws Exception {
clock.setTo(DateTime.parse("2020-01-01TZ")); clock.setTo(DateTime.parse("2020-01-01TZ"));
when(httpResponse.getContent()) when(httpResponse.getContent())
.thenReturn(loadBytes(TmchCrlActionTest.class, "icann-tmch-pilot-old.crl").read()); .thenReturn(loadBytes(TmchCrlActionTest.class, "icann-tmch-pilot-old.crl").read());
@ -67,7 +67,7 @@ public class TmchCrlActionTest extends TmchActionTestCase {
} }
@Test @Test
public void testFailure_crlNotSignedByRoot() throws Exception { void testFailure_crlNotSignedByRoot() throws Exception {
clock.setTo(DateTime.parse("2013-07-24TZ")); clock.setTo(DateTime.parse("2013-07-24TZ"));
when(httpResponse.getContent()) when(httpResponse.getContent())
.thenReturn(readResourceBytes(TmchCertificateAuthority.class, "icann-tmch.crl").read()); .thenReturn(readResourceBytes(TmchCertificateAuthority.class, "icann-tmch.crl").read());
@ -77,7 +77,7 @@ public class TmchCrlActionTest extends TmchActionTestCase {
} }
@Test @Test
public void testFailure_crlNotYetValid() throws Exception { void testFailure_crlNotYetValid() throws Exception {
clock.setTo(DateTime.parse("1984-01-01TZ")); clock.setTo(DateTime.parse("1984-01-01TZ"));
when(httpResponse.getContent()).thenReturn( when(httpResponse.getContent()).thenReturn(
readResourceBytes(TmchCertificateAuthority.class, "icann-tmch-pilot.crl").read()); readResourceBytes(TmchCertificateAuthority.class, "icann-tmch-pilot.crl").read());

View file

@ -23,10 +23,10 @@ import static org.mockito.Mockito.when;
import google.registry.model.tmch.ClaimsListShard; import google.registry.model.tmch.ClaimsListShard;
import java.util.Optional; import java.util.Optional;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** Unit tests for {@link TmchDnlAction}. */ /** Unit tests for {@link TmchDnlAction}. */
public class TmchDnlActionTest extends TmchActionTestCase { class TmchDnlActionTest extends TmchActionTestCase {
private TmchDnlAction newTmchDnlAction() { private TmchDnlAction newTmchDnlAction() {
TmchDnlAction action = new TmchDnlAction(); TmchDnlAction action = new TmchDnlAction();
@ -36,7 +36,7 @@ public class TmchDnlActionTest extends TmchActionTestCase {
} }
@Test @Test
public void testDnl() throws Exception { void testDnl() throws Exception {
assertThat(ClaimsListShard.get().getClaimKey("xn----7sbejwbn3axu3d")).isEmpty(); assertThat(ClaimsListShard.get().getClaimKey("xn----7sbejwbn3axu3d")).isEmpty();
when(httpResponse.getContent()) when(httpResponse.getContent())
.thenReturn(TmchTestData.loadBytes("dnl-latest.csv").read()) .thenReturn(TmchTestData.loadBytes("dnl-latest.csv").read())

View file

@ -23,10 +23,10 @@ import static org.mockito.Mockito.when;
import google.registry.model.smd.SignedMarkRevocationList; import google.registry.model.smd.SignedMarkRevocationList;
import java.util.Optional; import java.util.Optional;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** Unit tests for {@link TmchSmdrlAction}. */ /** Unit tests for {@link TmchSmdrlAction}. */
public class TmchSmdrlActionTest extends TmchActionTestCase { class TmchSmdrlActionTest extends TmchActionTestCase {
private static final DateTime now = DateTime.parse("2014-01-01T00:00:00Z"); private static final DateTime now = DateTime.parse("2014-01-01T00:00:00Z");
@ -38,7 +38,7 @@ public class TmchSmdrlActionTest extends TmchActionTestCase {
} }
@Test @Test
public void testSuccess_smdrl() throws Exception { void testSuccess_smdrl() throws Exception {
SignedMarkRevocationList smdrl = SignedMarkRevocationList.get(); SignedMarkRevocationList smdrl = SignedMarkRevocationList.get();
assertThat(smdrl.isSmdRevoked("0000001681375789102250-65535", now)).isFalse(); assertThat(smdrl.isSmdRevoked("0000001681375789102250-65535", now)).isFalse();
assertThat(smdrl.isSmdRevoked("0000001681375789102250-65536", now)).isFalse(); assertThat(smdrl.isSmdRevoked("0000001681375789102250-65536", now)).isFalse();

View file

@ -37,7 +37,7 @@ public final class TmchTestData {
} }
/** Extracts SMD XML from an ASCII-armored file. */ /** Extracts SMD XML from an ASCII-armored file. */
public static byte[] loadSmd(String file) { static byte[] loadSmd(String file) {
String data = loadFile(file); String data = loadFile(file);
return base64() return base64()
.decode( .decode(

View file

@ -27,22 +27,19 @@ import google.registry.util.ResourceUtils;
import google.registry.util.SystemClock; import google.registry.util.SystemClock;
import java.nio.file.Path; import java.nio.file.Path;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests that the ICANN testing signed mark files are valid and not expired. */ /** Tests that the ICANN testing signed mark files are valid and not expired. */
@RunWith(JUnit4.class) class TmchTestDataExpirationTest {
public class TmchTestDataExpirationTest {
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final FluentLogger logger = FluentLogger.forEnclosingClass();
@Test @Test
public void testActiveSignedMarkFiles_areValidAndNotExpired() throws Exception { void testActiveSignedMarkFiles_areValidAndNotExpired() throws Exception {
DomainFlowTmchUtils tmchUtils = DomainFlowTmchUtils tmchUtils =
new DomainFlowTmchUtils( new DomainFlowTmchUtils(
new TmchXmlSignature( new TmchXmlSignature(

View file

@ -28,25 +28,21 @@ import java.security.cert.CertificateNotYetValidException;
import java.security.cert.CertificateRevokedException; import java.security.cert.CertificateRevokedException;
import javax.xml.crypto.dsig.XMLSignatureException; import javax.xml.crypto.dsig.XMLSignatureException;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** /**
* Unit tests for {@link TmchXmlSignature}. * Unit tests for {@link TmchXmlSignature}.
* *
* <p>This class does not test the {@code revoked/smd/} folder because it's not a crypto issue. * <p>This class does not test the {@code revoked/smd/} folder because it's not a crypto issue.
*/ */
@RunWith(JUnit4.class) class TmchXmlSignatureTest {
public class TmchXmlSignatureTest {
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Rule @RegisterExtension public final InjectRule inject = new InjectRule();
public final InjectRule inject = new InjectRule();
// This should be a date which falls within the validity range of the test files contained in the // This should be a date which falls within the validity range of the test files contained in the
// testdata/active directory. Note that test files claiming to be valid for a particular date // testdata/active directory. Note that test files claiming to be valid for a particular date
@ -73,12 +69,11 @@ public class TmchXmlSignatureTest {
private TmchXmlSignature tmchXmlSignature = private TmchXmlSignature tmchXmlSignature =
new TmchXmlSignature(new TmchCertificateAuthority(TmchCaMode.PILOT, clock)); new TmchXmlSignature(new TmchCertificateAuthority(TmchCaMode.PILOT, clock));
@Before @BeforeEach
public void before() { void beforeEach() {}
}
@Test @Test
public void testWrongCertificateAuthority() { void testWrongCertificateAuthority() {
tmchXmlSignature = tmchXmlSignature =
new TmchXmlSignature(new TmchCertificateAuthority(TmchCaMode.PRODUCTION, clock)); new TmchXmlSignature(new TmchCertificateAuthority(TmchCaMode.PRODUCTION, clock));
smdData = loadSmd("active/Court-Agent-Arab-Active.smd"); smdData = loadSmd("active/Court-Agent-Arab-Active.smd");
@ -88,231 +83,231 @@ public class TmchXmlSignatureTest {
} }
@Test @Test
public void testTimeTravelBeforeCertificateWasCreated() { void testTimeTravelBeforeCertificateWasCreated() {
smdData = loadSmd("active/Court-Agent-Arab-Active.smd"); smdData = loadSmd("active/Court-Agent-Arab-Active.smd");
clock.setTo(DateTime.parse("2013-05-01T00:00:00Z")); clock.setTo(DateTime.parse("2013-05-01T00:00:00Z"));
assertThrows(CertificateNotYetValidException.class, () -> tmchXmlSignature.verify(smdData)); assertThrows(CertificateNotYetValidException.class, () -> tmchXmlSignature.verify(smdData));
} }
@Test @Test
public void testTimeTravelAfterCertificateHasExpired() { void testTimeTravelAfterCertificateHasExpired() {
smdData = loadSmd("active/Court-Agent-Arab-Active.smd"); smdData = loadSmd("active/Court-Agent-Arab-Active.smd");
clock.setTo(DateTime.parse("2023-06-01T00:00:00Z")); clock.setTo(DateTime.parse("2023-06-01T00:00:00Z"));
assertThrows(CertificateExpiredException.class, () -> tmchXmlSignature.verify(smdData)); assertThrows(CertificateExpiredException.class, () -> tmchXmlSignature.verify(smdData));
} }
@Test @Test
public void testActiveCourtAgentArabActive() throws Exception { void testActiveCourtAgentArabActive() throws Exception {
smdData = loadSmd("active/Court-Agent-Arab-Active.smd"); smdData = loadSmd("active/Court-Agent-Arab-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveCourtAgentChineseActive() throws Exception { void testActiveCourtAgentChineseActive() throws Exception {
smdData = loadSmd("active/Court-Agent-Chinese-Active.smd"); smdData = loadSmd("active/Court-Agent-Chinese-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveCourtAgentEnglishActive() throws Exception { void testActiveCourtAgentEnglishActive() throws Exception {
smdData = loadSmd("active/Court-Agent-English-Active.smd"); smdData = loadSmd("active/Court-Agent-English-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveCourtAgentFrenchActive() throws Exception { void testActiveCourtAgentFrenchActive() throws Exception {
smdData = loadSmd("active/Court-Agent-French-Active.smd"); smdData = loadSmd("active/Court-Agent-French-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveCourtAgentRussianActive() throws Exception { void testActiveCourtAgentRussianActive() throws Exception {
smdData = loadSmd("active/Court-Agent-Russian-Active.smd"); smdData = loadSmd("active/Court-Agent-Russian-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveCourtHolderArabActive() throws Exception { void testActiveCourtHolderArabActive() throws Exception {
smdData = loadSmd("active/Court-Holder-Arab-Active.smd"); smdData = loadSmd("active/Court-Holder-Arab-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveCourtHolderChineseActive() throws Exception { void testActiveCourtHolderChineseActive() throws Exception {
smdData = loadSmd("active/Court-Holder-Chinese-Active.smd"); smdData = loadSmd("active/Court-Holder-Chinese-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveCourtHolderEnglishActive() throws Exception { void testActiveCourtHolderEnglishActive() throws Exception {
smdData = loadSmd("active/Court-Holder-English-Active.smd"); smdData = loadSmd("active/Court-Holder-English-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveCourtHolderFrenchActive() throws Exception { void testActiveCourtHolderFrenchActive() throws Exception {
smdData = loadSmd("active/Court-Holder-French-Active.smd"); smdData = loadSmd("active/Court-Holder-French-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveCourtHolderRussianActive() throws Exception { void testActiveCourtHolderRussianActive() throws Exception {
smdData = loadSmd("active/Court-Holder-Russian-Active.smd"); smdData = loadSmd("active/Court-Holder-Russian-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveTrademarkAgentArabActive() throws Exception { void testActiveTrademarkAgentArabActive() throws Exception {
smdData = loadSmd("active/Trademark-Agent-Arab-Active.smd"); smdData = loadSmd("active/Trademark-Agent-Arab-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveTrademarkAgentChineseActive() throws Exception { void testActiveTrademarkAgentChineseActive() throws Exception {
smdData = loadSmd("active/Trademark-Agent-Chinese-Active.smd"); smdData = loadSmd("active/Trademark-Agent-Chinese-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveTrademarkAgentEnglishActive() throws Exception { void testActiveTrademarkAgentEnglishActive() throws Exception {
smdData = loadSmd("active/Trademark-Agent-English-Active.smd"); smdData = loadSmd("active/Trademark-Agent-English-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveTrademarkAgentFrenchActive() throws Exception { void testActiveTrademarkAgentFrenchActive() throws Exception {
smdData = loadSmd("active/Trademark-Agent-French-Active.smd"); smdData = loadSmd("active/Trademark-Agent-French-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveTrademarkAgentRussianActive() throws Exception { void testActiveTrademarkAgentRussianActive() throws Exception {
smdData = loadSmd("active/Trademark-Agent-Russian-Active.smd"); smdData = loadSmd("active/Trademark-Agent-Russian-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveTrademarkHolderArabActive() throws Exception { void testActiveTrademarkHolderArabActive() throws Exception {
smdData = loadSmd("active/Trademark-Holder-Arab-Active.smd"); smdData = loadSmd("active/Trademark-Holder-Arab-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveTrademarkHolderChineseActive() throws Exception { void testActiveTrademarkHolderChineseActive() throws Exception {
smdData = loadSmd("active/Trademark-Holder-Chinese-Active.smd"); smdData = loadSmd("active/Trademark-Holder-Chinese-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveTrademarkHolderEnglishActive() throws Exception { void testActiveTrademarkHolderEnglishActive() throws Exception {
smdData = loadSmd("active/Trademark-Holder-English-Active.smd"); smdData = loadSmd("active/Trademark-Holder-English-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveTrademarkHolderFrenchActive() throws Exception { void testActiveTrademarkHolderFrenchActive() throws Exception {
smdData = loadSmd("active/Trademark-Holder-French-Active.smd"); smdData = loadSmd("active/Trademark-Holder-French-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveTrademarkHolderRussianActive() throws Exception { void testActiveTrademarkHolderRussianActive() throws Exception {
smdData = loadSmd("active/Trademark-Holder-Russian-Active.smd"); smdData = loadSmd("active/Trademark-Holder-Russian-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveTreatystatuteAgentArabActive() throws Exception { void testActiveTreatystatuteAgentArabActive() throws Exception {
smdData = loadSmd("active/TreatyStatute-Agent-Arab-Active.smd"); smdData = loadSmd("active/TreatyStatute-Agent-Arab-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveTreatystatuteAgentChineseActive() throws Exception { void testActiveTreatystatuteAgentChineseActive() throws Exception {
smdData = loadSmd("active/TreatyStatute-Agent-Chinese-Active.smd"); smdData = loadSmd("active/TreatyStatute-Agent-Chinese-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveTreatystatuteAgentEnglishActive() throws Exception { void testActiveTreatystatuteAgentEnglishActive() throws Exception {
smdData = loadSmd("active/TreatyStatute-Agent-English-Active.smd"); smdData = loadSmd("active/TreatyStatute-Agent-English-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveTreatystatuteAgentFrenchActive() throws Exception { void testActiveTreatystatuteAgentFrenchActive() throws Exception {
smdData = loadSmd("active/TreatyStatute-Agent-French-Active.smd"); smdData = loadSmd("active/TreatyStatute-Agent-French-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveTreatystatuteAgentRussianActive() throws Exception { void testActiveTreatystatuteAgentRussianActive() throws Exception {
smdData = loadSmd("active/TreatyStatute-Agent-Russian-Active.smd"); smdData = loadSmd("active/TreatyStatute-Agent-Russian-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveTreatystatuteHolderArabActive() throws Exception { void testActiveTreatystatuteHolderArabActive() throws Exception {
smdData = loadSmd("active/TreatyStatute-Holder-Arab-Active.smd"); smdData = loadSmd("active/TreatyStatute-Holder-Arab-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveTreatystatuteHolderChineseActive() throws Exception { void testActiveTreatystatuteHolderChineseActive() throws Exception {
smdData = loadSmd("active/TreatyStatute-Holder-Chinese-Active.smd"); smdData = loadSmd("active/TreatyStatute-Holder-Chinese-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveTreatystatuteHolderEnglishActive() throws Exception { void testActiveTreatystatuteHolderEnglishActive() throws Exception {
smdData = loadSmd("active/TreatyStatute-Holder-English-Active.smd"); smdData = loadSmd("active/TreatyStatute-Holder-English-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveTreatystatuteHolderFrenchActive() throws Exception { void testActiveTreatystatuteHolderFrenchActive() throws Exception {
smdData = loadSmd("active/TreatyStatute-Holder-French-Active.smd"); smdData = loadSmd("active/TreatyStatute-Holder-French-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testActiveTreatystatuteHolderRussianActive() throws Exception { void testActiveTreatystatuteHolderRussianActive() throws Exception {
smdData = loadSmd("active/TreatyStatute-Holder-Russian-Active.smd"); smdData = loadSmd("active/TreatyStatute-Holder-Russian-Active.smd");
tmchXmlSignature.verify(smdData); tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testInvalidInvalidsignatureCourtAgentFrenchActive() { void testInvalidInvalidsignatureCourtAgentFrenchActive() {
smdData = loadSmd("invalid/InvalidSignature-Court-Agent-French-Active.smd"); smdData = loadSmd("invalid/InvalidSignature-Court-Agent-French-Active.smd");
assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData)); assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData));
} }
@Test @Test
public void testInvalidInvalidsignatureTrademarkAgentEnglishActive() { void testInvalidInvalidsignatureTrademarkAgentEnglishActive() {
smdData = loadSmd("invalid/InvalidSignature-Trademark-Agent-English-Active.smd"); smdData = loadSmd("invalid/InvalidSignature-Trademark-Agent-English-Active.smd");
assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData)); assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData));
} }
@Test @Test
public void testInvalidInvalidsignatureTrademarkAgentRussianActive() { void testInvalidInvalidsignatureTrademarkAgentRussianActive() {
smdData = loadSmd("invalid/InvalidSignature-Trademark-Agent-Russian-Active.smd"); smdData = loadSmd("invalid/InvalidSignature-Trademark-Agent-Russian-Active.smd");
assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData)); assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData));
} }
@Test @Test
public void testInvalidInvalidsignatureTreatystatuteAgentChineseActive() { void testInvalidInvalidsignatureTreatystatuteAgentChineseActive() {
smdData = loadSmd("invalid/InvalidSignature-TreatyStatute-Agent-Chinese-Active.smd"); smdData = loadSmd("invalid/InvalidSignature-TreatyStatute-Agent-Chinese-Active.smd");
assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData)); assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData));
} }
@Test @Test
public void testInvalidInvalidsignatureTreatystatuteAgentEnglishActive() { void testInvalidInvalidsignatureTreatystatuteAgentEnglishActive() {
smdData = loadSmd("invalid/InvalidSignature-TreatyStatute-Agent-English-Active.smd"); smdData = loadSmd("invalid/InvalidSignature-TreatyStatute-Agent-English-Active.smd");
assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData)); assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData));
} }
@Test @Test
public void testRevokedTmvTmvrevokedCourtAgentFrenchActive() { void testRevokedTmvTmvrevokedCourtAgentFrenchActive() {
smdData = loadSmd("revoked/tmv/TMVRevoked-Court-Agent-French-Active.smd"); smdData = loadSmd("revoked/tmv/TMVRevoked-Court-Agent-French-Active.smd");
CertificateRevokedException e = CertificateRevokedException e =
assertThrows(CertificateRevokedException.class, () -> tmchXmlSignature.verify(smdData)); assertThrows(CertificateRevokedException.class, () -> tmchXmlSignature.verify(smdData));
@ -320,7 +315,7 @@ public class TmchXmlSignatureTest {
} }
@Test @Test
public void testRevokedTmvTmvrevokedTrademarkAgentEnglishActive() { void testRevokedTmvTmvrevokedTrademarkAgentEnglishActive() {
smdData = loadSmd("revoked/tmv/TMVRevoked-Trademark-Agent-English-Active.smd"); smdData = loadSmd("revoked/tmv/TMVRevoked-Trademark-Agent-English-Active.smd");
CertificateRevokedException e = CertificateRevokedException e =
assertThrows(CertificateRevokedException.class, () -> tmchXmlSignature.verify(smdData)); assertThrows(CertificateRevokedException.class, () -> tmchXmlSignature.verify(smdData));
@ -328,7 +323,7 @@ public class TmchXmlSignatureTest {
} }
@Test @Test
public void testRevokedTmvTmvrevokedTrademarkAgentRussianActive() { void testRevokedTmvTmvrevokedTrademarkAgentRussianActive() {
smdData = loadSmd("revoked/tmv/TMVRevoked-Trademark-Agent-Russian-Active.smd"); smdData = loadSmd("revoked/tmv/TMVRevoked-Trademark-Agent-Russian-Active.smd");
CertificateRevokedException e = CertificateRevokedException e =
assertThrows(CertificateRevokedException.class, () -> tmchXmlSignature.verify(smdData)); assertThrows(CertificateRevokedException.class, () -> tmchXmlSignature.verify(smdData));
@ -336,7 +331,7 @@ public class TmchXmlSignatureTest {
} }
@Test @Test
public void testRevokedTmvTmvrevokedTreatystatuteAgentChineseActive() { void testRevokedTmvTmvrevokedTreatystatuteAgentChineseActive() {
smdData = loadSmd("revoked/tmv/TMVRevoked-TreatyStatute-Agent-Chinese-Active.smd"); smdData = loadSmd("revoked/tmv/TMVRevoked-TreatyStatute-Agent-Chinese-Active.smd");
CertificateRevokedException e = CertificateRevokedException e =
assertThrows(CertificateRevokedException.class, () -> tmchXmlSignature.verify(smdData)); assertThrows(CertificateRevokedException.class, () -> tmchXmlSignature.verify(smdData));
@ -344,7 +339,7 @@ public class TmchXmlSignatureTest {
} }
@Test @Test
public void testRevokedTmvTmvrevokedTreatystatuteAgentEnglishActive() { void testRevokedTmvTmvrevokedTreatystatuteAgentEnglishActive() {
smdData = loadSmd("revoked/tmv/TMVRevoked-TreatyStatute-Agent-English-Active.smd"); smdData = loadSmd("revoked/tmv/TMVRevoked-TreatyStatute-Agent-English-Active.smd");
CertificateRevokedException e = CertificateRevokedException e =
assertThrows(CertificateRevokedException.class, () -> tmchXmlSignature.verify(smdData)); assertThrows(CertificateRevokedException.class, () -> tmchXmlSignature.verify(smdData));

View file

@ -32,7 +32,7 @@ import google.registry.model.poll.PollMessage;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import google.registry.testing.CertificateSamples; import google.registry.testing.CertificateSamples;
import google.registry.testing.FakeClock; import google.registry.testing.FakeClock;
import google.registry.testing.SystemPropertyRule; import google.registry.testing.SystemPropertyExtension;
import google.registry.tools.params.ParameterFactory; import google.registry.tools.params.ParameterFactory;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
@ -76,14 +76,15 @@ public abstract class CommandTestCase<C extends Command> {
.withTaskQueue() .withTaskQueue()
.build(); .build();
@RegisterExtension final SystemPropertyRule systemPropertyRule = new SystemPropertyRule(); @RegisterExtension
final SystemPropertyExtension systemPropertyExtension = new SystemPropertyExtension();
@TempDir public Path tmpDir; @TempDir public Path tmpDir;
@BeforeEach @BeforeEach
public final void beforeEachCommandTestCase() throws Exception { public final void beforeEachCommandTestCase() throws Exception {
// Ensure the UNITTEST environment has been set before constructing a new command instance. // Ensure the UNITTEST environment has been set before constructing a new command instance.
RegistryToolEnvironment.UNITTEST.setup(systemPropertyRule); RegistryToolEnvironment.UNITTEST.setup(systemPropertyExtension);
command = newCommandInstance(); command = newCommandInstance();
// Capture standard output/error. This is problematic because gradle tests run in parallel in // Capture standard output/error. This is problematic because gradle tests run in parallel in
@ -104,7 +105,7 @@ public abstract class CommandTestCase<C extends Command> {
} }
void runCommandInEnvironment(RegistryToolEnvironment env, String... args) throws Exception { void runCommandInEnvironment(RegistryToolEnvironment env, String... args) throws Exception {
env.setup(systemPropertyRule); env.setup(systemPropertyExtension);
try { try {
JCommander jcommander = new JCommander(command); JCommander jcommander = new JCommander(command);
jcommander.addConverterFactory(new ParameterFactory()); jcommander.addConverterFactory(new ParameterFactory());
@ -115,7 +116,7 @@ public abstract class CommandTestCase<C extends Command> {
// This primarily matters for AutoTimestamp fields, which otherwise won't have updated values. // This primarily matters for AutoTimestamp fields, which otherwise won't have updated values.
ofy().clearSessionCache(); ofy().clearSessionCache();
// Reset back to UNITTEST environment. // Reset back to UNITTEST environment.
RegistryToolEnvironment.UNITTEST.setup(systemPropertyRule); RegistryToolEnvironment.UNITTEST.setup(systemPropertyExtension);
} }
} }

View file

@ -20,7 +20,7 @@ import static google.registry.testing.TestDataHelper.loadBytes;
import com.google.common.io.ByteSource; import com.google.common.io.ByteSource;
import com.google.common.io.Files; import com.google.common.io.Files;
import google.registry.rde.RdeTestData; import google.registry.rde.RdeTestData;
import google.registry.testing.BouncyCastleProviderRule; import google.registry.testing.BouncyCastleProviderExtension;
import google.registry.testing.FakeKeyringModule; import google.registry.testing.FakeKeyringModule;
import java.nio.file.Path; import java.nio.file.Path;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
@ -31,7 +31,8 @@ import org.junit.jupiter.api.extension.RegisterExtension;
public class EncryptEscrowDepositCommandTest public class EncryptEscrowDepositCommandTest
extends CommandTestCase<EncryptEscrowDepositCommand> { extends CommandTestCase<EncryptEscrowDepositCommand> {
@RegisterExtension public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule(); @RegisterExtension
public final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
private final ByteSource depositXml = loadBytes(RdeTestData.class, "deposit_full.xml"); private final ByteSource depositXml = loadBytes(RdeTestData.class, "deposit_full.xml");

View file

@ -20,7 +20,7 @@ import static org.junit.Assert.assertThrows;
import google.registry.keyring.api.Keyring; import google.registry.keyring.api.Keyring;
import google.registry.rde.Ghostryde; import google.registry.rde.Ghostryde;
import google.registry.testing.BouncyCastleProviderRule; import google.registry.testing.BouncyCastleProviderExtension;
import google.registry.testing.FakeKeyringModule; import google.registry.testing.FakeKeyringModule;
import google.registry.testing.InjectRule; import google.registry.testing.InjectRule;
import java.nio.file.Files; import java.nio.file.Files;
@ -53,7 +53,8 @@ class GhostrydeCommandTest extends CommandTestCase<GhostrydeCommand> {
@RegisterExtension final InjectRule inject = new InjectRule(); @RegisterExtension final InjectRule inject = new InjectRule();
@RegisterExtension final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule(); @RegisterExtension
final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
private Keyring keyring; private Keyring keyring;

View file

@ -17,14 +17,15 @@ package google.registry.tools;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertThrows;
import google.registry.testing.SystemPropertyRule; import google.registry.testing.SystemPropertyExtension;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link RegistryToolEnvironment}. */ /** Unit tests for {@link RegistryToolEnvironment}. */
class RegistryToolEnvironmentTest { class RegistryToolEnvironmentTest {
@RegisterExtension final SystemPropertyRule systemPropertyRule = new SystemPropertyRule(); @RegisterExtension
final SystemPropertyExtension systemPropertyExtension = new SystemPropertyExtension();
@Test @Test
void testGet_withoutSetup_throws() { void testGet_withoutSetup_throws() {
@ -34,10 +35,10 @@ class RegistryToolEnvironmentTest {
@Test @Test
void testSetup_changesEnvironmentReturnedByGet() { void testSetup_changesEnvironmentReturnedByGet() {
RegistryToolEnvironment.UNITTEST.setup(systemPropertyRule); RegistryToolEnvironment.UNITTEST.setup(systemPropertyExtension);
assertThat(RegistryToolEnvironment.get()).isEqualTo(RegistryToolEnvironment.UNITTEST); assertThat(RegistryToolEnvironment.get()).isEqualTo(RegistryToolEnvironment.UNITTEST);
RegistryToolEnvironment.ALPHA.setup(systemPropertyRule); RegistryToolEnvironment.ALPHA.setup(systemPropertyExtension);
assertThat(RegistryToolEnvironment.get()).isEqualTo(RegistryToolEnvironment.ALPHA); assertThat(RegistryToolEnvironment.get()).isEqualTo(RegistryToolEnvironment.ALPHA);
} }

View file

@ -26,7 +26,7 @@ import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpRequestInitializer;
import google.registry.config.RegistryConfig; import google.registry.config.RegistryConfig;
import google.registry.testing.SystemPropertyRule; import google.registry.testing.SystemPropertyExtension;
import google.registry.util.GoogleCredentialsBundle; import google.registry.util.GoogleCredentialsBundle;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -39,14 +39,15 @@ import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
public class RequestFactoryModuleTest { public class RequestFactoryModuleTest {
@RegisterExtension final SystemPropertyRule systemPropertyRule = new SystemPropertyRule(); @RegisterExtension
final SystemPropertyExtension systemPropertyExtension = new SystemPropertyExtension();
@Mock public GoogleCredentialsBundle credentialsBundle; @Mock public GoogleCredentialsBundle credentialsBundle;
@Mock public HttpRequestInitializer httpRequestInitializer; @Mock public HttpRequestInitializer httpRequestInitializer;
@BeforeEach @BeforeEach
void beforeEach() { void beforeEach() {
RegistryToolEnvironment.UNITTEST.setup(systemPropertyRule); RegistryToolEnvironment.UNITTEST.setup(systemPropertyExtension);
} }
@Test @Test

View file

@ -27,7 +27,7 @@ import com.beust.jcommander.Parameters;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import google.registry.testing.FakeClock; import google.registry.testing.FakeClock;
import google.registry.testing.SystemPropertyRule; import google.registry.testing.SystemPropertyExtension;
import google.registry.tools.ShellCommand.JCommanderCompletor; import google.registry.tools.ShellCommand.JCommanderCompletor;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
@ -47,7 +47,8 @@ import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link ShellCommand}. */ /** Unit tests for {@link ShellCommand}. */
class ShellCommandTest { class ShellCommandTest {
@RegisterExtension final SystemPropertyRule systemPropertyRule = new SystemPropertyRule(); @RegisterExtension
final SystemPropertyExtension systemPropertyExtension = new SystemPropertyExtension();
CommandRunner cli = mock(CommandRunner.class); CommandRunner cli = mock(CommandRunner.class);
private FakeClock clock = new FakeClock(DateTime.parse("2000-01-01TZ")); private FakeClock clock = new FakeClock(DateTime.parse("2000-01-01TZ"));
@ -109,7 +110,7 @@ class ShellCommandTest {
@Test @Test
void testNoIdleWhenInAlpha() throws Exception { void testNoIdleWhenInAlpha() throws Exception {
RegistryToolEnvironment.ALPHA.setup(systemPropertyRule); RegistryToolEnvironment.ALPHA.setup(systemPropertyExtension);
MockCli cli = new MockCli(); MockCli cli = new MockCli();
ShellCommand shellCommand = ShellCommand shellCommand =
createShellCommand(cli, Duration.standardDays(1), "test1 foo bar", "test2 foo bar"); createShellCommand(cli, Duration.standardDays(1), "test1 foo bar", "test2 foo bar");
@ -118,7 +119,7 @@ class ShellCommandTest {
@Test @Test
void testNoIdleWhenInSandbox() throws Exception { void testNoIdleWhenInSandbox() throws Exception {
RegistryToolEnvironment.SANDBOX.setup(systemPropertyRule); RegistryToolEnvironment.SANDBOX.setup(systemPropertyExtension);
MockCli cli = new MockCli(); MockCli cli = new MockCli();
ShellCommand shellCommand = ShellCommand shellCommand =
createShellCommand(cli, Duration.standardDays(1), "test1 foo bar", "test2 foo bar"); createShellCommand(cli, Duration.standardDays(1), "test1 foo bar", "test2 foo bar");
@ -127,7 +128,7 @@ class ShellCommandTest {
@Test @Test
void testIdleWhenOverHourInProduction() throws Exception { void testIdleWhenOverHourInProduction() throws Exception {
RegistryToolEnvironment.PRODUCTION.setup(systemPropertyRule); RegistryToolEnvironment.PRODUCTION.setup(systemPropertyExtension);
MockCli cli = new MockCli(); MockCli cli = new MockCli();
ShellCommand shellCommand = ShellCommand shellCommand =
createShellCommand(cli, Duration.standardMinutes(61), "test1 foo bar", "test2 foo bar"); createShellCommand(cli, Duration.standardMinutes(61), "test1 foo bar", "test2 foo bar");
@ -137,7 +138,7 @@ class ShellCommandTest {
@Test @Test
void testNoIdleWhenUnderHourInProduction() throws Exception { void testNoIdleWhenUnderHourInProduction() throws Exception {
RegistryToolEnvironment.PRODUCTION.setup(systemPropertyRule); RegistryToolEnvironment.PRODUCTION.setup(systemPropertyExtension);
MockCli cli = new MockCli(); MockCli cli = new MockCli();
ShellCommand shellCommand = ShellCommand shellCommand =
createShellCommand(cli, Duration.standardMinutes(59), "test1 foo bar", "test2 foo bar"); createShellCommand(cli, Duration.standardMinutes(59), "test1 foo bar", "test2 foo bar");
@ -157,7 +158,7 @@ class ShellCommandTest {
void testMultipleCommandInvocations() throws Exception { void testMultipleCommandInvocations() throws Exception {
try (RegistryCli cli = try (RegistryCli cli =
new RegistryCli("unittest", ImmutableMap.of("test_command", TestCommand.class))) { new RegistryCli("unittest", ImmutableMap.of("test_command", TestCommand.class))) {
RegistryToolEnvironment.UNITTEST.setup(systemPropertyRule); RegistryToolEnvironment.UNITTEST.setup(systemPropertyExtension);
cli.setEnvironment(RegistryToolEnvironment.UNITTEST); cli.setEnvironment(RegistryToolEnvironment.UNITTEST);
cli.run(new String[] {"test_command", "-x", "xval", "arg1", "arg2"}); cli.run(new String[] {"test_command", "-x", "xval", "arg1", "arg2"});
cli.run(new String[] {"test_command", "-x", "otherxval", "arg3"}); cli.run(new String[] {"test_command", "-x", "otherxval", "arg3"});
@ -272,7 +273,7 @@ class ShellCommandTest {
@Test @Test
void testEncapsulatedOutput_command() throws Exception { void testEncapsulatedOutput_command() throws Exception {
RegistryToolEnvironment.ALPHA.setup(systemPropertyRule); RegistryToolEnvironment.ALPHA.setup(systemPropertyExtension);
captureOutput(); captureOutput();
ShellCommand shellCommand = ShellCommand shellCommand =
new ShellCommand( new ShellCommand(
@ -296,7 +297,7 @@ class ShellCommandTest {
@Test @Test
void testEncapsulatedOutput_throws() throws Exception { void testEncapsulatedOutput_throws() throws Exception {
RegistryToolEnvironment.ALPHA.setup(systemPropertyRule); RegistryToolEnvironment.ALPHA.setup(systemPropertyExtension);
captureOutput(); captureOutput();
ShellCommand shellCommand = ShellCommand shellCommand =
new ShellCommand( new ShellCommand(

View file

@ -21,42 +21,37 @@ import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage; import static com.google.common.truth.Truth.assertWithMessage;
import com.beust.jcommander.Parameters; import com.beust.jcommander.Parameters;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView; import com.google.common.collect.Sets.SetView;
import com.google.common.reflect.ClassPath; import com.google.common.reflect.ClassPath;
import com.google.common.reflect.ClassPath.ClassInfo; import com.google.common.reflect.ClassPath.ClassInfo;
import com.google.common.truth.Expect; import google.registry.testing.SystemPropertyExtension;
import google.registry.testing.SystemPropertyRule;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Map; import java.util.Map;
import junitparams.JUnitParamsRunner; import java.util.stream.Stream;
import junitparams.naming.TestCaseName; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Rule; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.Test; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.runner.RunWith; import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
/** Unit tests for {@link RegistryTool} and {@link DevTool}. */ /** Unit tests for {@link RegistryTool} and {@link DevTool}. */
@RunWith(JUnitParamsRunner.class) class ToolsTest {
public class ToolsTest {
@Rule @RegisterExtension
public final Expect expect = Expect.create(); final SystemPropertyExtension systemPropertyExtension = new SystemPropertyExtension();
@Rule public final SystemPropertyRule systemPropertyRule = new SystemPropertyRule(); @BeforeEach
void beforeEach() {
@Before RegistryToolEnvironment.UNITTEST.setup(systemPropertyExtension);
public void init() {
RegistryToolEnvironment.UNITTEST.setup(systemPropertyRule);
} }
@Test @Test
public void test_commandMap_includesAllCommands() throws Exception { void test_commandMap_includesAllCommands() throws Exception {
ImmutableSet<?> registryToolCommands = ImmutableSet.copyOf(RegistryTool.COMMAND_MAP.values()); ImmutableSet<?> registryToolCommands = ImmutableSet.copyOf(RegistryTool.COMMAND_MAP.values());
ImmutableSet<?> devToolCommands = ImmutableSet.copyOf(DevTool.COMMAND_MAP.values()); ImmutableSet<?> devToolCommands = ImmutableSet.copyOf(DevTool.COMMAND_MAP.values());
assertWithMessage("RegistryTool and DevTool have overlapping commands") assertWithMessage("RegistryTool and DevTool have overlapping commands")
@ -73,32 +68,29 @@ public class ToolsTest {
.isEmpty(); .isEmpty();
} }
@Test @ParameterizedTest
@junitparams.Parameters(method = "getToolCommandMap") @MethodSource("provideTestCombinations")
@TestCaseName("{method}_{0}") void test_commandMap_namesAreInAlphabeticalOrder(
public void test_commandMap_namesAreInAlphabeticalOrder(
String toolName, ImmutableMap<String, Class<? extends Command>> commandMap) { String toolName, ImmutableMap<String, Class<? extends Command>> commandMap) {
assertThat(commandMap.keySet()).isInStrictOrder(); assertThat(commandMap.keySet()).isInStrictOrder();
} }
@Test @ParameterizedTest
@junitparams.Parameters(method = "getToolCommandMap") @MethodSource("provideTestCombinations")
@TestCaseName("{method}_{0}") void test_commandMap_namesAreDerivedFromClassNames(
public void test_commandMap_namesAreDerivedFromClassNames(
String toolName, ImmutableMap<String, Class<? extends Command>> commandMap) { String toolName, ImmutableMap<String, Class<? extends Command>> commandMap) {
for (Map.Entry<String, ? extends Class<? extends Command>> commandEntry : for (Map.Entry<String, ? extends Class<? extends Command>> commandEntry :
commandMap.entrySet()) { commandMap.entrySet()) {
String className = commandEntry.getValue().getSimpleName(); String className = commandEntry.getValue().getSimpleName();
expect.that(commandEntry.getKey()) assertThat(commandEntry.getKey())
// JCommander names should match the class name, up to "Command" and case formatting. // JCommander names should match the class name, up to "Command" and case formatting.
.isEqualTo(UPPER_CAMEL.to(LOWER_UNDERSCORE, className.replaceFirst("Command$", ""))); .isEqualTo(UPPER_CAMEL.to(LOWER_UNDERSCORE, className.replaceFirst("Command$", "")));
} }
} }
@Test @ParameterizedTest
@junitparams.Parameters(method = "getToolCommandMap") @MethodSource("provideTestCombinations")
@TestCaseName("{method}_{0}") void test_commandMap_allCommandsHaveDescriptions(
public void test_commandMap_allCommandsHaveDescriptions(
String toolName, ImmutableMap<String, Class<? extends Command>> commandMap) { String toolName, ImmutableMap<String, Class<? extends Command>> commandMap) {
for (Map.Entry<String, ? extends Class<? extends Command>> commandEntry : for (Map.Entry<String, ? extends Class<? extends Command>> commandEntry :
commandMap.entrySet()) { commandMap.entrySet()) {
@ -109,10 +101,10 @@ public class ToolsTest {
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")
private List<List<Object>> getToolCommandMap() { private static Stream<Arguments> provideTestCombinations() {
return ImmutableList.of( return Stream.of(
ImmutableList.of("RegistryTool", RegistryTool.COMMAND_MAP), Arguments.of("RegistryTool", RegistryTool.COMMAND_MAP),
ImmutableList.of("DevTool", DevTool.COMMAND_MAP)); Arguments.of("DevTool", DevTool.COMMAND_MAP));
} }
/** /**
@ -126,9 +118,9 @@ public class ToolsTest {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private ImmutableSet<Class<? extends Command>> getAllCommandClasses() throws IOException { private ImmutableSet<Class<? extends Command>> getAllCommandClasses() throws IOException {
ImmutableSet.Builder<Class<? extends Command>> builder = new ImmutableSet.Builder<>(); ImmutableSet.Builder<Class<? extends Command>> builder = new ImmutableSet.Builder<>();
for (ClassInfo classInfo : ClassPath for (ClassInfo classInfo :
.from(getClass().getClassLoader()) ClassPath.from(getClass().getClassLoader())
.getTopLevelClassesRecursive(getPackageName(getClass()))) { .getTopLevelClassesRecursive(getPackageName(getClass()))) {
Class<?> clazz = classInfo.load(); Class<?> clazz = classInfo.load();
if (Command.class.isAssignableFrom(clazz) if (Command.class.isAssignableFrom(clazz)
&& !Modifier.isAbstract(clazz.getModifiers()) && !Modifier.isAbstract(clazz.getModifiers())

View file

@ -39,10 +39,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class CreatePremiumListActionTest { public class CreatePremiumListActionTest {
/*@Rule
public final JpaIntegrationWithCoverageRule jpaRule =
new JpaTestRules.Builder().buildIntegrationWithCoverageRule();*/
@Rule @Rule
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();

View file

@ -41,7 +41,7 @@ import google.registry.testing.AppEngineRule;
import google.registry.testing.DeterministicStringGenerator; import google.registry.testing.DeterministicStringGenerator;
import google.registry.testing.FakeClock; import google.registry.testing.FakeClock;
import google.registry.testing.FakeResponse; import google.registry.testing.FakeResponse;
import google.registry.testing.SystemPropertyRule; import google.registry.testing.SystemPropertyExtension;
import google.registry.ui.server.SendEmailUtils; import google.registry.ui.server.SendEmailUtils;
import google.registry.util.EmailMessage; import google.registry.util.EmailMessage;
import google.registry.util.SendEmailService; import google.registry.util.SendEmailService;
@ -67,7 +67,7 @@ public final class ConsoleOteSetupActionTest {
@RegisterExtension @RegisterExtension
@Order(value = Integer.MAX_VALUE) @Order(value = Integer.MAX_VALUE)
public final SystemPropertyRule systemPropertyRule = new SystemPropertyRule(); final SystemPropertyExtension systemPropertyExtension = new SystemPropertyExtension();
private final FakeResponse response = new FakeResponse(); private final FakeResponse response = new FakeResponse();
private final ConsoleOteSetupAction action = new ConsoleOteSetupAction(); private final ConsoleOteSetupAction action = new ConsoleOteSetupAction();
@ -77,7 +77,7 @@ public final class ConsoleOteSetupActionTest {
@Mock SendEmailService emailService; @Mock SendEmailService emailService;
@BeforeEach @BeforeEach
public void setUp() throws Exception { void beforeEach() throws Exception {
persistPremiumList("default_sandbox_list", "sandbox,USD 1000"); persistPremiumList("default_sandbox_list", "sandbox,USD 1000");
action.req = request; action.req = request;
@ -106,7 +106,7 @@ public final class ConsoleOteSetupActionTest {
} }
@Test @Test
public void testNoUser_redirect() { void testNoUser_redirect() {
when(request.getRequestURI()).thenReturn("/test"); when(request.getRequestURI()).thenReturn("/test");
action.authResult = AuthResult.NOT_AUTHENTICATED; action.authResult = AuthResult.NOT_AUTHENTICATED;
action.run(); action.run();
@ -115,20 +115,20 @@ public final class ConsoleOteSetupActionTest {
} }
@Test @Test
public void testGet_authorized() { void testGet_authorized() {
action.run(); action.run();
assertThat(response.getPayload()).contains("<h1>Setup OT&E</h1>"); assertThat(response.getPayload()).contains("<h1>Setup OT&E</h1>");
assertThat(response.getPayload()).contains("gtag('config', 'sampleId')"); assertThat(response.getPayload()).contains("gtag('config', 'sampleId')");
} }
@Test @Test
public void testGet_authorized_onProduction() { void testGet_authorized_onProduction() {
RegistryEnvironment.PRODUCTION.setup(systemPropertyRule); RegistryEnvironment.PRODUCTION.setup(systemPropertyExtension);
assertThrows(IllegalStateException.class, action::run); assertThrows(IllegalStateException.class, action::run);
} }
@Test @Test
public void testGet_unauthorized() { void testGet_unauthorized() {
action.registrarAccessor = action.registrarAccessor =
AuthenticatedRegistrarAccessor.createForTesting(ImmutableSetMultimap.of()); AuthenticatedRegistrarAccessor.createForTesting(ImmutableSetMultimap.of());
action.run(); action.run();
@ -137,7 +137,7 @@ public final class ConsoleOteSetupActionTest {
} }
@Test @Test
public void testPost_authorized() { void testPost_authorized() {
action.clientId = Optional.of("myclientid"); action.clientId = Optional.of("myclientid");
action.email = Optional.of("contact@registry.example"); action.email = Optional.of("contact@registry.example");
action.method = Method.POST; action.method = Method.POST;
@ -169,7 +169,7 @@ public final class ConsoleOteSetupActionTest {
} }
@Test @Test
public void testPost_authorized_setPassword() { void testPost_authorized_setPassword() {
action.clientId = Optional.of("myclientid"); action.clientId = Optional.of("myclientid");
action.email = Optional.of("contact@registry.example"); action.email = Optional.of("contact@registry.example");
action.optionalPassword = Optional.of("SomePassword"); action.optionalPassword = Optional.of("SomePassword");
@ -187,7 +187,7 @@ public final class ConsoleOteSetupActionTest {
} }
@Test @Test
public void testPost_unauthorized() { void testPost_unauthorized() {
action.registrarAccessor = action.registrarAccessor =
AuthenticatedRegistrarAccessor.createForTesting(ImmutableSetMultimap.of()); AuthenticatedRegistrarAccessor.createForTesting(ImmutableSetMultimap.of());
action.clientId = Optional.of("myclientid"); action.clientId = Optional.of("myclientid");

View file

@ -42,7 +42,7 @@ import google.registry.testing.AppEngineRule;
import google.registry.testing.DeterministicStringGenerator; import google.registry.testing.DeterministicStringGenerator;
import google.registry.testing.FakeClock; import google.registry.testing.FakeClock;
import google.registry.testing.FakeResponse; import google.registry.testing.FakeResponse;
import google.registry.testing.SystemPropertyRule; import google.registry.testing.SystemPropertyExtension;
import google.registry.ui.server.SendEmailUtils; import google.registry.ui.server.SendEmailUtils;
import google.registry.util.EmailMessage; import google.registry.util.EmailMessage;
import google.registry.util.SendEmailService; import google.registry.util.SendEmailService;
@ -68,7 +68,7 @@ public final class ConsoleRegistrarCreatorActionTest {
@RegisterExtension @RegisterExtension
@Order(value = Integer.MAX_VALUE) @Order(value = Integer.MAX_VALUE)
public final SystemPropertyRule systemPropertyRule = new SystemPropertyRule(); final SystemPropertyExtension systemPropertyExtension = new SystemPropertyExtension();
private final FakeResponse response = new FakeResponse(); private final FakeResponse response = new FakeResponse();
private final ConsoleRegistrarCreatorAction action = new ConsoleRegistrarCreatorAction(); private final ConsoleRegistrarCreatorAction action = new ConsoleRegistrarCreatorAction();
@ -78,7 +78,7 @@ public final class ConsoleRegistrarCreatorActionTest {
@Mock SendEmailService emailService; @Mock SendEmailService emailService;
@BeforeEach @BeforeEach
public void setUp() throws Exception { void beforeEach() throws Exception {
persistPremiumList("default_sandbox_list", "sandbox,USD 1000"); persistPremiumList("default_sandbox_list", "sandbox,USD 1000");
action.req = request; action.req = request;
@ -125,7 +125,7 @@ public final class ConsoleRegistrarCreatorActionTest {
} }
@Test @Test
public void testNoUser_redirect() { void testNoUser_redirect() {
when(request.getRequestURI()).thenReturn("/test"); when(request.getRequestURI()).thenReturn("/test");
action.authResult = AuthResult.NOT_AUTHENTICATED; action.authResult = AuthResult.NOT_AUTHENTICATED;
action.run(); action.run();
@ -134,22 +134,22 @@ public final class ConsoleRegistrarCreatorActionTest {
} }
@Test @Test
public void testGet_authorized() { void testGet_authorized() {
action.run(); action.run();
assertThat(response.getPayload()).contains("<h1>Create Registrar</h1>"); assertThat(response.getPayload()).contains("<h1>Create Registrar</h1>");
assertThat(response.getPayload()).contains("gtag('config', 'sampleId')"); assertThat(response.getPayload()).contains("gtag('config', 'sampleId')");
} }
@Test @Test
public void testGet_authorized_onProduction() { void testGet_authorized_onProduction() {
RegistryEnvironment.PRODUCTION.setup(systemPropertyRule); RegistryEnvironment.PRODUCTION.setup(systemPropertyExtension);
action.run(); action.run();
assertThat(response.getPayload()).contains("<h1>Create Registrar</h1>"); assertThat(response.getPayload()).contains("<h1>Create Registrar</h1>");
assertThat(response.getPayload()).contains("gtag('config', 'sampleId')"); assertThat(response.getPayload()).contains("gtag('config', 'sampleId')");
} }
@Test @Test
public void testGet_unauthorized() { void testGet_unauthorized() {
action.registrarAccessor = action.registrarAccessor =
AuthenticatedRegistrarAccessor.createForTesting(ImmutableSetMultimap.of()); AuthenticatedRegistrarAccessor.createForTesting(ImmutableSetMultimap.of());
action.run(); action.run();
@ -158,7 +158,7 @@ public final class ConsoleRegistrarCreatorActionTest {
} }
@Test @Test
public void testPost_authorized_minimalAddress() { void testPost_authorized_minimalAddress() {
action.clientId = Optional.of("myclientid"); action.clientId = Optional.of("myclientid");
action.name = Optional.of("registrar name"); action.name = Optional.of("registrar name");
action.billingAccount = Optional.of("USD=billing-account"); action.billingAccount = Optional.of("USD=billing-account");
@ -226,7 +226,7 @@ public final class ConsoleRegistrarCreatorActionTest {
} }
@Test @Test
public void testPost_authorized_allAddress() { void testPost_authorized_allAddress() {
action.clientId = Optional.of("myclientid"); action.clientId = Optional.of("myclientid");
action.name = Optional.of("registrar name"); action.name = Optional.of("registrar name");
action.billingAccount = Optional.of("USD=billing-account"); action.billingAccount = Optional.of("USD=billing-account");
@ -263,7 +263,7 @@ public final class ConsoleRegistrarCreatorActionTest {
} }
@Test @Test
public void testPost_authorized_multipleBillingLines() { void testPost_authorized_multipleBillingLines() {
action.clientId = Optional.of("myclientid"); action.clientId = Optional.of("myclientid");
action.name = Optional.of("registrar name"); action.name = Optional.of("registrar name");
action.ianaId = Optional.of(12321); action.ianaId = Optional.of(12321);
@ -300,7 +300,7 @@ public final class ConsoleRegistrarCreatorActionTest {
} }
@Test @Test
public void testPost_authorized_repeatingCurrency_fails() { void testPost_authorized_repeatingCurrency_fails() {
action.clientId = Optional.of("myclientid"); action.clientId = Optional.of("myclientid");
action.name = Optional.of("registrar name"); action.name = Optional.of("registrar name");
action.ianaId = Optional.of(12321); action.ianaId = Optional.of(12321);
@ -328,7 +328,7 @@ public final class ConsoleRegistrarCreatorActionTest {
} }
@Test @Test
public void testPost_authorized_badCurrency_fails() { void testPost_authorized_badCurrency_fails() {
action.clientId = Optional.of("myclientid"); action.clientId = Optional.of("myclientid");
action.name = Optional.of("registrar name"); action.name = Optional.of("registrar name");
action.ianaId = Optional.of(12321); action.ianaId = Optional.of(12321);
@ -355,7 +355,7 @@ public final class ConsoleRegistrarCreatorActionTest {
} }
@Test @Test
public void testPost_authorized_badBillingLine_fails() { void testPost_authorized_badBillingLine_fails() {
action.clientId = Optional.of("myclientid"); action.clientId = Optional.of("myclientid");
action.name = Optional.of("registrar name"); action.name = Optional.of("registrar name");
action.ianaId = Optional.of(12321); action.ianaId = Optional.of(12321);
@ -384,7 +384,7 @@ public final class ConsoleRegistrarCreatorActionTest {
} }
@Test @Test
public void testPost_authorized_setPassword() { void testPost_authorized_setPassword() {
action.clientId = Optional.of("myclientid"); action.clientId = Optional.of("myclientid");
action.name = Optional.of("registrar name"); action.name = Optional.of("registrar name");
action.billingAccount = Optional.of("USD=billing-account"); action.billingAccount = Optional.of("USD=billing-account");
@ -413,7 +413,7 @@ public final class ConsoleRegistrarCreatorActionTest {
} }
@Test @Test
public void testPost_badEmailFails() { void testPost_badEmailFails() {
action.clientId = Optional.of("myclientid"); action.clientId = Optional.of("myclientid");
action.name = Optional.of("registrar name"); action.name = Optional.of("registrar name");
action.billingAccount = Optional.of("USD=billing-account"); action.billingAccount = Optional.of("USD=billing-account");
@ -434,7 +434,7 @@ public final class ConsoleRegistrarCreatorActionTest {
} }
@Test @Test
public void testPost_unauthorized() { void testPost_unauthorized() {
action.registrarAccessor = action.registrarAccessor =
AuthenticatedRegistrarAccessor.createForTesting(ImmutableSetMultimap.of()); AuthenticatedRegistrarAccessor.createForTesting(ImmutableSetMultimap.of());
action.clientId = Optional.of("myclientid"); action.clientId = Optional.of("myclientid");

View file

@ -28,21 +28,17 @@ import google.registry.model.registrar.RegistrarContact.Type;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** /**
* Unit tests for contact_settings.js use of {@link RegistrarSettingsAction}. * Unit tests for contact_settings.js use of {@link RegistrarSettingsAction}.
* *
* <p>The default read and session validation tests are handled by the * <p>The default read and session validation tests are handled by the superclass.
* superclass.
*/ */
@RunWith(JUnit4.class) class ContactSettingsTest extends RegistrarSettingsActionTestCase {
public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
@Test @Test
public void testPost_readContacts_success() { void testPost_readContacts_success() {
Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of( Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of(
"op", "read", "op", "read",
"id", CLIENT_ID, "id", CLIENT_ID,
@ -55,7 +51,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testPost_loadSaveRegistrar_success() { void testPost_loadSaveRegistrar_success() {
Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of( Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of(
"op", "update", "op", "update",
"id", CLIENT_ID, "id", CLIENT_ID,
@ -65,7 +61,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testPost_updateContacts_success() throws Exception { void testPost_updateContacts_success() throws Exception {
// Remove all the contacts but one by updating with a list of just it // Remove all the contacts but one by updating with a list of just it
Map<String, Object> adminContact = Map<String, Object> adminContact =
loadRegistrar(CLIENT_ID).getContacts().stream() loadRegistrar(CLIENT_ID).getContacts().stream()
@ -95,7 +91,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testPost_updateContacts_requiredTypes_error() { void testPost_updateContacts_requiredTypes_error() {
Map<String, Object> reqJson = loadRegistrar(CLIENT_ID).toJsonMap(); Map<String, Object> reqJson = loadRegistrar(CLIENT_ID).toJsonMap();
reqJson.put("contacts", ImmutableList.of(techContact.toJsonMap())); reqJson.put("contacts", ImmutableList.of(techContact.toJsonMap()));
Map<String, Object> response = Map<String, Object> response =
@ -110,7 +106,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testPost_updateContacts_requireTechPhone_error() { void testPost_updateContacts_requireTechPhone_error() {
Map<String, Object> reqJson = loadRegistrar(CLIENT_ID).toJsonMap(); Map<String, Object> reqJson = loadRegistrar(CLIENT_ID).toJsonMap();
reqJson.put( reqJson.put(
"contacts", "contacts",
@ -131,7 +127,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testPost_updateContacts_cannotRemoveWhoisAbuseContact_error() { void testPost_updateContacts_cannotRemoveWhoisAbuseContact_error() {
// First make the contact's info visible in whois as abuse contact info. // First make the contact's info visible in whois as abuse contact info.
Registrar registrar = loadRegistrar(CLIENT_ID); Registrar registrar = loadRegistrar(CLIENT_ID);
RegistrarContact rc = RegistrarContact rc =
@ -158,7 +154,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testPost_updateContacts_whoisAbuseContactMustHavePhoneNumber_error() { void testPost_updateContacts_whoisAbuseContactMustHavePhoneNumber_error() {
// First make the contact's info visible in whois as abuse contact info. // First make the contact's info visible in whois as abuse contact info.
Registrar registrar = loadRegistrar(CLIENT_ID); Registrar registrar = loadRegistrar(CLIENT_ID);
RegistrarContact rc = RegistrarContact rc =
@ -185,7 +181,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testSuccess_setRegistryLockPassword() { void testSuccess_setRegistryLockPassword() {
addPasswordToContactTwo(); addPasswordToContactTwo();
String emailAddress = AppEngineRule.makeRegistrarContact2().getEmailAddress(); String emailAddress = AppEngineRule.makeRegistrarContact2().getEmailAddress();
RegistrarContact newContactWithPassword = RegistrarContact newContactWithPassword =
@ -198,7 +194,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testSuccess_setRegistryLockPassword_notOverriddenLater() { void testSuccess_setRegistryLockPassword_notOverriddenLater() {
addPasswordToContactTwo(); addPasswordToContactTwo();
String emailAddress = AppEngineRule.makeRegistrarContact2().getEmailAddress(); String emailAddress = AppEngineRule.makeRegistrarContact2().getEmailAddress();
RegistrarContact newContactWithPassword = RegistrarContact newContactWithPassword =
@ -251,7 +247,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testPost_failure_setRegistryLockPassword_newContact() { void testPost_failure_setRegistryLockPassword_newContact() {
Map<String, Object> reqJson = loadRegistrar(CLIENT_ID).toJsonMap(); Map<String, Object> reqJson = loadRegistrar(CLIENT_ID).toJsonMap();
reqJson.put( reqJson.put(
"contacts", "contacts",
@ -279,7 +275,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testPost_failure_setRegistryLockPassword_notAllowed() { void testPost_failure_setRegistryLockPassword_notAllowed() {
// "allowedToSetRegistryLockPassword" must be set through the back end first // "allowedToSetRegistryLockPassword" must be set through the back end first
// before we can set a password through the UI // before we can set a password through the UI
Map<String, Object> contactMap = AppEngineRule.makeRegistrarContact2().toJsonMap(); Map<String, Object> contactMap = AppEngineRule.makeRegistrarContact2().toJsonMap();
@ -307,7 +303,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testPost_failure_setRegistryLockAllowed() { void testPost_failure_setRegistryLockAllowed() {
// One cannot set the "isAllowedToSetRegistryLockPassword" field through the UI // One cannot set the "isAllowedToSetRegistryLockPassword" field through the UI
Map<String, Object> reqJson = loadRegistrar(CLIENT_ID).toJsonMap(); Map<String, Object> reqJson = loadRegistrar(CLIENT_ID).toJsonMap();
reqJson.put( reqJson.put(
@ -330,7 +326,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testPost_failure_setRegistryLockEmail() { void testPost_failure_setRegistryLockEmail() {
addPasswordToContactTwo(); addPasswordToContactTwo();
Map<String, Object> reqJson = loadRegistrar(CLIENT_ID).toJsonMap(); Map<String, Object> reqJson = loadRegistrar(CLIENT_ID).toJsonMap();
String emailAddress = AppEngineRule.makeRegistrarContact2().getEmailAddress(); String emailAddress = AppEngineRule.makeRegistrarContact2().getEmailAddress();
@ -362,7 +358,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testPost_failure_removingRegistryLockContact() { void testPost_failure_removingRegistryLockContact() {
ImmutableMap<String, String> contact = ImmutableMap<String, String> contact =
ImmutableMap.of( ImmutableMap.of(
"name", "contact1", "name", "contact1",
@ -386,7 +382,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testPost_failure_setRegistryLock_passwordTooShort() { void testPost_failure_setRegistryLock_passwordTooShort() {
techContact = techContact =
persistResource(techContact.asBuilder().setAllowedToSetRegistryLockPassword(true).build()); persistResource(techContact.asBuilder().setAllowedToSetRegistryLockPassword(true).build());
Map<String, Object> contactMap = techContact.toJsonMap(); Map<String, Object> contactMap = techContact.toJsonMap();

View file

@ -36,7 +36,7 @@ import google.registry.model.registrar.Registrar;
import google.registry.request.auth.AuthenticatedRegistrarAccessor; import google.registry.request.auth.AuthenticatedRegistrarAccessor;
import google.registry.request.auth.AuthenticatedRegistrarAccessor.Role; import google.registry.request.auth.AuthenticatedRegistrarAccessor.Role;
import google.registry.testing.CertificateSamples; import google.registry.testing.CertificateSamples;
import google.registry.testing.SystemPropertyRule; import google.registry.testing.SystemPropertyExtension;
import google.registry.testing.TaskQueueHelper.TaskMatcher; import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.util.CidrAddressBlock; import google.registry.util.CidrAddressBlock;
import google.registry.util.EmailMessage; import google.registry.util.EmailMessage;
@ -45,21 +45,18 @@ import java.util.function.BiFunction;
import java.util.function.Function; import java.util.function.Function;
import org.json.simple.JSONValue; import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException; import org.json.simple.parser.ParseException;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
/** Tests for {@link RegistrarSettingsAction}. */ /** Tests for {@link RegistrarSettingsAction}. */
@RunWith(JUnit4.class) class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase {
public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase {
@Rule @RegisterExtension
public final SystemPropertyRule systemPropertyRule = new SystemPropertyRule(); final SystemPropertyExtension systemPropertyExtension = new SystemPropertyExtension();
@Test @Test
public void testSuccess_updateRegistrarInfo_andSendsNotificationEmail() throws Exception { void testSuccess_updateRegistrarInfo_andSendsNotificationEmail() throws Exception {
String expectedEmailBody = loadFile(getClass(), "update_registrar_email.txt"); String expectedEmailBody = loadFile(getClass(), "update_registrar_email.txt");
// This update changes some values on the admin contact and makes it a tech contact as well, // This update changes some values on the admin contact and makes it a tech contact as well,
// while deleting the existing tech contact (by omission). // while deleting the existing tech contact (by omission).
@ -77,7 +74,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
} }
@Test @Test
public void testFailure_updateRegistrarInfo_duplicateContacts() { void testFailure_updateRegistrarInfo_duplicateContacts() {
Map<String, Object> response = action.handleJsonRequest( Map<String, Object> response = action.handleJsonRequest(
readJsonFromFile("update_registrar_duplicate_contacts.json", getLastUpdateTime())); readJsonFromFile("update_registrar_duplicate_contacts.json", getLastUpdateTime()));
assertThat(response).containsExactly( assertThat(response).containsExactly(
@ -94,7 +91,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
* Also relevant if the person's privilege were revoked after the page load. * Also relevant if the person's privilege were revoked after the page load.
*/ */
@Test @Test
public void testFailure_readRegistrarInfo_notAuthorized() { void testFailure_readRegistrarInfo_notAuthorized() {
setUserWithoutAccess(); setUserWithoutAccess();
Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of("id", CLIENT_ID)); Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of("id", CLIENT_ID));
assertThat(response) assertThat(response)
@ -108,7 +105,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
/** This is the default read test for the registrar settings actions. */ /** This is the default read test for the registrar settings actions. */
@Test @Test
public void testSuccess_readRegistrarInfo_authorizedReadWrite() { void testSuccess_readRegistrarInfo_authorizedReadWrite() {
Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of("id", CLIENT_ID)); Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of("id", CLIENT_ID));
assertThat(response) assertThat(response)
.containsExactly( .containsExactly(
@ -119,7 +116,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
} }
@Test @Test
public void testUpdate_emptyJsonObject_errorLastUpdateTimeFieldRequired() { void testUpdate_emptyJsonObject_errorLastUpdateTimeFieldRequired() {
Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap()); Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap());
args.remove("lastUpdateTime"); args.remove("lastUpdateTime");
@ -138,7 +135,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
} }
@Test @Test
public void testUpdate_noEmail_errorEmailFieldRequired() { void testUpdate_noEmail_errorEmailFieldRequired() {
Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap()); Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap());
args.remove("emailAddress"); args.remove("emailAddress");
@ -157,7 +154,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
} }
@Test @Test
public void testFailure_updateRegistrarInfo_notAuthorized() { void testFailure_updateRegistrarInfo_notAuthorized() {
setUserWithoutAccess(); setUserWithoutAccess();
Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of( Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of(
@ -175,7 +172,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
} }
@Test @Test
public void testUpdate_badEmail_errorEmailField() { void testUpdate_badEmail_errorEmailField() {
Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap()); Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap());
args.put("emailAddress", "lolcat"); args.put("emailAddress", "lolcat");
@ -194,7 +191,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
} }
@Test @Test
public void testPost_nonParsableTime_getsAngry() { void testPost_nonParsableTime_getsAngry() {
Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap()); Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap());
args.put("lastUpdateTime", "cookies"); args.put("lastUpdateTime", "cookies");
@ -213,7 +210,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
} }
@Test @Test
public void testPost_nonAsciiCharacters_getsAngry() { void testPost_nonAsciiCharacters_getsAngry() {
Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap()); Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap());
args.put("emailAddress", "ヘ(◕。◕ヘ)@example.com"); args.put("emailAddress", "ヘ(◕。◕ヘ)@example.com");
@ -334,7 +331,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
} }
@Test @Test
public void testUpdate_whoisServer() { void testUpdate_whoisServer() {
doTestUpdate( doTestUpdate(
Role.OWNER, Role.OWNER,
Registrar::getWhoisServer, Registrar::getWhoisServer,
@ -343,24 +340,24 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
} }
@Test @Test
public void testUpdate_phoneNumber() { void testUpdate_phoneNumber() {
doTestUpdate( doTestUpdate(
Role.OWNER, Registrar::getPhoneNumber, "+1.2345678900", Registrar.Builder::setPhoneNumber); Role.OWNER, Registrar::getPhoneNumber, "+1.2345678900", Registrar.Builder::setPhoneNumber);
} }
@Test @Test
public void testUpdate_faxNumber() { void testUpdate_faxNumber() {
doTestUpdate( doTestUpdate(
Role.OWNER, Registrar::getFaxNumber, "+1.2345678900", Registrar.Builder::setFaxNumber); Role.OWNER, Registrar::getFaxNumber, "+1.2345678900", Registrar.Builder::setFaxNumber);
} }
@Test @Test
public void testUpdate_url() { void testUpdate_url() {
doTestUpdate(Role.OWNER, Registrar::getUrl, "new-url.example", Registrar.Builder::setUrl); doTestUpdate(Role.OWNER, Registrar::getUrl, "new-url.example", Registrar.Builder::setUrl);
} }
@Test @Test
public void testUpdate_ipAddressAllowList() { void testUpdate_ipAddressAllowList() {
doTestUpdate( doTestUpdate(
Role.OWNER, Role.OWNER,
Registrar::getIpAddressAllowList, Registrar::getIpAddressAllowList,
@ -369,7 +366,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
} }
@Test @Test
public void testUpdate_clientCertificate() { void testUpdate_clientCertificate() {
doTestUpdate( doTestUpdate(
Role.OWNER, Role.OWNER,
Registrar::getClientCertificate, Registrar::getClientCertificate,
@ -378,7 +375,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
} }
@Test @Test
public void testUpdate_failoverClientCertificate() { void testUpdate_failoverClientCertificate() {
doTestUpdate( doTestUpdate(
Role.OWNER, Role.OWNER,
Registrar::getFailoverClientCertificate, Registrar::getFailoverClientCertificate,
@ -387,7 +384,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
} }
@Test @Test
public void testUpdate_allowedTlds() { void testUpdate_allowedTlds() {
doTestUpdate( doTestUpdate(
Role.ADMIN, Role.ADMIN,
Registrar::getAllowedTlds, Registrar::getAllowedTlds,
@ -396,9 +393,9 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
} }
@Test @Test
public void testUpdate_allowedTlds_failedWhenNoWhoisAbuseContactExists() { void testUpdate_allowedTlds_failedWhenNoWhoisAbuseContactExists() {
setUserAdmin(); setUserAdmin();
RegistryEnvironment.PRODUCTION.setup(systemPropertyRule); RegistryEnvironment.PRODUCTION.setup(systemPropertyExtension);
Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap()); Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap());
args.put("allowedTlds", ImmutableList.of("newtld", "currenttld")); args.put("allowedTlds", ImmutableList.of("newtld", "currenttld"));
@ -419,7 +416,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
} }
@Test @Test
public void testUpdate_allowedTlds_failedWhenTldNotExist() { void testUpdate_allowedTlds_failedWhenTldNotExist() {
setUserAdmin(); setUserAdmin();
Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap()); Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap());
args.put("allowedTlds", ImmutableList.of("invalidtld", "currenttld")); args.put("allowedTlds", ImmutableList.of("invalidtld", "currenttld"));
@ -441,7 +438,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
} }
@Test @Test
public void testUpdate_allowedTlds_failedWhenRemovingTld() { void testUpdate_allowedTlds_failedWhenRemovingTld() {
setUserAdmin(); setUserAdmin();
Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap()); Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap());
args.put("allowedTlds", ImmutableList.of("newtld")); args.put("allowedTlds", ImmutableList.of("newtld"));
@ -463,7 +460,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
} }
@Test @Test
public void testUpdate_allowedTlds_noChange_successWhenUserIsNotAdmin() { void testUpdate_allowedTlds_noChange_successWhenUserIsNotAdmin() {
Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap()); Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap());
args.put("allowedTlds", ImmutableList.of("currenttld")); args.put("allowedTlds", ImmutableList.of("currenttld"));
@ -483,7 +480,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
} }
@Test @Test
public void testUpdate_localizedAddress_city() { void testUpdate_localizedAddress_city() {
doTestUpdate( doTestUpdate(
Role.OWNER, Role.OWNER,
Registrar::getLocalizedAddress, Registrar::getLocalizedAddress,
@ -492,7 +489,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
} }
@Test @Test
public void testUpdate_localizedAddress_countryCode() { void testUpdate_localizedAddress_countryCode() {
doTestUpdate( doTestUpdate(
Role.OWNER, Role.OWNER,
Registrar::getLocalizedAddress, Registrar::getLocalizedAddress,
@ -501,7 +498,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
} }
@Test @Test
public void testUpdate_localizedAddress_state() { void testUpdate_localizedAddress_state() {
doTestUpdate( doTestUpdate(
Role.OWNER, Role.OWNER,
Registrar::getLocalizedAddress, Registrar::getLocalizedAddress,
@ -510,7 +507,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
} }
@Test @Test
public void testUpdate_localizedAddress_street() { void testUpdate_localizedAddress_street() {
doTestUpdate( doTestUpdate(
Role.OWNER, Role.OWNER,
Registrar::getLocalizedAddress, Registrar::getLocalizedAddress,
@ -523,7 +520,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
} }
@Test @Test
public void testUpdate_localizedAddress_zip() { void testUpdate_localizedAddress_zip() {
doTestUpdate( doTestUpdate(
Role.OWNER, Role.OWNER,
Registrar::getLocalizedAddress, Registrar::getLocalizedAddress,

View file

@ -54,25 +54,28 @@ import javax.mail.internet.InternetAddress;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit; import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.MockitoRule; import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
/** Base class for tests using {@link RegistrarSettingsAction}. */ /** Base class for tests using {@link RegistrarSettingsAction}. */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
public abstract class RegistrarSettingsActionTestCase { public abstract class RegistrarSettingsActionTestCase {
static final String CLIENT_ID = "TheRegistrar"; static final String CLIENT_ID = "TheRegistrar";
@Rule @RegisterExtension
public final AppEngineRule appEngine = public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build(); AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@Rule public final InjectRule inject = new InjectRule(); @RegisterExtension public final InjectRule inject = new InjectRule();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@Mock AppEngineServiceUtils appEngineServiceUtils; @Mock AppEngineServiceUtils appEngineServiceUtils;
@Mock HttpServletRequest req; @Mock HttpServletRequest req;
@ -80,13 +83,13 @@ public abstract class RegistrarSettingsActionTestCase {
@Mock SendEmailService emailService; @Mock SendEmailService emailService;
final RegistrarSettingsAction action = new RegistrarSettingsAction(); final RegistrarSettingsAction action = new RegistrarSettingsAction();
final StringWriter writer = new StringWriter(); private final StringWriter writer = new StringWriter();
final FakeClock clock = new FakeClock(DateTime.parse("2014-01-01T00:00:00Z")); final FakeClock clock = new FakeClock(DateTime.parse("2014-01-01T00:00:00Z"));
RegistrarContact techContact; RegistrarContact techContact;
@Before @BeforeEach
public void setUp() throws Exception { public void beforeEachRegistrarSettingsActionTestCase() throws Exception {
// Registrar "TheRegistrar" has access to TLD "currenttld" but not to "newtld". // Registrar "TheRegistrar" has access to TLD "currenttld" but not to "newtld".
createTlds("currenttld", "newtld"); createTlds("currenttld", "newtld");
disallowRegistrarAccess(CLIENT_ID, "newtld"); disallowRegistrarAccess(CLIENT_ID, "newtld");
@ -123,26 +126,26 @@ public abstract class RegistrarSettingsActionTestCase {
RegistrarConsoleMetrics.settingsRequestMetric.reset(); RegistrarConsoleMetrics.settingsRequestMetric.reset();
} }
@After @AfterEach
public void tearDown() { public void afterEach() {
assertThat(RegistrarConsoleMetrics.settingsRequestMetric).hasNoOtherValues(); assertThat(RegistrarConsoleMetrics.settingsRequestMetric).hasNoOtherValues();
} }
public void assertMetric(String clientId, String op, String roles, String status) { void assertMetric(String clientId, String op, String roles, String status) {
assertThat(RegistrarConsoleMetrics.settingsRequestMetric) assertThat(RegistrarConsoleMetrics.settingsRequestMetric)
.hasValueForLabels(1, clientId, op, roles, status); .hasValueForLabels(1, clientId, op, roles, status);
RegistrarConsoleMetrics.settingsRequestMetric.reset(clientId, op, roles, status); RegistrarConsoleMetrics.settingsRequestMetric.reset(clientId, op, roles, status);
} }
/** Sets registrarAccessor.getRegistrar to succeed for CLIENT_ID only. */ /** Sets registrarAccessor.getRegistrar to succeed for CLIENT_ID only. */
protected void setUserWithAccess() { private void setUserWithAccess() {
action.registrarAccessor = action.registrarAccessor =
AuthenticatedRegistrarAccessor.createForTesting( AuthenticatedRegistrarAccessor.createForTesting(
ImmutableSetMultimap.of(CLIENT_ID, OWNER)); ImmutableSetMultimap.of(CLIENT_ID, OWNER));
} }
/** Sets registrarAccessor.getRegistrar to always fail. */ /** Sets registrarAccessor.getRegistrar to always fail. */
protected void setUserWithoutAccess() { void setUserWithoutAccess() {
action.registrarAccessor = action.registrarAccessor =
AuthenticatedRegistrarAccessor.createForTesting(ImmutableSetMultimap.of()); AuthenticatedRegistrarAccessor.createForTesting(ImmutableSetMultimap.of());
} }
@ -150,14 +153,14 @@ public abstract class RegistrarSettingsActionTestCase {
/** /**
* Sets registrarAccessor.getAllClientIdWithRoles to return a map with admin role for CLIENT_ID * Sets registrarAccessor.getAllClientIdWithRoles to return a map with admin role for CLIENT_ID
*/ */
protected void setUserAdmin() { void setUserAdmin() {
action.registrarAccessor = action.registrarAccessor =
AuthenticatedRegistrarAccessor.createForTesting( AuthenticatedRegistrarAccessor.createForTesting(
ImmutableSetMultimap.of(CLIENT_ID, ADMIN)); ImmutableSetMultimap.of(CLIENT_ID, ADMIN));
} }
/** Verifies that the original contact of TheRegistrar is among those notified of a change. */ /** Verifies that the original contact of TheRegistrar is among those notified of a change. */
protected void verifyNotificationEmailsSent() throws Exception { void verifyNotificationEmailsSent() throws Exception {
ArgumentCaptor<EmailMessage> captor = ArgumentCaptor.forClass(EmailMessage.class); ArgumentCaptor<EmailMessage> captor = ArgumentCaptor.forClass(EmailMessage.class);
verify(emailService).sendEmail(captor.capture()); verify(emailService).sendEmail(captor.capture());
Truth.assertThat(captor.getValue().recipients()) Truth.assertThat(captor.getValue().recipients())

View file

@ -27,21 +27,17 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import google.registry.model.registrar.Registrar; import google.registry.model.registrar.Registrar;
import java.util.Map; import java.util.Map;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** /**
* Unit tests for security_settings.js use of {@link RegistrarSettingsAction}. * Unit tests for security_settings.js use of {@link RegistrarSettingsAction}.
* *
* <p>The default read and session validation tests are handled by the * <p>The default read and session validation tests are handled by the superclass.
* superclass.
*/ */
@RunWith(JUnit4.class) class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
public class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
@Test @Test
public void testPost_updateCert_success() throws Exception { void testPost_updateCert_success() throws Exception {
Registrar modified = Registrar modified =
loadRegistrar(CLIENT_ID) loadRegistrar(CLIENT_ID)
.asBuilder() .asBuilder()
@ -59,7 +55,7 @@ public class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testPost_updateCert_failure() { void testPost_updateCert_failure() {
Map<String, Object> reqJson = loadRegistrar(CLIENT_ID).toJsonMap(); Map<String, Object> reqJson = loadRegistrar(CLIENT_ID).toJsonMap();
reqJson.put("clientCertificate", "BLAH"); reqJson.put("clientCertificate", "BLAH");
Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of( Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of(
@ -72,7 +68,7 @@ public class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testChangeCertificates() throws Exception { void testChangeCertificates() throws Exception {
Map<String, Object> jsonMap = loadRegistrar(CLIENT_ID).toJsonMap(); Map<String, Object> jsonMap = loadRegistrar(CLIENT_ID).toJsonMap();
jsonMap.put("clientCertificate", SAMPLE_CERT); jsonMap.put("clientCertificate", SAMPLE_CERT);
jsonMap.put("failoverClientCertificate", null); jsonMap.put("failoverClientCertificate", null);
@ -89,7 +85,7 @@ public class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testChangeFailoverCertificate() throws Exception { void testChangeFailoverCertificate() throws Exception {
Map<String, Object> jsonMap = loadRegistrar(CLIENT_ID).toJsonMap(); Map<String, Object> jsonMap = loadRegistrar(CLIENT_ID).toJsonMap();
jsonMap.put("failoverClientCertificate", SAMPLE_CERT2); jsonMap.put("failoverClientCertificate", SAMPLE_CERT2);
Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of( Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of(
@ -103,7 +99,7 @@ public class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testEmptyOrNullCertificate_doesNotClearOutCurrentOne() throws Exception { void testEmptyOrNullCertificate_doesNotClearOutCurrentOne() throws Exception {
Registrar initialRegistrar = Registrar initialRegistrar =
persistResource( persistResource(
loadRegistrar(CLIENT_ID) loadRegistrar(CLIENT_ID)
@ -126,7 +122,7 @@ public class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testToJsonMap_containsCertificate() { void testToJsonMap_containsCertificate() {
Map<String, Object> jsonMap = Map<String, Object> jsonMap =
loadRegistrar(CLIENT_ID) loadRegistrar(CLIENT_ID)
.asBuilder() .asBuilder()
@ -138,7 +134,7 @@ public class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testToJsonMap_containsFailoverCertificate() { void testToJsonMap_containsFailoverCertificate() {
Map<String, Object> jsonMap = Map<String, Object> jsonMap =
loadRegistrar(CLIENT_ID) loadRegistrar(CLIENT_ID)
.asBuilder() .asBuilder()

View file

@ -23,20 +23,17 @@ import com.google.common.collect.ImmutableMap;
import google.registry.model.registrar.Registrar; import google.registry.model.registrar.Registrar;
import google.registry.model.registrar.RegistrarAddress; import google.registry.model.registrar.RegistrarAddress;
import java.util.Map; import java.util.Map;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** /**
* Unit tests for security_settings.js use of {@link RegistrarSettingsAction}. * Unit tests for security_settings.js use of {@link RegistrarSettingsAction}.
* *
* <p>The default read and session validation tests are handled by the superclass. * <p>The default read and session validation tests are handled by the superclass.
*/ */
@RunWith(JUnit4.class) class WhoisSettingsTest extends RegistrarSettingsActionTestCase {
public class WhoisSettingsTest extends RegistrarSettingsActionTestCase {
@Test @Test
public void testPost_update_success() throws Exception { void testPost_update_success() throws Exception {
Registrar modified = Registrar modified =
loadRegistrar(CLIENT_ID) loadRegistrar(CLIENT_ID)
.asBuilder() .asBuilder()
@ -65,7 +62,7 @@ public class WhoisSettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testPost_badUsStateCode_returnsFormFieldError() { void testPost_badUsStateCode_returnsFormFieldError() {
Registrar modified = Registrar modified =
loadRegistrar(CLIENT_ID) loadRegistrar(CLIENT_ID)
.asBuilder() .asBuilder()
@ -92,7 +89,7 @@ public class WhoisSettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testPost_badAddress_returnsFormFieldError() { void testPost_badAddress_returnsFormFieldError() {
Registrar modified = Registrar modified =
loadRegistrar(CLIENT_ID) loadRegistrar(CLIENT_ID)
.asBuilder() .asBuilder()
@ -120,7 +117,7 @@ public class WhoisSettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
public void testPost_badWhoisServer_returnsFormFieldError() { void testPost_badWhoisServer_returnsFormFieldError() {
Registrar modified = Registrar modified =
loadRegistrar(CLIENT_ID).asBuilder().setWhoisServer("tears@dry.tragical.lol").build(); loadRegistrar(CLIENT_ID).asBuilder().setWhoisServer("tears@dry.tragical.lol").build();
Map<String, Object> response = Map<String, Object> response =

View file

@ -58,7 +58,7 @@ import google.registry.testing.FakeClock;
import google.registry.testing.FakeResponse; import google.registry.testing.FakeResponse;
import google.registry.testing.FakeSleeper; import google.registry.testing.FakeSleeper;
import google.registry.testing.InjectRule; import google.registry.testing.InjectRule;
import google.registry.testing.TestCacheRule; import google.registry.testing.TestCacheExtension;
import google.registry.util.Retrier; import google.registry.util.Retrier;
import google.registry.whois.WhoisMetrics.WhoisMetric; import google.registry.whois.WhoisMetrics.WhoisMetric;
import java.io.IOException; import java.io.IOException;
@ -80,8 +80,8 @@ public class WhoisActionTest {
@RegisterExtension public final InjectRule inject = new InjectRule(); @RegisterExtension public final InjectRule inject = new InjectRule();
@RegisterExtension @RegisterExtension
public final TestCacheRule testCacheRule = public final TestCacheExtension testCacheExtension =
new TestCacheRule.Builder() new TestCacheExtension.Builder()
.withEppResourceCache(Duration.standardDays(1)) .withEppResourceCache(Duration.standardDays(1))
.withForeignIndexKeyCache(Duration.standardDays(1)) .withForeignIndexKeyCache(Duration.standardDays(1))
.build(); .build();