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.reporting.HistoryEntry;
import google.registry.testing.FakeResponse;
import google.registry.testing.SystemPropertyRule;
import google.registry.testing.SystemPropertyExtension;
import google.registry.testing.mapreduce.MapreduceTestCase;
import java.util.Optional;
import java.util.Set;
@ -61,7 +61,8 @@ class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDataActio
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
void beforeEach() {
@ -92,7 +93,7 @@ class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDataActio
action.isDryRun = false;
action.tlds = ImmutableSet.of();
action.registryAdminClientId = "TheRegistrar";
RegistryEnvironment.SANDBOX.setup(systemPropertyRule);
RegistryEnvironment.SANDBOX.setup(systemPropertyExtension);
}
private void runMapreduce() throws Exception {
@ -154,7 +155,7 @@ class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDataActio
@Test
void testFail_givenNonDotTestTldOnProd() {
action.tlds = ImmutableSet.of("example");
RegistryEnvironment.PRODUCTION.setup(systemPropertyRule);
RegistryEnvironment.PRODUCTION.setup(systemPropertyExtension);
IllegalArgumentException thrown =
assertThrows(IllegalArgumentException.class, this::runMapreduce);
assertThat(thrown)

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -19,7 +19,7 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import com.google.common.collect.ImmutableMap;
import google.registry.model.ImmutableObject;
import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import google.registry.schema.replay.EntityTest.EntityForTesting;
import java.math.BigDecimal;
import java.util.Arrays;
@ -38,10 +38,8 @@ import javax.persistence.MapKeyColumn;
import javax.persistence.PostLoad;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/**
* Unit tests for 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
* is 0, which is different from the default scale that {@link BigDecimal} is persisted in database.
*/
@RunWith(JUnit4.class)
public class JodaMoneyConverterTest {
@Rule
public final JpaUnitTestRule jpaRule =
@RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder()
.withEntityClass(TestEntity.class, ComplexTestEntity.class)
.buildUnitTestRule();
@Test
public void roundTripConversion() {
void roundTripConversion() {
Money money = Money.of(CurrencyUnit.USD, 100);
TestEntity entity = new TestEntity(money);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(entity));
@ -94,7 +92,7 @@ public class JodaMoneyConverterTest {
}
@Test
public void roundTripConversionWithComplexEntity() {
void roundTripConversionWithComplexEntity() {
Money myMoney = Money.of(CurrencyUnit.USD, 100);
Money yourMoney = Money.of(CurrencyUnit.GBP, 80);
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.persistence.VKey;
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 javax.persistence.Entity;
import javax.persistence.Id;
@ -33,7 +33,7 @@ import org.junit.jupiter.api.extension.RegisterExtension;
public class LocalDateConverterTest {
@RegisterExtension
public final JpaUnitTestRule jpaRule =
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder()
.withEntityClass(LocalDateConverterTestEntity.class)
.buildUnitTestRule();
@ -41,13 +41,13 @@ public class LocalDateConverterTest {
private final LocalDate exampleDate = LocalDate.parse("2020-06-10", ISODateTimeFormat.date());
@Test
public void testNullInput() {
void testNullInput() {
LocalDateConverterTestEntity retrievedEntity = persistAndLoadTestEntity(null);
assertThat(retrievedEntity.date).isNull();
}
@Test
public void testSaveAndLoad_success() {
void testSaveAndLoad_success() {
LocalDateConverterTestEntity retrievedEntity = persistAndLoadTestEntity(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.WithLongVKey;
import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Test SQL persistence of VKey. */
@RunWith(JUnit4.class)
public class LongVKeyConverterTest {
@Rule
public final JpaUnitTestRule jpaRule =
@RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder()
.withEntityClass(TestEntity.class, VKeyConverter_LongType.class)
.buildUnitTestRule();
@Test
public void testRoundTrip() {
void testRoundTrip() {
TestEntity original = new TestEntity(VKey.createSql(TestEntity.class, 10L));
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 google.registry.model.eppcommon.StatusValue;
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 javax.persistence.Entity;
import javax.persistence.Id;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link StatusValueSetConverter}. */
@RunWith(JUnit4.class)
public class StatusValueSetConverterTest {
@Rule
public final JpaUnitTestRule jpaRule =
@RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule();
@Test
public void testRoundTrip() {
void testRoundTrip() {
Set<StatusValue> enums = ImmutableSet.of(StatusValue.INACTIVE, StatusValue.PENDING_DELETE);
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 google.registry.model.ImmutableObject;
import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NoResultException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link StringListConverter}. */
@RunWith(JUnit4.class)
public class StringListConverterTest {
@Rule
public final JpaUnitTestRule jpaRule =
@RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule();
@Test
public void roundTripConversion_returnsSameStringList() {
void roundTripConversion_returnsSameStringList() {
List<String> tlds = ImmutableList.of("app", "dev", "how");
TestEntity testEntity = new TestEntity(tlds);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
@ -49,7 +47,7 @@ public class StringListConverterTest {
}
@Test
public void testMerge_succeeds() {
void testMerge_succeeds() {
List<String> tlds = ImmutableList.of("app", "dev", "how");
TestEntity testEntity = new TestEntity(tlds);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
@ -63,7 +61,7 @@ public class StringListConverterTest {
}
@Test
public void testNullValue_writesAndReadsNullSuccessfully() {
void testNullValue_writesAndReadsNullSuccessfully() {
TestEntity testEntity = new TestEntity(null);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
TestEntity persisted =
@ -72,7 +70,7 @@ public class StringListConverterTest {
}
@Test
public void testEmptyCollection_writesAndReadsEmptyCollectionSuccessfully() {
void testEmptyCollection_writesAndReadsEmptyCollectionSuccessfully() {
TestEntity testEntity = new TestEntity(ImmutableList.of());
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
TestEntity persisted =
@ -81,7 +79,7 @@ public class StringListConverterTest {
}
@Test
public void testNativeQuery_succeeds() throws Exception {
void testNativeQuery_succeeds() throws Exception {
executeNativeQuery("INSERT INTO \"TestEntity\" (name, tlds) VALUES ('id', '{app, dev}')");
assertThat(

View file

@ -22,21 +22,20 @@ import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import google.registry.model.ImmutableObject;
import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import java.util.Map;
import javax.persistence.Converter;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NoResultException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link StringMapConverterBase}. */
@RunWith(JUnit4.class)
public class StringMapConverterBaseTest {
@Rule
public final JpaTestRules.JpaUnitTestRule jpaRule =
@RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder()
.withInitScript("sql/flyway/V14__load_extension_for_hstore.sql")
.withEntityClass(TestStringMapConverter.class, TestEntity.class)
@ -49,7 +48,7 @@ public class StringMapConverterBaseTest {
new Key("key3"), new Value("value3"));
@Test
public void roundTripConversion_returnsSameMap() {
void roundTripConversion_returnsSameMap() {
TestEntity testEntity = new TestEntity(MAP);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
TestEntity persisted =
@ -58,7 +57,7 @@ public class StringMapConverterBaseTest {
}
@Test
public void testUpdateColumn_succeeds() {
void testUpdateColumn_succeeds() {
TestEntity testEntity = new TestEntity(MAP);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
TestEntity persisted =
@ -72,7 +71,7 @@ public class StringMapConverterBaseTest {
}
@Test
public void testNullValue_writesAndReadsNullSuccessfully() {
void testNullValue_writesAndReadsNullSuccessfully() {
TestEntity testEntity = new TestEntity(null);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
TestEntity persisted =
@ -81,7 +80,7 @@ public class StringMapConverterBaseTest {
}
@Test
public void testEmptyMap_writesAndReadsEmptyCollectionSuccessfully() {
void testEmptyMap_writesAndReadsEmptyCollectionSuccessfully() {
TestEntity testEntity = new TestEntity(ImmutableMap.of());
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
TestEntity persisted =
@ -90,7 +89,7 @@ public class StringMapConverterBaseTest {
}
@Test
public void testNativeQuery_succeeds() {
void testNativeQuery_succeeds() {
executeNativeQuery(
"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 google.registry.model.ImmutableObject;
import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link StringSetConverter}. */
@RunWith(JUnit4.class)
public class StringSetConverterTest {
@Rule
public final JpaUnitTestRule jpaRule =
@RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule();
@Test
public void roundTripConversion_returnsSameStringList() {
void roundTripConversion_returnsSameStringList() {
Set<String> tlds = ImmutableSet.of("app", "dev", "how");
TestEntity testEntity = new TestEntity(tlds);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
@ -47,7 +45,7 @@ public class StringSetConverterTest {
}
@Test
public void testNullValue_writesAndReadsNullSuccessfully() {
void testNullValue_writesAndReadsNullSuccessfully() {
TestEntity testEntity = new TestEntity(null);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
TestEntity persisted =
@ -56,7 +54,7 @@ public class StringSetConverterTest {
}
@Test
public void testEmptyCollection_writesAndReadsEmptyCollectionSuccessfully() {
void testEmptyCollection_writesAndReadsEmptyCollectionSuccessfully() {
TestEntity testEntity = new TestEntity(ImmutableSet.of());
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
TestEntity persisted =

View file

@ -20,28 +20,23 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.
import google.registry.persistence.VKey;
import google.registry.persistence.WithStringVKey;
import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Test SQL persistence of VKey. */
@RunWith(JUnit4.class)
public class StringVKeyConverterTest {
@Rule
public final JpaUnitTestRule jpaRule =
@RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder()
.withEntityClass(TestEntity.class, VKeyConverter_StringType.class)
.buildUnitTestRule();
public StringVKeyConverterTest() {}
@Test
public void testRoundTrip() {
void testRoundTrip() {
TestEntity original =
new TestEntity("TheRealSpartacus", VKey.createSql(TestEntity.class, "ImSpartacus!"));
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.registrar.Registrar.State;
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.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link Enumerated} annotation. */
@RunWith(JUnit4.class)
public class StringValueEnumeratedTest {
@Rule
public final JpaUnitTestRule jpaRule =
@RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule();
@Test
public void roundTripConversion_returnsSameEnum() {
void roundTripConversion_returnsSameEnum() {
TestEntity testEntity = new TestEntity(State.ACTIVE);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(testEntity));
TestEntity persisted =
@ -48,7 +45,7 @@ public class StringValueEnumeratedTest {
}
@Test
public void testNativeQuery_succeeds() {
void testNativeQuery_succeeds() {
TestEntity testEntity = new TestEntity(State.DISABLED);
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.TimedTransition;
import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import java.util.Map;
import javax.persistence.Converter;
import javax.persistence.Entity;
@ -36,10 +36,10 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link TimedTransitionPropertyConverterBase}. */
public class TimedTransitionPropertyConverterBaseTest {
class TimedTransitionPropertyConverterBaseTest {
@RegisterExtension
public final JpaUnitTestRule jpa =
public final JpaUnitTestExtension jpa =
new JpaTestRules.Builder()
.withInitScript("sql/flyway/V14__load_extension_for_hstore.sql")
.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.TldStateTransition;
import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.joda.time.DateTime;
@ -32,10 +32,10 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link TldStateTransitionConverter}. */
public class TldStateTransitionConverterTest {
class TldStateTransitionConverterTest {
@RegisterExtension
public final JpaUnitTestRule jpa =
public final JpaUnitTestExtension jpa =
new JpaTestRules.Builder()
.withInitScript("sql/flyway/V14__load_extension_for_hstore.sql")
.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.UpdateAutoTimestamp;
import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import google.registry.schema.replay.EntityTest.EntityForTesting;
import google.registry.testing.FakeClock;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link UpdateAutoTimestampConverter}. */
@RunWith(JUnit4.class)
public class UpdateAutoTimestampConverterTest {
private final FakeClock fakeClock = new FakeClock();
@Rule
public final JpaUnitTestRule jpaRule =
@RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder()
.withClock(fakeClock)
.withEntityClass(TestEntity.class)
.buildUnitTestRule();
@Test
public void testTypeConversion() {
void testTypeConversion() {
TestEntity ent = new TestEntity("myinst", null);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(ent));
@ -56,7 +53,7 @@ public class UpdateAutoTimestampConverterTest {
}
@Test
public void testTimeChangesOnSubsequentTransactions() {
void testTimeChangesOnSubsequentTransactions() {
TestEntity ent1 = new TestEntity("myinst1", null);
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.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestRule;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.ZonedDateTime;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link ZonedDateTimeConverter}. */
@RunWith(JUnit4.class)
public class ZonedDateTimeConverterTest {
@Rule
public final JpaUnitTestRule jpaRule =
@RegisterExtension
public final JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withEntityClass(TestEntity.class).buildUnitTestRule();
private final ZonedDateTimeConverter converter = new ZonedDateTimeConverter();
@Test
public void convertToDatabaseColumn_returnsNullIfInputIsNull() {
void convertToDatabaseColumn_returnsNullIfInputIsNull() {
assertThat(converter.convertToDatabaseColumn(null)).isNull();
}
@Test
public void convertToDatabaseColumn_convertsCorrectly() {
void convertToDatabaseColumn_convertsCorrectly() {
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2019-09-01T01:01:01Z");
assertThat(converter.convertToDatabaseColumn(zonedDateTime).toInstant())
.isEqualTo(zonedDateTime.toInstant());
}
@Test
public void convertToEntityAttribute_returnsNullIfInputIsNull() {
void convertToEntityAttribute_returnsNullIfInputIsNull() {
assertThat(converter.convertToEntityAttribute(null)).isNull();
}
@Test
public void convertToEntityAttribute_convertsCorrectly() {
void convertToEntityAttribute_convertsCorrectly() {
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2019-09-01T01:01:01Z");
Instant instant = zonedDateTime.toInstant();
assertThat(converter.convertToEntityAttribute(Timestamp.from(instant)))
@ -66,7 +63,7 @@ public class ZonedDateTimeConverterTest {
}
@Test
public void converter_generatesTimestampWithNormalizedZone() {
void converter_generatesTimestampWithNormalizedZone() {
ZonedDateTime zdt = ZonedDateTime.parse("2019-09-01T01:01:01Z");
TestEntity entity = new TestEntity("normalized_utc_time", zdt);
jpaTm().transact(() -> jpaTm().getEntityManager().persist(entity));
@ -78,7 +75,7 @@ public class ZonedDateTimeConverterTest {
}
@Test
public void converter_convertsNonNormalizedZoneCorrectly() {
void converter_convertsNonNormalizedZoneCorrectly() {
ZonedDateTime zdt = ZonedDateTime.parse("2019-09-01T01:01:01Z[UTC]");
TestEntity entity = new TestEntity("non_normalized_utc_time", zdt);
@ -91,7 +88,7 @@ public class ZonedDateTimeConverterTest {
}
@Test
public void converter_convertsNonUtcZoneCorrectly() {
void converter_convertsNonUtcZoneCorrectly() {
ZonedDateTime zdt = ZonedDateTime.parse("2019-09-01T01:01:01+05:00");
TestEntity entity = new TestEntity("new_york_time", zdt);

View file

@ -43,6 +43,7 @@ import org.junit.runners.model.Statement;
* JpaTransactionManager} instances.
*/
public class JpaTestRules {
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.
*/
public static class JpaIntegrationTestRule extends JpaTransactionManagerRule {
private JpaIntegrationTestRule(
Clock clock,
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
* optional init script (which must not be the Nomulus Cloud SQL schema). This rule can also be
* used as am extension for JUnit5 tests.
* JUnit extension for unit tests with JPA framework, when the underlying database is populated by
* the optional init script (which must not be the Nomulus Cloud SQL schema).
*/
public static class JpaUnitTestRule extends JpaTransactionManagerRule
implements BeforeEachCallback, AfterEachCallback {
private JpaUnitTestRule(
public static class JpaUnitTestExtension extends JpaTransactionManagerRule {
private JpaUnitTestExtension(
Clock clock,
Optional<String> initScriptPath,
ImmutableList<Class> extraEntityClasses,
@ -75,13 +76,13 @@ public class JpaTestRules {
}
@Override
public void beforeEach(ExtensionContext context) throws Exception {
this.before();
public void before() {
throw EXCEPTION_OF_DISAPPROVAL;
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
this.after();
public void 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,
* 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) {
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(
!Objects.equals(GOLDEN_SCHEMA_SQL_PATH, initScript),
"Unit tests must not depend on the Nomulus schema.");
return new JpaUnitTestRule(
return new JpaUnitTestExtension(
clock == null ? new FakeClock(DateTime.now(UTC)) : clock,
Optional.ofNullable(initScript),
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 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.PrintStream;
import java.io.UnsupportedEncodingException;
@ -28,23 +28,24 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit test for {@link JpaTestRules.Builder#withSqlLogging()}. */
public class JpaTestRulesSqlLoggingTest {
class JpaTestRulesSqlLoggingTest {
// Entity under test: configured to log SQL statements to Stdout.
@RegisterExtension
JpaUnitTestRule jpaRule = new JpaTestRules.Builder().withSqlLogging().buildUnitTestRule();
JpaUnitTestExtension jpaExtension =
new JpaTestRules.Builder().withSqlLogging().buildUnitTestRule();
private PrintStream orgStdout;
private ByteArrayOutputStream stdoutBuffer;
@BeforeEach
public void beforeEach() {
void beforeEach() {
orgStdout = System.out;
System.setOut(new PrintStream(stdoutBuffer = new ByteArrayOutputStream()));
}
@AfterEach
public void afterEach() {
void afterEach() {
System.setOut(orgStdout);
}

View file

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

View file

@ -31,6 +31,7 @@ import google.registry.persistence.HibernateSchemaExporter;
import google.registry.persistence.NomulusPostgreSql;
import google.registry.persistence.PersistenceModule;
import google.registry.persistence.PersistenceXmlUtility;
import google.registry.persistence.transaction.JpaTestRules.JpaUnitTestExtension;
import google.registry.util.Clock;
import java.io.File;
import java.io.IOException;
@ -55,6 +56,9 @@ import javax.persistence.EntityManagerFactory;
import org.hibernate.cfg.Environment;
import org.hibernate.jpa.boot.internal.ParsedPersistenceXmlDescriptor;
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.testcontainers.containers.JdbcDatabaseContainer;
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
* PostgreSQLContainer}. This class is not for direct use. Use specialized subclasses, {@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
* 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
* 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 =
"google/registry/persistence/transaction/cleanup_database.sql";
private static final String POSTGRES_DB_NAME = "postgres";
@ -191,7 +197,7 @@ abstract class JpaTransactionManagerRule extends ExternalResource {
}
@Override
public void before() throws Exception {
public void beforeEach(ExtensionContext context) throws Exception {
if (entityHash == emfEntityHash) {
checkState(emf != null, "Missing EntityManagerFactory.");
resetTablesAndSequences();
@ -204,11 +210,21 @@ abstract class JpaTransactionManagerRule extends ExternalResource {
}
@Override
public void after() {
public void afterEach(ExtensionContext context) {
TransactionManagerFactory.setJpaTm(Suppliers.ofInstance(cachedTm));
cachedTm = null;
}
@Override
public void before() throws Exception {
beforeEach(null);
}
@Override
public void after() {
afterEach(null);
}
public String getDatabaseUrl() {
return database.getJdbcUrl();
}

View file

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

View file

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

View file

@ -26,12 +26,10 @@ import google.registry.rdap.AbstractJsonableObject.JsonableException;
import google.registry.rdap.AbstractJsonableObject.RestrictJsonNames;
import java.util.Optional;
import org.joda.time.DateTime;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
@RunWith(JUnit4.class)
public final class AbstractJsonableObjectTest {
/** Unit tests for {@link AbstractJsonableObject}. */
final class AbstractJsonableObjectTest {
private final Gson gson = new Gson();
@ -40,7 +38,7 @@ public final class AbstractJsonableObjectTest {
}
@Test
public void testPrimitives() {
void testPrimitives() {
Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement String myString = "Hello, world!";
@JsonableElement int myInt = 42;
@ -53,9 +51,8 @@ public final class AbstractJsonableObjectTest {
"{'myBoolean':false,'myDouble':3.14,'myInt':42,'myString':'Hello, world!'}"));
}
@Test
public void testDateTime() {
void testDateTime() {
Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement DateTime dateTime = DateTime.parse("2019-01-02T13:53Z");
};
@ -63,7 +60,7 @@ public final class AbstractJsonableObjectTest {
}
@Test
public void testRenaming() {
void testRenaming() {
Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement("newName") String myString = "Hello, world!";
};
@ -71,7 +68,7 @@ public final class AbstractJsonableObjectTest {
}
@Test
public void testDuplicateNames_fails() {
void testDuplicateNames_fails() {
Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement String myString = "A";
@JsonableElement("myString") String anotherString = "B";
@ -81,7 +78,7 @@ public final class AbstractJsonableObjectTest {
}
@Test
public void testMethod() {
void testMethod() {
Jsonable jsonable =
new AbstractJsonableObject() {
@JsonableElement String myString() {
@ -92,7 +89,7 @@ public final class AbstractJsonableObjectTest {
}
@Test
public void testMethodWithArguments_fails() {
void testMethodWithArguments_fails() {
Jsonable jsonable =
new AbstractJsonableObject() {
@JsonableElement String myString(String in) {
@ -103,9 +100,8 @@ public final class AbstractJsonableObjectTest {
.hasMessageThat().contains("must have no arguments");
}
@Test
public void testRecursive() {
void testRecursive() {
Jsonable myJsonableObject = new AbstractJsonableObject() {
@JsonableElement double myDouble = 3.14;
@JsonableElement boolean myBoolean = false;
@ -124,7 +120,7 @@ public final class AbstractJsonableObjectTest {
}
@Test
public void testList() {
void testList() {
Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement
ImmutableList<String> myList = ImmutableList.of("my", "immutable", "list");
@ -133,7 +129,7 @@ public final class AbstractJsonableObjectTest {
}
@Test
public void testMultipleLists() {
void testMultipleLists() {
Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement
ImmutableList<String> myList = ImmutableList.of("my", "immutable", "list");
@ -145,7 +141,7 @@ public final class AbstractJsonableObjectTest {
}
@Test
public void testListElements() {
void testListElements() {
Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement
ImmutableList<String> myList = ImmutableList.of("my", "immutable", "list");
@ -159,7 +155,7 @@ public final class AbstractJsonableObjectTest {
}
@Test
public void testListElementsWithoutList() {
void testListElementsWithoutList() {
Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement("myList[]")
Integer myListMeaningOfLife = 42;
@ -170,7 +166,7 @@ public final class AbstractJsonableObjectTest {
}
@Test
public void testListOptionalElements() {
void testListOptionalElements() {
Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement
ImmutableList<String> myList = ImmutableList.of("my", "immutable", "list");
@ -183,7 +179,7 @@ public final class AbstractJsonableObjectTest {
}
@Test
public void testList_sameNameAsElement_failes() {
void testList_sameNameAsElement_failes() {
Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement("myList")
String myString = "A";
@ -211,7 +207,7 @@ public final class AbstractJsonableObjectTest {
}
@Test
public void testRestricted_withAllowedNames() {
void testRestricted_withAllowedNames() {
Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement
JsonableWithNameRestrictions allowed = new JsonableWithNameRestrictions();
@ -225,7 +221,7 @@ public final class AbstractJsonableObjectTest {
}
@Test
public void testRestricted_withWrongName_failes() {
void testRestricted_withWrongName_failes() {
Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement
JsonableWithNameRestrictions wrong = new JsonableWithNameRestrictions();
@ -236,7 +232,7 @@ public final class AbstractJsonableObjectTest {
}
@Test
public void testRestricted_withNoNamesAllowed_fails() {
void testRestricted_withNoNamesAllowed_fails() {
Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement
JsonableWithNoAllowedNames wrong = new JsonableWithNoAllowedNames();
@ -252,14 +248,14 @@ public final class AbstractJsonableObjectTest {
}
@Test
public void testRestricted_withNoNamesAllowed_canBeOutermost() {
void testRestricted_withNoNamesAllowed_canBeOutermost() {
Jsonable jsonable = new JsonableObjectWithNoAllowedNames();
assertThat(jsonable.toJson())
.isEqualTo(createJson("{'key':'value'}"));
}
@Test
public void testRestricted_withNoNamesAllowed_canBeMerged() {
void testRestricted_withNoNamesAllowed_canBeMerged() {
Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement("*") final Jsonable inner = new JsonableObjectWithNoAllowedNames();
@JsonableElement final String otherKey = "otherValue";
@ -283,7 +279,7 @@ public final class AbstractJsonableObjectTest {
}
@Test
public void testInheritingStaticMembers_works() {
void testInheritingStaticMembers_works() {
Jsonable jsonable = new InheritedWithStatic();
assertThat(jsonable.toJson())
.isEqualTo(createJson("{'messages':['message 1','more messages','message 2']}"));
@ -317,7 +313,7 @@ public final class AbstractJsonableObjectTest {
}
@Test
public void testOverriding_works() {
void testOverriding_works() {
Jsonable jsonable = new InheritedOverriding();
assertThat(jsonable.toJson())
.isEqualTo(
@ -330,7 +326,7 @@ public final class AbstractJsonableObjectTest {
}
@Test
public void testMerge_works() {
void testMerge_works() {
Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement String key = "value";
@JsonableElement("*") Object subObject = new AbstractJsonableObject() {
@ -342,7 +338,7 @@ public final class AbstractJsonableObjectTest {
}
@Test
public void testMerge_joinsArrays_works() {
void testMerge_joinsArrays_works() {
Jsonable jsonable = new AbstractJsonableObject() {
@JsonableElement("lst[]") String a = "value";
@JsonableElement("*") Object subObject = new AbstractJsonableObject() {
@ -354,7 +350,7 @@ public final class AbstractJsonableObjectTest {
}
@Test
public void testMerge_multiLayer_works() {
void testMerge_multiLayer_works() {
Jsonable jsonable = new AbstractJsonableObject() {
@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.auth.Auth;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link RdapActionBase}. */
@RunWith(JUnit4.class)
public class RdapActionBaseTest extends RdapActionBaseTestCase<RdapActionBaseTest.RdapTestAction> {
class RdapActionBaseTest extends RdapActionBaseTestCase<RdapActionBaseTest.RdapTestAction> {
public RdapActionBaseTest() {
RdapActionBaseTest() {
super(RdapTestAction.class);
}
@ -72,13 +69,13 @@ public class RdapActionBaseTest extends RdapActionBaseTestCase<RdapActionBaseTes
}
}
@Before
public void setUp() {
@BeforeEach
void beforeEach() {
createTld("thing");
}
@Test
public void testIllegalValue_showsReadableTypeName() {
void testIllegalValue_showsReadableTypeName() {
assertThat(generateActualJson("IllegalArgumentException")).isEqualTo(generateExpectedJsonError(
"Not a valid human-readable string",
400));
@ -86,45 +83,45 @@ public class RdapActionBaseTest extends RdapActionBaseTestCase<RdapActionBaseTes
}
@Test
public void testRuntimeException_returns500Error() {
void testRuntimeException_returns500Error() {
assertThat(generateActualJson("RuntimeException"))
.isEqualTo(generateExpectedJsonError("An error was encountered", 500));
assertThat(response.getStatus()).isEqualTo(500);
}
@Test
public void testValidName_works() {
void testValidName_works() {
assertThat(generateActualJson("no.thing")).isEqualTo(loadJsonFile("rdapjson_toplevel.json"));
assertThat(response.getStatus()).isEqualTo(200);
}
@Test
public void testContentType_rdapjson_utf8() {
void testContentType_rdapjson_utf8() {
generateActualJson("no.thing");
assertThat(response.getContentType().toString())
.isEqualTo("application/rdap+json; charset=utf-8");
}
@Test
public void testHeadRequest_returnsNoContent() {
void testHeadRequest_returnsNoContent() {
assertThat(generateHeadPayload("no.thing")).isEmpty();
assertThat(response.getStatus()).isEqualTo(200);
}
@Test
public void testHeadRequestIllegalValue_returnsNoContent() {
void testHeadRequestIllegalValue_returnsNoContent() {
assertThat(generateHeadPayload("IllegalArgumentException")).isEmpty();
assertThat(response.getStatus()).isEqualTo(400);
}
@Test
public void testRdapServer_allowsAllCrossOriginRequests() {
void testRdapServer_allowsAllCrossOriginRequests() {
generateActualJson("no.thing");
assertThat(response.getHeaders().get(ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("*");
}
@Test
public void testMetrics_onSuccess() {
void testMetrics_onSuccess() {
generateActualJson("no.thing");
verify(rdapMetrics)
.updateMetrics(
@ -143,7 +140,7 @@ public class RdapActionBaseTest extends RdapActionBaseTestCase<RdapActionBaseTes
}
@Test
public void testMetrics_onError() {
void testMetrics_onError() {
generateActualJson("IllegalArgumentException");
verify(rdapMetrics)
.updateMetrics(
@ -162,7 +159,7 @@ public class RdapActionBaseTest extends RdapActionBaseTestCase<RdapActionBaseTes
}
@Test
public void testUnformatted() {
void testUnformatted() {
action.requestPath = actionPath + "no.thing";
action.requestMethod = GET;
action.run();
@ -172,7 +169,7 @@ public class RdapActionBaseTest extends RdapActionBaseTestCase<RdapActionBaseTes
}
@Test
public void testFormatted() {
void testFormatted() {
action.requestPath = actionPath + "no.thing?formatOutput=true";
action.requestMethod = GET;
action.formatOutputParam = Optional.of(true);

View file

@ -39,17 +39,16 @@ import google.registry.util.TypeUtils;
import java.util.HashMap;
import java.util.Optional;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.RegisterExtension;
/** 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();
@Rule
public final InjectRule inject = new InjectRule();
@RegisterExtension public final InjectRule inject = new InjectRule();
protected static final AuthResult AUTH_RESULT =
AuthResult.create(
@ -63,21 +62,21 @@ public abstract class RdapActionBaseTestCase<A extends RdapActionBase> {
protected FakeResponse response = new FakeResponse();
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 final String actionPath;
protected final Class<A> rdapActionClass;
final String actionPath;
private final Class<A> rdapActionClass;
protected RdapActionBaseTestCase(Class<A> rdapActionClass) {
RdapActionBaseTestCase(Class<A> rdapActionClass) {
this.rdapActionClass = rdapActionClass;
this.actionPath = Actions.getPathForAction(rdapActionClass);
}
@Before
public void baseSetUp() {
@BeforeEach
public void beforeEachRdapActionBaseTestCase() {
inject.setStaticField(Ofy.class, "clock", clock);
action = TypeUtils.instantiate(rdapActionClass);
action.includeDeletedParam = Optional.empty();
@ -101,29 +100,27 @@ public abstract class RdapActionBaseTestCase<A extends RdapActionBase> {
metricRole = PUBLIC;
}
protected void loginAsAdmin() {
void loginAsAdmin() {
action.rdapAuthorization = RdapAuthorization.ADMINISTRATOR_AUTHORIZATION;
action.rdapJsonFormatter.rdapAuthorization = action.rdapAuthorization;
metricRole = ADMINISTRATOR;
}
protected JsonObject generateActualJson(String domainName) {
JsonObject generateActualJson(String domainName) {
action.requestPath = actionPath + domainName;
action.requestMethod = GET;
action.run();
return RdapTestHelper.parseJsonObject(response.getPayload());
}
protected String generateHeadPayload(String domainName) {
String generateHeadPayload(String domainName) {
action.requestPath = actionPath + domainName;
action.requestMethod = HEAD;
action.run();
return response.getPayload();
}
protected JsonObject generateExpectedJsonError(
String description,
int code) {
JsonObject generateExpectedJsonError(String description, int code) {
String title;
switch (code) {
case 404:
@ -147,12 +144,15 @@ public abstract class RdapActionBaseTestCase<A extends RdapActionBase> {
}
return RdapTestHelper.loadJsonFile(
"rdap_error.json",
"DESCRIPTION", description,
"TITLE", title,
"CODE", String.valueOf(code));
"DESCRIPTION",
description,
"TITLE",
title,
"CODE",
String.valueOf(code));
}
protected static JsonFileBuilder jsonFileBuilder() {
static JsonFileBuilder jsonFileBuilder() {
return new JsonFileBuilder();
}
@ -173,7 +173,7 @@ public abstract class RdapActionBaseTestCase<A extends RdapActionBase> {
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);
int index = putNextAndReturnIndex(key, value);
for (int i = 0; i < moreKeyValues.length; i += 2) {
@ -182,29 +182,29 @@ public abstract class RdapActionBaseTestCase<A extends RdapActionBase> {
return this;
}
public JsonFileBuilder addDomain(String name, String handle) {
JsonFileBuilder addDomain(String name, String handle) {
return putNext(
"DOMAIN_PUNYCODE_NAME_", Idn.toASCII(name),
"DOMAIN_UNICODE_NAME_", name,
"DOMAIN_HANDLE_", handle);
}
public JsonFileBuilder addNameserver(String name, String handle) {
JsonFileBuilder addNameserver(String name, String handle) {
return putNext(
"NAMESERVER_NAME_", Idn.toASCII(name),
"NAMESERVER_UNICODE_NAME_", name,
"NAMESERVER_HANDLE_", handle);
}
public JsonFileBuilder addRegistrar(String fullName) {
JsonFileBuilder addRegistrar(String fullName) {
return putNext("REGISTRAR_FULL_NAME_", fullName);
}
public JsonFileBuilder addContact(String handle) {
JsonFileBuilder addContact(String handle) {
return putNext("CONTACT_HANDLE_", handle);
}
public JsonFileBuilder setNextQuery(String nextQuery) {
JsonFileBuilder setNextQuery(String 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.Remark;
import org.joda.time.DateTime;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
@RunWith(JUnit4.class)
public final class RdapDataStructuresTest {
/** Unit tests for {@link RdapDataStructures}. */
final class RdapDataStructuresTest {
private void assertRestrictedNames(Object object, String... names) {
assertThat(AbstractJsonableObject.getNameRestriction(object.getClass()).get())
@ -43,7 +41,7 @@ public final class RdapDataStructuresTest {
}
@Test
public void testRdapConformance() {
void testRdapConformance() {
assertThat(RdapConformance.INSTANCE.toJson())
.isEqualTo(createJson(
"[",
@ -54,7 +52,7 @@ public final class RdapDataStructuresTest {
}
@Test
public void testLink() {
void testLink() {
Link link =
Link.builder()
.setHref("myHref")
@ -68,7 +66,7 @@ public final class RdapDataStructuresTest {
}
@Test
public void testNotice() {
void testNotice() {
Notice notice = Notice.builder()
.setDescription("AAA", "BBB")
.setTitle("myTitle")
@ -88,7 +86,7 @@ public final class RdapDataStructuresTest {
}
@Test
public void testRemark() {
void testRemark() {
Remark remark = Remark.builder()
.setDescription("AAA", "BBB")
.setTitle("myTitle")
@ -108,13 +106,13 @@ public final class RdapDataStructuresTest {
}
@Test
public void testLanguage() {
void testLanguage() {
assertThat(LanguageIdentifier.EN.toJson()).isEqualTo(createJson("'en'"));
assertRestrictedNames(LanguageIdentifier.EN, "lang");
}
@Test
public void testEvent() {
void testEvent() {
Event event =
Event.builder()
.setEventAction(EventAction.REGISTRATION)
@ -135,7 +133,7 @@ public final class RdapDataStructuresTest {
}
@Test
public void testEventWithoutActor() {
void testEventWithoutActor() {
EventWithoutActor event =
EventWithoutActor.builder()
.setEventAction(EventAction.REGISTRATION)
@ -154,20 +152,20 @@ public final class RdapDataStructuresTest {
}
@Test
public void testRdapStatus() {
void testRdapStatus() {
assertThat(RdapStatus.ACTIVE.toJson()).isEqualTo(createJson("'active'"));
assertRestrictedNames(RdapStatus.ACTIVE, "status[]");
}
@Test
public void testPort43() {
void testPort43() {
Port43WhoisServer port43 = Port43WhoisServer.create("myServer");
assertThat(port43.toJson()).isEqualTo(createJson("'myServer'"));
assertRestrictedNames(port43, "port43");
}
@Test
public void testPublicId() {
void testPublicId() {
PublicId publicId = PublicId.create(PublicId.Type.IANA_REGISTRAR_ID, "myId");
assertThat(publicId.toJson())
.isEqualTo(createJson("{'identifier':'myId','type':'IANA Registrar ID'}"));
@ -175,7 +173,7 @@ public final class RdapDataStructuresTest {
}
@Test
public void testObjectClassName() {
void testObjectClassName() {
assertThat(ObjectClassName.DOMAIN.toJson()).isEqualTo(createJson("'domain'"));
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.request.Action;
import java.util.Optional;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link RdapDomainAction}. */
@RunWith(JUnit4.class)
public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainAction> {
class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainAction> {
public RdapDomainActionTest() {
RdapDomainActionTest() {
super(RdapDomainAction.class);
}
@Before
public void setUp() {
@BeforeEach
void beforeEach() {
// lol
createTld("lol");
Registrar registrarLol = persistResource(makeRegistrar(
@ -246,7 +243,7 @@ public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainActio
}
@Test
public void testInvalidDomain_returns400() {
void testInvalidDomain_returns400() {
assertThat(generateActualJson("invalid/domain/name"))
.isEqualTo(
generateExpectedJsonError(
@ -257,7 +254,7 @@ public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainActio
}
@Test
public void testUnknownDomain_returns400() {
void testUnknownDomain_returns400() {
assertThat(generateActualJson("missingdomain.com"))
.isEqualTo(
generateExpectedJsonError(
@ -268,45 +265,45 @@ public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainActio
}
@Test
public void testValidDomain_works() {
void testValidDomain_works() {
login("evilregistrar");
assertProperResponseForCatLol("cat.lol", "rdap_domain.json");
}
@Test
public void testValidDomain_asAdministrator_works() {
void testValidDomain_asAdministrator_works() {
loginAsAdmin();
assertProperResponseForCatLol("cat.lol", "rdap_domain.json");
}
@Test
public void testValidDomain_notLoggedIn_noContacts() {
void testValidDomain_notLoggedIn_noContacts() {
assertProperResponseForCatLol("cat.lol", "rdap_domain_no_contacts_with_remark.json");
}
@Test
public void testValidDomain_loggedInAsOtherRegistrar_noContacts() {
void testValidDomain_loggedInAsOtherRegistrar_noContacts() {
login("idnregistrar");
assertProperResponseForCatLol("cat.lol", "rdap_domain_no_contacts_with_remark.json");
}
@Test
public void testUpperCase_ignored() {
void testUpperCase_ignored() {
assertProperResponseForCatLol("CaT.lOl", "rdap_domain_no_contacts_with_remark.json");
}
@Test
public void testTrailingDot_ignored() {
void testTrailingDot_ignored() {
assertProperResponseForCatLol("cat.lol.", "rdap_domain_no_contacts_with_remark.json");
}
@Test
public void testQueryParameter_ignored() {
void testQueryParameter_ignored() {
assertProperResponseForCatLol("cat.lol?key=value", "rdap_domain_no_contacts_with_remark.json");
}
@Test
public void testIdnDomain_works() {
void testIdnDomain_works() {
login("idnregistrar");
assertThat(generateActualJson("cat.みんな"))
.isEqualTo(
@ -324,7 +321,7 @@ public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainActio
}
@Test
public void testIdnDomainWithPercentEncoding_works() {
void testIdnDomainWithPercentEncoding_works() {
login("idnregistrar");
assertThat(generateActualJson("cat.%E3%81%BF%E3%82%93%E3%81%AA"))
.isEqualTo(
@ -342,7 +339,7 @@ public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainActio
}
@Test
public void testPunycodeDomain_works() {
void testPunycodeDomain_works() {
login("idnregistrar");
assertThat(generateActualJson("cat.xn--q9jyb4c"))
.isEqualTo(
@ -360,7 +357,7 @@ public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainActio
}
@Test
public void testMultilevelDomain_works() {
void testMultilevelDomain_works() {
login("1tldregistrar");
assertThat(generateActualJson("cat.1.tld"))
.isEqualTo(
@ -378,37 +375,37 @@ public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainActio
}
// todo (b/27378695): reenable or delete this test
@Ignore
@Disabled
@Test
public void testDomainInTestTld_notFound() {
void testDomainInTestTld_notFound() {
persistResource(Registry.get("lol").asBuilder().setTldType(Registry.TldType.TEST).build());
generateActualJson("cat.lol");
assertThat(response.getStatus()).isEqualTo(404);
}
@Test
public void testDeletedDomain_notFound() {
void testDeletedDomain_notFound() {
assertThat(generateActualJson("dodo.lol"))
.isEqualTo(generateExpectedJsonError("dodo.lol not found", 404));
assertThat(response.getStatus()).isEqualTo(404);
}
@Test
public void testDeletedDomain_notFound_includeDeletedSetFalse() {
void testDeletedDomain_notFound_includeDeletedSetFalse() {
action.includeDeletedParam = Optional.of(true);
generateActualJson("dodo.lol");
assertThat(response.getStatus()).isEqualTo(404);
}
@Test
public void testDeletedDomain_notFound_notLoggedIn() {
void testDeletedDomain_notFound_notLoggedIn() {
action.includeDeletedParam = Optional.of(true);
generateActualJson("dodo.lol");
assertThat(response.getStatus()).isEqualTo(404);
}
@Test
public void testDeletedDomain_notFound_loggedInAsDifferentRegistrar() {
void testDeletedDomain_notFound_loggedInAsDifferentRegistrar() {
login("1tldregistrar");
action.includeDeletedParam = Optional.of(true);
generateActualJson("dodo.lol");
@ -416,7 +413,7 @@ public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainActio
}
@Test
public void testDeletedDomain_works_loggedInAsCorrectRegistrar() {
void testDeletedDomain_works_loggedInAsCorrectRegistrar() {
login("evilregistrar");
action.includeDeletedParam = Optional.of(true);
assertThat(generateActualJson("dodo.lol"))
@ -435,7 +432,7 @@ public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainActio
}
@Test
public void testDeletedDomain_works_loggedInAsAdmin() {
void testDeletedDomain_works_loggedInAsAdmin() {
loginAsAdmin();
action.includeDeletedParam = Optional.of(true);
assertThat(generateActualJson("dodo.lol"))
@ -454,7 +451,7 @@ public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainActio
}
@Test
public void testMetrics() {
void testMetrics() {
generateActualJson("cat.lol");
verify(rdapMetrics)
.updateMetrics(

View file

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

View file

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

View file

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

View file

@ -50,20 +50,17 @@ import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock;
import google.registry.testing.InjectRule;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link RdapJsonFormatter}. */
@RunWith(JUnit4.class)
public class RdapJsonFormatterTest {
class RdapJsonFormatterTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Rule public final InjectRule inject = new InjectRule();
@RegisterExtension public final InjectRule inject = new InjectRule();
private final FakeClock clock = new FakeClock(DateTime.parse("1999-01-01T00:00:00Z"));
@ -83,9 +80,8 @@ public class RdapJsonFormatterTest {
private ContactResource contactResourceTech;
private ContactResource contactResourceNotLinked;
@Before
public void setUp() {
@BeforeEach
void beforeEach() {
inject.setStaticField(Ofy.class, "clock", clock);
rdapJsonFormatter = RdapTestHelper.getTestRdapJsonFormatter(clock);
@ -259,7 +255,7 @@ public class RdapJsonFormatterTest {
clock.nowUtc().minusMonths(3)));
}
public static ImmutableList<RegistrarContact> makeMoreRegistrarContacts(Registrar registrar) {
static ImmutableList<RegistrarContact> makeMoreRegistrarContacts(Registrar registrar) {
return ImmutableList.of(
new RegistrarContact.Builder()
.setParent(registrar)
@ -306,41 +302,41 @@ public class RdapJsonFormatterTest {
}
@Test
public void testRegistrar() {
void testRegistrar() {
assertThat(rdapJsonFormatter.createRdapRegistrarEntity(registrar, OutputDataType.FULL).toJson())
.isEqualTo(loadJson("rdapjson_registrar.json"));
}
@Test
public void testRegistrar_summary() {
void testRegistrar_summary() {
assertThat(
rdapJsonFormatter.createRdapRegistrarEntity(registrar, OutputDataType.SUMMARY).toJson())
.isEqualTo(loadJson("rdapjson_registrar_summary.json"));
}
@Test
public void testHost_ipv4() {
void testHost_ipv4() {
assertThat(
rdapJsonFormatter.createRdapNameserver(hostResourceIpv4, OutputDataType.FULL).toJson())
.isEqualTo(loadJson("rdapjson_host_ipv4.json"));
}
@Test
public void testHost_ipv6() {
void testHost_ipv6() {
assertThat(
rdapJsonFormatter.createRdapNameserver(hostResourceIpv6, OutputDataType.FULL).toJson())
.isEqualTo(loadJson("rdapjson_host_ipv6.json"));
}
@Test
public void testHost_both() {
void testHost_both() {
assertThat(
rdapJsonFormatter.createRdapNameserver(hostResourceBoth, OutputDataType.FULL).toJson())
.isEqualTo(loadJson("rdapjson_host_both.json"));
}
@Test
public void testHost_both_summary() {
void testHost_both_summary() {
assertThat(
rdapJsonFormatter
.createRdapNameserver(hostResourceBoth, OutputDataType.SUMMARY)
@ -349,7 +345,7 @@ public class RdapJsonFormatterTest {
}
@Test
public void testHost_noAddresses() {
void testHost_noAddresses() {
assertThat(
rdapJsonFormatter
.createRdapNameserver(hostResourceNoAddresses, OutputDataType.FULL)
@ -358,7 +354,7 @@ public class RdapJsonFormatterTest {
}
@Test
public void testHost_notLinked() {
void testHost_notLinked() {
assertThat(
rdapJsonFormatter
.createRdapNameserver(hostResourceNotLinked, OutputDataType.FULL)
@ -367,7 +363,7 @@ public class RdapJsonFormatterTest {
}
@Test
public void testHost_superordinateHasPendingTransfer() {
void testHost_superordinateHasPendingTransfer() {
assertThat(
rdapJsonFormatter
.createRdapNameserver(hostResourceSuperordinatePendingTransfer, OutputDataType.FULL)
@ -376,7 +372,7 @@ public class RdapJsonFormatterTest {
}
@Test
public void testRegistrant() {
void testRegistrant() {
assertThat(
rdapJsonFormatter
.createRdapContactEntity(
@ -388,7 +384,7 @@ public class RdapJsonFormatterTest {
}
@Test
public void testRegistrant_summary() {
void testRegistrant_summary() {
assertThat(
rdapJsonFormatter
.createRdapContactEntity(
@ -400,7 +396,7 @@ public class RdapJsonFormatterTest {
}
@Test
public void testRegistrant_loggedOut() {
void testRegistrant_loggedOut() {
rdapJsonFormatter.rdapAuthorization = RdapAuthorization.PUBLIC_AUTHORIZATION;
assertThat(
rdapJsonFormatter
@ -413,7 +409,7 @@ public class RdapJsonFormatterTest {
}
@Test
public void testRegistrant_baseHasNoTrailingSlash() {
void testRegistrant_baseHasNoTrailingSlash() {
// 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
// doesn't help.
@ -432,7 +428,7 @@ public class RdapJsonFormatterTest {
}
@Test
public void testAdmin() {
void testAdmin() {
assertThat(
rdapJsonFormatter
.createRdapContactEntity(
@ -444,7 +440,7 @@ public class RdapJsonFormatterTest {
}
@Test
public void testTech() {
void testTech() {
assertThat(
rdapJsonFormatter
.createRdapContactEntity(
@ -454,7 +450,7 @@ public class RdapJsonFormatterTest {
}
@Test
public void testRolelessContact() {
void testRolelessContact() {
assertThat(
rdapJsonFormatter
.createRdapContactEntity(
@ -464,7 +460,7 @@ public class RdapJsonFormatterTest {
}
@Test
public void testUnlinkedContact() {
void testUnlinkedContact() {
assertThat(
rdapJsonFormatter
.createRdapContactEntity(
@ -474,26 +470,26 @@ public class RdapJsonFormatterTest {
}
@Test
public void testDomain_full() {
void testDomain_full() {
assertThat(rdapJsonFormatter.createRdapDomain(domainBaseFull, OutputDataType.FULL).toJson())
.isEqualTo(loadJson("rdapjson_domain_full.json"));
}
@Test
public void testDomain_summary() {
void testDomain_summary() {
assertThat(rdapJsonFormatter.createRdapDomain(domainBaseFull, OutputDataType.SUMMARY).toJson())
.isEqualTo(loadJson("rdapjson_domain_summary.json"));
}
@Test
public void testDomain_logged_out() {
void testDomain_logged_out() {
rdapJsonFormatter.rdapAuthorization = RdapAuthorization.PUBLIC_AUTHORIZATION;
assertThat(rdapJsonFormatter.createRdapDomain(domainBaseFull, OutputDataType.FULL).toJson())
.isEqualTo(loadJson("rdapjson_domain_logged_out.json"));
}
@Test
public void testDomain_noNameserversNoTransfersMultipleRoleContact() {
void testDomain_noNameserversNoTransfersMultipleRoleContact() {
assertThat(
rdapJsonFormatter
.createRdapDomain(domainBaseNoNameserversNoTransfers, OutputDataType.FULL)
@ -502,7 +498,7 @@ public class RdapJsonFormatterTest {
}
@Test
public void testError() {
void testError() {
assertThat(
RdapObjectClasses.ErrorResponse.create(
SC_BAD_REQUEST, "Invalid Domain Name", "Not a valid domain name")
@ -511,7 +507,7 @@ public class RdapJsonFormatterTest {
}
@Test
public void testTopLevel() {
void testTopLevel() {
assertThat(
TopLevelReplyObject.create(
new ReplyPayloadBase(BoilerplateType.OTHER) {
@ -523,7 +519,7 @@ public class RdapJsonFormatterTest {
}
@Test
public void testTopLevel_domain() {
void testTopLevel_domain() {
assertThat(
TopLevelReplyObject.create(
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.RdapSearchResults.IncompletenessWarningType;
import google.registry.request.Action;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link RdapMetrics}. */
@RunWith(JUnit4.class)
public class RdapMetricsTest {
class RdapMetricsTest {
private final RdapMetrics rdapMetrics = new RdapMetrics();
@Before
public void setUp() {
@BeforeEach
void beforeEach() {
RdapMetrics.requests.reset();
RdapMetrics.responses.reset();
RdapMetrics.numberOfDomainsRetrieved.reset();
@ -58,7 +55,7 @@ public class RdapMetricsTest {
}
@Test
public void testPost() {
void testPost() {
rdapMetrics.updateMetrics(getBuilder().setRequestMethod(Action.Method.POST).build());
assertThat(RdapMetrics.requests)
.hasValueForLabels(1, "DOMAINS", "NO", "NO", "PUBLIC", "POST")
@ -67,7 +64,7 @@ public class RdapMetricsTest {
}
@Test
public void testHead() {
void testHead() {
rdapMetrics.updateMetrics(getBuilder().setRequestMethod(Action.Method.HEAD).build());
assertThat(RdapMetrics.requests)
.hasValueForLabels(1, "DOMAINS", "NO", "NO", "PUBLIC", "HEAD")
@ -76,7 +73,7 @@ public class RdapMetricsTest {
}
@Test
public void testPrefixLength_cappedAt5() {
void testPrefixLength_cappedAt5() {
rdapMetrics.updateMetrics(
getBuilder().setPrefixLength(6).setNumDomainsRetrieved(1).build());
assertThat(RdapMetrics.numberOfDomainsRetrieved)
@ -86,7 +83,7 @@ public class RdapMetricsTest {
}
@Test
public void testIncludeDeleted() {
void testIncludeDeleted() {
rdapMetrics.updateMetrics(getBuilder().setIncludeDeleted(true).build());
assertThat(RdapMetrics.requests)
.hasValueForLabels(1, "DOMAINS", "YES", "NO", "PUBLIC", "GET")
@ -95,7 +92,7 @@ public class RdapMetricsTest {
}
@Test
public void testDesiredRegistrar() {
void testDesiredRegistrar() {
rdapMetrics.updateMetrics(getBuilder().setRegistrarSpecified(true).build());
assertThat(RdapMetrics.requests)
.hasValueForLabels(1, "DOMAINS", "NO", "YES", "PUBLIC", "GET")
@ -104,7 +101,7 @@ public class RdapMetricsTest {
}
@Test
public void testCompleteResultSet() {
void testCompleteResultSet() {
rdapMetrics.updateMetrics(
getBuilder()
.setIncompletenessWarningType(IncompletenessWarningType.COMPLETE)
@ -116,7 +113,7 @@ public class RdapMetricsTest {
}
@Test
public void testTruncatedResultSet() {
void testTruncatedResultSet() {
rdapMetrics.updateMetrics(
getBuilder()
.setIncompletenessWarningType(IncompletenessWarningType.TRUNCATED)
@ -128,7 +125,7 @@ public class RdapMetricsTest {
}
@Test
public void testPossiblyIncompleteResultSet() {
void testPossiblyIncompleteResultSet() {
rdapMetrics.updateMetrics(
getBuilder()
.setIncompletenessWarningType(IncompletenessWarningType.MIGHT_BE_INCOMPLETE)
@ -140,7 +137,7 @@ public class RdapMetricsTest {
}
@Test
public void testPublicRole() {
void testPublicRole() {
rdapMetrics.updateMetrics(getBuilder().setRole(RdapAuthorization.Role.PUBLIC).build());
assertThat(RdapMetrics.requests)
.hasValueForLabels(1, "DOMAINS", "NO", "NO", "PUBLIC", "GET")
@ -149,7 +146,7 @@ public class RdapMetricsTest {
}
@Test
public void testRegistrarRole() {
void testRegistrarRole() {
rdapMetrics.updateMetrics(getBuilder().setRole(RdapAuthorization.Role.REGISTRAR).build());
assertThat(RdapMetrics.requests)
.hasValueForLabels(1, "DOMAINS", "NO", "NO", "REGISTRAR", "GET")
@ -158,7 +155,7 @@ public class RdapMetricsTest {
}
@Test
public void testAdminRole() {
void testAdminRole() {
rdapMetrics.updateMetrics(getBuilder().setRole(RdapAuthorization.Role.ADMINISTRATOR).build());
assertThat(RdapMetrics.requests)
.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. */
@Test
public void testSimpleDomainSearch() {
void testSimpleDomainSearch() {
rdapMetrics.updateMetrics(
getBuilder()
.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.
*/
@Test
public void testDomainSearchByNameserverWithWildcardAndDeleted() {
void testDomainSearchByNameserverWithWildcardAndDeleted() {
rdapMetrics.updateMetrics(
getBuilder()
.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. */
@Test
public void testNoNameserversFound() {
void testNoNameserversFound() {
rdapMetrics.updateMetrics(
getBuilder()
.setEndpointType(EndpointType.NAMESERVERS)
@ -262,7 +259,7 @@ public class RdapMetricsTest {
/** Tests what would happen in an entity search for "Mike*" which found 50 contacts. */
@Test
public void testEntitySearchByNameWithWildcard() {
void testEntitySearchByNameWithWildcard() {
rdapMetrics.updateMetrics(
getBuilder()
.setEndpointType(EndpointType.ENTITIES)

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -37,14 +37,11 @@ import google.registry.model.registry.Registry.TldType;
import google.registry.testing.AppEngineRule;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link UpdateRegistrarRdapBaseUrlsAction}. */
@RunWith(JUnit4.class)
public final class UpdateRegistrarRdapBaseUrlsActionTest {
/**
@ -78,7 +75,7 @@ public final class UpdateRegistrarRdapBaseUrlsActionTest {
+ "],"
+ "\"version\":\"1.0\"}";
@Rule
@RegisterExtension
public AppEngineRule appEngineRule =
new AppEngineRule.Builder().withDatastoreAndCloudSql().build();
@ -89,6 +86,7 @@ public final class UpdateRegistrarRdapBaseUrlsActionTest {
void addNextResponse(MockLowLevelHttpResponse response) {
simulatedResponses.add(response);
}
List<MockLowLevelHttpRequest> getRequestsSent() {
return requestsSent;
}
@ -106,8 +104,8 @@ public final class UpdateRegistrarRdapBaseUrlsActionTest {
private TestHttpTransport httpTransport;
private UpdateRegistrarRdapBaseUrlsAction action;
@Before
public void setUp() {
@BeforeEach
void beforeEach() {
httpTransport = new TestHttpTransport();
action = new UpdateRegistrarRdapBaseUrlsAction();
@ -148,22 +146,22 @@ public final class UpdateRegistrarRdapBaseUrlsActionTest {
String clientId, Long ianaId, Registrar.Type type, String... rdapBaseUrls) {
persistSimpleResource(
new Registrar.Builder()
.setClientId(clientId)
.setRegistrarName(clientId)
.setType(type)
.setIanaIdentifier(ianaId)
.setRdapBaseUrls(ImmutableSet.copyOf(rdapBaseUrls))
.setLocalizedAddress(
new RegistrarAddress.Builder()
.setStreet(ImmutableList.of("123 fake st"))
.setCity("fakeCity")
.setCountryCode("XX")
.build())
.build());
.setClientId(clientId)
.setRegistrarName(clientId)
.setType(type)
.setIanaIdentifier(ianaId)
.setRdapBaseUrls(ImmutableSet.copyOf(rdapBaseUrls))
.setLocalizedAddress(
new RegistrarAddress.Builder()
.setStreet(ImmutableList.of("123 fake st"))
.setCity("fakeCity")
.setCountryCode("XX")
.build())
.build());
}
@Test
public void testUnknownIana_cleared() {
void testUnknownIana_cleared() {
// The IANA ID isn't in the JSON_LIST_REPLY
persistRegistrar("someRegistrar", 4123L, Registrar.Type.REAL, "http://rdap.example/blah");
@ -175,7 +173,7 @@ public final class UpdateRegistrarRdapBaseUrlsActionTest {
}
@Test
public void testKnownIana_changed() {
void testKnownIana_changed() {
// The IANA ID is in the JSON_LIST_REPLY
persistRegistrar("someRegistrar", 1448L, Registrar.Type.REAL, "http://rdap.example/blah");
@ -188,7 +186,7 @@ public final class UpdateRegistrarRdapBaseUrlsActionTest {
}
@Test
public void testKnownIana_notReal_noChange() {
void testKnownIana_notReal_noChange() {
// The IANA ID is in the JSON_LIST_REPLY
persistRegistrar("someRegistrar", 9999L, Registrar.Type.INTERNAL, "http://rdap.example/blah");
@ -201,7 +199,7 @@ public final class UpdateRegistrarRdapBaseUrlsActionTest {
}
@Test
public void testKnownIana_notReal_nullIANA_noChange() {
void testKnownIana_notReal_nullIANA_noChange() {
persistRegistrar("someRegistrar", null, Registrar.Type.TEST, "http://rdap.example/blah");
action.run();
@ -213,7 +211,7 @@ public final class UpdateRegistrarRdapBaseUrlsActionTest {
}
@Test
public void testKnownIana_multipleValues() {
void testKnownIana_multipleValues() {
// The IANA ID is in the JSON_LIST_REPLY
persistRegistrar("registrar4000", 4000L, 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
public void testNoTlds() {
void testNoTlds() {
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.");
}
@Test
public void testOnlyTestTlds() {
void testOnlyTestTlds() {
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.");
}
@Test
public void testSecondTldSucceeds() {
void testSecondTldSucceeds() {
createTld("secondtld");
httpTransport = new TestHttpTransport();
action.httpTransport = httpTransport;
// the first TLD request will return a bad cookie but the second will succeed
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");
httpTransport.addNextResponse(badLoginResponse);
@ -261,25 +262,27 @@ public final class UpdateRegistrarRdapBaseUrlsActionTest {
}
@Test
public void testBothFail() {
void testBothFail() {
createTld("secondtld");
httpTransport = new TestHttpTransport();
action.httpTransport = httpTransport;
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");
// it should fail for both TLDs
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]");
}
@Test
public void testFailureCause_ignoresLoginFailure() {
void testFailureCause_ignoresLoginFailure() {
// Login failures aren't particularly interesting so we should log them, but the final
// throwable should be some other failure if one existed
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.io.CharStreams;
import google.registry.testing.BouncyCastleProviderRule;
import google.registry.testing.BouncyCastleProviderExtension;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
@ -118,7 +118,8 @@ public class BouncyCastleTest {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
@RegisterExtension public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule();
@RegisterExtension
public final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
@Test
void testCompressDecompress() throws Exception {

View file

@ -30,10 +30,10 @@ import com.google.common.io.Files;
import google.registry.gcs.GcsUtils;
import google.registry.keyring.api.Keyring;
import google.registry.testing.AppEngineRule;
import google.registry.testing.BouncyCastleProviderRule;
import google.registry.testing.BouncyCastleProviderExtension;
import google.registry.testing.FakeKeyringModule;
import google.registry.testing.GcsTestingUtils;
import google.registry.testing.GpgSystemCommandRule;
import google.registry.testing.GpgSystemCommandExtension;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@ -61,14 +61,15 @@ public class BrdaCopyActionTest {
private static final GcsFilename SIG_FILE =
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
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@RegisterExtension
public final GpgSystemCommandRule gpg =
new GpgSystemCommandRule(
public final GpgSystemCommandExtension gpg =
new GpgSystemCommandExtension(
RdeTestData.loadBytes("pgp-public-keyring.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.io.CharStreams;
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.GpgSystemCommandRule;
import google.registry.testing.GpgSystemCommandExtension;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
@ -43,11 +43,12 @@ import org.junit.jupiter.params.provider.MethodSource;
/** GnuPG integration tests for {@link Ghostryde}. */
class GhostrydeGpgIntegrationTest {
@RegisterExtension public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule();
@RegisterExtension
public final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
@RegisterExtension
public final GpgSystemCommandRule gpg =
new GpgSystemCommandRule(
public final GpgSystemCommandExtension gpg =
new GpgSystemCommandExtension(
RdeTestData.loadBytes("pgp-public-keyring.asc"),
RdeTestData.loadBytes("pgp-private-keyring-registry.asc"));
@ -59,6 +60,7 @@ class GhostrydeGpgIntegrationTest {
"\0yolo",
"");
@SuppressWarnings("unused")
static Stream<Arguments> provideTestCombinations() {
Stream.Builder<Arguments> stream = Stream.builder();
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.io.ByteStreams;
import google.registry.keyring.api.Keyring;
import google.registry.testing.BouncyCastleProviderRule;
import google.registry.testing.BouncyCastleProviderExtension;
import google.registry.testing.FakeKeyringModule;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@ -50,7 +50,8 @@ import org.junit.jupiter.params.provider.MethodSource;
@SuppressWarnings("resource")
public class GhostrydeTest {
@RegisterExtension public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule();
@RegisterExtension
public final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
private static final ImmutableList<String> CONTENTS =
ImmutableList.of(
@ -60,6 +61,7 @@ public class GhostrydeTest {
"\0yolo",
"");
@SuppressWarnings("unused")
static Stream<Arguments> provideTestCombinations() {
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.NoContentException;
import google.registry.testing.AppEngineRule;
import google.registry.testing.BouncyCastleProviderRule;
import google.registry.testing.BouncyCastleProviderExtension;
import google.registry.testing.FakeClock;
import google.registry.testing.FakeKeyringModule;
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_GOOD_XML = RdeTestData.loadBytes("iirdea_good.xml");
@RegisterExtension public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule();
@RegisterExtension
public final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
@RegisterExtension
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.RequestParameters;
import google.registry.testing.AppEngineRule;
import google.registry.testing.BouncyCastleProviderRule;
import google.registry.testing.BouncyCastleProviderExtension;
import google.registry.testing.FakeClock;
import google.registry.testing.FakeKeyringModule;
import google.registry.testing.FakeResponse;
import google.registry.testing.FakeSleeper;
import google.registry.testing.GpgSystemCommandRule;
import google.registry.testing.GpgSystemCommandExtension;
import google.registry.testing.Lazies;
import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.testing.sftp.SftpServerRule;
@ -116,11 +116,12 @@ public class RdeUploadActionTest {
@TempDir
File folder;
@RegisterExtension public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule();
@RegisterExtension
public final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
@RegisterExtension
public final GpgSystemCommandRule gpg =
new GpgSystemCommandRule(
public final GpgSystemCommandExtension gpg =
new GpgSystemCommandExtension(
RdeTestData.loadBytes("pgp-public-keyring.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.io.ByteStreams;
import google.registry.testing.BouncyCastleProviderRule;
import google.registry.testing.BouncyCastleProviderExtension;
import google.registry.testing.FakeKeyringModule;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@ -36,7 +36,8 @@ import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link RydeEncryption} */
public final class RydeEncryptionTest {
@RegisterExtension public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule();
@RegisterExtension
public final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
@Test
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.io.CharStreams;
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.GpgSystemCommandRule;
import google.registry.testing.GpgSystemCommandExtension;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
@ -49,11 +49,12 @@ public class RydeGpgIntegrationTest {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
@RegisterExtension public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule();
@RegisterExtension
public final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
@RegisterExtension
public final GpgSystemCommandRule gpg =
new GpgSystemCommandRule(
public final GpgSystemCommandExtension gpg =
new GpgSystemCommandExtension(
RdeTestData.loadBytes("pgp-public-keyring.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.JpaIntegrationWithCoverageExtension;
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 java.io.ByteArrayInputStream;
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. */
TemporaryFolder temporaryFolder = new TemporaryFolder();
/**
* Sets up a SQL database when running on JUnit 5. This is for test classes that are not member of
* 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
* class. This is for {@code SqlIntegrationTestSuite} members.
*/
JpaIntegrationWithCoverageExtension jpaIntegrationWithCoverageExtension = null;
private JpaIntegrationWithCoverageExtension jpaIntegrationWithCoverageExtension = null;
JpaUnitTestRule jpaUnitTestRule;
private JpaUnitTestExtension jpaUnitTestRule;
private boolean withDatastore;
private boolean withoutCannedData;
@ -369,10 +371,10 @@ public final class AppEngineRule extends ExternalResource
builder
.withEntityClass(jpaTestEntities.toArray(new Class[jpaTestEntities.size()]))
.buildUnitTestRule();
jpaUnitTestRule.before();
jpaUnitTestRule.beforeEach(context);
} else {
jpaIntegrationTestRule = builder.buildIntegrationTestRule();
jpaIntegrationTestRule.before();
jpaIntegrationTestRule.beforeEach(context);
}
}
if (isWithDatastoreAndCloudSql()) {
@ -387,9 +389,9 @@ public final class AppEngineRule extends ExternalResource
if (enableJpaEntityCoverageCheck) {
jpaIntegrationWithCoverageExtension.afterEach(context);
} else if (withJpaUnitTest) {
jpaUnitTestRule.after();
jpaUnitTestRule.afterEach(context);
} else {
jpaIntegrationTestRule.after();
jpaIntegrationTestRule.afterEach(context);
}
}
after();
@ -603,7 +605,7 @@ public final class AppEngineRule extends ExternalResource
}
/** Create some fake registrars. */
public static void loadInitialData() {
private static void loadInitialData() {
persistSimpleResources(
ImmutableList.of(
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.BeforeEachCallback;
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.
* Normally you would perform this registration in your {@code main()} function.
* <p>This extension is necessary in order to use the {@code "BC"} provider of cryptographic
* functions. Normally you would perform this registration in your {@code main()} function.
*
* @see BouncyCastleProvider
* @see org.junit.rules.ExternalResource
* @see org.junit.jupiter.api.extension.Extension
* @see java.security.Security#addProvider(java.security.Provider)
*/
public class BouncyCastleProviderRule extends ExternalResource
implements BeforeEachCallback, AfterEachCallback {
public class BouncyCastleProviderExtension implements BeforeEachCallback, AfterEachCallback {
@Override
public void beforeEach(ExtensionContext context) {
before();
}
@Override
public void afterEach(ExtensionContext context) {
after();
}
@Override
protected void before() {
Security.addProvider(new BouncyCastleProvider());
}
@Override
protected void after() {
public void afterEach(ExtensionContext context) {
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;
/**
* 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
* integration tests. It reduces a lot of the boilerplate of setting up the shell environment and
* 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 String TEMP_FILE_PREFIX = "gpgtest";
@ -53,8 +53,8 @@ public final class GpgSystemCommandRule implements BeforeEachCallback, AfterEach
private final ByteSource privateKeyring;
private final Runtime runtime = Runtime.getRuntime();
/** Constructs a new {@link GpgSystemCommandRule} instance. */
public GpgSystemCommandRule(ByteSource publicKeyring, ByteSource privateKeyring) {
/** Constructs a new {@link GpgSystemCommandExtension} instance. */
public GpgSystemCommandExtension(ByteSource publicKeyring, ByteSource privateKeyring) {
this.publicKeyring = checkNotNull(publicKeyring, "publicKeyring");
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.BeforeEachCallback;
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
* {@code @Order(value = Integer.MAX_VALUE)} to the extension.
*/
public final class SystemPropertyRule extends ExternalResource
public final class SystemPropertyExtension
implements SystemPropertySetter, BeforeEachCallback, AfterEachCallback {
/** 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)
*/
@Override
public SystemPropertyRule setProperty(String key, @Nullable String value) {
public SystemPropertyExtension setProperty(String key, @Nullable String value) {
originals.computeIfAbsent(
key, k -> new Property(k, Optional.ofNullable(System.getProperty(k))));
Property property = new Property(key, Optional.ofNullable(value));
@ -85,7 +84,7 @@ public final class SystemPropertyRule extends ExternalResource
}
@Override
protected void before() {
public void beforeEach(ExtensionContext context) {
checkState(!isRunning);
for (Property pending : pendings) {
pending.set();
@ -94,19 +93,9 @@ public final class SystemPropertyRule extends ExternalResource
}
@Override
protected void after() {
public void afterEach(ExtensionContext context) {
for (Property original : originals.values()) {
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;
/**
* Sets up caches with desired data expiry for testing and restores their default configurations
* when tests complete.
* A JUnit extension that overloads cache expiry for tests.
*
* <p>This rule is necessary because many caches in the system are singleton and referenced through
* static fields.
*/
public class TestCacheRule implements BeforeEachCallback, AfterEachCallback {
public class TestCacheExtension implements BeforeEachCallback, AfterEachCallback {
private final ImmutableList<TestCacheHandler> cacheHandlers;
private TestCacheRule(ImmutableList<TestCacheHandler> cacheHandlers) {
private TestCacheExtension(ImmutableList<TestCacheHandler> cacheHandlers) {
this.cacheHandlers = cacheHandlers;
}
@ -51,7 +50,7 @@ public class TestCacheRule implements BeforeEachCallback, AfterEachCallback {
cacheHandlers.forEach(TestCacheHandler::after);
}
/** Builder for {@link TestCacheRule}. */
/** Builder for {@link TestCacheExtension}. */
public static class Builder {
private final Map<String, TestCacheHandler> cacheHandlerMap = Maps.newHashMap();
@ -83,8 +82,8 @@ public class TestCacheRule implements BeforeEachCallback, AfterEachCallback {
return this;
}
public TestCacheRule build() {
return new TestCacheRule(ImmutableList.copyOf(cacheHandlerMap.values()));
public TestCacheExtension build() {
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 java.util.Map.Entry;
import org.joda.time.DateTime;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link LordnLog}. */
@RunWith(JUnit4.class)
public class LordnLogTest {
class LordnLogTest {
public static final ImmutableList<String> EXAMPLE_FROM_RFC =
private static final ImmutableList<String> EXAMPLE_FROM_RFC =
ImmutableList.of(
"1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,"
+ "0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,"
@ -37,7 +34,7 @@ public class LordnLogTest {
"roid,result-code",
"SH8013-REP,2000");
public static final ImmutableList<String> EXAMPLE_WITH_WARNINGS =
private static final ImmutableList<String> EXAMPLE_WITH_WARNINGS =
ImmutableList.of(
"1,2014-03-21T15:40:08.4Z,2014-03-21T15:35:28.0Z,"
+ "0000000000000004799,accepted,warnings-present,2",
@ -46,7 +43,7 @@ public class LordnLogTest {
"1580e26-roid,3610");
@Test
public void testSuccess_parseFirstLine() {
void testSuccess_parseFirstLine() {
LordnLog log = LordnLog.parse(EXAMPLE_FROM_RFC);
assertThat(log.getStatus()).isEqualTo(LordnLog.Status.ACCEPTED);
assertThat(log.getLogCreation()).isEqualTo(DateTime.parse("2012-08-16T02:15:00.0Z"));
@ -57,7 +54,7 @@ public class LordnLogTest {
}
@Test
public void testSuccess_parseDnLines() {
void testSuccess_parseDnLines() {
LordnLog log = LordnLog.parse(EXAMPLE_FROM_RFC);
Result result = log.getResult("SH8013-REP");
assertThat(result).isNotNull();
@ -67,7 +64,7 @@ public class LordnLogTest {
}
@Test
public void testSuccess_iterate() {
void testSuccess_iterate() {
for (Entry<String, Result> result : LordnLog.parse(EXAMPLE_FROM_RFC)) {
assertThat(result.getKey()).isEqualTo("SH8013-REP");
assertThat(result.getValue().getCode()).isEqualTo(2000);
@ -77,14 +74,14 @@ public class LordnLogTest {
}
@Test
public void testSuccess_noDnLines() {
void testSuccess_noDnLines() {
LordnLog.parse(ImmutableList.of(
"1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,lolcat,accepted,no-warnings,0",
"roid,result-code"));
}
@Test
public void testFailure_noDnLineMismatch() {
void testFailure_noDnLineMismatch() {
assertThrows(
IllegalArgumentException.class,
() ->
@ -95,17 +92,17 @@ public class LordnLogTest {
}
@Test
public void testFailure_parseNull() {
void testFailure_parseNull() {
assertThrows(NullPointerException.class, () -> LordnLog.parse(null));
}
@Test
public void testFailure_parseEmpty() {
void testFailure_parseEmpty() {
assertThrows(Exception.class, () -> LordnLog.parse(ImmutableList.of()));
}
@Test
public void testFailure_parseMissingHeaderLine() {
void testFailure_parseMissingHeaderLine() {
assertThrows(
Exception.class,
() ->
@ -115,7 +112,7 @@ public class LordnLogTest {
}
@Test
public void testSuccess_toString() {
void testSuccess_toString() {
assertThat(LordnLog.parse(EXAMPLE_WITH_WARNINGS).toString()).isEqualTo(
"LordnLog{"
+ "logId=0000000000000004799, "
@ -132,14 +129,14 @@ public class LordnLogTest {
}
@Test
public void testSuccess_resultToString() {
void testSuccess_resultToString() {
assertThat(
LordnLog.parse(EXAMPLE_FROM_RFC).iterator().next().toString())
.isEqualTo("SH8013-REP=Result{code=2000, outcome=OK, description=OK}");
}
@Test
public void testSuccess_withWarnings() {
void testSuccess_withWarnings() {
LordnLog log = LordnLog.parse(EXAMPLE_WITH_WARNINGS);
assertThat(log.getStatus()).isEqualTo(LordnLog.Status.ACCEPTED);
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.util.Clock;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link LordnTaskUtils}. */
@RunWith(JUnit4.class)
public class LordnTaskUtilsTest {
private static final Clock clock = new FakeClock(DateTime.parse("2010-05-01T10:11:12Z"));
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@Rule
public final InjectRule inject = new InjectRule();
@RegisterExtension public final InjectRule inject = new InjectRule();
@Before
public void before() {
@BeforeEach
void beforeEach() {
createTld("example");
inject.setStaticField(Ofy.class, "clock", clock);
}
@ -68,7 +64,7 @@ public class LordnTaskUtilsTest {
}
@Test
public void test_enqueueDomainBaseTask_sunrise() {
void test_enqueueDomainBaseTask_sunrise() {
persistDomainAndEnqueueLordn(newDomainBuilder().setRepoId("A-EXAMPLE").build());
String expectedPayload =
"A-EXAMPLE,fleece.example,smdzzzz,1,2010-05-01T10:11:12.000Z";
@ -77,7 +73,7 @@ public class LordnTaskUtilsTest {
}
@Test
public void test_enqueueDomainBaseTask_claims() {
void test_enqueueDomainBaseTask_claims() {
DomainBase domain =
newDomainBuilder()
.setRepoId("11-EXAMPLE")
@ -93,7 +89,7 @@ public class LordnTaskUtilsTest {
}
@Test
public void test_oteRegistrarWithNullIanaId() {
void test_oteRegistrarWithNullIanaId() {
tm()
.transact(
() ->
@ -112,7 +108,7 @@ public class LordnTaskUtilsTest {
}
@Test
public void test_enqueueDomainBaseTask_throwsExceptionOnInvalidRegistrar() {
void test_enqueueDomainBaseTask_throwsExceptionOnInvalidRegistrar() {
DomainBase domain =
newDomainBuilder()
.setRepoId("9000-EXAMPLE")
@ -126,7 +122,7 @@ public class LordnTaskUtilsTest {
}
@Test
public void test_enqueueDomainBaseTask_throwsNpeOnNullDomain() {
void test_enqueueDomainBaseTask_throwsNpeOnNullDomain() {
assertThrows(
NullPointerException.class,
() -> tm().transactNew(() -> LordnTaskUtils.enqueueDomainBaseTask(null)));

View file

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

View file

@ -38,51 +38,49 @@ import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeResponse;
import java.net.URL;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.junit.jupiter.MockitoExtension;
/** Unit tests for {@link NordnVerifyAction}. */
@RunWith(JUnit4.class)
public class NordnVerifyActionTest {
@ExtendWith(MockitoExtension.class)
class NordnVerifyActionTest {
private static final String LOG_ACCEPTED = "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,"
+ "0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,accepted,no-warnings,1\n"
+ "roid,result-code\n"
+ "SH8013-REP,2000";
private static final String LOG_ACCEPTED =
"1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,"
+ "0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,accepted,no-warnings,1\n"
+ "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,"
+ "0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,rejected,no-warnings,1\n"
+ "roid,result-code\n"
+ "SH8013-REP,2001";
private static final String LOG_REJECTED =
"1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,"
+ "0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,rejected,no-warnings,1\n"
+ "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,"
+ "0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,accepted,warnings-present,3\n"
+ "roid,result-code\n"
+ "SH8013-REP,2001\n"
+ "lulz-roid,3609\n"
+ "sabokitty-roid,3610\n";
private static final String LOG_WARNINGS =
"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"
+ "SH8013-REP,2001\n"
+ "lulz-roid,3609\n"
+ "sabokitty-roid,3610\n";
private static final String LOG_ERRORS = "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"
+ "SH8013-REP,2000\n"
+ "lulz-roid,4601\n"
+ "bogpog,4611\n";
private static final String LOG_ERRORS =
"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"
+ "SH8013-REP,2000\n"
+ "lulz-roid,4601\n"
+ "bogpog,4611\n";
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@Mock private URLFetchService fetchService;
@Mock private HTTPResponse httpResponse;
@Captor private ArgumentCaptor<HTTPRequest> httpRequestCaptor;
@ -92,8 +90,8 @@ public class NordnVerifyActionTest {
new LordnRequestInitializer(Optional.of("attack"));
private final NordnVerifyAction action = new NordnVerifyAction();
@Before
public void before() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
when(httpResponse.getResponseCode()).thenReturn(SC_OK);
when(httpResponse.getContent()).thenReturn(LOG_ACCEPTED.getBytes(UTF_8));
when(fetchService.fetch(any(HTTPRequest.class))).thenReturn(httpResponse);
@ -112,54 +110,54 @@ public class NordnVerifyActionTest {
}
@Test
public void testSuccess_sendHttpRequest_urlIsCorrect() throws Exception {
void testSuccess_sendHttpRequest_urlIsCorrect() throws Exception {
action.run();
assertThat(getCapturedHttpRequest().getURL()).isEqualTo(new URL("http://127.0.0.1/blobio"));
}
@Test
public void testSuccess_hasLordnPassword_sendsAuthorizationHeader() throws Exception {
void testSuccess_hasLordnPassword_sendsAuthorizationHeader() throws Exception {
action.run();
assertThat(getHeaderFirst(getCapturedHttpRequest(), AUTHORIZATION))
.hasValue("Basic bG9sY2F0OmF0dGFjaw=="); // echo -n lolcat:attack | base64
.hasValue("Basic bG9sY2F0OmF0dGFjaw=="); // echo -n lolcat:attack | base64
}
@Test
public void testSuccess_noLordnPassword_doesntSetAuthorizationHeader() throws Exception {
void testSuccess_noLordnPassword_doesntSetAuthorizationHeader() throws Exception {
action.lordnRequestInitializer = new LordnRequestInitializer(Optional.empty());
action.run();
assertThat(getHeaderFirst(getCapturedHttpRequest(), AUTHORIZATION)).isEmpty();
}
@Test
public void successVerifyRejected() throws Exception {
void successVerifyRejected() throws Exception {
when(httpResponse.getContent()).thenReturn(LOG_REJECTED.getBytes(UTF_8));
LordnLog lastLog = action.verify();
assertThat(lastLog.getStatus()).isEqualTo(LordnLog.Status.REJECTED);
}
@Test
public void successVerifyWarnings() throws Exception {
void successVerifyWarnings() throws Exception {
when(httpResponse.getContent()).thenReturn(LOG_WARNINGS.getBytes(UTF_8));
LordnLog lastLog = action.verify();
assertThat(lastLog.hasWarnings()).isTrue();
}
@Test
public void successVerifyErrors() throws Exception {
void successVerifyErrors() throws Exception {
when(httpResponse.getContent()).thenReturn(LOG_ERRORS.getBytes(UTF_8));
LordnLog lastLog = action.verify();
assertThat(lastLog.hasWarnings()).isTrue();
}
@Test
public void failureVerifyUnauthorized() {
void failureVerifyUnauthorized() {
when(httpResponse.getResponseCode()).thenReturn(SC_UNAUTHORIZED);
assertThrows(Exception.class, action::run);
}
@Test
public void failureVerifyNotReady() {
void failureVerifyNotReady() {
when(httpResponse.getResponseCode()).thenReturn(SC_NO_CONTENT);
ConflictException thrown = assertThrows(ConflictException.class, action::run);
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.FakeClock;
import org.joda.time.DateTime;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link SmdrlCsvParser}. */
@RunWith(JUnit4.class)
public class SmdrlCsvParserTest {
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 static final CharSource SMDRL_LATEST_CSV =
TmchTestData.loadBytes("smdrl-latest.csv").asCharSource(US_ASCII);
@Test
public void testParse() throws Exception {
void testParse() throws Exception {
SignedMarkRevocationList smdrl = SmdrlCsvParser.parse(SMDRL_LATEST_CSV.readLines());
assertThat(smdrl.size()).isEqualTo(150);
assertThat(smdrl.getCreationTime()).isEqualTo(DateTime.parse("2013-11-24T23:30:04.3Z"));
}
@Test
public void testFirstRow() throws Exception {
void testFirstRow() throws Exception {
SignedMarkRevocationList smdrl = SmdrlCsvParser.parse(SMDRL_LATEST_CSV.readLines());
clock.setTo(DateTime.parse("2013-08-09T12:00:00.0Z"));
assertThat(smdrl.isSmdRevoked("0000001681375789102250-65535", clock.nowUtc())).isTrue();
@ -62,7 +58,7 @@ public class SmdrlCsvParserTest {
}
@Test
public void testLastRow() throws Exception {
void testLastRow() throws Exception {
SignedMarkRevocationList smdrl = SmdrlCsvParser.parse(SMDRL_LATEST_CSV.readLines());
clock.setTo(DateTime.parse("2013-08-09T12:00:00.0Z"));
assertThat(smdrl.isSmdRevoked("0000002211373633641407-65535", clock.nowUtc())).isTrue();
@ -73,7 +69,7 @@ public class SmdrlCsvParserTest {
}
@Test
public void testRowWithDifferentDate() throws Exception {
void testRowWithDifferentDate() throws Exception {
SignedMarkRevocationList smdrl = SmdrlCsvParser.parse(SMDRL_LATEST_CSV.readLines());
clock.setTo(DateTime.parse("2013-08-09T12:00:00.0Z"));
assertThat(smdrl.isSmdRevoked("0000002101376042766438-65535", clock.nowUtc())).isFalse();
@ -82,11 +78,13 @@ public class SmdrlCsvParserTest {
}
@Test
public void testOneRow() {
SignedMarkRevocationList smdrl = SmdrlCsvParser.parse(ImmutableList.of(
"1,2013-11-24T23:30:04.3Z",
"smd-id,insertion-datetime",
"0000001681375789102250-65535,2013-08-09T12:00:00.0Z"));
void testOneRow() {
SignedMarkRevocationList smdrl =
SmdrlCsvParser.parse(
ImmutableList.of(
"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.getCreationTime()).isEqualTo(DateTime.parse("2013-11-24T23:30:04.3Z"));
clock.setTo(DateTime.parse("2020-08-09T12:00:00.0Z"));
@ -94,10 +92,10 @@ public class SmdrlCsvParserTest {
}
@Test
public void testEmpty() {
SignedMarkRevocationList smdrl = SmdrlCsvParser.parse(ImmutableList.of(
"1,2014-11-24T23:30:04.3Z",
"smd-id,insertion-datetime"));
void testEmpty() {
SignedMarkRevocationList smdrl =
SmdrlCsvParser.parse(
ImmutableList.of("1,2014-11-24T23:30:04.3Z", "smd-id,insertion-datetime"));
assertThat(smdrl.size()).isEqualTo(0);
assertThat(smdrl.getCreationTime()).isEqualTo(DateTime.parse("2014-11-24T23:30:04.3Z"));
clock.setTo(DateTime.parse("2020-08-09T12:00:00.0Z"));
@ -105,7 +103,7 @@ public class SmdrlCsvParserTest {
}
@Test
public void testFail_badVersion() {
void testFail_badVersion() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@ -119,7 +117,7 @@ public class SmdrlCsvParserTest {
}
@Test
public void testFail_badHeader() {
void testFail_badHeader() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@ -133,7 +131,7 @@ public class SmdrlCsvParserTest {
}
@Test
public void testFail_tooManyColumns() {
void testFail_tooManyColumns() {
IllegalArgumentException thrown =
assertThrows(
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.URLFetchService;
import google.registry.testing.AppEngineRule;
import google.registry.testing.BouncyCastleProviderRule;
import google.registry.testing.BouncyCastleProviderExtension;
import google.registry.testing.FakeClock;
import org.junit.Before;
import org.junit.Rule;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.junit.jupiter.MockitoExtension;
/** Common code for unit tests of classes that extend {@link Marksdb}. */
@RunWith(JUnit4.class)
public abstract class TmchActionTestCase {
@ExtendWith(MockitoExtension.class)
abstract class TmchActionTestCase {
static final String MARKSDB_LOGIN_AND_PASSWORD = "lolcat:attack";
static final String MARKSDB_URL = "http://127.0.0.1/love";
@Rule
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@Rule public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule();
@RegisterExtension
public final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension();
@Mock URLFetchService fetchService;
@Mock HTTPResponse httpResponse;
@ -54,8 +52,8 @@ public abstract class TmchActionTestCase {
final FakeClock clock = new FakeClock();
final Marksdb marksdb = new Marksdb();
@Before
public void commonBefore() throws Exception {
@BeforeEach
public void beforeEachTmchActionTestCase() throws Exception {
marksdb.fetchService = fetchService;
marksdb.tmchMarksdbUrl = MARKSDB_URL;
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.CertificateRevokedException;
import org.joda.time.DateTime;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link TmchCertificateAuthority}. */
@RunWith(JUnit4.class)
public class TmchCertificateAuthorityTest {
class TmchCertificateAuthorityTest {
public 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 GOOD_TEST_CERTIFICATE = loadFile("icann-tmch-test-good.crt");
private static final String REVOKED_TEST_CERTIFICATE = loadFile("icann-tmch-test-revoked.crt");
@Rule
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
private FakeClock clock = new FakeClock(DateTime.parse("2014-01-01T00:00:00Z"));
@Test
public void testFailure_prodRootExpired() {
void testFailure_prodRootExpired() {
TmchCertificateAuthority tmchCertificateAuthority =
new TmchCertificateAuthority(PRODUCTION, clock);
clock.setTo(DateTime.parse("2024-01-01T00:00:00Z"));
@ -59,7 +56,7 @@ public class TmchCertificateAuthorityTest {
}
@Test
public void testFailure_prodRootNotYetValid() {
void testFailure_prodRootNotYetValid() {
TmchCertificateAuthority tmchCertificateAuthority =
new TmchCertificateAuthority(PRODUCTION, clock);
clock.setTo(DateTime.parse("2000-01-01T00:00:00Z"));
@ -70,7 +67,7 @@ public class TmchCertificateAuthorityTest {
}
@Test
public void testFailure_crlDoesntMatchCerts() {
void testFailure_crlDoesntMatchCerts() {
// Use the prod cl, which won't match our test certificate.
TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PILOT, clock);
TmchCrl.set(
@ -83,13 +80,13 @@ public class TmchCertificateAuthorityTest {
}
@Test
public void testSuccess_verify() throws Exception {
void testSuccess_verify() throws Exception {
TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PILOT, clock);
tmchCertificateAuthority.verify(loadCertificate(GOOD_TEST_CERTIFICATE));
}
@Test
public void testFailure_verifySignatureDoesntMatch() {
void testFailure_verifySignatureDoesntMatch() {
TmchCertificateAuthority tmchCertificateAuthority =
new TmchCertificateAuthority(PRODUCTION, clock);
SignatureException e =
@ -100,7 +97,7 @@ public class TmchCertificateAuthorityTest {
}
@Test
public void testFailure_verifyRevoked() {
void testFailure_verifyRevoked() {
TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PILOT, clock);
CertificateRevokedException thrown =
assertThrows(

View file

@ -28,10 +28,10 @@ import java.security.SignatureException;
import java.security.cert.CRLException;
import java.security.cert.CertificateNotYetValidException;
import org.joda.time.DateTime;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link TmchCrlAction}. */
public class TmchCrlActionTest extends TmchActionTestCase {
class TmchCrlActionTest extends TmchActionTestCase {
private TmchCrlAction newTmchCrlAction(TmchCaMode tmchCaMode) throws MalformedURLException {
TmchCrlAction action = new TmchCrlAction();
@ -42,7 +42,7 @@ public class TmchCrlActionTest extends TmchActionTestCase {
}
@Test
public void testSuccess() throws Exception {
void testSuccess() throws Exception {
clock.setTo(DateTime.parse("2013-07-24TZ"));
when(httpResponse.getContent()).thenReturn(
readResourceBytes(TmchCertificateAuthority.class, "icann-tmch.crl").read());
@ -53,7 +53,7 @@ public class TmchCrlActionTest extends TmchActionTestCase {
}
@Test
public void testFailure_crlTooOld() throws Exception {
void testFailure_crlTooOld() throws Exception {
clock.setTo(DateTime.parse("2020-01-01TZ"));
when(httpResponse.getContent())
.thenReturn(loadBytes(TmchCrlActionTest.class, "icann-tmch-pilot-old.crl").read());
@ -67,7 +67,7 @@ public class TmchCrlActionTest extends TmchActionTestCase {
}
@Test
public void testFailure_crlNotSignedByRoot() throws Exception {
void testFailure_crlNotSignedByRoot() throws Exception {
clock.setTo(DateTime.parse("2013-07-24TZ"));
when(httpResponse.getContent())
.thenReturn(readResourceBytes(TmchCertificateAuthority.class, "icann-tmch.crl").read());
@ -77,7 +77,7 @@ public class TmchCrlActionTest extends TmchActionTestCase {
}
@Test
public void testFailure_crlNotYetValid() throws Exception {
void testFailure_crlNotYetValid() throws Exception {
clock.setTo(DateTime.parse("1984-01-01TZ"));
when(httpResponse.getContent()).thenReturn(
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 java.util.Optional;
import org.joda.time.DateTime;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link TmchDnlAction}. */
public class TmchDnlActionTest extends TmchActionTestCase {
class TmchDnlActionTest extends TmchActionTestCase {
private TmchDnlAction newTmchDnlAction() {
TmchDnlAction action = new TmchDnlAction();
@ -36,7 +36,7 @@ public class TmchDnlActionTest extends TmchActionTestCase {
}
@Test
public void testDnl() throws Exception {
void testDnl() throws Exception {
assertThat(ClaimsListShard.get().getClaimKey("xn----7sbejwbn3axu3d")).isEmpty();
when(httpResponse.getContent())
.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 java.util.Optional;
import org.joda.time.DateTime;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/** 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");
@ -38,7 +38,7 @@ public class TmchSmdrlActionTest extends TmchActionTestCase {
}
@Test
public void testSuccess_smdrl() throws Exception {
void testSuccess_smdrl() throws Exception {
SignedMarkRevocationList smdrl = SignedMarkRevocationList.get();
assertThat(smdrl.isSmdRevoked("0000001681375789102250-65535", 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. */
public static byte[] loadSmd(String file) {
static byte[] loadSmd(String file) {
String data = loadFile(file);
return base64()
.decode(

View file

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

View file

@ -28,25 +28,21 @@ import java.security.cert.CertificateNotYetValidException;
import java.security.cert.CertificateRevokedException;
import javax.xml.crypto.dsig.XMLSignatureException;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/**
* Unit tests for {@link TmchXmlSignature}.
*
* <p>This class does not test the {@code revoked/smd/} folder because it's not a crypto issue.
*/
@RunWith(JUnit4.class)
public class TmchXmlSignatureTest {
class TmchXmlSignatureTest {
@Rule
@RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Rule
public final InjectRule inject = new InjectRule();
@RegisterExtension public final InjectRule inject = new InjectRule();
// 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
@ -73,12 +69,11 @@ public class TmchXmlSignatureTest {
private TmchXmlSignature tmchXmlSignature =
new TmchXmlSignature(new TmchCertificateAuthority(TmchCaMode.PILOT, clock));
@Before
public void before() {
}
@BeforeEach
void beforeEach() {}
@Test
public void testWrongCertificateAuthority() {
void testWrongCertificateAuthority() {
tmchXmlSignature =
new TmchXmlSignature(new TmchCertificateAuthority(TmchCaMode.PRODUCTION, clock));
smdData = loadSmd("active/Court-Agent-Arab-Active.smd");
@ -88,231 +83,231 @@ public class TmchXmlSignatureTest {
}
@Test
public void testTimeTravelBeforeCertificateWasCreated() {
void testTimeTravelBeforeCertificateWasCreated() {
smdData = loadSmd("active/Court-Agent-Arab-Active.smd");
clock.setTo(DateTime.parse("2013-05-01T00:00:00Z"));
assertThrows(CertificateNotYetValidException.class, () -> tmchXmlSignature.verify(smdData));
}
@Test
public void testTimeTravelAfterCertificateHasExpired() {
void testTimeTravelAfterCertificateHasExpired() {
smdData = loadSmd("active/Court-Agent-Arab-Active.smd");
clock.setTo(DateTime.parse("2023-06-01T00:00:00Z"));
assertThrows(CertificateExpiredException.class, () -> tmchXmlSignature.verify(smdData));
}
@Test
public void testActiveCourtAgentArabActive() throws Exception {
void testActiveCourtAgentArabActive() throws Exception {
smdData = loadSmd("active/Court-Agent-Arab-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveCourtAgentChineseActive() throws Exception {
void testActiveCourtAgentChineseActive() throws Exception {
smdData = loadSmd("active/Court-Agent-Chinese-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveCourtAgentEnglishActive() throws Exception {
void testActiveCourtAgentEnglishActive() throws Exception {
smdData = loadSmd("active/Court-Agent-English-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveCourtAgentFrenchActive() throws Exception {
void testActiveCourtAgentFrenchActive() throws Exception {
smdData = loadSmd("active/Court-Agent-French-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveCourtAgentRussianActive() throws Exception {
void testActiveCourtAgentRussianActive() throws Exception {
smdData = loadSmd("active/Court-Agent-Russian-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveCourtHolderArabActive() throws Exception {
void testActiveCourtHolderArabActive() throws Exception {
smdData = loadSmd("active/Court-Holder-Arab-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveCourtHolderChineseActive() throws Exception {
void testActiveCourtHolderChineseActive() throws Exception {
smdData = loadSmd("active/Court-Holder-Chinese-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveCourtHolderEnglishActive() throws Exception {
void testActiveCourtHolderEnglishActive() throws Exception {
smdData = loadSmd("active/Court-Holder-English-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveCourtHolderFrenchActive() throws Exception {
void testActiveCourtHolderFrenchActive() throws Exception {
smdData = loadSmd("active/Court-Holder-French-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveCourtHolderRussianActive() throws Exception {
void testActiveCourtHolderRussianActive() throws Exception {
smdData = loadSmd("active/Court-Holder-Russian-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveTrademarkAgentArabActive() throws Exception {
void testActiveTrademarkAgentArabActive() throws Exception {
smdData = loadSmd("active/Trademark-Agent-Arab-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveTrademarkAgentChineseActive() throws Exception {
void testActiveTrademarkAgentChineseActive() throws Exception {
smdData = loadSmd("active/Trademark-Agent-Chinese-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveTrademarkAgentEnglishActive() throws Exception {
void testActiveTrademarkAgentEnglishActive() throws Exception {
smdData = loadSmd("active/Trademark-Agent-English-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveTrademarkAgentFrenchActive() throws Exception {
void testActiveTrademarkAgentFrenchActive() throws Exception {
smdData = loadSmd("active/Trademark-Agent-French-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveTrademarkAgentRussianActive() throws Exception {
void testActiveTrademarkAgentRussianActive() throws Exception {
smdData = loadSmd("active/Trademark-Agent-Russian-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveTrademarkHolderArabActive() throws Exception {
void testActiveTrademarkHolderArabActive() throws Exception {
smdData = loadSmd("active/Trademark-Holder-Arab-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveTrademarkHolderChineseActive() throws Exception {
void testActiveTrademarkHolderChineseActive() throws Exception {
smdData = loadSmd("active/Trademark-Holder-Chinese-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveTrademarkHolderEnglishActive() throws Exception {
void testActiveTrademarkHolderEnglishActive() throws Exception {
smdData = loadSmd("active/Trademark-Holder-English-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveTrademarkHolderFrenchActive() throws Exception {
void testActiveTrademarkHolderFrenchActive() throws Exception {
smdData = loadSmd("active/Trademark-Holder-French-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveTrademarkHolderRussianActive() throws Exception {
void testActiveTrademarkHolderRussianActive() throws Exception {
smdData = loadSmd("active/Trademark-Holder-Russian-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveTreatystatuteAgentArabActive() throws Exception {
void testActiveTreatystatuteAgentArabActive() throws Exception {
smdData = loadSmd("active/TreatyStatute-Agent-Arab-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveTreatystatuteAgentChineseActive() throws Exception {
void testActiveTreatystatuteAgentChineseActive() throws Exception {
smdData = loadSmd("active/TreatyStatute-Agent-Chinese-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveTreatystatuteAgentEnglishActive() throws Exception {
void testActiveTreatystatuteAgentEnglishActive() throws Exception {
smdData = loadSmd("active/TreatyStatute-Agent-English-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveTreatystatuteAgentFrenchActive() throws Exception {
void testActiveTreatystatuteAgentFrenchActive() throws Exception {
smdData = loadSmd("active/TreatyStatute-Agent-French-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveTreatystatuteAgentRussianActive() throws Exception {
void testActiveTreatystatuteAgentRussianActive() throws Exception {
smdData = loadSmd("active/TreatyStatute-Agent-Russian-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveTreatystatuteHolderArabActive() throws Exception {
void testActiveTreatystatuteHolderArabActive() throws Exception {
smdData = loadSmd("active/TreatyStatute-Holder-Arab-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveTreatystatuteHolderChineseActive() throws Exception {
void testActiveTreatystatuteHolderChineseActive() throws Exception {
smdData = loadSmd("active/TreatyStatute-Holder-Chinese-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveTreatystatuteHolderEnglishActive() throws Exception {
void testActiveTreatystatuteHolderEnglishActive() throws Exception {
smdData = loadSmd("active/TreatyStatute-Holder-English-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveTreatystatuteHolderFrenchActive() throws Exception {
void testActiveTreatystatuteHolderFrenchActive() throws Exception {
smdData = loadSmd("active/TreatyStatute-Holder-French-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testActiveTreatystatuteHolderRussianActive() throws Exception {
void testActiveTreatystatuteHolderRussianActive() throws Exception {
smdData = loadSmd("active/TreatyStatute-Holder-Russian-Active.smd");
tmchXmlSignature.verify(smdData);
}
@Test
public void testInvalidInvalidsignatureCourtAgentFrenchActive() {
void testInvalidInvalidsignatureCourtAgentFrenchActive() {
smdData = loadSmd("invalid/InvalidSignature-Court-Agent-French-Active.smd");
assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData));
}
@Test
public void testInvalidInvalidsignatureTrademarkAgentEnglishActive() {
void testInvalidInvalidsignatureTrademarkAgentEnglishActive() {
smdData = loadSmd("invalid/InvalidSignature-Trademark-Agent-English-Active.smd");
assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData));
}
@Test
public void testInvalidInvalidsignatureTrademarkAgentRussianActive() {
void testInvalidInvalidsignatureTrademarkAgentRussianActive() {
smdData = loadSmd("invalid/InvalidSignature-Trademark-Agent-Russian-Active.smd");
assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData));
}
@Test
public void testInvalidInvalidsignatureTreatystatuteAgentChineseActive() {
void testInvalidInvalidsignatureTreatystatuteAgentChineseActive() {
smdData = loadSmd("invalid/InvalidSignature-TreatyStatute-Agent-Chinese-Active.smd");
assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData));
}
@Test
public void testInvalidInvalidsignatureTreatystatuteAgentEnglishActive() {
void testInvalidInvalidsignatureTreatystatuteAgentEnglishActive() {
smdData = loadSmd("invalid/InvalidSignature-TreatyStatute-Agent-English-Active.smd");
assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData));
}
@Test
public void testRevokedTmvTmvrevokedCourtAgentFrenchActive() {
void testRevokedTmvTmvrevokedCourtAgentFrenchActive() {
smdData = loadSmd("revoked/tmv/TMVRevoked-Court-Agent-French-Active.smd");
CertificateRevokedException e =
assertThrows(CertificateRevokedException.class, () -> tmchXmlSignature.verify(smdData));
@ -320,7 +315,7 @@ public class TmchXmlSignatureTest {
}
@Test
public void testRevokedTmvTmvrevokedTrademarkAgentEnglishActive() {
void testRevokedTmvTmvrevokedTrademarkAgentEnglishActive() {
smdData = loadSmd("revoked/tmv/TMVRevoked-Trademark-Agent-English-Active.smd");
CertificateRevokedException e =
assertThrows(CertificateRevokedException.class, () -> tmchXmlSignature.verify(smdData));
@ -328,7 +323,7 @@ public class TmchXmlSignatureTest {
}
@Test
public void testRevokedTmvTmvrevokedTrademarkAgentRussianActive() {
void testRevokedTmvTmvrevokedTrademarkAgentRussianActive() {
smdData = loadSmd("revoked/tmv/TMVRevoked-Trademark-Agent-Russian-Active.smd");
CertificateRevokedException e =
assertThrows(CertificateRevokedException.class, () -> tmchXmlSignature.verify(smdData));
@ -336,7 +331,7 @@ public class TmchXmlSignatureTest {
}
@Test
public void testRevokedTmvTmvrevokedTreatystatuteAgentChineseActive() {
void testRevokedTmvTmvrevokedTreatystatuteAgentChineseActive() {
smdData = loadSmd("revoked/tmv/TMVRevoked-TreatyStatute-Agent-Chinese-Active.smd");
CertificateRevokedException e =
assertThrows(CertificateRevokedException.class, () -> tmchXmlSignature.verify(smdData));
@ -344,7 +339,7 @@ public class TmchXmlSignatureTest {
}
@Test
public void testRevokedTmvTmvrevokedTreatystatuteAgentEnglishActive() {
void testRevokedTmvTmvrevokedTreatystatuteAgentEnglishActive() {
smdData = loadSmd("revoked/tmv/TMVRevoked-TreatyStatute-Agent-English-Active.smd");
CertificateRevokedException e =
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.CertificateSamples;
import google.registry.testing.FakeClock;
import google.registry.testing.SystemPropertyRule;
import google.registry.testing.SystemPropertyExtension;
import google.registry.tools.params.ParameterFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@ -76,14 +76,15 @@ public abstract class CommandTestCase<C extends Command> {
.withTaskQueue()
.build();
@RegisterExtension final SystemPropertyRule systemPropertyRule = new SystemPropertyRule();
@RegisterExtension
final SystemPropertyExtension systemPropertyExtension = new SystemPropertyExtension();
@TempDir public Path tmpDir;
@BeforeEach
public final void beforeEachCommandTestCase() throws Exception {
// Ensure the UNITTEST environment has been set before constructing a new command instance.
RegistryToolEnvironment.UNITTEST.setup(systemPropertyRule);
RegistryToolEnvironment.UNITTEST.setup(systemPropertyExtension);
command = newCommandInstance();
// 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 {
env.setup(systemPropertyRule);
env.setup(systemPropertyExtension);
try {
JCommander jcommander = new JCommander(command);
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.
ofy().clearSessionCache();
// 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.Files;
import google.registry.rde.RdeTestData;
import google.registry.testing.BouncyCastleProviderRule;
import google.registry.testing.BouncyCastleProviderExtension;
import google.registry.testing.FakeKeyringModule;
import java.nio.file.Path;
import org.junit.jupiter.api.BeforeEach;
@ -31,7 +31,8 @@ import org.junit.jupiter.api.extension.RegisterExtension;
public class EncryptEscrowDepositCommandTest
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");

View file

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

View file

@ -17,14 +17,15 @@ package google.registry.tools;
import static com.google.common.truth.Truth.assertThat;
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.extension.RegisterExtension;
/** Unit tests for {@link RegistryToolEnvironment}. */
class RegistryToolEnvironmentTest {
@RegisterExtension final SystemPropertyRule systemPropertyRule = new SystemPropertyRule();
@RegisterExtension
final SystemPropertyExtension systemPropertyExtension = new SystemPropertyExtension();
@Test
void testGet_withoutSetup_throws() {
@ -34,10 +35,10 @@ class RegistryToolEnvironmentTest {
@Test
void testSetup_changesEnvironmentReturnedByGet() {
RegistryToolEnvironment.UNITTEST.setup(systemPropertyRule);
RegistryToolEnvironment.UNITTEST.setup(systemPropertyExtension);
assertThat(RegistryToolEnvironment.get()).isEqualTo(RegistryToolEnvironment.UNITTEST);
RegistryToolEnvironment.ALPHA.setup(systemPropertyRule);
RegistryToolEnvironment.ALPHA.setup(systemPropertyExtension);
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.HttpRequestInitializer;
import google.registry.config.RegistryConfig;
import google.registry.testing.SystemPropertyRule;
import google.registry.testing.SystemPropertyExtension;
import google.registry.util.GoogleCredentialsBundle;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -39,14 +39,15 @@ import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class RequestFactoryModuleTest {
@RegisterExtension final SystemPropertyRule systemPropertyRule = new SystemPropertyRule();
@RegisterExtension
final SystemPropertyExtension systemPropertyExtension = new SystemPropertyExtension();
@Mock public GoogleCredentialsBundle credentialsBundle;
@Mock public HttpRequestInitializer httpRequestInitializer;
@BeforeEach
void beforeEach() {
RegistryToolEnvironment.UNITTEST.setup(systemPropertyRule);
RegistryToolEnvironment.UNITTEST.setup(systemPropertyExtension);
}
@Test

View file

@ -27,7 +27,7 @@ import com.beust.jcommander.Parameters;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import google.registry.testing.FakeClock;
import google.registry.testing.SystemPropertyRule;
import google.registry.testing.SystemPropertyExtension;
import google.registry.tools.ShellCommand.JCommanderCompletor;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
@ -47,7 +47,8 @@ import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link ShellCommand}. */
class ShellCommandTest {
@RegisterExtension final SystemPropertyRule systemPropertyRule = new SystemPropertyRule();
@RegisterExtension
final SystemPropertyExtension systemPropertyExtension = new SystemPropertyExtension();
CommandRunner cli = mock(CommandRunner.class);
private FakeClock clock = new FakeClock(DateTime.parse("2000-01-01TZ"));
@ -109,7 +110,7 @@ class ShellCommandTest {
@Test
void testNoIdleWhenInAlpha() throws Exception {
RegistryToolEnvironment.ALPHA.setup(systemPropertyRule);
RegistryToolEnvironment.ALPHA.setup(systemPropertyExtension);
MockCli cli = new MockCli();
ShellCommand shellCommand =
createShellCommand(cli, Duration.standardDays(1), "test1 foo bar", "test2 foo bar");
@ -118,7 +119,7 @@ class ShellCommandTest {
@Test
void testNoIdleWhenInSandbox() throws Exception {
RegistryToolEnvironment.SANDBOX.setup(systemPropertyRule);
RegistryToolEnvironment.SANDBOX.setup(systemPropertyExtension);
MockCli cli = new MockCli();
ShellCommand shellCommand =
createShellCommand(cli, Duration.standardDays(1), "test1 foo bar", "test2 foo bar");
@ -127,7 +128,7 @@ class ShellCommandTest {
@Test
void testIdleWhenOverHourInProduction() throws Exception {
RegistryToolEnvironment.PRODUCTION.setup(systemPropertyRule);
RegistryToolEnvironment.PRODUCTION.setup(systemPropertyExtension);
MockCli cli = new MockCli();
ShellCommand shellCommand =
createShellCommand(cli, Duration.standardMinutes(61), "test1 foo bar", "test2 foo bar");
@ -137,7 +138,7 @@ class ShellCommandTest {
@Test
void testNoIdleWhenUnderHourInProduction() throws Exception {
RegistryToolEnvironment.PRODUCTION.setup(systemPropertyRule);
RegistryToolEnvironment.PRODUCTION.setup(systemPropertyExtension);
MockCli cli = new MockCli();
ShellCommand shellCommand =
createShellCommand(cli, Duration.standardMinutes(59), "test1 foo bar", "test2 foo bar");
@ -157,7 +158,7 @@ class ShellCommandTest {
void testMultipleCommandInvocations() throws Exception {
try (RegistryCli cli =
new RegistryCli("unittest", ImmutableMap.of("test_command", TestCommand.class))) {
RegistryToolEnvironment.UNITTEST.setup(systemPropertyRule);
RegistryToolEnvironment.UNITTEST.setup(systemPropertyExtension);
cli.setEnvironment(RegistryToolEnvironment.UNITTEST);
cli.run(new String[] {"test_command", "-x", "xval", "arg1", "arg2"});
cli.run(new String[] {"test_command", "-x", "otherxval", "arg3"});
@ -272,7 +273,7 @@ class ShellCommandTest {
@Test
void testEncapsulatedOutput_command() throws Exception {
RegistryToolEnvironment.ALPHA.setup(systemPropertyRule);
RegistryToolEnvironment.ALPHA.setup(systemPropertyExtension);
captureOutput();
ShellCommand shellCommand =
new ShellCommand(
@ -296,7 +297,7 @@ class ShellCommandTest {
@Test
void testEncapsulatedOutput_throws() throws Exception {
RegistryToolEnvironment.ALPHA.setup(systemPropertyRule);
RegistryToolEnvironment.ALPHA.setup(systemPropertyExtension);
captureOutput();
ShellCommand 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 com.beust.jcommander.Parameters;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;
import com.google.common.reflect.ClassPath;
import com.google.common.reflect.ClassPath.ClassInfo;
import com.google.common.truth.Expect;
import google.registry.testing.SystemPropertyRule;
import google.registry.testing.SystemPropertyExtension;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Map;
import junitparams.JUnitParamsRunner;
import junitparams.naming.TestCaseName;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
/** Unit tests for {@link RegistryTool} and {@link DevTool}. */
@RunWith(JUnitParamsRunner.class)
public class ToolsTest {
class ToolsTest {
@Rule
public final Expect expect = Expect.create();
@RegisterExtension
final SystemPropertyExtension systemPropertyExtension = new SystemPropertyExtension();
@Rule public final SystemPropertyRule systemPropertyRule = new SystemPropertyRule();
@Before
public void init() {
RegistryToolEnvironment.UNITTEST.setup(systemPropertyRule);
@BeforeEach
void beforeEach() {
RegistryToolEnvironment.UNITTEST.setup(systemPropertyExtension);
}
@Test
public void test_commandMap_includesAllCommands() throws Exception {
void test_commandMap_includesAllCommands() throws Exception {
ImmutableSet<?> registryToolCommands = ImmutableSet.copyOf(RegistryTool.COMMAND_MAP.values());
ImmutableSet<?> devToolCommands = ImmutableSet.copyOf(DevTool.COMMAND_MAP.values());
assertWithMessage("RegistryTool and DevTool have overlapping commands")
@ -73,32 +68,29 @@ public class ToolsTest {
.isEmpty();
}
@Test
@junitparams.Parameters(method = "getToolCommandMap")
@TestCaseName("{method}_{0}")
public void test_commandMap_namesAreInAlphabeticalOrder(
@ParameterizedTest
@MethodSource("provideTestCombinations")
void test_commandMap_namesAreInAlphabeticalOrder(
String toolName, ImmutableMap<String, Class<? extends Command>> commandMap) {
assertThat(commandMap.keySet()).isInStrictOrder();
}
@Test
@junitparams.Parameters(method = "getToolCommandMap")
@TestCaseName("{method}_{0}")
public void test_commandMap_namesAreDerivedFromClassNames(
@ParameterizedTest
@MethodSource("provideTestCombinations")
void test_commandMap_namesAreDerivedFromClassNames(
String toolName, ImmutableMap<String, Class<? extends Command>> commandMap) {
for (Map.Entry<String, ? extends Class<? extends Command>> commandEntry :
commandMap.entrySet()) {
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.
.isEqualTo(UPPER_CAMEL.to(LOWER_UNDERSCORE, className.replaceFirst("Command$", "")));
}
}
@Test
@junitparams.Parameters(method = "getToolCommandMap")
@TestCaseName("{method}_{0}")
public void test_commandMap_allCommandsHaveDescriptions(
@ParameterizedTest
@MethodSource("provideTestCombinations")
void test_commandMap_allCommandsHaveDescriptions(
String toolName, ImmutableMap<String, Class<? extends Command>> commandMap) {
for (Map.Entry<String, ? extends Class<? extends Command>> commandEntry :
commandMap.entrySet()) {
@ -109,10 +101,10 @@ public class ToolsTest {
}
@SuppressWarnings("unused")
private List<List<Object>> getToolCommandMap() {
return ImmutableList.of(
ImmutableList.of("RegistryTool", RegistryTool.COMMAND_MAP),
ImmutableList.of("DevTool", DevTool.COMMAND_MAP));
private static Stream<Arguments> provideTestCombinations() {
return Stream.of(
Arguments.of("RegistryTool", RegistryTool.COMMAND_MAP),
Arguments.of("DevTool", DevTool.COMMAND_MAP));
}
/**
@ -126,9 +118,9 @@ public class ToolsTest {
@SuppressWarnings("unchecked")
private ImmutableSet<Class<? extends Command>> getAllCommandClasses() throws IOException {
ImmutableSet.Builder<Class<? extends Command>> builder = new ImmutableSet.Builder<>();
for (ClassInfo classInfo : ClassPath
.from(getClass().getClassLoader())
.getTopLevelClassesRecursive(getPackageName(getClass()))) {
for (ClassInfo classInfo :
ClassPath.from(getClass().getClassLoader())
.getTopLevelClassesRecursive(getPackageName(getClass()))) {
Class<?> clazz = classInfo.load();
if (Command.class.isAssignableFrom(clazz)
&& !Modifier.isAbstract(clazz.getModifiers())

View file

@ -39,10 +39,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class CreatePremiumListActionTest {
/*@Rule
public final JpaIntegrationWithCoverageRule jpaRule =
new JpaTestRules.Builder().buildIntegrationWithCoverageRule();*/
@Rule
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.FakeClock;
import google.registry.testing.FakeResponse;
import google.registry.testing.SystemPropertyRule;
import google.registry.testing.SystemPropertyExtension;
import google.registry.ui.server.SendEmailUtils;
import google.registry.util.EmailMessage;
import google.registry.util.SendEmailService;
@ -67,7 +67,7 @@ public final class ConsoleOteSetupActionTest {
@RegisterExtension
@Order(value = Integer.MAX_VALUE)
public final SystemPropertyRule systemPropertyRule = new SystemPropertyRule();
final SystemPropertyExtension systemPropertyExtension = new SystemPropertyExtension();
private final FakeResponse response = new FakeResponse();
private final ConsoleOteSetupAction action = new ConsoleOteSetupAction();
@ -77,7 +77,7 @@ public final class ConsoleOteSetupActionTest {
@Mock SendEmailService emailService;
@BeforeEach
public void setUp() throws Exception {
void beforeEach() throws Exception {
persistPremiumList("default_sandbox_list", "sandbox,USD 1000");
action.req = request;
@ -106,7 +106,7 @@ public final class ConsoleOteSetupActionTest {
}
@Test
public void testNoUser_redirect() {
void testNoUser_redirect() {
when(request.getRequestURI()).thenReturn("/test");
action.authResult = AuthResult.NOT_AUTHENTICATED;
action.run();
@ -115,20 +115,20 @@ public final class ConsoleOteSetupActionTest {
}
@Test
public void testGet_authorized() {
void testGet_authorized() {
action.run();
assertThat(response.getPayload()).contains("<h1>Setup OT&E</h1>");
assertThat(response.getPayload()).contains("gtag('config', 'sampleId')");
}
@Test
public void testGet_authorized_onProduction() {
RegistryEnvironment.PRODUCTION.setup(systemPropertyRule);
void testGet_authorized_onProduction() {
RegistryEnvironment.PRODUCTION.setup(systemPropertyExtension);
assertThrows(IllegalStateException.class, action::run);
}
@Test
public void testGet_unauthorized() {
void testGet_unauthorized() {
action.registrarAccessor =
AuthenticatedRegistrarAccessor.createForTesting(ImmutableSetMultimap.of());
action.run();
@ -137,7 +137,7 @@ public final class ConsoleOteSetupActionTest {
}
@Test
public void testPost_authorized() {
void testPost_authorized() {
action.clientId = Optional.of("myclientid");
action.email = Optional.of("contact@registry.example");
action.method = Method.POST;
@ -169,7 +169,7 @@ public final class ConsoleOteSetupActionTest {
}
@Test
public void testPost_authorized_setPassword() {
void testPost_authorized_setPassword() {
action.clientId = Optional.of("myclientid");
action.email = Optional.of("contact@registry.example");
action.optionalPassword = Optional.of("SomePassword");
@ -187,7 +187,7 @@ public final class ConsoleOteSetupActionTest {
}
@Test
public void testPost_unauthorized() {
void testPost_unauthorized() {
action.registrarAccessor =
AuthenticatedRegistrarAccessor.createForTesting(ImmutableSetMultimap.of());
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.FakeClock;
import google.registry.testing.FakeResponse;
import google.registry.testing.SystemPropertyRule;
import google.registry.testing.SystemPropertyExtension;
import google.registry.ui.server.SendEmailUtils;
import google.registry.util.EmailMessage;
import google.registry.util.SendEmailService;
@ -68,7 +68,7 @@ public final class ConsoleRegistrarCreatorActionTest {
@RegisterExtension
@Order(value = Integer.MAX_VALUE)
public final SystemPropertyRule systemPropertyRule = new SystemPropertyRule();
final SystemPropertyExtension systemPropertyExtension = new SystemPropertyExtension();
private final FakeResponse response = new FakeResponse();
private final ConsoleRegistrarCreatorAction action = new ConsoleRegistrarCreatorAction();
@ -78,7 +78,7 @@ public final class ConsoleRegistrarCreatorActionTest {
@Mock SendEmailService emailService;
@BeforeEach
public void setUp() throws Exception {
void beforeEach() throws Exception {
persistPremiumList("default_sandbox_list", "sandbox,USD 1000");
action.req = request;
@ -125,7 +125,7 @@ public final class ConsoleRegistrarCreatorActionTest {
}
@Test
public void testNoUser_redirect() {
void testNoUser_redirect() {
when(request.getRequestURI()).thenReturn("/test");
action.authResult = AuthResult.NOT_AUTHENTICATED;
action.run();
@ -134,22 +134,22 @@ public final class ConsoleRegistrarCreatorActionTest {
}
@Test
public void testGet_authorized() {
void testGet_authorized() {
action.run();
assertThat(response.getPayload()).contains("<h1>Create Registrar</h1>");
assertThat(response.getPayload()).contains("gtag('config', 'sampleId')");
}
@Test
public void testGet_authorized_onProduction() {
RegistryEnvironment.PRODUCTION.setup(systemPropertyRule);
void testGet_authorized_onProduction() {
RegistryEnvironment.PRODUCTION.setup(systemPropertyExtension);
action.run();
assertThat(response.getPayload()).contains("<h1>Create Registrar</h1>");
assertThat(response.getPayload()).contains("gtag('config', 'sampleId')");
}
@Test
public void testGet_unauthorized() {
void testGet_unauthorized() {
action.registrarAccessor =
AuthenticatedRegistrarAccessor.createForTesting(ImmutableSetMultimap.of());
action.run();
@ -158,7 +158,7 @@ public final class ConsoleRegistrarCreatorActionTest {
}
@Test
public void testPost_authorized_minimalAddress() {
void testPost_authorized_minimalAddress() {
action.clientId = Optional.of("myclientid");
action.name = Optional.of("registrar name");
action.billingAccount = Optional.of("USD=billing-account");
@ -226,7 +226,7 @@ public final class ConsoleRegistrarCreatorActionTest {
}
@Test
public void testPost_authorized_allAddress() {
void testPost_authorized_allAddress() {
action.clientId = Optional.of("myclientid");
action.name = Optional.of("registrar name");
action.billingAccount = Optional.of("USD=billing-account");
@ -263,7 +263,7 @@ public final class ConsoleRegistrarCreatorActionTest {
}
@Test
public void testPost_authorized_multipleBillingLines() {
void testPost_authorized_multipleBillingLines() {
action.clientId = Optional.of("myclientid");
action.name = Optional.of("registrar name");
action.ianaId = Optional.of(12321);
@ -300,7 +300,7 @@ public final class ConsoleRegistrarCreatorActionTest {
}
@Test
public void testPost_authorized_repeatingCurrency_fails() {
void testPost_authorized_repeatingCurrency_fails() {
action.clientId = Optional.of("myclientid");
action.name = Optional.of("registrar name");
action.ianaId = Optional.of(12321);
@ -328,7 +328,7 @@ public final class ConsoleRegistrarCreatorActionTest {
}
@Test
public void testPost_authorized_badCurrency_fails() {
void testPost_authorized_badCurrency_fails() {
action.clientId = Optional.of("myclientid");
action.name = Optional.of("registrar name");
action.ianaId = Optional.of(12321);
@ -355,7 +355,7 @@ public final class ConsoleRegistrarCreatorActionTest {
}
@Test
public void testPost_authorized_badBillingLine_fails() {
void testPost_authorized_badBillingLine_fails() {
action.clientId = Optional.of("myclientid");
action.name = Optional.of("registrar name");
action.ianaId = Optional.of(12321);
@ -384,7 +384,7 @@ public final class ConsoleRegistrarCreatorActionTest {
}
@Test
public void testPost_authorized_setPassword() {
void testPost_authorized_setPassword() {
action.clientId = Optional.of("myclientid");
action.name = Optional.of("registrar name");
action.billingAccount = Optional.of("USD=billing-account");
@ -413,7 +413,7 @@ public final class ConsoleRegistrarCreatorActionTest {
}
@Test
public void testPost_badEmailFails() {
void testPost_badEmailFails() {
action.clientId = Optional.of("myclientid");
action.name = Optional.of("registrar name");
action.billingAccount = Optional.of("USD=billing-account");
@ -434,7 +434,7 @@ public final class ConsoleRegistrarCreatorActionTest {
}
@Test
public void testPost_unauthorized() {
void testPost_unauthorized() {
action.registrarAccessor =
AuthenticatedRegistrarAccessor.createForTesting(ImmutableSetMultimap.of());
action.clientId = Optional.of("myclientid");

View file

@ -28,21 +28,17 @@ import google.registry.model.registrar.RegistrarContact.Type;
import google.registry.testing.AppEngineRule;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/**
* Unit tests for contact_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)
public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
class ContactSettingsTest extends RegistrarSettingsActionTestCase {
@Test
public void testPost_readContacts_success() {
void testPost_readContacts_success() {
Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of(
"op", "read",
"id", CLIENT_ID,
@ -55,7 +51,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
}
@Test
public void testPost_loadSaveRegistrar_success() {
void testPost_loadSaveRegistrar_success() {
Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of(
"op", "update",
"id", CLIENT_ID,
@ -65,7 +61,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
}
@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
Map<String, Object> adminContact =
loadRegistrar(CLIENT_ID).getContacts().stream()
@ -95,7 +91,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
}
@Test
public void testPost_updateContacts_requiredTypes_error() {
void testPost_updateContacts_requiredTypes_error() {
Map<String, Object> reqJson = loadRegistrar(CLIENT_ID).toJsonMap();
reqJson.put("contacts", ImmutableList.of(techContact.toJsonMap()));
Map<String, Object> response =
@ -110,7 +106,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
}
@Test
public void testPost_updateContacts_requireTechPhone_error() {
void testPost_updateContacts_requireTechPhone_error() {
Map<String, Object> reqJson = loadRegistrar(CLIENT_ID).toJsonMap();
reqJson.put(
"contacts",
@ -131,7 +127,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
}
@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.
Registrar registrar = loadRegistrar(CLIENT_ID);
RegistrarContact rc =
@ -158,7 +154,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
}
@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.
Registrar registrar = loadRegistrar(CLIENT_ID);
RegistrarContact rc =
@ -185,7 +181,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
}
@Test
public void testSuccess_setRegistryLockPassword() {
void testSuccess_setRegistryLockPassword() {
addPasswordToContactTwo();
String emailAddress = AppEngineRule.makeRegistrarContact2().getEmailAddress();
RegistrarContact newContactWithPassword =
@ -198,7 +194,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
}
@Test
public void testSuccess_setRegistryLockPassword_notOverriddenLater() {
void testSuccess_setRegistryLockPassword_notOverriddenLater() {
addPasswordToContactTwo();
String emailAddress = AppEngineRule.makeRegistrarContact2().getEmailAddress();
RegistrarContact newContactWithPassword =
@ -251,7 +247,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
}
@Test
public void testPost_failure_setRegistryLockPassword_newContact() {
void testPost_failure_setRegistryLockPassword_newContact() {
Map<String, Object> reqJson = loadRegistrar(CLIENT_ID).toJsonMap();
reqJson.put(
"contacts",
@ -279,7 +275,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
}
@Test
public void testPost_failure_setRegistryLockPassword_notAllowed() {
void testPost_failure_setRegistryLockPassword_notAllowed() {
// "allowedToSetRegistryLockPassword" must be set through the back end first
// before we can set a password through the UI
Map<String, Object> contactMap = AppEngineRule.makeRegistrarContact2().toJsonMap();
@ -307,7 +303,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
}
@Test
public void testPost_failure_setRegistryLockAllowed() {
void testPost_failure_setRegistryLockAllowed() {
// One cannot set the "isAllowedToSetRegistryLockPassword" field through the UI
Map<String, Object> reqJson = loadRegistrar(CLIENT_ID).toJsonMap();
reqJson.put(
@ -330,7 +326,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
}
@Test
public void testPost_failure_setRegistryLockEmail() {
void testPost_failure_setRegistryLockEmail() {
addPasswordToContactTwo();
Map<String, Object> reqJson = loadRegistrar(CLIENT_ID).toJsonMap();
String emailAddress = AppEngineRule.makeRegistrarContact2().getEmailAddress();
@ -362,7 +358,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
}
@Test
public void testPost_failure_removingRegistryLockContact() {
void testPost_failure_removingRegistryLockContact() {
ImmutableMap<String, String> contact =
ImmutableMap.of(
"name", "contact1",
@ -386,7 +382,7 @@ public class ContactSettingsTest extends RegistrarSettingsActionTestCase {
}
@Test
public void testPost_failure_setRegistryLock_passwordTooShort() {
void testPost_failure_setRegistryLock_passwordTooShort() {
techContact =
persistResource(techContact.asBuilder().setAllowedToSetRegistryLockPassword(true).build());
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.Role;
import google.registry.testing.CertificateSamples;
import google.registry.testing.SystemPropertyRule;
import google.registry.testing.SystemPropertyExtension;
import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.util.CidrAddressBlock;
import google.registry.util.EmailMessage;
@ -45,21 +45,18 @@ import java.util.function.BiFunction;
import java.util.function.Function;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.ArgumentCaptor;
/** Tests for {@link RegistrarSettingsAction}. */
@RunWith(JUnit4.class)
public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase {
class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase {
@Rule
public final SystemPropertyRule systemPropertyRule = new SystemPropertyRule();
@RegisterExtension
final SystemPropertyExtension systemPropertyExtension = new SystemPropertyExtension();
@Test
public void testSuccess_updateRegistrarInfo_andSendsNotificationEmail() throws Exception {
void testSuccess_updateRegistrarInfo_andSendsNotificationEmail() throws Exception {
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,
// while deleting the existing tech contact (by omission).
@ -77,7 +74,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
}
@Test
public void testFailure_updateRegistrarInfo_duplicateContacts() {
void testFailure_updateRegistrarInfo_duplicateContacts() {
Map<String, Object> response = action.handleJsonRequest(
readJsonFromFile("update_registrar_duplicate_contacts.json", getLastUpdateTime()));
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.
*/
@Test
public void testFailure_readRegistrarInfo_notAuthorized() {
void testFailure_readRegistrarInfo_notAuthorized() {
setUserWithoutAccess();
Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of("id", CLIENT_ID));
assertThat(response)
@ -108,7 +105,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
/** This is the default read test for the registrar settings actions. */
@Test
public void testSuccess_readRegistrarInfo_authorizedReadWrite() {
void testSuccess_readRegistrarInfo_authorizedReadWrite() {
Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of("id", CLIENT_ID));
assertThat(response)
.containsExactly(
@ -119,7 +116,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
}
@Test
public void testUpdate_emptyJsonObject_errorLastUpdateTimeFieldRequired() {
void testUpdate_emptyJsonObject_errorLastUpdateTimeFieldRequired() {
Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap());
args.remove("lastUpdateTime");
@ -138,7 +135,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
}
@Test
public void testUpdate_noEmail_errorEmailFieldRequired() {
void testUpdate_noEmail_errorEmailFieldRequired() {
Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap());
args.remove("emailAddress");
@ -157,7 +154,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
}
@Test
public void testFailure_updateRegistrarInfo_notAuthorized() {
void testFailure_updateRegistrarInfo_notAuthorized() {
setUserWithoutAccess();
Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of(
@ -175,7 +172,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
}
@Test
public void testUpdate_badEmail_errorEmailField() {
void testUpdate_badEmail_errorEmailField() {
Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap());
args.put("emailAddress", "lolcat");
@ -194,7 +191,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
}
@Test
public void testPost_nonParsableTime_getsAngry() {
void testPost_nonParsableTime_getsAngry() {
Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap());
args.put("lastUpdateTime", "cookies");
@ -213,7 +210,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
}
@Test
public void testPost_nonAsciiCharacters_getsAngry() {
void testPost_nonAsciiCharacters_getsAngry() {
Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap());
args.put("emailAddress", "ヘ(◕。◕ヘ)@example.com");
@ -334,7 +331,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
}
@Test
public void testUpdate_whoisServer() {
void testUpdate_whoisServer() {
doTestUpdate(
Role.OWNER,
Registrar::getWhoisServer,
@ -343,24 +340,24 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
}
@Test
public void testUpdate_phoneNumber() {
void testUpdate_phoneNumber() {
doTestUpdate(
Role.OWNER, Registrar::getPhoneNumber, "+1.2345678900", Registrar.Builder::setPhoneNumber);
}
@Test
public void testUpdate_faxNumber() {
void testUpdate_faxNumber() {
doTestUpdate(
Role.OWNER, Registrar::getFaxNumber, "+1.2345678900", Registrar.Builder::setFaxNumber);
}
@Test
public void testUpdate_url() {
void testUpdate_url() {
doTestUpdate(Role.OWNER, Registrar::getUrl, "new-url.example", Registrar.Builder::setUrl);
}
@Test
public void testUpdate_ipAddressAllowList() {
void testUpdate_ipAddressAllowList() {
doTestUpdate(
Role.OWNER,
Registrar::getIpAddressAllowList,
@ -369,7 +366,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
}
@Test
public void testUpdate_clientCertificate() {
void testUpdate_clientCertificate() {
doTestUpdate(
Role.OWNER,
Registrar::getClientCertificate,
@ -378,7 +375,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
}
@Test
public void testUpdate_failoverClientCertificate() {
void testUpdate_failoverClientCertificate() {
doTestUpdate(
Role.OWNER,
Registrar::getFailoverClientCertificate,
@ -387,7 +384,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
}
@Test
public void testUpdate_allowedTlds() {
void testUpdate_allowedTlds() {
doTestUpdate(
Role.ADMIN,
Registrar::getAllowedTlds,
@ -396,9 +393,9 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
}
@Test
public void testUpdate_allowedTlds_failedWhenNoWhoisAbuseContactExists() {
void testUpdate_allowedTlds_failedWhenNoWhoisAbuseContactExists() {
setUserAdmin();
RegistryEnvironment.PRODUCTION.setup(systemPropertyRule);
RegistryEnvironment.PRODUCTION.setup(systemPropertyExtension);
Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap());
args.put("allowedTlds", ImmutableList.of("newtld", "currenttld"));
@ -419,7 +416,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
}
@Test
public void testUpdate_allowedTlds_failedWhenTldNotExist() {
void testUpdate_allowedTlds_failedWhenTldNotExist() {
setUserAdmin();
Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap());
args.put("allowedTlds", ImmutableList.of("invalidtld", "currenttld"));
@ -441,7 +438,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
}
@Test
public void testUpdate_allowedTlds_failedWhenRemovingTld() {
void testUpdate_allowedTlds_failedWhenRemovingTld() {
setUserAdmin();
Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap());
args.put("allowedTlds", ImmutableList.of("newtld"));
@ -463,7 +460,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
}
@Test
public void testUpdate_allowedTlds_noChange_successWhenUserIsNotAdmin() {
void testUpdate_allowedTlds_noChange_successWhenUserIsNotAdmin() {
Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap());
args.put("allowedTlds", ImmutableList.of("currenttld"));
@ -483,7 +480,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
}
@Test
public void testUpdate_localizedAddress_city() {
void testUpdate_localizedAddress_city() {
doTestUpdate(
Role.OWNER,
Registrar::getLocalizedAddress,
@ -492,7 +489,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
}
@Test
public void testUpdate_localizedAddress_countryCode() {
void testUpdate_localizedAddress_countryCode() {
doTestUpdate(
Role.OWNER,
Registrar::getLocalizedAddress,
@ -501,7 +498,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
}
@Test
public void testUpdate_localizedAddress_state() {
void testUpdate_localizedAddress_state() {
doTestUpdate(
Role.OWNER,
Registrar::getLocalizedAddress,
@ -510,7 +507,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
}
@Test
public void testUpdate_localizedAddress_street() {
void testUpdate_localizedAddress_street() {
doTestUpdate(
Role.OWNER,
Registrar::getLocalizedAddress,
@ -523,7 +520,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
}
@Test
public void testUpdate_localizedAddress_zip() {
void testUpdate_localizedAddress_zip() {
doTestUpdate(
Role.OWNER,
Registrar::getLocalizedAddress,

View file

@ -54,25 +54,28 @@ import javax.mail.internet.InternetAddress;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.joda.time.DateTime;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
/** Base class for tests using {@link RegistrarSettingsAction}. */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
public abstract class RegistrarSettingsActionTestCase {
static final String CLIENT_ID = "TheRegistrar";
@Rule
@RegisterExtension
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withTaskQueue().build();
@Rule public final InjectRule inject = new InjectRule();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@RegisterExtension public final InjectRule inject = new InjectRule();
@Mock AppEngineServiceUtils appEngineServiceUtils;
@Mock HttpServletRequest req;
@ -80,13 +83,13 @@ public abstract class RegistrarSettingsActionTestCase {
@Mock SendEmailService emailService;
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"));
RegistrarContact techContact;
@Before
public void setUp() throws Exception {
@BeforeEach
public void beforeEachRegistrarSettingsActionTestCase() throws Exception {
// Registrar "TheRegistrar" has access to TLD "currenttld" but not to "newtld".
createTlds("currenttld", "newtld");
disallowRegistrarAccess(CLIENT_ID, "newtld");
@ -123,26 +126,26 @@ public abstract class RegistrarSettingsActionTestCase {
RegistrarConsoleMetrics.settingsRequestMetric.reset();
}
@After
public void tearDown() {
@AfterEach
public void afterEach() {
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)
.hasValueForLabels(1, clientId, op, roles, status);
RegistrarConsoleMetrics.settingsRequestMetric.reset(clientId, op, roles, status);
}
/** Sets registrarAccessor.getRegistrar to succeed for CLIENT_ID only. */
protected void setUserWithAccess() {
private void setUserWithAccess() {
action.registrarAccessor =
AuthenticatedRegistrarAccessor.createForTesting(
ImmutableSetMultimap.of(CLIENT_ID, OWNER));
}
/** Sets registrarAccessor.getRegistrar to always fail. */
protected void setUserWithoutAccess() {
void setUserWithoutAccess() {
action.registrarAccessor =
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
*/
protected void setUserAdmin() {
void setUserAdmin() {
action.registrarAccessor =
AuthenticatedRegistrarAccessor.createForTesting(
ImmutableSetMultimap.of(CLIENT_ID, ADMIN));
}
/** 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);
verify(emailService).sendEmail(captor.capture());
Truth.assertThat(captor.getValue().recipients())

View file

@ -27,21 +27,17 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import google.registry.model.registrar.Registrar;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/**
* 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)
public class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
@Test
public void testPost_updateCert_success() throws Exception {
void testPost_updateCert_success() throws Exception {
Registrar modified =
loadRegistrar(CLIENT_ID)
.asBuilder()
@ -59,7 +55,7 @@ public class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
}
@Test
public void testPost_updateCert_failure() {
void testPost_updateCert_failure() {
Map<String, Object> reqJson = loadRegistrar(CLIENT_ID).toJsonMap();
reqJson.put("clientCertificate", "BLAH");
Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of(
@ -72,7 +68,7 @@ public class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
}
@Test
public void testChangeCertificates() throws Exception {
void testChangeCertificates() throws Exception {
Map<String, Object> jsonMap = loadRegistrar(CLIENT_ID).toJsonMap();
jsonMap.put("clientCertificate", SAMPLE_CERT);
jsonMap.put("failoverClientCertificate", null);
@ -89,7 +85,7 @@ public class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
}
@Test
public void testChangeFailoverCertificate() throws Exception {
void testChangeFailoverCertificate() throws Exception {
Map<String, Object> jsonMap = loadRegistrar(CLIENT_ID).toJsonMap();
jsonMap.put("failoverClientCertificate", SAMPLE_CERT2);
Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of(
@ -103,7 +99,7 @@ public class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
}
@Test
public void testEmptyOrNullCertificate_doesNotClearOutCurrentOne() throws Exception {
void testEmptyOrNullCertificate_doesNotClearOutCurrentOne() throws Exception {
Registrar initialRegistrar =
persistResource(
loadRegistrar(CLIENT_ID)
@ -126,7 +122,7 @@ public class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
}
@Test
public void testToJsonMap_containsCertificate() {
void testToJsonMap_containsCertificate() {
Map<String, Object> jsonMap =
loadRegistrar(CLIENT_ID)
.asBuilder()
@ -138,7 +134,7 @@ public class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
}
@Test
public void testToJsonMap_containsFailoverCertificate() {
void testToJsonMap_containsFailoverCertificate() {
Map<String, Object> jsonMap =
loadRegistrar(CLIENT_ID)
.asBuilder()

View file

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

View file

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