Upgrade most of remaining tests from JUnit 4 to JUnit 5 (#708)

This commit is contained in:
Ben McIlwain 2020-07-23 15:43:59 -04:00 committed by GitHub
parent ab88ade44a
commit bdebf7c325
67 changed files with 974 additions and 1186 deletions

View file

@ -22,14 +22,11 @@ import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord; import org.apache.avro.generic.GenericRecord;
import org.apache.beam.sdk.io.gcp.bigquery.SchemaAndRecord; import org.apache.beam.sdk.io.gcp.bigquery.SchemaAndRecord;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link BeamUtils} */ /** Unit tests for {@link BeamUtils} */
@RunWith(JUnit4.class) class BeamUtilsTest {
public class BeamUtilsTest {
private static final String GENERIC_SCHEMA = private static final String GENERIC_SCHEMA =
"{\"name\": \"AnObject\", " "{\"name\": \"AnObject\", "
@ -41,8 +38,8 @@ public class BeamUtilsTest {
private SchemaAndRecord schemaAndRecord; private SchemaAndRecord schemaAndRecord;
@Before @BeforeEach
public void initializeRecord() { void beforeEach() {
// Create a record with a given JSON schema. // Create a record with a given JSON schema.
GenericRecord record = new GenericData.Record(new Schema.Parser().parse(GENERIC_SCHEMA)); GenericRecord record = new GenericData.Record(new Schema.Parser().parse(GENERIC_SCHEMA));
record.put("aString", "hello world"); record.put("aString", "hello world");
@ -51,26 +48,26 @@ public class BeamUtilsTest {
} }
@Test @Test
public void testExtractField_fieldExists_returnsExpectedStringValues() { void testExtractField_fieldExists_returnsExpectedStringValues() {
assertThat(BeamUtils.extractField(schemaAndRecord.getRecord(), "aString")) assertThat(BeamUtils.extractField(schemaAndRecord.getRecord(), "aString"))
.isEqualTo("hello world"); .isEqualTo("hello world");
assertThat(BeamUtils.extractField(schemaAndRecord.getRecord(), "aFloat")).isEqualTo("2.54"); assertThat(BeamUtils.extractField(schemaAndRecord.getRecord(), "aFloat")).isEqualTo("2.54");
} }
@Test @Test
public void testExtractField_fieldDoesntExist_returnsNull() { void testExtractField_fieldDoesntExist_returnsNull() {
schemaAndRecord.getRecord().put("aFloat", null); schemaAndRecord.getRecord().put("aFloat", null);
assertThat(BeamUtils.extractField(schemaAndRecord.getRecord(), "aFloat")).isEqualTo("null"); assertThat(BeamUtils.extractField(schemaAndRecord.getRecord(), "aFloat")).isEqualTo("null");
assertThat(BeamUtils.extractField(schemaAndRecord.getRecord(), "missing")).isEqualTo("null"); assertThat(BeamUtils.extractField(schemaAndRecord.getRecord(), "missing")).isEqualTo("null");
} }
@Test @Test
public void testCheckFieldsNotNull_noExceptionIfAllPresent() { void testCheckFieldsNotNull_noExceptionIfAllPresent() {
BeamUtils.checkFieldsNotNull(ImmutableList.of("aString", "aFloat"), schemaAndRecord); BeamUtils.checkFieldsNotNull(ImmutableList.of("aString", "aFloat"), schemaAndRecord);
} }
@Test @Test
public void testCheckFieldsNotNull_fieldMissing_throwsException() { void testCheckFieldsNotNull_fieldMissing_throwsException() {
IllegalStateException expected = IllegalStateException expected =
assertThrows( assertThrows(
IllegalStateException.class, IllegalStateException.class,

View file

@ -55,6 +55,7 @@ import org.junit.runners.JUnit4;
// a wrapper. // a wrapper.
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class CommitLogTransformsTest implements Serializable { public class CommitLogTransformsTest implements Serializable {
private static final DateTime START_TIME = DateTime.parse("2000-01-01T00:00:00.0Z"); private static final DateTime START_TIME = DateTime.parse("2000-01-01T00:00:00.0Z");
@Rule public final transient TemporaryFolder temporaryFolder = new TemporaryFolder(); @Rule public final transient TemporaryFolder temporaryFolder = new TemporaryFolder();

View file

@ -29,14 +29,11 @@ import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord; import org.apache.avro.generic.GenericRecord;
import org.apache.beam.sdk.io.gcp.bigquery.SchemaAndRecord; import org.apache.beam.sdk.io.gcp.bigquery.SchemaAndRecord;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link BillingEvent} */ /** Unit tests for {@link BillingEvent} */
@RunWith(JUnit4.class) class BillingEventTest {
public class BillingEventTest {
private static final String BILLING_EVENT_SCHEMA = private static final String BILLING_EVENT_SCHEMA =
"{\"name\": \"BillingEvent\", " "{\"name\": \"BillingEvent\", "
@ -60,8 +57,8 @@ public class BillingEventTest {
private SchemaAndRecord schemaAndRecord; private SchemaAndRecord schemaAndRecord;
@Before @BeforeEach
public void initializeRecord() { void beforeEach() {
// Create a record with a given JSON schema. // Create a record with a given JSON schema.
schemaAndRecord = new SchemaAndRecord(createRecord(), null); schemaAndRecord = new SchemaAndRecord(createRecord(), null);
} }
@ -86,7 +83,7 @@ public class BillingEventTest {
} }
@Test @Test
public void testParseBillingEventFromRecord_success() { void testParseBillingEventFromRecord_success() {
BillingEvent event = BillingEvent.parseFromRecord(schemaAndRecord); BillingEvent event = BillingEvent.parseFromRecord(schemaAndRecord);
assertThat(event.id()).isEqualTo(1); assertThat(event.id()).isEqualTo(1);
assertThat(event.billingTime()) assertThat(event.billingTime())
@ -107,7 +104,7 @@ public class BillingEventTest {
} }
@Test @Test
public void testParseBillingEventFromRecord_sunriseCreate_reducedPrice_success() { void testParseBillingEventFromRecord_sunriseCreate_reducedPrice_success() {
schemaAndRecord.getRecord().put("flags", "SUNRISE"); schemaAndRecord.getRecord().put("flags", "SUNRISE");
BillingEvent event = BillingEvent.parseFromRecord(schemaAndRecord); BillingEvent event = BillingEvent.parseFromRecord(schemaAndRecord);
assertThat(event.amount()).isEqualTo(17.43); assertThat(event.amount()).isEqualTo(17.43);
@ -115,7 +112,7 @@ public class BillingEventTest {
} }
@Test @Test
public void testParseBillingEventFromRecord_anchorTenant_zeroPrice_success() { void testParseBillingEventFromRecord_anchorTenant_zeroPrice_success() {
schemaAndRecord.getRecord().put("flags", "SUNRISE ANCHOR_TENANT"); schemaAndRecord.getRecord().put("flags", "SUNRISE ANCHOR_TENANT");
BillingEvent event = BillingEvent.parseFromRecord(schemaAndRecord); BillingEvent event = BillingEvent.parseFromRecord(schemaAndRecord);
assertThat(event.amount()).isZero(); assertThat(event.amount()).isZero();
@ -123,13 +120,13 @@ public class BillingEventTest {
} }
@Test @Test
public void testParseBillingEventFromRecord_nullValue_throwsException() { void testParseBillingEventFromRecord_nullValue_throwsException() {
schemaAndRecord.getRecord().put("tld", null); schemaAndRecord.getRecord().put("tld", null);
assertThrows(IllegalStateException.class, () -> BillingEvent.parseFromRecord(schemaAndRecord)); assertThrows(IllegalStateException.class, () -> BillingEvent.parseFromRecord(schemaAndRecord));
} }
@Test @Test
public void testConvertBillingEvent_toCsv() { void testConvertBillingEvent_toCsv() {
BillingEvent event = BillingEvent.parseFromRecord(schemaAndRecord); BillingEvent event = BillingEvent.parseFromRecord(schemaAndRecord);
assertThat(event.toCsv()) assertThat(event.toCsv())
.isEqualTo( .isEqualTo(
@ -138,7 +135,7 @@ public class BillingEventTest {
} }
@Test @Test
public void testConvertBillingEvent_nonNullPoNumber_toCsv() { void testConvertBillingEvent_nonNullPoNumber_toCsv() {
GenericRecord record = createRecord(); GenericRecord record = createRecord();
record.put("poNumber", "905610"); record.put("poNumber", "905610");
BillingEvent event = BillingEvent.parseFromRecord(new SchemaAndRecord(record, null)); BillingEvent event = BillingEvent.parseFromRecord(new SchemaAndRecord(record, null));
@ -149,13 +146,13 @@ public class BillingEventTest {
} }
@Test @Test
public void testGenerateBillingEventFilename() { void testGenerateBillingEventFilename() {
BillingEvent event = BillingEvent.parseFromRecord(schemaAndRecord); BillingEvent event = BillingEvent.parseFromRecord(schemaAndRecord);
assertThat(event.toFilename("2017-10")).isEqualTo("invoice_details_2017-10_myRegistrar_test"); assertThat(event.toFilename("2017-10")).isEqualTo("invoice_details_2017-10_myRegistrar_test");
} }
@Test @Test
public void testGetInvoiceGroupingKey_fromBillingEvent() { void testGetInvoiceGroupingKey_fromBillingEvent() {
BillingEvent event = BillingEvent.parseFromRecord(schemaAndRecord); BillingEvent event = BillingEvent.parseFromRecord(schemaAndRecord);
InvoiceGroupingKey invoiceKey = event.getInvoiceGroupingKey(); InvoiceGroupingKey invoiceKey = event.getInvoiceGroupingKey();
assertThat(invoiceKey.startDate()).isEqualTo("2017-10-01"); assertThat(invoiceKey.startDate()).isEqualTo("2017-10-01");
@ -169,7 +166,7 @@ public class BillingEventTest {
} }
@Test @Test
public void test_nonNullPoNumber() { void test_nonNullPoNumber() {
GenericRecord record = createRecord(); GenericRecord record = createRecord();
record.put("poNumber", "905610"); record.put("poNumber", "905610");
BillingEvent event = BillingEvent.parseFromRecord(new SchemaAndRecord(record, null)); BillingEvent event = BillingEvent.parseFromRecord(new SchemaAndRecord(record, null));
@ -179,7 +176,7 @@ public class BillingEventTest {
} }
@Test @Test
public void testConvertInvoiceGroupingKey_toCsv() { void testConvertInvoiceGroupingKey_toCsv() {
BillingEvent event = BillingEvent.parseFromRecord(schemaAndRecord); BillingEvent event = BillingEvent.parseFromRecord(schemaAndRecord);
InvoiceGroupingKey invoiceKey = event.getInvoiceGroupingKey(); InvoiceGroupingKey invoiceKey = event.getInvoiceGroupingKey();
assertThat(invoiceKey.toCsv(3L)) assertThat(invoiceKey.toCsv(3L))
@ -189,7 +186,7 @@ public class BillingEventTest {
} }
@Test @Test
public void testInvoiceGroupingKeyCoder_deterministicSerialization() throws IOException { void testInvoiceGroupingKeyCoder_deterministicSerialization() throws IOException {
InvoiceGroupingKey invoiceKey = InvoiceGroupingKey invoiceKey =
BillingEvent.parseFromRecord(schemaAndRecord).getInvoiceGroupingKey(); BillingEvent.parseFromRecord(schemaAndRecord).getInvoiceGroupingKey();
InvoiceGroupingKeyCoder coder = new InvoiceGroupingKeyCoder(); InvoiceGroupingKeyCoder coder = new InvoiceGroupingKeyCoder();
@ -200,7 +197,7 @@ public class BillingEventTest {
} }
@Test @Test
public void testGetDetailReportHeader() { void testGetDetailReportHeader() {
assertThat(BillingEvent.getHeader()) assertThat(BillingEvent.getHeader())
.isEqualTo( .isEqualTo(
"id,billingTime,eventTime,registrarId,billingId,poNumber,tld,action," "id,billingTime,eventTime,registrarId,billingId,poNumber,tld,action,"
@ -208,7 +205,7 @@ public class BillingEventTest {
} }
@Test @Test
public void testGetOverallInvoiceHeader() { void testGetOverallInvoiceHeader() {
assertThat(InvoiceGroupingKey.invoiceHeader()) assertThat(InvoiceGroupingKey.invoiceHeader())
.isEqualTo("StartDate,EndDate,ProductAccountKey,Amount,AmountCurrency,BillingProductCode," .isEqualTo("StartDate,EndDate,ProductAccountKey,Amount,AmountCurrency,BillingProductCode,"
+ "SalesChannel,LineItemType,UsageGroupingKey,Quantity,Description,UnitPrice," + "SalesChannel,LineItemType,UsageGroupingKey,Quantity,Description,UnitPrice,"

View file

@ -25,16 +25,13 @@ import org.apache.beam.sdk.io.FileBasedSink;
import org.apache.beam.sdk.options.ValueProvider; import org.apache.beam.sdk.options.ValueProvider;
import org.apache.beam.sdk.options.ValueProvider.StaticValueProvider; import org.apache.beam.sdk.options.ValueProvider.StaticValueProvider;
import org.apache.beam.sdk.transforms.SerializableFunction; import org.apache.beam.sdk.transforms.SerializableFunction;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link InvoicingUtils}. */ /** Unit tests for {@link InvoicingUtils}. */
@RunWith(JUnit4.class) class InvoicingUtilsTest {
public class InvoicingUtilsTest {
@Test @Test
public void testDestinationFunction_generatesProperFileParams() { void testDestinationFunction_generatesProperFileParams() {
SerializableFunction<BillingEvent, Params> destinationFunction = SerializableFunction<BillingEvent, Params> destinationFunction =
InvoicingUtils.makeDestinationFunction("my/directory", StaticValueProvider.of("2017-10")); InvoicingUtils.makeDestinationFunction("my/directory", StaticValueProvider.of("2017-10"));
@ -53,7 +50,7 @@ public class InvoicingUtilsTest {
} }
@Test @Test
public void testEmptyDestinationParams() { void testEmptyDestinationParams() {
assertThat(InvoicingUtils.makeEmptyDestinationParams("my/directory")) assertThat(InvoicingUtils.makeEmptyDestinationParams("my/directory"))
.isEqualTo( .isEqualTo(
new Params() new Params()
@ -63,7 +60,7 @@ public class InvoicingUtilsTest {
/** Asserts that the instantiated sql template matches a golden expected file. */ /** Asserts that the instantiated sql template matches a golden expected file. */
@Test @Test
public void testMakeQueryProvider() { void testMakeQueryProvider() {
ValueProvider<String> queryProvider = ValueProvider<String> queryProvider =
InvoicingUtils.makeQueryProvider(StaticValueProvider.of("2017-10"), "my-project-id"); InvoicingUtils.makeQueryProvider(StaticValueProvider.of("2017-10"), "my-project-id");
assertThat(queryProvider.get()).isEqualTo(loadFile("billing_events_test.sql")); assertThat(queryProvider.get()).isEqualTo(loadFile("billing_events_test.sql"));

View file

@ -1,31 +0,0 @@
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.bigquery;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link BigqueryConnection}. */
@RunWith(JUnit4.class)
public class BigqueryConnectionTest {
@Test
public void testNothing() {
// Placeholder test class for now.
// TODO(b/16569089): figure out a good way for testing our Bigquery usage overall - maybe unit
// tests here, maybe end-to-end testing.
}
}

View file

@ -27,20 +27,18 @@ import com.google.api.services.bigquery.model.JobReference;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.DateTimeZone; import org.joda.time.DateTimeZone;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link BigqueryUtils}. */ /** Unit tests for {@link BigqueryUtils}. */
@RunWith(JUnit4.class) class BigqueryUtilsTest {
public class BigqueryUtilsTest {
private static final DateTime DATE_0 = DateTime.parse("2014-07-17T20:35:42Z"); private static final DateTime DATE_0 = DateTime.parse("2014-07-17T20:35:42Z");
private static final DateTime DATE_1 = DateTime.parse("2014-07-17T20:35:42.1Z"); private static final DateTime DATE_1 = DateTime.parse("2014-07-17T20:35:42.1Z");
private static final DateTime DATE_2 = DateTime.parse("2014-07-17T20:35:42.12Z"); private static final DateTime DATE_2 = DateTime.parse("2014-07-17T20:35:42.12Z");
private static final DateTime DATE_3 = DateTime.parse("2014-07-17T20:35:42.123Z"); private static final DateTime DATE_3 = DateTime.parse("2014-07-17T20:35:42.123Z");
@Test @Test
public void test_toBigqueryTimestampString() { void test_toBigqueryTimestampString() {
assertThat(toBigqueryTimestampString(START_OF_TIME)).isEqualTo("1970-01-01 00:00:00.000"); assertThat(toBigqueryTimestampString(START_OF_TIME)).isEqualTo("1970-01-01 00:00:00.000");
assertThat(toBigqueryTimestampString(DATE_0)).isEqualTo("2014-07-17 20:35:42.000"); assertThat(toBigqueryTimestampString(DATE_0)).isEqualTo("2014-07-17 20:35:42.000");
assertThat(toBigqueryTimestampString(DATE_1)).isEqualTo("2014-07-17 20:35:42.100"); assertThat(toBigqueryTimestampString(DATE_1)).isEqualTo("2014-07-17 20:35:42.100");
@ -50,7 +48,7 @@ public class BigqueryUtilsTest {
} }
@Test @Test
public void test_toBigqueryTimestampString_convertsToUtc() { void test_toBigqueryTimestampString_convertsToUtc() {
assertThat(toBigqueryTimestampString(START_OF_TIME.withZone(DateTimeZone.forOffsetHours(5)))) assertThat(toBigqueryTimestampString(START_OF_TIME.withZone(DateTimeZone.forOffsetHours(5))))
.isEqualTo("1970-01-01 00:00:00.000"); .isEqualTo("1970-01-01 00:00:00.000");
assertThat(toBigqueryTimestampString(DateTime.parse("1970-01-01T00:00:00-0500"))) assertThat(toBigqueryTimestampString(DateTime.parse("1970-01-01T00:00:00-0500")))
@ -58,13 +56,13 @@ public class BigqueryUtilsTest {
} }
@Test @Test
public void test_fromBigqueryTimestampString_startAndEndOfTime() { void test_fromBigqueryTimestampString_startAndEndOfTime() {
assertThat(fromBigqueryTimestampString("1970-01-01 00:00:00 UTC")).isEqualTo(START_OF_TIME); assertThat(fromBigqueryTimestampString("1970-01-01 00:00:00 UTC")).isEqualTo(START_OF_TIME);
assertThat(fromBigqueryTimestampString("294247-01-10 04:00:54.775 UTC")).isEqualTo(END_OF_TIME); assertThat(fromBigqueryTimestampString("294247-01-10 04:00:54.775 UTC")).isEqualTo(END_OF_TIME);
} }
@Test @Test
public void test_fromBigqueryTimestampString_trailingZerosOkay() { void test_fromBigqueryTimestampString_trailingZerosOkay() {
assertThat(fromBigqueryTimestampString("2014-07-17 20:35:42 UTC")).isEqualTo(DATE_0); assertThat(fromBigqueryTimestampString("2014-07-17 20:35:42 UTC")).isEqualTo(DATE_0);
assertThat(fromBigqueryTimestampString("2014-07-17 20:35:42.0 UTC")).isEqualTo(DATE_0); assertThat(fromBigqueryTimestampString("2014-07-17 20:35:42.0 UTC")).isEqualTo(DATE_0);
assertThat(fromBigqueryTimestampString("2014-07-17 20:35:42.00 UTC")).isEqualTo(DATE_0); assertThat(fromBigqueryTimestampString("2014-07-17 20:35:42.00 UTC")).isEqualTo(DATE_0);
@ -78,27 +76,27 @@ public class BigqueryUtilsTest {
} }
@Test @Test
public void testFailure_fromBigqueryTimestampString_nonUtcTimeZone() { void testFailure_fromBigqueryTimestampString_nonUtcTimeZone() {
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> fromBigqueryTimestampString("2014-01-01 01:01:01 +05:00")); () -> fromBigqueryTimestampString("2014-01-01 01:01:01 +05:00"));
} }
@Test @Test
public void testFailure_fromBigqueryTimestampString_noTimeZone() { void testFailure_fromBigqueryTimestampString_noTimeZone() {
assertThrows( assertThrows(
IllegalArgumentException.class, () -> fromBigqueryTimestampString("2014-01-01 01:01:01")); IllegalArgumentException.class, () -> fromBigqueryTimestampString("2014-01-01 01:01:01"));
} }
@Test @Test
public void testFailure_fromBigqueryTimestampString_tooManyMillisecondDigits() { void testFailure_fromBigqueryTimestampString_tooManyMillisecondDigits() {
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> fromBigqueryTimestampString("2014-01-01 01:01:01.1234 UTC")); () -> fromBigqueryTimestampString("2014-01-01 01:01:01.1234 UTC"));
} }
@Test @Test
public void test_toBigqueryTimestamp_timeunitConversion() { void test_toBigqueryTimestamp_timeunitConversion() {
assertThat(toBigqueryTimestamp(1234567890L, TimeUnit.SECONDS)) assertThat(toBigqueryTimestamp(1234567890L, TimeUnit.SECONDS))
.isEqualTo("1234567890.000000"); .isEqualTo("1234567890.000000");
assertThat(toBigqueryTimestamp(1234567890123L, TimeUnit.MILLISECONDS)) assertThat(toBigqueryTimestamp(1234567890123L, TimeUnit.MILLISECONDS))
@ -110,14 +108,14 @@ public class BigqueryUtilsTest {
} }
@Test @Test
public void test_toBigqueryTimestamp_timeunitConversionForZero() { void test_toBigqueryTimestamp_timeunitConversionForZero() {
assertThat(toBigqueryTimestamp(0L, TimeUnit.SECONDS)).isEqualTo("0.000000"); assertThat(toBigqueryTimestamp(0L, TimeUnit.SECONDS)).isEqualTo("0.000000");
assertThat(toBigqueryTimestamp(0L, TimeUnit.MILLISECONDS)).isEqualTo("0.000000"); assertThat(toBigqueryTimestamp(0L, TimeUnit.MILLISECONDS)).isEqualTo("0.000000");
assertThat(toBigqueryTimestamp(0L, TimeUnit.MICROSECONDS)).isEqualTo("0.000000"); assertThat(toBigqueryTimestamp(0L, TimeUnit.MICROSECONDS)).isEqualTo("0.000000");
} }
@Test @Test
public void test_toBigqueryTimestamp_datetimeConversion() { void test_toBigqueryTimestamp_datetimeConversion() {
assertThat(toBigqueryTimestamp(START_OF_TIME)).isEqualTo("0.000000"); assertThat(toBigqueryTimestamp(START_OF_TIME)).isEqualTo("0.000000");
assertThat(toBigqueryTimestamp(DATE_0)).isEqualTo("1405629342.000000"); assertThat(toBigqueryTimestamp(DATE_0)).isEqualTo("1405629342.000000");
assertThat(toBigqueryTimestamp(DATE_1)).isEqualTo("1405629342.100000"); assertThat(toBigqueryTimestamp(DATE_1)).isEqualTo("1405629342.100000");
@ -127,18 +125,18 @@ public class BigqueryUtilsTest {
} }
@Test @Test
public void test_toJobReferenceString_normalSucceeds() { void test_toJobReferenceString_normalSucceeds() {
assertThat(toJobReferenceString(new JobReference().setProjectId("foo").setJobId("bar"))) assertThat(toJobReferenceString(new JobReference().setProjectId("foo").setJobId("bar")))
.isEqualTo("foo:bar"); .isEqualTo("foo:bar");
} }
@Test @Test
public void test_toJobReferenceString_emptyReferenceSucceeds() { void test_toJobReferenceString_emptyReferenceSucceeds() {
assertThat(toJobReferenceString(new JobReference())).isEqualTo("null:null"); assertThat(toJobReferenceString(new JobReference())).isEqualTo("null:null");
} }
@Test @Test
public void test_toJobReferenceString_nullThrowsNpe() { void test_toJobReferenceString_nullThrowsNpe() {
assertThrows(NullPointerException.class, () -> toJobReferenceString(null)); assertThrows(NullPointerException.class, () -> toJobReferenceString(null));
} }
} }

View file

@ -29,15 +29,12 @@ import com.google.api.services.bigquery.model.TableFieldSchema;
import com.google.api.services.bigquery.model.TableReference; import com.google.api.services.bigquery.model.TableReference;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
/** Unit tests for {@link CheckedBigquery}. */ /** Unit tests for {@link CheckedBigquery}. */
@RunWith(JUnit4.class) class CheckedBigqueryTest {
public class CheckedBigqueryTest {
private final Bigquery bigquery = mock(Bigquery.class); private final Bigquery bigquery = mock(Bigquery.class);
private final Bigquery.Datasets bigqueryDatasets = mock(Bigquery.Datasets.class); private final Bigquery.Datasets bigqueryDatasets = mock(Bigquery.Datasets.class);
@ -48,8 +45,8 @@ public class CheckedBigqueryTest {
private CheckedBigquery checkedBigquery; private CheckedBigquery checkedBigquery;
@Before @BeforeEach
public void before() throws Exception { void beforeEach() throws Exception {
when(bigquery.datasets()).thenReturn(bigqueryDatasets); when(bigquery.datasets()).thenReturn(bigqueryDatasets);
when(bigqueryDatasets.insert(eq("Project-Id"), any(Dataset.class))) when(bigqueryDatasets.insert(eq("Project-Id"), any(Dataset.class)))
.thenReturn(bigqueryDatasetsInsert); .thenReturn(bigqueryDatasetsInsert);
@ -70,7 +67,7 @@ public class CheckedBigqueryTest {
} }
@Test @Test
public void testSuccess_datastoreCreation() throws Exception { void testSuccess_datastoreCreation() throws Exception {
checkedBigquery.ensureDataSetExists("Project-Id", "Dataset-Id"); checkedBigquery.ensureDataSetExists("Project-Id", "Dataset-Id");
ArgumentCaptor<Dataset> datasetArg = ArgumentCaptor.forClass(Dataset.class); ArgumentCaptor<Dataset> datasetArg = ArgumentCaptor.forClass(Dataset.class);
@ -83,7 +80,7 @@ public class CheckedBigqueryTest {
} }
@Test @Test
public void testSuccess_datastoreAndTableCreation() throws Exception { void testSuccess_datastoreAndTableCreation() throws Exception {
checkedBigquery.ensureDataSetAndTableExist("Project-Id", "Dataset2", "Table2"); checkedBigquery.ensureDataSetAndTableExist("Project-Id", "Dataset2", "Table2");
ArgumentCaptor<Dataset> datasetArg = ArgumentCaptor.forClass(Dataset.class); ArgumentCaptor<Dataset> datasetArg = ArgumentCaptor.forClass(Dataset.class);

View file

@ -18,15 +18,13 @@ import static com.google.common.truth.Truth.assertThat;
import static google.registry.config.RegistryConfig.CONFIG_SETTINGS; import static google.registry.config.RegistryConfig.CONFIG_SETTINGS;
import static google.registry.config.RegistryConfig.ConfigModule.provideReservedTermsExportDisclaimer; import static google.registry.config.RegistryConfig.ConfigModule.provideReservedTermsExportDisclaimer;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) /** Unit tests for {@link RegistryConfig}. */
public class RegistryConfigTest { class RegistryConfigTest {
@Test @Test
public void test_reservedTermsExportDisclaimer_isPrependedWithOctothorpes() { void test_reservedTermsExportDisclaimer_isPrependedWithOctothorpes() {
assertThat(provideReservedTermsExportDisclaimer(CONFIG_SETTINGS.get())) assertThat(provideReservedTermsExportDisclaimer(CONFIG_SETTINGS.get()))
.isEqualTo("# Disclaimer line 1.\n" + "# Line 2 is this 1."); .isEqualTo("# Disclaimer line 1.\n" + "# Line 2 is this 1.");
} }

View file

@ -14,16 +14,13 @@
package google.registry.config; package google.registry.config;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RegistryEnvironment}. */ /** Unit tests for {@link RegistryEnvironment}. */
@RunWith(JUnit4.class) class RegistryEnvironmentTest {
public class RegistryEnvironmentTest {
@Test @Test
public void testGet() { void testGet() {
RegistryEnvironment.get(); RegistryEnvironment.get();
} }
} }

View file

@ -26,20 +26,17 @@ import google.registry.util.TaskQueueUtils;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link CommitLogFanoutAction}. */ /** Unit tests for {@link CommitLogFanoutAction}. */
@RunWith(JUnit4.class) class CommitLogFanoutActionTest {
public class CommitLogFanoutActionTest {
private static final String ENDPOINT = "/the/servlet"; private static final String ENDPOINT = "/the/servlet";
private static final String QUEUE = "the-queue"; private static final String QUEUE = "the-queue";
@Rule @RegisterExtension
public final AppEngineRule appEngine = final AppEngineRule appEngineRule =
AppEngineRule.builder() AppEngineRule.builder()
.withDatastoreAndCloudSql() .withDatastoreAndCloudSql()
.withTaskQueue( .withTaskQueue(
@ -55,7 +52,7 @@ public class CommitLogFanoutActionTest {
.build(); .build();
@Test @Test
public void testSuccess() { void testSuccess() {
CommitLogFanoutAction action = new CommitLogFanoutAction(); CommitLogFanoutAction action = new CommitLogFanoutAction();
action.taskQueueUtils = new TaskQueueUtils(new Retrier(null, 1)); action.taskQueueUtils = new TaskQueueUtils(new Retrier(null, 1));
action.endpoint = ENDPOINT; action.endpoint = ENDPOINT;

View file

@ -39,22 +39,19 @@ import google.registry.util.TaskQueueUtils;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Stream; import java.util.stream.Stream;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link TldFanoutAction}. */ /** Unit tests for {@link TldFanoutAction}. */
@RunWith(JUnit4.class) class TldFanoutActionTest {
public class TldFanoutActionTest {
private static final String ENDPOINT = "/the/servlet"; private static final String ENDPOINT = "/the/servlet";
private static final String QUEUE = "the-queue"; private static final String QUEUE = "the-queue";
private final FakeResponse response = new FakeResponse(); private final FakeResponse response = new FakeResponse();
@Rule @RegisterExtension
public final AppEngineRule appEngine = final AppEngineRule appEngine =
AppEngineRule.builder() AppEngineRule.builder()
.withDatastoreAndCloudSql() .withDatastoreAndCloudSql()
.withTaskQueue( .withTaskQueue(
@ -96,8 +93,8 @@ public class TldFanoutActionTest {
action.run(); action.run();
} }
@Before @BeforeEach
public void before() { void beforeEach() {
createTlds("com", "net", "org", "example"); createTlds("com", "net", "org", "example");
persistResource(Registry.get("example").asBuilder().setTldType(TldType.TEST).build()); persistResource(Registry.get("example").asBuilder().setTldType(TldType.TEST).build());
} }
@ -123,36 +120,36 @@ public class TldFanoutActionTest {
} }
@Test @Test
public void testSuccess_methodPostIsDefault() { void testSuccess_methodPostIsDefault() {
run(getParamsMap("runInEmpty", "")); run(getParamsMap("runInEmpty", ""));
assertTasksEnqueued(QUEUE, new TaskMatcher().method("POST")); assertTasksEnqueued(QUEUE, new TaskMatcher().method("POST"));
} }
@Test @Test
public void testFailure_noTlds() { void testFailure_noTlds() {
assertThrows(IllegalArgumentException.class, () -> run(getParamsMap())); assertThrows(IllegalArgumentException.class, () -> run(getParamsMap()));
} }
@Test @Test
public void testSuccess_runInEmpty() { void testSuccess_runInEmpty() {
run(getParamsMap("runInEmpty", "")); run(getParamsMap("runInEmpty", ""));
assertTaskWithoutTld(); assertTaskWithoutTld();
} }
@Test @Test
public void testSuccess_forEachRealTld() { void testSuccess_forEachRealTld() {
run(getParamsMap("forEachRealTld", "")); run(getParamsMap("forEachRealTld", ""));
assertTasks("com", "net", "org"); assertTasks("com", "net", "org");
} }
@Test @Test
public void testSuccess_forEachTestTld() { void testSuccess_forEachTestTld() {
run(getParamsMap("forEachTestTld", "")); run(getParamsMap("forEachTestTld", ""));
assertTasks("example"); assertTasks("example");
} }
@Test @Test
public void testSuccess_forEachTestTldAndForEachRealTld() { void testSuccess_forEachTestTldAndForEachRealTld() {
run(getParamsMap( run(getParamsMap(
"forEachTestTld", "", "forEachTestTld", "",
"forEachRealTld", "")); "forEachRealTld", ""));
@ -160,13 +157,13 @@ public class TldFanoutActionTest {
} }
@Test @Test
public void testSuccess_runEverywhere() { void testSuccess_runEverywhere() {
run(getParamsMap("forEachTestTld", "", "forEachRealTld", "")); run(getParamsMap("forEachTestTld", "", "forEachRealTld", ""));
assertTasks("com", "net", "org", "example"); assertTasks("com", "net", "org", "example");
} }
@Test @Test
public void testSuccess_excludeRealTlds() { void testSuccess_excludeRealTlds() {
run(getParamsMap( run(getParamsMap(
"forEachRealTld", "", "forEachRealTld", "",
"exclude", "com,net")); "exclude", "com,net"));
@ -174,7 +171,7 @@ public class TldFanoutActionTest {
} }
@Test @Test
public void testSuccess_excludeTestTlds() { void testSuccess_excludeTestTlds() {
run(getParamsMap( run(getParamsMap(
"forEachTestTld", "", "forEachTestTld", "",
"exclude", "example")); "exclude", "example"));
@ -182,7 +179,7 @@ public class TldFanoutActionTest {
} }
@Test @Test
public void testSuccess_excludeNonexistentTlds() { void testSuccess_excludeNonexistentTlds() {
run(getParamsMap( run(getParamsMap(
"forEachTestTld", "", "forEachTestTld", "",
"forEachRealTld", "", "forEachRealTld", "",
@ -191,7 +188,7 @@ public class TldFanoutActionTest {
} }
@Test @Test
public void testFailure_runInEmptyAndTest() { void testFailure_runInEmptyAndTest() {
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> () ->
@ -202,7 +199,7 @@ public class TldFanoutActionTest {
} }
@Test @Test
public void testFailure_runInEmptyAndReal() { void testFailure_runInEmptyAndReal() {
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> () ->
@ -213,7 +210,7 @@ public class TldFanoutActionTest {
} }
@Test @Test
public void testFailure_runInEmptyAndExclude() { void testFailure_runInEmptyAndExclude() {
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> () ->
@ -224,14 +221,14 @@ public class TldFanoutActionTest {
} }
@Test @Test
public void testSuccess_additionalArgsFlowThroughToPostParams() { void testSuccess_additionalArgsFlowThroughToPostParams() {
run(getParamsMap("forEachTestTld", "", "newkey", "newval")); run(getParamsMap("forEachTestTld", "", "newkey", "newval"));
assertTasksEnqueued(QUEUE, assertTasksEnqueued(QUEUE,
new TaskMatcher().url("/the/servlet").param("newkey", "newval")); new TaskMatcher().url("/the/servlet").param("newkey", "newval"));
} }
@Test @Test
public void testSuccess_returnHttpResponse() { void testSuccess_returnHttpResponse() {
run(getParamsMap("forEachRealTld", "", "endpoint", "/the/servlet")); run(getParamsMap("forEachRealTld", "", "endpoint", "/the/servlet"));
List<TaskStateInfo> taskList = List<TaskStateInfo> taskList =
@ -250,7 +247,7 @@ public class TldFanoutActionTest {
} }
@Test @Test
public void testSuccess_returnHttpResponse_runInEmpty() { void testSuccess_returnHttpResponse_runInEmpty() {
run(getParamsMap("runInEmpty", "", "endpoint", "/the/servlet")); run(getParamsMap("runInEmpty", "", "endpoint", "/the/servlet"));
List<TaskStateInfo> taskList = List<TaskStateInfo> taskList =

View file

@ -22,13 +22,10 @@ import com.google.common.base.Joiner;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests to ensure that generated flow documentation matches the expected documentation. */ /** Tests to ensure that generated flow documentation matches the expected documentation. */
@RunWith(JUnit4.class) class FlowDocumentationTest {
public class FlowDocumentationTest {
private static final Path GOLDEN_MARKDOWN_FILEPATH = getProjectRoot().resolve("docs/flows.md"); private static final Path GOLDEN_MARKDOWN_FILEPATH = getProjectRoot().resolve("docs/flows.md");
private static final String UPDATE_COMMAND = "./gradlew :core:flowDocsTool"; private static final String UPDATE_COMMAND = "./gradlew :core:flowDocsTool";
@ -43,7 +40,7 @@ public class FlowDocumentationTest {
""); "");
@Test @Test
public void testGeneratedMatchesGolden() throws IOException { void testGeneratedMatchesGolden() throws IOException {
// Read the markdown file. // Read the markdown file.
Path goldenMarkdownPath = Path goldenMarkdownPath =
GOLDEN_MARKDOWN_FILEPATH; GOLDEN_MARKDOWN_FILEPATH;

View file

@ -21,9 +21,7 @@ import com.google.common.flogger.FluentLogger;
import google.registry.documentation.FlowDocumentation.ErrorCase; import google.registry.documentation.FlowDocumentation.ErrorCase;
import java.io.IOException; import java.io.IOException;
import java.util.Set; import java.util.Set;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** /**
* Test to ensure accurate documentation of flow exceptions. * Test to ensure accurate documentation of flow exceptions.
@ -47,13 +45,12 @@ import org.junit.runners.JUnit4;
* removing the javadoc tag. * removing the javadoc tag.
*/ */
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
@RunWith(JUnit4.class) class FlowExceptionsTest {
public class FlowExceptionsTest {
private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final FluentLogger logger = FluentLogger.forEnclosingClass();
@Test @Test
public void testExceptionCorrespondence() throws IOException { void testExceptionCorrespondence() throws IOException {
DocumentationGenerator docGenerator = new DocumentationGenerator(); DocumentationGenerator docGenerator = new DocumentationGenerator();
Set<ErrorCase> possibleErrors = Sets.newHashSet(docGenerator.getAllErrors()); Set<ErrorCase> possibleErrors = Sets.newHashSet(docGenerator.getAllErrors());
Set<String> mismatchingFlows = Sets.newHashSet(); Set<String> mismatchingFlows = Sets.newHashSet();

View file

@ -18,15 +18,13 @@ import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertThrows;
import java.util.Arrays; import java.util.Arrays;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Test conversion of javadocs to markdown. */ /** Test conversion of javadocs to markdown. */
@RunWith(JUnit4.class) class MarkdownDocumentationFormatterTest {
public class MarkdownDocumentationFormatterTest {
@Test @Test
public void testHtmlSanitization() { void testHtmlSanitization() {
assertThat( assertThat(
MarkdownDocumentationFormatter.fixHtml( MarkdownDocumentationFormatter.fixHtml(
"First. <p>Second. &lt; &gt; &amp; &squot; &quot;")) "First. <p>Second. &lt; &gt; &amp; &squot; &quot;"))
@ -38,27 +36,27 @@ public class MarkdownDocumentationFormatterTest {
} }
@Test @Test
public void testDedents() { void testDedents() {
assertThat(MarkdownDocumentationFormatter.fixHtml( assertThat(
"First line\n\n <p>Second line.\n Third line.")) MarkdownDocumentationFormatter.fixHtml("First line\n\n <p>Second line.\n Third line."))
.isEqualTo("First line\n\nSecond line.\nThird line."); .isEqualTo("First line\n\nSecond line.\nThird line.");
} }
@Test @Test
public void testUnknownSequences() { void testUnknownSequences() {
assertThrows( assertThrows(
IllegalArgumentException.class, () -> MarkdownDocumentationFormatter.fixHtml("&blech;")); IllegalArgumentException.class, () -> MarkdownDocumentationFormatter.fixHtml("&blech;"));
} }
@Test @Test
public void testParagraphFormatting() { void testParagraphFormatting() {
String[] words = {"first", "second", "third", "really-really-long-word", "more", "stuff"}; String[] words = {"first", "second", "third", "really-really-long-word", "more", "stuff"};
String formatted = MarkdownDocumentationFormatter.formatParagraph(Arrays.asList(words), 16); String formatted = MarkdownDocumentationFormatter.formatParagraph(Arrays.asList(words), 16);
assertThat(formatted).isEqualTo("first second\nthird\nreally-really-long-word\nmore stuff\n"); assertThat(formatted).isEqualTo("first second\nthird\nreally-really-long-word\nmore stuff\n");
} }
@Test @Test
public void testReflow() { void testReflow() {
String input = String input =
"This is the very first line.\n" "This is the very first line.\n"
+ " \n" // add a little blank space to this line just to make things interesting. + " \n" // add a little blank space to this line just to make things interesting.
@ -88,5 +86,5 @@ public class MarkdownDocumentationFormatterTest {
assertThat(MarkdownDocumentationFormatter.reflow(input, 16)).isEqualTo(expected); assertThat(MarkdownDocumentationFormatter.reflow(input, 16)).isEqualTo(expected);
} }
public MarkdownDocumentationFormatterTest() {} MarkdownDocumentationFormatterTest() {}
} }

View file

@ -49,16 +49,12 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import google.registry.groups.GroupsConnection.Role; import google.registry.groups.GroupsConnection.Role;
import java.util.Set; import java.util.Set;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; /** Unit tests for {@link DirectoryGroupsConnection}. */
class DirectoryGroupsConnectionTest {
/**
* Unit tests for {@link DirectoryGroupsConnection}.
*/
@RunWith(JUnit4.class)
public class DirectoryGroupsConnectionTest {
private final Directory directory = mock(Directory.class); private final Directory directory = mock(Directory.class);
private final Groupssettings groupsSettings = mock(Groupssettings.class); private final Groupssettings groupsSettings = mock(Groupssettings.class);
private final Directory.Members members = mock(Directory.Members.class); private final Directory.Members members = mock(Directory.Members.class);
@ -75,8 +71,8 @@ public class DirectoryGroupsConnectionTest {
private DirectoryGroupsConnection connection; private DirectoryGroupsConnection connection;
private Member expectedOwner = new Member(); private Member expectedOwner = new Member();
@Before @BeforeEach
public void init() throws Exception { void beforeEach() throws Exception {
when(directory.members()).thenReturn(members); when(directory.members()).thenReturn(members);
when(members.insert(anyString(), any(Member.class))).thenReturn(membersInsert); when(members.insert(anyString(), any(Member.class))).thenReturn(membersInsert);
when(members.get(anyString(), anyString())).thenReturn(membersGet); when(members.get(anyString(), anyString())).thenReturn(membersGet);
@ -94,12 +90,12 @@ public class DirectoryGroupsConnectionTest {
} }
@Test @Test
public void test_addMemberToGroup_succeeds() throws Exception { void test_addMemberToGroup_succeeds() throws Exception {
runAddMemberTest(); runAddMemberTest();
} }
@Test @Test
public void test_addMemberToGroup_isIdempotent_whenMemberAlreadyExists() throws Exception { void test_addMemberToGroup_isIdempotent_whenMemberAlreadyExists() throws Exception {
Member expected = runAddMemberTest(); Member expected = runAddMemberTest();
when(membersInsert.execute()) when(membersInsert.execute())
.thenThrow(makeResponseException(SC_CONFLICT, "Member already exists.")); .thenThrow(makeResponseException(SC_CONFLICT, "Member already exists."));
@ -109,14 +105,14 @@ public class DirectoryGroupsConnectionTest {
} }
@Test @Test
public void test_addMemberToGroup_handlesExceptionThrownByDirectoryService() throws Exception { void test_addMemberToGroup_handlesExceptionThrownByDirectoryService() throws Exception {
when(membersInsert.execute()).thenThrow( when(membersInsert.execute()).thenThrow(
makeResponseException(SC_INTERNAL_SERVER_ERROR, "Could not contact Directory server.")); makeResponseException(SC_INTERNAL_SERVER_ERROR, "Could not contact Directory server."));
assertThrows(GoogleJsonResponseException.class, this::runAddMemberTest); assertThrows(GoogleJsonResponseException.class, this::runAddMemberTest);
} }
@Test @Test
public void test_addMemberToGroup_handlesMemberKeyNotFoundException() throws Exception { void test_addMemberToGroup_handlesMemberKeyNotFoundException() throws Exception {
when(membersInsert.execute()).thenThrow( when(membersInsert.execute()).thenThrow(
makeResponseException(SC_NOT_FOUND, "Resource Not Found: memberKey")); makeResponseException(SC_NOT_FOUND, "Resource Not Found: memberKey"));
RuntimeException thrown = RuntimeException thrown =
@ -131,7 +127,7 @@ public class DirectoryGroupsConnectionTest {
} }
@Test @Test
public void test_addMemberToGroup_createsGroupWhenNonexistent() throws Exception { void test_addMemberToGroup_createsGroupWhenNonexistent() throws Exception {
Member expected = new Member(); Member expected = new Member();
expected.setEmail("tim@example.com"); expected.setEmail("tim@example.com");
expected.setRole("MEMBER"); expected.setRole("MEMBER");
@ -157,12 +153,12 @@ public class DirectoryGroupsConnectionTest {
} }
@Test @Test
public void test_createGroup_succeeds() throws Exception { void test_createGroup_succeeds() throws Exception {
runCreateGroupTest(); runCreateGroupTest();
} }
@Test @Test
public void test_createGroup_isIdempotent_whenGroupAlreadyExists() throws Exception { void test_createGroup_isIdempotent_whenGroupAlreadyExists() throws Exception {
Group expected = runCreateGroupTest(); Group expected = runCreateGroupTest();
when(groupsInsert.execute()) when(groupsInsert.execute())
.thenThrow(makeResponseException(SC_CONFLICT, "Entity already exists.")); .thenThrow(makeResponseException(SC_CONFLICT, "Entity already exists."));
@ -173,14 +169,14 @@ public class DirectoryGroupsConnectionTest {
} }
@Test @Test
public void test_createGroup_handlesExceptionThrownByDirectoryService() throws Exception { void test_createGroup_handlesExceptionThrownByDirectoryService() throws Exception {
when(groupsInsert.execute()).thenThrow( when(groupsInsert.execute()).thenThrow(
makeResponseException(SC_INTERNAL_SERVER_ERROR, "Could not contact Directory server.")); makeResponseException(SC_INTERNAL_SERVER_ERROR, "Could not contact Directory server."));
assertThrows(GoogleJsonResponseException.class, this::runCreateGroupTest); assertThrows(GoogleJsonResponseException.class, this::runCreateGroupTest);
} }
@Test @Test
public void test_getMembersOfGroup_succeeds() throws Exception { void test_getMembersOfGroup_succeeds() throws Exception {
Member member1 = new Member(); Member member1 = new Member();
member1.setEmail("john@example.com"); member1.setEmail("john@example.com");
Member member2 = new Member(); Member member2 = new Member();
@ -208,7 +204,7 @@ public class DirectoryGroupsConnectionTest {
} }
@Test @Test
public void test_getMembersOfNonexistentGroup_returnsEmptySet() throws Exception { void test_getMembersOfNonexistentGroup_returnsEmptySet() throws Exception {
when(members.list("nonexistent_group@fake.notreal")).thenReturn(membersList); when(members.list("nonexistent_group@fake.notreal")).thenReturn(membersList);
when(membersList.setRoles("MEMBER")).thenReturn(membersList); when(membersList.setRoles("MEMBER")).thenReturn(membersList);
when(membersList.execute()) when(membersList.execute())
@ -217,7 +213,7 @@ public class DirectoryGroupsConnectionTest {
} }
@Test @Test
public void test_isMemberOfSupportGroup_userInGroup_True() throws Exception { void test_isMemberOfSupportGroup_userInGroup_True() throws Exception {
when(members.get("support@domain-registry.example", "user@example.com")).thenReturn(membersGet); when(members.get("support@domain-registry.example", "user@example.com")).thenReturn(membersGet);
when(membersGet.execute()).thenReturn(new Member()); when(membersGet.execute()).thenReturn(new Member());
assertThat(connection.isMemberOfGroup("user@example.com", "support@domain-registry.example")) assertThat(connection.isMemberOfGroup("user@example.com", "support@domain-registry.example"))
@ -225,7 +221,7 @@ public class DirectoryGroupsConnectionTest {
} }
@Test @Test
public void test_isMemberOfSupportGroup_userExistButNotInGroup_returnsFalse() throws Exception { void test_isMemberOfSupportGroup_userExistButNotInGroup_returnsFalse() throws Exception {
when(members.get("support@domain-registry.example", "user@example.com")) when(members.get("support@domain-registry.example", "user@example.com"))
.thenThrow(makeResponseException(0, "Resource Not Found: memberKey")); .thenThrow(makeResponseException(0, "Resource Not Found: memberKey"));
when(membersGet.execute()).thenReturn(new Member()); when(membersGet.execute()).thenReturn(new Member());
@ -234,7 +230,7 @@ public class DirectoryGroupsConnectionTest {
} }
@Test @Test
public void test_isMemberOfSupportGroup_userDoesntExist_returnsFalse() throws Exception { void test_isMemberOfSupportGroup_userDoesntExist_returnsFalse() throws Exception {
when(members.get("support@domain-registry.example", "user@example.com")) when(members.get("support@domain-registry.example", "user@example.com"))
.thenThrow(makeResponseException(0, "Missing required field: memberKey")); .thenThrow(makeResponseException(0, "Missing required field: memberKey"));
when(membersGet.execute()).thenReturn(new Member()); when(membersGet.execute()).thenReturn(new Member());
@ -243,7 +239,7 @@ public class DirectoryGroupsConnectionTest {
} }
@Test @Test
public void test_isMemberOfSupportGroup_otherError_throws() throws Exception { void test_isMemberOfSupportGroup_otherError_throws() throws Exception {
when(members.get("support@domain-registry.example", "user@example.com")) when(members.get("support@domain-registry.example", "user@example.com"))
.thenThrow(makeResponseException(0, "some error")); .thenThrow(makeResponseException(0, "some error"));
when(membersGet.execute()).thenReturn(new Member()); when(membersGet.execute()).thenReturn(new Member());

View file

@ -30,15 +30,12 @@ import org.bouncycastle.bcpg.PublicKeyPacket;
import org.bouncycastle.openpgp.PGPKeyPair; import org.bouncycastle.openpgp.PGPKeyPair;
import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPPublicKey;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link ComparatorKeyring}. */ /** Unit tests for {@link ComparatorKeyring}. */
@RunWith(JUnit4.class) class ComparatorKeyringTest {
public class ComparatorKeyringTest {
private static final String PUBLIC_KEY_FINGERPRINT = "fingerprint"; private static final String PUBLIC_KEY_FINGERPRINT = "fingerprint";
private static final String PUBLIC_KEY_TO_STRING = private static final String PUBLIC_KEY_TO_STRING =
@ -79,18 +76,18 @@ public class ComparatorKeyringTest {
private final TestLogHandler testLogHandler = new TestLogHandler(); private final TestLogHandler testLogHandler = new TestLogHandler();
@Before @BeforeEach
public void setUp() { void beforeEach() {
LoggerConfig.getConfig(ComparatorKeyring.class).addHandler(testLogHandler); LoggerConfig.getConfig(ComparatorKeyring.class).addHandler(testLogHandler);
} }
@After @AfterEach
public void tearDown() { void afterEach() {
LoggerConfig.getConfig(ComparatorKeyring.class).removeHandler(testLogHandler); LoggerConfig.getConfig(ComparatorKeyring.class).removeHandler(testLogHandler);
} }
@Test @Test
public void testPublicKeyToString() throws Exception { void testPublicKeyToString() throws Exception {
assertThat( assertThat(
ComparatorKeyring.stringify( ComparatorKeyring.stringify(
mockPublicKey(false, false))) mockPublicKey(false, false)))
@ -98,7 +95,7 @@ public class ComparatorKeyringTest {
} }
@Test @Test
public void testPublicKeyEquals() throws Exception { void testPublicKeyEquals() throws Exception {
assertThat( assertThat(
ComparatorKeyring.compare( ComparatorKeyring.compare(
mockPublicKey(false, false), mockPublicKey(false, false),
@ -107,7 +104,7 @@ public class ComparatorKeyringTest {
} }
@Test @Test
public void testPublicKeyDifferFingerprint_notEqual() throws Exception { void testPublicKeyDifferFingerprint_notEqual() throws Exception {
assertThat( assertThat(
ComparatorKeyring.compare( ComparatorKeyring.compare(
mockPublicKey(false, false), mockPublicKey(false, false),
@ -116,7 +113,7 @@ public class ComparatorKeyringTest {
} }
@Test @Test
public void testPublicKeyDifferEncoded_notEqual() throws Exception { void testPublicKeyDifferEncoded_notEqual() throws Exception {
assertThat( assertThat(
ComparatorKeyring.compare( ComparatorKeyring.compare(
mockPublicKey(false, false), mockPublicKey(false, false),
@ -125,7 +122,7 @@ public class ComparatorKeyringTest {
} }
@Test @Test
public void testPrivateKeyToString() throws Exception { void testPrivateKeyToString() throws Exception {
assertThat( assertThat(
ComparatorKeyring.stringify( ComparatorKeyring.stringify(
mockPrivateKey(false, false, false, false))) mockPrivateKey(false, false, false, false)))
@ -133,7 +130,7 @@ public class ComparatorKeyringTest {
} }
@Test @Test
public void testPrivateKeyEquals() throws Exception { void testPrivateKeyEquals() throws Exception {
assertThat( assertThat(
ComparatorKeyring.compare( ComparatorKeyring.compare(
mockPrivateKey(false, false, false, false), mockPrivateKey(false, false, false, false),
@ -142,7 +139,7 @@ public class ComparatorKeyringTest {
} }
@Test @Test
public void testPrivateKeyDifferId_notEquals() throws Exception { void testPrivateKeyDifferId_notEquals() throws Exception {
assertThat( assertThat(
ComparatorKeyring.compare( ComparatorKeyring.compare(
mockPrivateKey(false, false, false, false), mockPrivateKey(false, false, false, false),
@ -151,7 +148,7 @@ public class ComparatorKeyringTest {
} }
@Test @Test
public void testPrivateKeyDifferBcpgFormat_notEquals() throws Exception { void testPrivateKeyDifferBcpgFormat_notEquals() throws Exception {
assertThat( assertThat(
ComparatorKeyring.compare( ComparatorKeyring.compare(
mockPrivateKey(false, false, false, false), mockPrivateKey(false, false, false, false),
@ -160,7 +157,7 @@ public class ComparatorKeyringTest {
} }
@Test @Test
public void testPrivateKeyDifferBcpgEncoding_notEquals() throws Exception { void testPrivateKeyDifferBcpgEncoding_notEquals() throws Exception {
assertThat( assertThat(
ComparatorKeyring.compare( ComparatorKeyring.compare(
mockPrivateKey(false, false, false, false), mockPrivateKey(false, false, false, false),
@ -169,7 +166,7 @@ public class ComparatorKeyringTest {
} }
@Test @Test
public void testPrivateKeyDifferPublicKeyEncoding_notEquals() throws Exception { void testPrivateKeyDifferPublicKeyEncoding_notEquals() throws Exception {
assertThat( assertThat(
ComparatorKeyring.compare( ComparatorKeyring.compare(
mockPrivateKey(false, false, false, false), mockPrivateKey(false, false, false, false),
@ -178,7 +175,7 @@ public class ComparatorKeyringTest {
} }
@Test @Test
public void testKeyPairToString() throws Exception { void testKeyPairToString() throws Exception {
assertThat( assertThat(
ComparatorKeyring.stringify( ComparatorKeyring.stringify(
new PGPKeyPair( new PGPKeyPair(
@ -188,7 +185,7 @@ public class ComparatorKeyringTest {
} }
@Test @Test
public void testKeyPairEquals() throws Exception { void testKeyPairEquals() throws Exception {
assertThat( assertThat(
ComparatorKeyring.compare( ComparatorKeyring.compare(
new PGPKeyPair( new PGPKeyPair(
@ -201,7 +198,7 @@ public class ComparatorKeyringTest {
} }
@Test @Test
public void testKeyPairDifferPublicKey_notEqual() throws Exception { void testKeyPairDifferPublicKey_notEqual() throws Exception {
assertThat( assertThat(
ComparatorKeyring.compare( ComparatorKeyring.compare(
new PGPKeyPair( new PGPKeyPair(
@ -214,7 +211,7 @@ public class ComparatorKeyringTest {
} }
@Test @Test
public void testKeyPairDifferPrivateKey_notEqual() throws Exception { void testKeyPairDifferPrivateKey_notEqual() throws Exception {
assertThat( assertThat(
ComparatorKeyring.compare( ComparatorKeyring.compare(
new PGPKeyPair( new PGPKeyPair(
@ -232,7 +229,7 @@ public class ComparatorKeyringTest {
// We will fully test a single method just to make sure everything is "connected" correctly. // We will fully test a single method just to make sure everything is "connected" correctly.
@Test @Test
public void testRdeSigningKey_actualThrows() throws Exception { void testRdeSigningKey_actualThrows() throws Exception {
Keyring actualKeyring = mock(Keyring.class); Keyring actualKeyring = mock(Keyring.class);
Keyring secondKeyring = mock(Keyring.class); Keyring secondKeyring = mock(Keyring.class);
PGPKeyPair keyPair = PGPKeyPair keyPair =
@ -252,7 +249,7 @@ public class ComparatorKeyringTest {
} }
@Test @Test
public void testRdeSigningKey_secondThrows() throws Exception { void testRdeSigningKey_secondThrows() throws Exception {
Keyring actualKeyring = mock(Keyring.class); Keyring actualKeyring = mock(Keyring.class);
Keyring secondKeyring = mock(Keyring.class); Keyring secondKeyring = mock(Keyring.class);
PGPKeyPair keyPair = PGPKeyPair keyPair =
@ -272,7 +269,7 @@ public class ComparatorKeyringTest {
} }
@Test @Test
public void testRdeSigningKey_bothThrow() { void testRdeSigningKey_bothThrow() {
Keyring actualKeyring = mock(Keyring.class); Keyring actualKeyring = mock(Keyring.class);
Keyring secondKeyring = mock(Keyring.class); Keyring secondKeyring = mock(Keyring.class);
when(actualKeyring.getRdeSigningKey()).thenThrow(new KeyringException("message")); when(actualKeyring.getRdeSigningKey()).thenThrow(new KeyringException("message"));
@ -285,7 +282,7 @@ public class ComparatorKeyringTest {
} }
@Test @Test
public void testRdeSigningKey_same() throws Exception { void testRdeSigningKey_same() throws Exception {
Keyring actualKeyring = mock(Keyring.class); Keyring actualKeyring = mock(Keyring.class);
Keyring secondKeyring = mock(Keyring.class); Keyring secondKeyring = mock(Keyring.class);
PGPKeyPair keyPair = PGPKeyPair keyPair =
@ -306,7 +303,7 @@ public class ComparatorKeyringTest {
} }
@Test @Test
public void testRdeSigningKey_different() throws Exception { void testRdeSigningKey_different() throws Exception {
Keyring actualKeyring = mock(Keyring.class); Keyring actualKeyring = mock(Keyring.class);
Keyring secondKeyring = mock(Keyring.class); Keyring secondKeyring = mock(Keyring.class);
PGPKeyPair keyPair = PGPKeyPair keyPair =

View file

@ -38,21 +38,20 @@ import google.registry.testing.FakeClock;
import google.registry.testing.FakeSleeper; import google.registry.testing.FakeSleeper;
import google.registry.util.Retrier; import google.registry.util.Retrier;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Captor; import org.mockito.Captor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit; import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.MockitoRule; import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
@RunWith(JUnit4.class) /** Unit tests for {@link KmsConnectionImpl}. */
public class KmsConnectionImplTest { @ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@Rule public final MockitoRule mocks = MockitoJUnit.rule(); class KmsConnectionImplTest {
@Mock private CloudKMS kms; @Mock private CloudKMS kms;
@Mock private CloudKMS.Projects kmsProjects; @Mock private CloudKMS.Projects kmsProjects;
@ -91,8 +90,8 @@ public class KmsConnectionImplTest {
private final Retrier retrier = new Retrier(new FakeSleeper(new FakeClock()), 3); private final Retrier retrier = new Retrier(new FakeSleeper(new FakeClock()), 3);
@Before @BeforeEach
public void setUp() throws Exception { void beforeEach() throws Exception {
when(kms.projects()).thenReturn(kmsProjects); when(kms.projects()).thenReturn(kmsProjects);
when(kmsProjects.locations()).thenReturn(kmsLocations); when(kmsProjects.locations()).thenReturn(kmsLocations);
when(kmsLocations.keyRings()).thenReturn(kmsKeyRings); when(kmsLocations.keyRings()).thenReturn(kmsKeyRings);
@ -123,7 +122,7 @@ public class KmsConnectionImplTest {
} }
@Test @Test
public void test_encrypt_createsKeyRingIfNotFound() throws Exception { void test_encrypt_createsKeyRingIfNotFound() throws Exception {
when(kmsKeyRingsGet.execute()).thenThrow(createNotFoundException()); when(kmsKeyRingsGet.execute()).thenThrow(createNotFoundException());
new KmsConnectionImpl("foo", "bar", retrier, kms).encrypt("key", "moo".getBytes(UTF_8)); new KmsConnectionImpl("foo", "bar", retrier, kms).encrypt("key", "moo".getBytes(UTF_8));
@ -142,7 +141,7 @@ public class KmsConnectionImplTest {
} }
@Test @Test
public void test_encrypt_newCryptoKey() throws Exception { void test_encrypt_newCryptoKey() throws Exception {
when(kmsCryptoKeysGet.execute()).thenThrow(createNotFoundException()); when(kmsCryptoKeysGet.execute()).thenThrow(createNotFoundException());
new KmsConnectionImpl("foo", "bar", retrier, kms).encrypt("key", "moo".getBytes(UTF_8)); new KmsConnectionImpl("foo", "bar", retrier, kms).encrypt("key", "moo".getBytes(UTF_8));
@ -163,10 +162,9 @@ public class KmsConnectionImplTest {
} }
@Test @Test
public void test_encrypt() throws Exception { void test_encrypt() throws Exception {
new KmsConnectionImpl("foo", "bar", retrier, kms).encrypt("key", "moo".getBytes(UTF_8)); new KmsConnectionImpl("foo", "bar", retrier, kms).encrypt("key", "moo".getBytes(UTF_8));
verify(kmsCryptoKeyVersions).create(cryptoKeyName.capture(), cryptoKeyVersion.capture()); verify(kmsCryptoKeyVersions).create(cryptoKeyName.capture(), cryptoKeyVersion.capture());
assertThat(cryptoKeyName.getValue()) assertThat(cryptoKeyName.getValue())
.isEqualTo("projects/foo/locations/global/keyRings/bar/cryptoKeys/key"); .isEqualTo("projects/foo/locations/global/keyRings/bar/cryptoKeys/key");
@ -188,7 +186,7 @@ public class KmsConnectionImplTest {
} }
@Test @Test
public void test_decrypt() throws Exception { void test_decrypt() throws Exception {
when(kmsCryptoKeysDecrypt.execute()) when(kmsCryptoKeysDecrypt.execute())
.thenReturn(new DecryptResponse().encodePlaintext("moo".getBytes(UTF_8))); .thenReturn(new DecryptResponse().encodePlaintext("moo".getBytes(UTF_8)));

View file

@ -50,45 +50,39 @@ import java.util.Set;
import org.joda.money.Money; import org.joda.money.Money;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.DateTimeZone; import org.joda.time.DateTimeZone;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests {@link ChildEntityInput} */ /** Tests {@link ChildEntityInput} */
@RunWith(JUnit4.class) class ChildEntityInputTest {
public class ChildEntityInputTest {
private static final DateTime now = DateTime.now(DateTimeZone.UTC); private static final DateTime now = DateTime.now(DateTimeZone.UTC);
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
DomainBase domainA; private DomainBase domainA;
DomainBase domainB; private DomainBase domainB;
HistoryEntry domainHistoryEntryA; private HistoryEntry domainHistoryEntryA;
HistoryEntry domainHistoryEntryB; private HistoryEntry domainHistoryEntryB;
HistoryEntry contactHistoryEntry; private HistoryEntry contactHistoryEntry;
BillingEvent.OneTime oneTimeA; private BillingEvent.OneTime oneTimeA;
BillingEvent.OneTime oneTimeB; private BillingEvent.OneTime oneTimeB;
BillingEvent.Recurring recurringA; private BillingEvent.Recurring recurringA;
BillingEvent.Recurring recurringB; private BillingEvent.Recurring recurringB;
private void setupResources() { private void setupResources() {
createTld("tld"); createTld("tld");
ContactResource contact = persistEppResourceInFirstBucket(newContactResource("contact1234")); ContactResource contact = persistEppResourceInFirstBucket(newContactResource("contact1234"));
domainA = persistEppResourceInFirstBucket(newDomainBase("a.tld", contact)); domainA = persistEppResourceInFirstBucket(newDomainBase("a.tld", contact));
domainHistoryEntryA = persistResource( domainHistoryEntryA =
new HistoryEntry.Builder() persistResource(
.setParent(domainA) new HistoryEntry.Builder().setParent(domainA).setModificationTime(now).build());
.setModificationTime(now) contactHistoryEntry =
.build()); persistResource(
contactHistoryEntry = persistResource( new HistoryEntry.Builder().setParent(contact).setModificationTime(now).build());
new HistoryEntry.Builder() oneTimeA =
.setParent(contact) persistResource(
.setModificationTime(now)
.build());
oneTimeA = persistResource(
new BillingEvent.OneTime.Builder() new BillingEvent.OneTime.Builder()
.setParent(domainHistoryEntryA) .setParent(domainHistoryEntryA)
.setReason(Reason.CREATE) .setReason(Reason.CREATE)
@ -100,7 +94,8 @@ public class ChildEntityInputTest {
.setClientId("TheRegistrar") .setClientId("TheRegistrar")
.setTargetId("a.tld") .setTargetId("a.tld")
.build()); .build());
recurringA = persistResource( recurringA =
persistResource(
new BillingEvent.Recurring.Builder() new BillingEvent.Recurring.Builder()
.setParent(domainHistoryEntryA) .setParent(domainHistoryEntryA)
.setReason(Reason.RENEW) .setReason(Reason.RENEW)
@ -113,12 +108,11 @@ public class ChildEntityInputTest {
private void setupSecondDomainBases() { private void setupSecondDomainBases() {
domainB = persistEppResourceInFirstBucket(newDomainBase("b.tld")); domainB = persistEppResourceInFirstBucket(newDomainBase("b.tld"));
domainHistoryEntryB = persistResource( domainHistoryEntryB =
new HistoryEntry.Builder() persistResource(
.setParent(domainB) new HistoryEntry.Builder().setParent(domainB).setModificationTime(now).build());
.setModificationTime(now) oneTimeB =
.build()); persistResource(
oneTimeB = persistResource(
new BillingEvent.OneTime.Builder() new BillingEvent.OneTime.Builder()
.setParent(domainHistoryEntryA) .setParent(domainHistoryEntryA)
.setReason(Reason.CREATE) .setReason(Reason.CREATE)
@ -130,7 +124,8 @@ public class ChildEntityInputTest {
.setClientId("TheRegistrar") .setClientId("TheRegistrar")
.setTargetId("a.tld") .setTargetId("a.tld")
.build()); .build());
recurringB = persistResource( recurringB =
persistResource(
new BillingEvent.Recurring.Builder() new BillingEvent.Recurring.Builder()
.setParent(domainHistoryEntryA) .setParent(domainHistoryEntryA)
.setReason(Reason.RENEW) .setReason(Reason.RENEW)
@ -154,15 +149,17 @@ public class ChildEntityInputTest {
} }
@Test @Test
public void testSuccess_childEntityReader_multipleParentsAndChildren() throws Exception { void testSuccess_childEntityReader_multipleParentsAndChildren() throws Exception {
setupResources(); setupResources();
setupSecondDomainBases(); setupSecondDomainBases();
Set<ImmutableObject> seen = new HashSet<>(); Set<ImmutableObject> seen = new HashSet<>();
InputReader<ImmutableObject> reader = EppResourceInputs.createChildEntityInput( InputReader<ImmutableObject> reader =
EppResourceInputs.createChildEntityInput(
ImmutableSet.of(EppResource.class), ImmutableSet.of(EppResource.class),
ImmutableSet.<Class<? extends ImmutableObject>>of( ImmutableSet.<Class<? extends ImmutableObject>>of(
HistoryEntry.class, BillingEvent.OneTime.class, BillingEvent.Recurring.class)) HistoryEntry.class, BillingEvent.OneTime.class, BillingEvent.Recurring.class))
.createReaders().get(0); .createReaders()
.get(0);
reader.beginShard(); reader.beginShard();
reader.beginSlice(); reader.beginSlice();
for (int i = 0; i < 8; i++) { for (int i = 0; i < 8; i++) {
@ -177,7 +174,8 @@ public class ChildEntityInputTest {
seen.add(reader.next()); seen.add(reader.next());
} }
} }
assertThat(seen).containsExactly( assertThat(seen)
.containsExactly(
domainHistoryEntryA, domainHistoryEntryA,
domainHistoryEntryB, domainHistoryEntryB,
contactHistoryEntry, contactHistoryEntry,
@ -188,20 +186,22 @@ public class ChildEntityInputTest {
} }
@Test @Test
public void testSuccess_childEntityInput_polymorphicBaseType() { void testSuccess_childEntityInput_polymorphicBaseType() {
createChildEntityInput(ImmutableSet.of(EppResource.class), ImmutableSet.of(BillingEvent.class)); createChildEntityInput(ImmutableSet.of(EppResource.class), ImmutableSet.of(BillingEvent.class));
} }
@Test @Test
public void testSuccess_childEntityReader_multipleChildTypes() throws Exception { void testSuccess_childEntityReader_multipleChildTypes() throws Exception {
setupResources(); setupResources();
InputReader<ImmutableObject> reader = EppResourceInputs.createChildEntityInput( InputReader<ImmutableObject> reader =
EppResourceInputs.createChildEntityInput(
ImmutableSet.of(EppResource.class), ImmutableSet.of(EppResource.class),
ImmutableSet.<Class<? extends ImmutableObject>>of( ImmutableSet.<Class<? extends ImmutableObject>>of(
HistoryEntry.class, BillingEvent.OneTime.class, BillingEvent.Recurring.class)) HistoryEntry.class, BillingEvent.OneTime.class, BillingEvent.Recurring.class))
.createReaders().get(0); .createReaders()
assertThat(getAllFromReader(reader)).containsExactly( .get(0);
domainHistoryEntryA, contactHistoryEntry, oneTimeA, recurringA); assertThat(getAllFromReader(reader))
.containsExactly(domainHistoryEntryA, contactHistoryEntry, oneTimeA, recurringA);
} }
private static Set<ImmutableObject> getAllFromReader(InputReader<ImmutableObject> reader) private static Set<ImmutableObject> getAllFromReader(InputReader<ImmutableObject> reader)
@ -220,61 +220,72 @@ public class ChildEntityInputTest {
} }
@Test @Test
public void testSuccess_childEntityReader_filterParentTypes() throws Exception { void testSuccess_childEntityReader_filterParentTypes() throws Exception {
setupResources(); setupResources();
InputReader<ImmutableObject> reader = EppResourceInputs.createChildEntityInput( InputReader<ImmutableObject> reader =
EppResourceInputs.createChildEntityInput(
ImmutableSet.<Class<? extends EppResource>>of(ContactResource.class), ImmutableSet.<Class<? extends EppResource>>of(ContactResource.class),
ImmutableSet.<Class<? extends ImmutableObject>>of( ImmutableSet.<Class<? extends ImmutableObject>>of(
HistoryEntry.class, BillingEvent.OneTime.class, BillingEvent.Recurring.class)) HistoryEntry.class, BillingEvent.OneTime.class, BillingEvent.Recurring.class))
.createReaders().get(0); .createReaders()
.get(0);
assertThat(getAllFromReader(reader)).containsExactly(contactHistoryEntry); assertThat(getAllFromReader(reader)).containsExactly(contactHistoryEntry);
} }
@Test @Test
public void testSuccess_childEntityReader_polymorphicChildFiltering() throws Exception { void testSuccess_childEntityReader_polymorphicChildFiltering() throws Exception {
setupResources(); setupResources();
InputReader<ImmutableObject> reader = EppResourceInputs.createChildEntityInput( InputReader<ImmutableObject> reader =
EppResourceInputs.createChildEntityInput(
ImmutableSet.of(EppResource.class), ImmutableSet.of(EppResource.class),
ImmutableSet.<Class<? extends ImmutableObject>>of(BillingEvent.OneTime.class)) ImmutableSet.<Class<? extends ImmutableObject>>of(BillingEvent.OneTime.class))
.createReaders().get(0); .createReaders()
.get(0);
assertThat(getAllFromReader(reader)).containsExactly(oneTimeA); assertThat(getAllFromReader(reader)).containsExactly(oneTimeA);
} }
@Test @Test
public void testSuccess_childEntityReader_polymorphicChildClass() throws Exception { void testSuccess_childEntityReader_polymorphicChildClass() throws Exception {
setupResources(); setupResources();
InputReader<ImmutableObject> reader = EppResourceInputs.createChildEntityInput( InputReader<ImmutableObject> reader =
EppResourceInputs.createChildEntityInput(
ImmutableSet.of(EppResource.class), ImmutableSet.of(EppResource.class),
ImmutableSet.<Class<? extends ImmutableObject>>of(BillingEvent.class)) ImmutableSet.<Class<? extends ImmutableObject>>of(BillingEvent.class))
.createReaders().get(0); .createReaders()
.get(0);
assertThat(getAllFromReader(reader)).containsExactly(oneTimeA, recurringA); assertThat(getAllFromReader(reader)).containsExactly(oneTimeA, recurringA);
} }
@Test @Test
public void testSuccess_childEntityReader_noneReturned() throws Exception { void testSuccess_childEntityReader_noneReturned() throws Exception {
createTld("tld"); createTld("tld");
InputReader<ImmutableObject> reader = EppResourceInputs.createChildEntityInput( InputReader<ImmutableObject> reader =
EppResourceInputs.createChildEntityInput(
ImmutableSet.<Class<? extends EppResource>>of(ContactResource.class), ImmutableSet.<Class<? extends EppResource>>of(ContactResource.class),
ImmutableSet.<Class<? extends ImmutableObject>>of( ImmutableSet.<Class<? extends ImmutableObject>>of(BillingEvent.OneTime.class))
BillingEvent.OneTime.class)).createReaders().get(0); .createReaders()
.get(0);
assertThat(getAllFromReader(reader)).isEmpty(); assertThat(getAllFromReader(reader)).isEmpty();
} }
@Test @Test
public void testSuccess_childEntityReader_readerCountMatchesBucketCount() throws Exception { void testSuccess_childEntityReader_readerCountMatchesBucketCount() throws Exception {
assertThat(EppResourceInputs.createChildEntityInput( assertThat(
EppResourceInputs.createChildEntityInput(
ImmutableSet.<Class<? extends EppResource>>of(DomainBase.class), ImmutableSet.<Class<? extends EppResource>>of(DomainBase.class),
ImmutableSet.<Class<? extends ImmutableObject>>of( ImmutableSet.<Class<? extends ImmutableObject>>of(BillingEvent.OneTime.class))
BillingEvent.OneTime.class)).createReaders()).hasSize(3); .createReaders())
.hasSize(3);
} }
@Test @Test
public void testSuccess_childEntityReader_oneReaderPerBucket() throws Exception { void testSuccess_childEntityReader_oneReaderPerBucket() throws Exception {
createTld("tld"); createTld("tld");
Set<ImmutableObject> historyEntries = new HashSet<>(); Set<ImmutableObject> historyEntries = new HashSet<>();
for (int i = 1; i <= 3; i++) { for (int i = 1; i <= 3; i++) {
DomainBase domain = persistSimpleResource(newDomainBase(i + ".tld")); DomainBase domain = persistSimpleResource(newDomainBase(i + ".tld"));
historyEntries.add(persistResource( historyEntries.add(
persistResource(
new HistoryEntry.Builder() new HistoryEntry.Builder()
.setParent(domain) .setParent(domain)
.setModificationTime(now) .setModificationTime(now)
@ -283,9 +294,11 @@ public class ChildEntityInputTest {
persistResource(EppResourceIndex.create(getBucketKey(i), Key.create(domain))); persistResource(EppResourceIndex.create(getBucketKey(i), Key.create(domain)));
} }
Set<ImmutableObject> seen = new HashSet<>(); Set<ImmutableObject> seen = new HashSet<>();
for (InputReader<ImmutableObject> reader : EppResourceInputs.createChildEntityInput( for (InputReader<ImmutableObject> reader :
EppResourceInputs.createChildEntityInput(
ImmutableSet.<Class<? extends EppResource>>of(DomainBase.class), ImmutableSet.<Class<? extends EppResource>>of(DomainBase.class),
ImmutableSet.<Class<? extends ImmutableObject>>of(HistoryEntry.class)).createReaders()) { ImmutableSet.<Class<? extends ImmutableObject>>of(HistoryEntry.class))
.createReaders()) {
reader.beginShard(); reader.beginShard();
reader.beginSlice(); reader.beginSlice();
seen.add(reader.next()); seen.add(reader.next());
@ -299,7 +312,7 @@ public class ChildEntityInputTest {
} }
@Test @Test
public void testSuccess_childEntityReader_survivesAcrossSerialization() throws Exception { void testSuccess_childEntityReader_survivesAcrossSerialization() throws Exception {
setupResources(); setupResources();
Set<ImmutableObject> seen = new HashSet<>(); Set<ImmutableObject> seen = new HashSet<>();
InputReader<ImmutableObject> reader = InputReader<ImmutableObject> reader =

View file

@ -30,14 +30,11 @@ import java.util.List;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Set; import java.util.Set;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link CommitLogManifestInput}. */ /** Unit tests for {@link CommitLogManifestInput}. */
@RunWith(JUnit4.class) final class CommitLogManifestInputTest {
public final class CommitLogManifestInputTest {
private static final DateTime DATE_TIME_OLD = DateTime.parse("2015-12-19T12:00Z"); private static final DateTime DATE_TIME_OLD = DateTime.parse("2015-12-19T12:00Z");
private static final DateTime DATE_TIME_OLD2 = DateTime.parse("2016-12-19T11:59Z"); private static final DateTime DATE_TIME_OLD2 = DateTime.parse("2016-12-19T11:59Z");
@ -47,19 +44,18 @@ public final class CommitLogManifestInputTest {
private static final DateTime DATE_TIME_NEW = DateTime.parse("2016-12-19T12:01Z"); private static final DateTime DATE_TIME_NEW = DateTime.parse("2016-12-19T12:01Z");
private static final DateTime DATE_TIME_NEW2 = DateTime.parse("2017-12-19T12:00Z"); private static final DateTime DATE_TIME_NEW2 = DateTime.parse("2017-12-19T12:00Z");
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Test @Test
public void testInputOlderThan_allFound() throws Exception { void testInputOlderThan_allFound() throws Exception {
Set<Key<CommitLogManifest>> created = new HashSet<>(); Set<Key<CommitLogManifest>> created = new HashSet<>();
for (int i = 1; i <= 3; i++) { for (int i = 1; i <= 3; i++) {
created.add(createManifest(CommitLogBucket.getBucketKey(i), DATE_TIME_OLD)); created.add(createManifest(CommitLogBucket.getBucketKey(i), DATE_TIME_OLD));
} }
List<Key<CommitLogManifest>> seen = new ArrayList<>(); List<Key<CommitLogManifest>> seen = new ArrayList<>();
Input<Key<CommitLogManifest>> input = new CommitLogManifestInput(DATE_TIME_THRESHOLD); Input<Key<CommitLogManifest>> input = new CommitLogManifestInput(DATE_TIME_THRESHOLD);
for (InputReader<Key<CommitLogManifest>> reader for (InputReader<Key<CommitLogManifest>> reader : input.createReaders()) {
: input.createReaders()) {
reader.beginShard(); reader.beginShard();
reader.beginSlice(); reader.beginSlice();
seen.add(reader.next()); seen.add(reader.next());
@ -73,7 +69,7 @@ public final class CommitLogManifestInputTest {
} }
@Test @Test
public void testInputOlderThan_skipsNew() throws Exception { void testInputOlderThan_skipsNew() throws Exception {
Set<Key<CommitLogManifest>> old = new HashSet<>(); Set<Key<CommitLogManifest>> old = new HashSet<>();
for (int i = 1; i <= 3; i++) { for (int i = 1; i <= 3; i++) {
createManifest(CommitLogBucket.getBucketKey(i), DATE_TIME_NEW); createManifest(CommitLogBucket.getBucketKey(i), DATE_TIME_NEW);
@ -83,8 +79,7 @@ public final class CommitLogManifestInputTest {
} }
List<Key<CommitLogManifest>> seen = new ArrayList<>(); List<Key<CommitLogManifest>> seen = new ArrayList<>();
Input<Key<CommitLogManifest>> input = new CommitLogManifestInput(DATE_TIME_THRESHOLD); Input<Key<CommitLogManifest>> input = new CommitLogManifestInput(DATE_TIME_THRESHOLD);
for (InputReader<Key<CommitLogManifest>> reader for (InputReader<Key<CommitLogManifest>> reader : input.createReaders()) {
: input.createReaders()) {
reader.beginShard(); reader.beginShard();
reader.beginSlice(); reader.beginSlice();
try { try {
@ -101,7 +96,7 @@ public final class CommitLogManifestInputTest {
} }
@Test @Test
public void testInputAll() throws Exception { void testInputAll() throws Exception {
Set<Key<CommitLogManifest>> created = new HashSet<>(); Set<Key<CommitLogManifest>> created = new HashSet<>();
for (int i = 1; i <= 3; i++) { for (int i = 1; i <= 3; i++) {
created.add(createManifest(CommitLogBucket.getBucketKey(i), DATE_TIME_NEW)); created.add(createManifest(CommitLogBucket.getBucketKey(i), DATE_TIME_NEW));
@ -111,8 +106,7 @@ public final class CommitLogManifestInputTest {
} }
List<Key<CommitLogManifest>> seen = new ArrayList<>(); List<Key<CommitLogManifest>> seen = new ArrayList<>();
Input<Key<CommitLogManifest>> input = new CommitLogManifestInput(); Input<Key<CommitLogManifest>> input = new CommitLogManifestInput();
for (InputReader<Key<CommitLogManifest>> reader for (InputReader<Key<CommitLogManifest>> reader : input.createReaders()) {
: input.createReaders()) {
reader.beginShard(); reader.beginShard();
reader.beginSlice(); reader.beginSlice();
try { try {
@ -129,8 +123,7 @@ public final class CommitLogManifestInputTest {
} }
private static Key<CommitLogManifest> createManifest( private static Key<CommitLogManifest> createManifest(
Key<CommitLogBucket> parent, Key<CommitLogBucket> parent, DateTime dateTime) {
DateTime dateTime) {
CommitLogManifest commitLogManifest = CommitLogManifest.create(parent, dateTime, null); CommitLogManifest commitLogManifest = CommitLogManifest.create(parent, dateTime, null);
DatastoreHelper.persistResource(commitLogManifest); DatastoreHelper.persistResource(commitLogManifest);
return Key.create(commitLogManifest); return Key.create(commitLogManifest);

View file

@ -44,19 +44,16 @@ import java.io.ObjectOutputStream;
import java.util.HashSet; import java.util.HashSet;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Set; import java.util.Set;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests {@link EppResourceInputs} */ /** Tests {@link EppResourceInputs} */
@RunWith(JUnit4.class) class EppResourceInputsTest {
public class EppResourceInputsTest {
private static final double EPSILON = 0.0001; private static final double EPSILON = 0.0001;
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private <T> T serializeAndDeserialize(T obj) throws Exception { private <T> T serializeAndDeserialize(T obj) throws Exception {
@ -71,12 +68,12 @@ public class EppResourceInputsTest {
} }
@Test @Test
public void testSuccess_keyInputType_polymorphicBaseType() { void testSuccess_keyInputType_polymorphicBaseType() {
createKeyInput(EppResource.class); createKeyInput(EppResource.class);
} }
@Test @Test
public void testFailure_keyInputType_noInheritanceBetweenTypes_eppResource() { void testFailure_keyInputType_noInheritanceBetweenTypes_eppResource() {
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
@ -85,7 +82,7 @@ public class EppResourceInputsTest {
} }
@Test @Test
public void testFailure_entityInputType_noInheritanceBetweenTypes_eppResource() { void testFailure_entityInputType_noInheritanceBetweenTypes_eppResource() {
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
@ -94,7 +91,7 @@ public class EppResourceInputsTest {
} }
@Test @Test
public void testFailure_entityInputType_noInheritanceBetweenTypes_subclasses() { void testFailure_entityInputType_noInheritanceBetweenTypes_subclasses() {
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
@ -103,13 +100,13 @@ public class EppResourceInputsTest {
} }
@Test @Test
public void testReaderCountMatchesBucketCount() throws Exception { void testReaderCountMatchesBucketCount() throws Exception {
assertThat(createKeyInput(DomainBase.class).createReaders()).hasSize(3); assertThat(createKeyInput(DomainBase.class).createReaders()).hasSize(3);
assertThat(createEntityInput(DomainBase.class).createReaders()).hasSize(3); assertThat(createEntityInput(DomainBase.class).createReaders()).hasSize(3);
} }
@Test @Test
public void testKeyInput_oneReaderPerBucket() throws Exception { void testKeyInput_oneReaderPerBucket() throws Exception {
createTld("tld"); createTld("tld");
Set<Key<DomainBase>> domains = new HashSet<>(); Set<Key<DomainBase>> domains = new HashSet<>();
for (int i = 1; i <= 3; i++) { for (int i = 1; i <= 3; i++) {
@ -132,7 +129,7 @@ public class EppResourceInputsTest {
} }
@Test @Test
public void testEntityInput_oneReaderPerBucket() throws Exception { void testEntityInput_oneReaderPerBucket() throws Exception {
createTld("tld"); createTld("tld");
Set<DomainBase> domains = new HashSet<>(); Set<DomainBase> domains = new HashSet<>();
for (int i = 1; i <= 3; i++) { for (int i = 1; i <= 3; i++) {
@ -142,8 +139,7 @@ public class EppResourceInputsTest {
persistResource(EppResourceIndex.create(getBucketKey(i), Key.create(domain))); persistResource(EppResourceIndex.create(getBucketKey(i), Key.create(domain)));
} }
Set<DomainBase> seen = new HashSet<>(); Set<DomainBase> seen = new HashSet<>();
for (InputReader<DomainBase> reader for (InputReader<DomainBase> reader : createEntityInput(DomainBase.class).createReaders()) {
: createEntityInput(DomainBase.class).createReaders()) {
reader.beginShard(); reader.beginShard();
reader.beginSlice(); reader.beginSlice();
seen.add(reader.next()); seen.add(reader.next());
@ -157,7 +153,7 @@ public class EppResourceInputsTest {
} }
@Test @Test
public void testSuccess_keyReader_survivesAcrossSerialization() throws Exception { void testSuccess_keyReader_survivesAcrossSerialization() throws Exception {
createTld("tld"); createTld("tld");
DomainBase domainA = persistEppResourceInFirstBucket(newDomainBase("a.tld")); DomainBase domainA = persistEppResourceInFirstBucket(newDomainBase("a.tld"));
DomainBase domainB = persistEppResourceInFirstBucket(newDomainBase("b.tld")); DomainBase domainB = persistEppResourceInFirstBucket(newDomainBase("b.tld"));
@ -181,15 +177,14 @@ public class EppResourceInputsTest {
} }
@Test @Test
public void testSuccess_entityReader_survivesAcrossSerialization() throws Exception { void testSuccess_entityReader_survivesAcrossSerialization() throws Exception {
createTld("tld"); createTld("tld");
DomainBase domainA = persistEppResourceInFirstBucket(newDomainBase("a.tld")); DomainBase domainA = persistEppResourceInFirstBucket(newDomainBase("a.tld"));
DomainBase domainB = persistEppResourceInFirstBucket(newDomainBase("b.tld")); DomainBase domainB = persistEppResourceInFirstBucket(newDomainBase("b.tld"));
// Should be ignored. We'll know if it isn't because the progress counts will be off. // Should be ignored. We'll know if it isn't because the progress counts will be off.
persistActiveContact("contact"); persistActiveContact("contact");
Set<DomainBase> seen = new HashSet<>(); Set<DomainBase> seen = new HashSet<>();
InputReader<DomainBase> reader = InputReader<DomainBase> reader = createEntityInput(DomainBase.class).createReaders().get(0);
createEntityInput(DomainBase.class).createReaders().get(0);
reader.beginShard(); reader.beginShard();
reader.beginSlice(); reader.beginSlice();
assertThat(reader.getProgress()).isWithin(EPSILON).of(0); assertThat(reader.getProgress()).isWithin(EPSILON).of(0);
@ -208,15 +203,16 @@ public class EppResourceInputsTest {
} }
@Test @Test
public void testSuccess_entityReader_filtersOnMultipleTypes() throws Exception { void testSuccess_entityReader_filtersOnMultipleTypes() throws Exception {
createTld("tld"); createTld("tld");
DomainBase domain = persistEppResourceInFirstBucket(newDomainBase("a.tld")); DomainBase domain = persistEppResourceInFirstBucket(newDomainBase("a.tld"));
HostResource host = persistEppResourceInFirstBucket(newHostResource("ns1.example.com")); HostResource host = persistEppResourceInFirstBucket(newHostResource("ns1.example.com"));
persistEppResourceInFirstBucket(newContactResource("contact")); persistEppResourceInFirstBucket(newContactResource("contact"));
Set<EppResource> seen = new HashSet<>(); Set<EppResource> seen = new HashSet<>();
InputReader<EppResource> reader = InputReader<EppResource> reader =
EppResourceInputs.<EppResource>createEntityInput( EppResourceInputs.<EppResource>createEntityInput(DomainBase.class, HostResource.class)
DomainBase.class, HostResource.class).createReaders().get(0); .createReaders()
.get(0);
reader.beginShard(); reader.beginShard();
reader.beginSlice(); reader.beginSlice();
assertThat(reader.getProgress()).isWithin(EPSILON).of(0); assertThat(reader.getProgress()).isWithin(EPSILON).of(0);
@ -229,7 +225,7 @@ public class EppResourceInputsTest {
} }
@Test @Test
public void testSuccess_entityReader_noFilteringWhenUsingEppResource() throws Exception { void testSuccess_entityReader_noFilteringWhenUsingEppResource() throws Exception {
createTld("tld"); createTld("tld");
ContactResource contact = persistEppResourceInFirstBucket(newContactResource("contact")); ContactResource contact = persistEppResourceInFirstBucket(newContactResource("contact"));
// Specify the contact since persistActiveDomain{Application} creates a hidden one. // Specify the contact since persistActiveDomain{Application} creates a hidden one.

View file

@ -22,40 +22,38 @@ import static google.registry.model.rde.RdeNamingUtils.makeRydeFilename;
import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertThrows;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RdeNamingUtils}. */ /** Unit tests for {@link RdeNamingUtils}. */
@RunWith(JUnit4.class) class RdeNamingUtilsTest {
public class RdeNamingUtilsTest {
@Test @Test
public void testMakeRydeFilename_rdeDeposit() { void testMakeRydeFilename_rdeDeposit() {
assertThat(makeRydeFilename("numbness", DateTime.parse("1984-12-18TZ"), FULL, 1, 0)) assertThat(makeRydeFilename("numbness", DateTime.parse("1984-12-18TZ"), FULL, 1, 0))
.isEqualTo("numbness_1984-12-18_full_S1_R0"); .isEqualTo("numbness_1984-12-18_full_S1_R0");
} }
@Test @Test
public void testMakeRydeFilename_brdaDeposit() { void testMakeRydeFilename_brdaDeposit() {
assertThat(makeRydeFilename("dreary", DateTime.parse("2000-12-18TZ"), THIN, 1, 0)) assertThat(makeRydeFilename("dreary", DateTime.parse("2000-12-18TZ"), THIN, 1, 0))
.isEqualTo("dreary_2000-12-18_thin_S1_R0"); .isEqualTo("dreary_2000-12-18_thin_S1_R0");
} }
@Test @Test
public void testMakeRydeFilename_revisionNumber() { void testMakeRydeFilename_revisionNumber() {
assertThat(makeRydeFilename("wretched", DateTime.parse("2000-12-18TZ"), THIN, 1, 123)) assertThat(makeRydeFilename("wretched", DateTime.parse("2000-12-18TZ"), THIN, 1, 123))
.isEqualTo("wretched_2000-12-18_thin_S1_R123"); .isEqualTo("wretched_2000-12-18_thin_S1_R123");
} }
@Test @Test
public void testMakeRydeFilename_timestampNotAtTheWitchingHour_throwsIae() { void testMakeRydeFilename_timestampNotAtTheWitchingHour_throwsIae() {
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> makeRydeFilename("wretched", DateTime.parse("2000-12-18T04:20Z"), THIN, 1, 0)); () -> makeRydeFilename("wretched", DateTime.parse("2000-12-18T04:20Z"), THIN, 1, 0));
} }
@Test @Test
public void testMakePartialName() { void testMakePartialName() {
assertThat(makePartialName("unholy", DateTime.parse("2000-12-18TZ"), THIN)) assertThat(makePartialName("unholy", DateTime.parse("2000-12-18TZ"), THIN))
.isEqualTo("unholy_2000-12-18_thin"); .isEqualTo("unholy_2000-12-18_thin");
} }

View file

@ -25,106 +25,95 @@ import static org.junit.Assert.assertThrows;
import com.google.common.base.VerifyException; import com.google.common.base.VerifyException;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RdeRevision}. */ /** Unit tests for {@link RdeRevision}. */
@RunWith(JUnit4.class)
public class RdeRevisionTest { public class RdeRevisionTest {
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Test @Test
public void testGetNextRevision_objectDoesntExist_returnsZero() { void testGetNextRevision_objectDoesntExist_returnsZero() {
assertThat(getNextRevision("torment", DateTime.parse("1984-12-18TZ"), FULL)) assertThat(getNextRevision("torment", DateTime.parse("1984-12-18TZ"), FULL)).isEqualTo(0);
.isEqualTo(0);
} }
@Test @Test
public void testGetNextRevision_objectExistsAtZero_returnsOne() { void testGetNextRevision_objectExistsAtZero_returnsOne() {
save("sorrow", DateTime.parse("1984-12-18TZ"), FULL, 0); save("sorrow", DateTime.parse("1984-12-18TZ"), FULL, 0);
assertThat(getNextRevision("sorrow", DateTime.parse("1984-12-18TZ"), FULL)) assertThat(getNextRevision("sorrow", DateTime.parse("1984-12-18TZ"), FULL)).isEqualTo(1);
.isEqualTo(1);
} }
@Test @Test
public void testSaveRevision_objectDoesntExist_newRevisionIsZero_nextRevIsOne() { void testSaveRevision_objectDoesntExist_newRevisionIsZero_nextRevIsOne() {
tm().transact(() -> saveRevision("despondency", DateTime.parse("1984-12-18TZ"), FULL, 0)); tm().transact(() -> saveRevision("despondency", DateTime.parse("1984-12-18TZ"), FULL, 0));
tm() tm().transact(
.transact(
() -> () ->
assertThat(getNextRevision("despondency", DateTime.parse("1984-12-18TZ"), FULL)) assertThat(getNextRevision("despondency", DateTime.parse("1984-12-18TZ"), FULL))
.isEqualTo(1)); .isEqualTo(1));
} }
@Test @Test
public void testSaveRevision_objectDoesntExist_newRevisionIsOne_throwsVe() { void testSaveRevision_objectDoesntExist_newRevisionIsOne_throwsVe() {
VerifyException thrown = VerifyException thrown =
assertThrows( assertThrows(
VerifyException.class, VerifyException.class,
() -> () ->
tm() tm().transact(
.transact(
() -> () ->
saveRevision("despondency", DateTime.parse("1984-12-18TZ"), FULL, 1))); saveRevision("despondency", DateTime.parse("1984-12-18TZ"), FULL, 1)));
assertThat(thrown).hasMessageThat().contains("object missing"); assertThat(thrown).hasMessageThat().contains("object missing");
} }
@Test @Test
public void testSaveRevision_objectExistsAtZero_newRevisionIsZero_throwsVe() { void testSaveRevision_objectExistsAtZero_newRevisionIsZero_throwsVe() {
save("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0); save("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0);
VerifyException thrown = VerifyException thrown =
assertThrows( assertThrows(
VerifyException.class, VerifyException.class,
() -> () ->
tm() tm().transact(
.transact(
() -> saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0))); () -> saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0)));
assertThat(thrown).hasMessageThat().contains("object already created"); assertThat(thrown).hasMessageThat().contains("object already created");
} }
@Test @Test
public void testSaveRevision_objectExistsAtZero_newRevisionIsOne_nextRevIsTwo() { void testSaveRevision_objectExistsAtZero_newRevisionIsOne_nextRevIsTwo() {
save("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0); save("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0);
tm().transact(() -> saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 1)); tm().transact(() -> saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 1));
tm() tm().transact(
.transact(
() -> () ->
assertThat(getNextRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL)) assertThat(getNextRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL))
.isEqualTo(2)); .isEqualTo(2));
} }
@Test @Test
public void testSaveRevision_objectExistsAtZero_newRevisionIsTwo_throwsVe() { void testSaveRevision_objectExistsAtZero_newRevisionIsTwo_throwsVe() {
save("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0); save("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0);
VerifyException thrown = VerifyException thrown =
assertThrows( assertThrows(
VerifyException.class, VerifyException.class,
() -> () ->
tm() tm().transact(
.transact(
() -> saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 2))); () -> saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 2)));
assertThat(thrown).hasMessageThat().contains("should be at 1 "); assertThat(thrown).hasMessageThat().contains("should be at 1 ");
} }
@Test @Test
public void testSaveRevision_negativeRevision_throwsIae() { void testSaveRevision_negativeRevision_throwsIae() {
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> () ->
tm() tm().transact(
.transact(
() -> () ->
saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, -1))); saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, -1)));
assertThat(thrown).hasMessageThat().contains("Negative revision"); assertThat(thrown).hasMessageThat().contains("Negative revision");
} }
@Test @Test
public void testSaveRevision_callerNotInTransaction_throwsIse() { void testSaveRevision_callerNotInTransaction_throwsIse() {
IllegalStateException thrown = IllegalStateException thrown =
assertThrows( assertThrows(
IllegalStateException.class, IllegalStateException.class,

View file

@ -24,30 +24,27 @@ import static org.junit.Assert.assertThrows;
import com.google.common.net.InternetDomainName; import com.google.common.net.InternetDomainName;
import google.registry.model.registry.Registry.TldType; import google.registry.model.registry.Registry.TldType;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link Registries}. */ /** Unit tests for {@link Registries}. */
@RunWith(JUnit4.class) class RegistriesTest {
public class RegistriesTest {
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
private void initTestTlds() { private void initTestTlds() {
createTlds("foo", "a.b.c"); // Test a multipart tld. createTlds("foo", "a.b.c"); // Test a multipart tld.
} }
@Test @Test
public void testGetTlds() { void testGetTlds() {
initTestTlds(); initTestTlds();
assertThat(Registries.getTlds()).containsExactly("foo", "a.b.c"); assertThat(Registries.getTlds()).containsExactly("foo", "a.b.c");
} }
@Test @Test
public void test_getTldEntities() { void test_getTldEntities() {
initTestTlds(); initTestTlds();
persistResource(newRegistry("testtld", "TESTTLD").asBuilder().setTldType(TldType.TEST).build()); persistResource(newRegistry("testtld", "TESTTLD").asBuilder().setTldType(TldType.TEST).build());
assertThat(Registries.getTldEntitiesOfType(TldType.REAL)) assertThat(Registries.getTldEntitiesOfType(TldType.REAL))
@ -57,25 +54,25 @@ public class RegistriesTest {
} }
@Test @Test
public void testGetTlds_withNoRegistriesPersisted_returnsEmptySet() { void testGetTlds_withNoRegistriesPersisted_returnsEmptySet() {
assertThat(Registries.getTlds()).isEmpty(); assertThat(Registries.getTlds()).isEmpty();
} }
@Test @Test
public void testAssertTldExists_doesExist() { void testAssertTldExists_doesExist() {
initTestTlds(); initTestTlds();
Registries.assertTldExists("foo"); Registries.assertTldExists("foo");
Registries.assertTldExists("a.b.c"); Registries.assertTldExists("a.b.c");
} }
@Test @Test
public void testAssertTldExists_doesntExist() { void testAssertTldExists_doesntExist() {
initTestTlds(); initTestTlds();
assertThrows(IllegalArgumentException.class, () -> Registries.assertTldExists("baz")); assertThrows(IllegalArgumentException.class, () -> Registries.assertTldExists("baz"));
} }
@Test @Test
public void testFindTldForName() { void testFindTldForName() {
initTestTlds(); initTestTlds();
assertThat(Registries.findTldForName(InternetDomainName.from("example.foo")).get().toString()) assertThat(Registries.findTldForName(InternetDomainName.from("example.foo")).get().toString())
.isEqualTo("foo"); .isEqualTo("foo");

View file

@ -24,23 +24,20 @@ import com.google.common.reflect.ClassPath.ResourceInfo;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import java.net.URL; import java.net.URL;
import java.util.List; import java.util.List;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Presubmit tests for {@link PremiumList} configuration files. */ /** Presubmit tests for {@link PremiumList} configuration files. */
@RunWith(JUnit4.class) class GenrulePremiumListTest {
public class GenrulePremiumListTest {
private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final String LISTS_DIRECTORY = "google/registry/config/files/premium/"; private static final String LISTS_DIRECTORY = "google/registry/config/files/premium/";
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Test @Test
public void testParse_allPremiumLists() throws Exception { void testParse_allPremiumLists() throws Exception {
ClassPath classpath = ClassPath.from(getClass().getClassLoader()); ClassPath classpath = ClassPath.from(getClass().getClassLoader());
int numParsed = 0; int numParsed = 0;
for (ResourceInfo resource : classpath.getResources()) { for (ResourceInfo resource : classpath.getResources()) {

View file

@ -24,23 +24,20 @@ import com.google.common.reflect.ClassPath.ResourceInfo;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import java.net.URL; import java.net.URL;
import java.util.List; import java.util.List;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Presubmit tests for {@link ReservedList} configuration files. */ /** Presubmit tests for {@link ReservedList} configuration files. */
@RunWith(JUnit4.class) class GenruleReservedListTest {
public class GenruleReservedListTest {
private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final String LISTS_DIRECTORY = "google/registry/config/files/reserved/"; private static final String LISTS_DIRECTORY = "google/registry/config/files/reserved/";
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Test @Test
public void testParse_allReservedLists() throws Exception { void testParse_allReservedLists() throws Exception {
ClassPath classpath = ClassPath.from(getClass().getClassLoader()); ClassPath classpath = ClassPath.from(getClass().getClassLoader());
int numParsed = 0; int numParsed = 0;
for (ResourceInfo resource : classpath.getResources()) { for (ResourceInfo resource : classpath.getResources()) {

View file

@ -39,26 +39,22 @@ import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock; import google.registry.testing.FakeClock;
import google.registry.testing.InjectRule; import google.registry.testing.InjectRule;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link ReservedList}. */ /** Unit tests for {@link ReservedList}. */
@RunWith(JUnit4.class) class ReservedListTest {
public class ReservedListTest {
@Rule @RegisterExtension final InjectRule inject = new InjectRule();
public final InjectRule inject = new InjectRule();
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
FakeClock clock = new FakeClock(DateTime.parse("2010-01-01T10:00:00Z")); private FakeClock clock = new FakeClock(DateTime.parse("2010-01-01T10:00:00Z"));
@Before @BeforeEach
public void before() { void beforeEach() {
inject.setStaticField(Ofy.class, "clock", clock); inject.setStaticField(Ofy.class, "clock", clock);
createTld("tld"); createTld("tld");
reservedListChecks.reset(); reservedListChecks.reset();
@ -79,7 +75,7 @@ public class ReservedListTest {
} }
@Test @Test
public void testGetReservationTypes_allLabelsAreUnreserved_withNoReservedLists() { void testGetReservationTypes_allLabelsAreUnreserved_withNoReservedLists() {
assertThat(Registry.get("tld").getReservedLists()).isEmpty(); assertThat(Registry.get("tld").getReservedLists()).isEmpty();
assertThat(getReservationTypes("doodle", "tld")).isEmpty(); assertThat(getReservationTypes("doodle", "tld")).isEmpty();
assertThat(getReservationTypes("access", "tld")).isEmpty(); assertThat(getReservationTypes("access", "tld")).isEmpty();
@ -88,13 +84,13 @@ public class ReservedListTest {
} }
@Test @Test
public void testZeroReservedLists_doesNotCauseError() { void testZeroReservedLists_doesNotCauseError() {
assertThat(getReservationTypes("doodle", "tld")).isEmpty(); assertThat(getReservationTypes("doodle", "tld")).isEmpty();
verifyUnreservedCheckCount(1); verifyUnreservedCheckCount(1);
} }
@Test @Test
public void testGetReservationTypes_twoLetterCodesAreAvailable() { void testGetReservationTypes_twoLetterCodesAreAvailable() {
for (String sld : ImmutableList.of("aa", "az", "zz", "91", "1n", "j5")) { for (String sld : ImmutableList.of("aa", "az", "zz", "91", "1n", "j5")) {
assertThat(getReservationTypes(sld, "tld")).isEmpty(); assertThat(getReservationTypes(sld, "tld")).isEmpty();
} }
@ -102,7 +98,7 @@ public class ReservedListTest {
} }
@Test @Test
public void testGetReservationTypes_singleCharacterDomainsAreAllowed() { void testGetReservationTypes_singleCharacterDomainsAreAllowed() {
// This isn't quite exhaustive but it's close. // This isn't quite exhaustive but it's close.
for (char c = 'a'; c <= 'z'; c++) { for (char c = 'a'; c <= 'z'; c++) {
assertThat(getReservationTypes("" + c, "tld")).isEmpty(); assertThat(getReservationTypes("" + c, "tld")).isEmpty();
@ -111,7 +107,7 @@ public class ReservedListTest {
} }
@Test @Test
public void testGetReservationTypes_concatsMultipleListsCorrectly() { void testGetReservationTypes_concatsMultipleListsCorrectly() {
ReservedList rl1 = persistReservedList( ReservedList rl1 = persistReservedList(
"reserved1", "reserved1",
"lol,FULLY_BLOCKED # yup", "lol,FULLY_BLOCKED # yup",
@ -153,7 +149,7 @@ public class ReservedListTest {
} }
@Test @Test
public void testGetReservationTypes_returnsAllReservationTypesFromMultipleListsForTheSameLabel() { void testGetReservationTypes_returnsAllReservationTypesFromMultipleListsForTheSameLabel() {
ReservedList rl1 = ReservedList rl1 =
persistReservedList("reserved1", "lol,NAME_COLLISION # yup", "cat,FULLY_BLOCKED"); persistReservedList("reserved1", "lol,NAME_COLLISION # yup", "cat,FULLY_BLOCKED");
ReservedList rl2 = ReservedList rl2 =
@ -167,9 +163,8 @@ public class ReservedListTest {
assertThat(getReservationTypes("snowcrash", "tld")).containsExactly(FULLY_BLOCKED); assertThat(getReservationTypes("snowcrash", "tld")).containsExactly(FULLY_BLOCKED);
} }
@Test @Test
public void testGetReservationTypes_worksAfterReservedListRemovedUsingSet() { void testGetReservationTypes_worksAfterReservedListRemovedUsingSet() {
ReservedList rl1 = persistReservedList( ReservedList rl1 = persistReservedList(
"reserved1", "lol,FULLY_BLOCKED", "cat,FULLY_BLOCKED"); "reserved1", "lol,FULLY_BLOCKED", "cat,FULLY_BLOCKED");
ReservedList rl2 = persistReservedList( ReservedList rl2 = persistReservedList(
@ -202,7 +197,7 @@ public class ReservedListTest {
} }
@Test @Test
public void testGetReservationTypes_combinesMultipleLists() { void testGetReservationTypes_combinesMultipleLists() {
ReservedList rl1 = persistReservedList( ReservedList rl1 = persistReservedList(
"reserved1", "lol,NAME_COLLISION", "roflcopter,ALLOWED_IN_SUNRISE"); "reserved1", "lol,NAME_COLLISION", "roflcopter,ALLOWED_IN_SUNRISE");
ReservedList rl2 = persistReservedList("reserved2", "lol,FULLY_BLOCKED"); ReservedList rl2 = persistReservedList("reserved2", "lol,FULLY_BLOCKED");
@ -233,7 +228,7 @@ public class ReservedListTest {
} }
@Test @Test
public void testSave() { void testSave() {
ReservedList rl = persistReservedList("tld-reserved", "lol,FULLY_BLOCKED # yup"); ReservedList rl = persistReservedList("tld-reserved", "lol,FULLY_BLOCKED # yup");
createTld("tld"); createTld("tld");
persistResource(Registry.get("tld").asBuilder().setReservedLists(rl).build()); persistResource(Registry.get("tld").asBuilder().setReservedLists(rl).build());
@ -241,7 +236,7 @@ public class ReservedListTest {
} }
@Test @Test
public void testSave_commentsArePersistedCorrectly() { void testSave_commentsArePersistedCorrectly() {
ReservedList reservedList = persistReservedList( ReservedList reservedList = persistReservedList(
"reserved", "reserved",
"trombone,FULLY_BLOCKED # yup", "trombone,FULLY_BLOCKED # yup",
@ -266,20 +261,20 @@ public class ReservedListTest {
} }
@Test @Test
public void testIsInUse_returnsTrueWhenInUse() { void testIsInUse_returnsTrueWhenInUse() {
ReservedList rl = persistReservedList("reserved", "trombone,FULLY_BLOCKED"); ReservedList rl = persistReservedList("reserved", "trombone,FULLY_BLOCKED");
persistResource(Registry.get("tld").asBuilder().setReservedLists(ImmutableSet.of(rl)).build()); persistResource(Registry.get("tld").asBuilder().setReservedLists(ImmutableSet.of(rl)).build());
assertThat(rl.isInUse()).isTrue(); assertThat(rl.isInUse()).isTrue();
} }
@Test @Test
public void testIsInUse_returnsFalseWhenNotInUse() { void testIsInUse_returnsFalseWhenNotInUse() {
ReservedList rl = persistReservedList("reserved", "trombone,FULLY_BLOCKED"); ReservedList rl = persistReservedList("reserved", "trombone,FULLY_BLOCKED");
assertThat(rl.isInUse()).isFalse(); assertThat(rl.isInUse()).isFalse();
} }
@Test @Test
public void testSetFromInputLines() { void testSetFromInputLines() {
ReservedList reservedList = persistReservedList("reserved", "trombone,FULLY_BLOCKED"); ReservedList reservedList = persistReservedList("reserved", "trombone,FULLY_BLOCKED");
assertThat(ReservedList.get("reserved").get().getReservedListEntries()).hasSize(1); assertThat(ReservedList.get("reserved").get().getReservedListEntries()).hasSize(1);
reservedList = reservedList.asBuilder() reservedList = reservedList.asBuilder()
@ -290,7 +285,7 @@ public class ReservedListTest {
} }
@Test @Test
public void testAsBuilderReturnsIdenticalReservedList() { void testAsBuilderReturnsIdenticalReservedList() {
ReservedList original = persistReservedList("tld-reserved-cloning", "trombone,FULLY_BLOCKED"); ReservedList original = persistReservedList("tld-reserved-cloning", "trombone,FULLY_BLOCKED");
ReservedList clone = original.asBuilder().build(); ReservedList clone = original.asBuilder().build();
assertThat(clone.getName()).isEqualTo("tld-reserved-cloning"); assertThat(clone.getName()).isEqualTo("tld-reserved-cloning");
@ -301,7 +296,7 @@ public class ReservedListTest {
} }
@Test @Test
public void testSave_badSyntax() { void testSave_badSyntax() {
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
@ -310,13 +305,13 @@ public class ReservedListTest {
} }
@Test @Test
public void testSave_badReservationType() { void testSave_badReservationType() {
assertThrows( assertThrows(
IllegalArgumentException.class, () -> persistReservedList("tld", "lol,FULLY_BLOCKZ # yup")); IllegalArgumentException.class, () -> persistReservedList("tld", "lol,FULLY_BLOCKZ # yup"));
} }
@Test @Test
public void testParse_cannotIncludeDuplicateLabels() { void testParse_cannotIncludeDuplicateLabels() {
ReservedList rl = new ReservedList.Builder().setName("blah").build(); ReservedList rl = new ReservedList.Builder().setName("blah").build();
IllegalStateException thrown = IllegalStateException thrown =
assertThrows( assertThrows(
@ -336,7 +331,7 @@ public class ReservedListTest {
} }
@Test @Test
public void testValidation_labelMustBeLowercase() { void testValidation_labelMustBeLowercase() {
Exception e = Exception e =
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
@ -345,7 +340,7 @@ public class ReservedListTest {
} }
@Test @Test
public void testValidation_labelMustBePunyCoded() { void testValidation_labelMustBePunyCoded() {
Exception e = Exception e =
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,

View file

@ -19,23 +19,20 @@ import static com.google.common.truth.Truth.assertThat;
import google.registry.request.Action; import google.registry.request.Action;
import google.registry.request.RouterDisplayHelper; import google.registry.request.RouterDisplayHelper;
import google.registry.testing.GoldenFileTestHelper; import google.registry.testing.GoldenFileTestHelper;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link BackendRequestComponent}. */ /** Unit tests for {@link BackendRequestComponent}. */
@RunWith(JUnit4.class) class BackendRequestComponentTest {
public class BackendRequestComponentTest {
@Test @Test
public void testRoutingMap() { void testRoutingMap() {
GoldenFileTestHelper.assertThatRoutesFromComponent(BackendRequestComponent.class) GoldenFileTestHelper.assertThatRoutesFromComponent(BackendRequestComponent.class)
.describedAs("backend routing map") .describedAs("backend routing map")
.isEqualToGolden(BackendRequestComponentTest.class, "backend_routing.txt"); .isEqualToGolden(BackendRequestComponentTest.class, "backend_routing.txt");
} }
@Test @Test
public void testRoutingService() { void testRoutingService() {
assertThat( assertThat(
RouterDisplayHelper.extractHumanReadableRoutesWithWrongService( RouterDisplayHelper.extractHumanReadableRoutesWithWrongService(
BackendRequestComponent.class, Action.Service.BACKEND)) BackendRequestComponent.class, Action.Service.BACKEND))

View file

@ -21,24 +21,21 @@ import static org.mockito.Mockito.when;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link BackendServlet}. */ /** Unit tests for {@link BackendServlet}. */
@RunWith(JUnit4.class) class BackendServletTest {
public class BackendServletTest {
@Rule @RegisterExtension
public final AppEngineRule appEngine = final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withLocalModules().build(); AppEngineRule.builder().withDatastoreAndCloudSql().withLocalModules().build();
private final HttpServletRequest req = mock(HttpServletRequest.class); private final HttpServletRequest req = mock(HttpServletRequest.class);
private final HttpServletResponse rsp = mock(HttpServletResponse.class); private final HttpServletResponse rsp = mock(HttpServletResponse.class);
@Test @Test
public void testService_unknownPath_returnsNotFound() throws Exception { void testService_unknownPath_returnsNotFound() throws Exception {
when(req.getMethod()).thenReturn("GET"); when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/lol"); when(req.getRequestURI()).thenReturn("/lol");
new BackendServlet().service(req, rsp); new BackendServlet().service(req, rsp);

View file

@ -19,23 +19,20 @@ import static com.google.common.truth.Truth.assertThat;
import google.registry.request.Action; import google.registry.request.Action;
import google.registry.request.RouterDisplayHelper; import google.registry.request.RouterDisplayHelper;
import google.registry.testing.GoldenFileTestHelper; import google.registry.testing.GoldenFileTestHelper;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link FrontendRequestComponent}. */ /** Unit tests for {@link FrontendRequestComponent}. */
@RunWith(JUnit4.class) class FrontendRequestComponentTest {
public class FrontendRequestComponentTest {
@Test @Test
public void testRoutingMap() { void testRoutingMap() {
GoldenFileTestHelper.assertThatRoutesFromComponent(FrontendRequestComponent.class) GoldenFileTestHelper.assertThatRoutesFromComponent(FrontendRequestComponent.class)
.describedAs("frontend routing map") .describedAs("frontend routing map")
.isEqualToGolden(FrontendRequestComponentTest.class, "frontend_routing.txt"); .isEqualToGolden(FrontendRequestComponentTest.class, "frontend_routing.txt");
} }
@Test @Test
public void testRoutingService() { void testRoutingService() {
assertThat( assertThat(
RouterDisplayHelper.extractHumanReadableRoutesWithWrongService( RouterDisplayHelper.extractHumanReadableRoutesWithWrongService(
FrontendRequestComponent.class, Action.Service.DEFAULT)) FrontendRequestComponent.class, Action.Service.DEFAULT))

View file

@ -21,24 +21,21 @@ import static org.mockito.Mockito.when;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link FrontendServlet}. */ /** Unit tests for {@link FrontendServlet}. */
@RunWith(JUnit4.class) class FrontendServletTest {
public class FrontendServletTest {
@Rule @RegisterExtension
public final AppEngineRule appEngine = final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withLocalModules().build(); AppEngineRule.builder().withDatastoreAndCloudSql().withLocalModules().build();
private final HttpServletRequest req = mock(HttpServletRequest.class); private final HttpServletRequest req = mock(HttpServletRequest.class);
private final HttpServletResponse rsp = mock(HttpServletResponse.class); private final HttpServletResponse rsp = mock(HttpServletResponse.class);
@Test @Test
public void testService_unknownPath_returnNotFound() throws Exception { void testService_unknownPath_returnNotFound() throws Exception {
when(req.getMethod()).thenReturn("GET"); when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/lol"); when(req.getRequestURI()).thenReturn("/lol");
new FrontendServlet().service(req, rsp); new FrontendServlet().service(req, rsp);

View file

@ -19,23 +19,20 @@ import static com.google.common.truth.Truth.assertThat;
import google.registry.request.Action; import google.registry.request.Action;
import google.registry.request.RouterDisplayHelper; import google.registry.request.RouterDisplayHelper;
import google.registry.testing.GoldenFileTestHelper; import google.registry.testing.GoldenFileTestHelper;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link PubApiRequestComponent}. */ /** Unit tests for {@link PubApiRequestComponent}. */
@RunWith(JUnit4.class) class PubApiRequestComponentTest {
public class PubApiRequestComponentTest {
@Test @Test
public void testRoutingMap() { void testRoutingMap() {
GoldenFileTestHelper.assertThatRoutesFromComponent(PubApiRequestComponent.class) GoldenFileTestHelper.assertThatRoutesFromComponent(PubApiRequestComponent.class)
.describedAs("pubapi routing map") .describedAs("pubapi routing map")
.isEqualToGolden(PubApiRequestComponentTest.class, "pubapi_routing.txt"); .isEqualToGolden(PubApiRequestComponentTest.class, "pubapi_routing.txt");
} }
@Test @Test
public void testRoutingService() { void testRoutingService() {
assertThat( assertThat(
RouterDisplayHelper.extractHumanReadableRoutesWithWrongService( RouterDisplayHelper.extractHumanReadableRoutesWithWrongService(
PubApiRequestComponent.class, Action.Service.PUBAPI)) PubApiRequestComponent.class, Action.Service.PUBAPI))

View file

@ -21,24 +21,21 @@ import static org.mockito.Mockito.when;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link PubApiServlet}. */ /** Unit tests for {@link PubApiServlet}. */
@RunWith(JUnit4.class) class PubApiServletTest {
public class PubApiServletTest {
@Rule @RegisterExtension
public final AppEngineRule appEngine = final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withLocalModules().build(); AppEngineRule.builder().withDatastoreAndCloudSql().withLocalModules().build();
private final HttpServletRequest req = mock(HttpServletRequest.class); private final HttpServletRequest req = mock(HttpServletRequest.class);
private final HttpServletResponse rsp = mock(HttpServletResponse.class); private final HttpServletResponse rsp = mock(HttpServletResponse.class);
@Test @Test
public void testService_unknownPath_returnNotFound() throws Exception { void testService_unknownPath_returnNotFound() throws Exception {
when(req.getMethod()).thenReturn("GET"); when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/lol"); when(req.getRequestURI()).thenReturn("/lol");
new PubApiServlet().service(req, rsp); new PubApiServlet().service(req, rsp);

View file

@ -19,23 +19,20 @@ import static com.google.common.truth.Truth.assertThat;
import google.registry.request.Action; import google.registry.request.Action;
import google.registry.request.RouterDisplayHelper; import google.registry.request.RouterDisplayHelper;
import google.registry.testing.GoldenFileTestHelper; import google.registry.testing.GoldenFileTestHelper;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link ToolsRequestComponent}. */ /** Unit tests for {@link ToolsRequestComponent}. */
@RunWith(JUnit4.class) class ToolsRequestComponentTest {
public class ToolsRequestComponentTest {
@Test @Test
public void testRoutingMap() { void testRoutingMap() {
GoldenFileTestHelper.assertThatRoutesFromComponent(ToolsRequestComponent.class) GoldenFileTestHelper.assertThatRoutesFromComponent(ToolsRequestComponent.class)
.describedAs("tools routing map") .describedAs("tools routing map")
.isEqualToGolden(ToolsRequestComponentTest.class, "tools_routing.txt"); .isEqualToGolden(ToolsRequestComponentTest.class, "tools_routing.txt");
} }
@Test @Test
public void testRoutingService() { void testRoutingService() {
assertThat( assertThat(
RouterDisplayHelper.extractHumanReadableRoutesWithWrongService( RouterDisplayHelper.extractHumanReadableRoutesWithWrongService(
ToolsRequestComponent.class, Action.Service.TOOLS)) ToolsRequestComponent.class, Action.Service.TOOLS))

View file

@ -20,19 +20,16 @@ import static org.mockito.Mockito.when;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link ToolsServlet}. */ /** Unit tests for {@link ToolsServlet}. */
@RunWith(JUnit4.class) class ToolsServletTest {
public class ToolsServletTest {
private final HttpServletRequest req = mock(HttpServletRequest.class); private final HttpServletRequest req = mock(HttpServletRequest.class);
private final HttpServletResponse rsp = mock(HttpServletResponse.class); private final HttpServletResponse rsp = mock(HttpServletResponse.class);
@Test @Test
public void testService_unknownPath_returnsNotFound() throws Exception { void testService_unknownPath_returnsNotFound() throws Exception {
when(req.getMethod()).thenReturn("GET"); when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/lol"); when(req.getRequestURI()).thenReturn("/lol");
new ToolsServlet().service(req, rsp); new ToolsServlet().service(req, rsp);

View file

@ -19,26 +19,23 @@ import static com.google.common.truth.Truth.assertThat;
import google.registry.monitoring.whitebox.CheckApiMetric.Status; import google.registry.monitoring.whitebox.CheckApiMetric.Status;
import google.registry.testing.FakeClock; import google.registry.testing.FakeClock;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link CheckApiMetric}. */ /** Unit tests for {@link CheckApiMetric}. */
@RunWith(JUnit4.class) class CheckApiMetricTest {
public class CheckApiMetricTest {
private static final DateTime START_TIME = DateTime.parse("2000-01-01T00:00:00.0Z"); private static final DateTime START_TIME = DateTime.parse("2000-01-01T00:00:00.0Z");
private final FakeClock clock = new FakeClock(START_TIME); private final FakeClock clock = new FakeClock(START_TIME);
private CheckApiMetric.Builder metricBuilder; private CheckApiMetric.Builder metricBuilder;
@Before @BeforeEach
public void setup() { void beforeEach() {
metricBuilder = CheckApiMetric.builder(clock); metricBuilder = CheckApiMetric.builder(clock);
} }
@Test @Test
public void testSuccess_timestampsAreSet() { void testSuccess_timestampsAreSet() {
clock.advanceOneMilli(); clock.advanceOneMilli();
CheckApiMetric metric = metricBuilder.status(Status.SUCCESS).build(); CheckApiMetric metric = metricBuilder.status(Status.SUCCESS).build();

View file

@ -21,20 +21,17 @@ import static google.registry.testing.DatastoreHelper.createTlds;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock; import google.registry.testing.FakeClock;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link EppMetric}. */ /** Unit tests for {@link EppMetric}. */
@RunWith(JUnit4.class) class EppMetricTest {
public class EppMetricTest {
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Test @Test
public void test_invalidTld_isRecordedAsInvalid() { void test_invalidTld_isRecordedAsInvalid() {
EppMetric metric = EppMetric metric =
EppMetric.builderForRequest(new FakeClock()) EppMetric.builderForRequest(new FakeClock())
.setTlds(ImmutableSet.of("notarealtld")) .setTlds(ImmutableSet.of("notarealtld"))
@ -43,7 +40,7 @@ public class EppMetricTest {
} }
@Test @Test
public void test_validTld_isRecorded() { void test_validTld_isRecorded() {
createTld("example"); createTld("example");
EppMetric metric = EppMetric metric =
EppMetric.builderForRequest(new FakeClock()).setTlds(ImmutableSet.of("example")).build(); EppMetric.builderForRequest(new FakeClock()).setTlds(ImmutableSet.of("example")).build();
@ -51,7 +48,7 @@ public class EppMetricTest {
} }
@Test @Test
public void test_multipleTlds_areRecordedAsVarious() { void test_multipleTlds_areRecordedAsVarious() {
createTlds("foo", "bar"); createTlds("foo", "bar");
EppMetric metric = EppMetric metric =
EppMetric.builderForRequest(new FakeClock()) EppMetric.builderForRequest(new FakeClock())
@ -61,7 +58,7 @@ public class EppMetricTest {
} }
@Test @Test
public void test_zeroTlds_areRecordedAsAbsent() { void test_zeroTlds_areRecordedAsAbsent() {
EppMetric metric = EppMetric metric =
EppMetric.builderForRequest(new FakeClock()).setTlds(ImmutableSet.of()).build(); EppMetric.builderForRequest(new FakeClock()).setTlds(ImmutableSet.of()).build();
assertThat(metric.getTld()).isEmpty(); assertThat(metric.getTld()).isEmpty();

View file

@ -21,40 +21,42 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import org.joda.money.CurrencyUnit; import org.joda.money.CurrencyUnit;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.ClassRule; import org.junit.jupiter.api.Test;
import org.junit.Rule; import org.junit.jupiter.api.io.TempDir;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
/** Unit tests for {@link HibernateSchemaExporter}. */ /** Unit tests for {@link HibernateSchemaExporter}. */
@RunWith(JUnit4.class) @Testcontainers
public class HibernateSchemaExporterTest { class HibernateSchemaExporterTest {
@ClassRule
public static final PostgreSQLContainer database = @Container
private static final PostgreSQLContainer database =
new PostgreSQLContainer(NomulusPostgreSql.getDockerTag()); new PostgreSQLContainer(NomulusPostgreSql.getDockerTag());
private static HibernateSchemaExporter exporter; private static HibernateSchemaExporter exporter;
@Rule public final TemporaryFolder tempFolder = new TemporaryFolder(); @SuppressWarnings("WeakerAccess")
@TempDir
Path tmpDir;
@BeforeClass @BeforeAll
public static void init() { static void beforeAll() {
exporter = exporter =
HibernateSchemaExporter.create( HibernateSchemaExporter.create(
database.getJdbcUrl(), database.getUsername(), database.getPassword()); database.getJdbcUrl(), database.getUsername(), database.getPassword());
} }
@Test @Test
public void export_succeeds() throws IOException { void export_succeeds() throws IOException {
File sqlFile = tempFolder.newFile(); File sqlFile = Files.createFile(tmpDir.resolve("tempfile.dat")).toFile();
exporter.export(ImmutableList.of(TestEntity.class), sqlFile); exporter.export(ImmutableList.of(HibernateSchemaTestEntity.class), sqlFile);
assertThat(Files.readAllBytes(sqlFile.toPath())) assertThat(Files.readAllBytes(sqlFile.toPath()))
.isEqualTo( .isEqualTo(
("\n" ("\n"
@ -67,7 +69,7 @@ public class HibernateSchemaExporterTest {
} }
@Entity(name = "TestEntity") // Override entity name to avoid the nested class reference. @Entity(name = "TestEntity") // Override entity name to avoid the nested class reference.
private static class TestEntity { private static class HibernateSchemaTestEntity {
@Id String name; @Id String name;
CurrencyUnit cu; CurrencyUnit cu;

View file

@ -16,26 +16,20 @@ package google.registry.persistence;
import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.truth.Truth.assertWithMessage;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.truth.Expect;
import java.util.Collections; import java.util.Collections;
import javax.persistence.AttributeConverter; import javax.persistence.AttributeConverter;
import javax.persistence.Entity; import javax.persistence.Entity;
import org.junit.ClassRule; import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests to verify persistence.xml is valid. */ /** Unit tests to verify persistence.xml is valid. */
@RunWith(JUnit4.class) class PersistenceXmlTest {
public class PersistenceXmlTest {
@ClassRule public static final Expect expect = Expect.create();
@Test @Test
public void verifyClassTags_containOnlyRequiredClasses() { void verifyClassTags_containOnlyRequiredClasses() {
ImmutableList<Class> managedClassed = PersistenceXmlUtility.getManagedClasses(); ImmutableList<Class> managedClassed = PersistenceXmlUtility.getManagedClasses();
ImmutableList<Class> unnecessaryClasses = ImmutableList<Class> unnecessaryClasses =
@ -51,13 +45,11 @@ public class PersistenceXmlTest {
.filter(clazz -> Collections.frequency(managedClassed, clazz) > 1) .filter(clazz -> Collections.frequency(managedClassed, clazz) > 1)
.collect(toImmutableSet()); .collect(toImmutableSet());
expect assertWithMessage("Found duplicate <class> tags defined in persistence.xml.")
.withMessage("Found duplicate <class> tags defined in persistence.xml.")
.that(duplicateClasses) .that(duplicateClasses)
.isEmpty(); .isEmpty();
expect assertWithMessage(
.withMessage(
"Found unnecessary <class> tags defined in persistence.xml. Only entity class and" "Found unnecessary <class> tags defined in persistence.xml. Only entity class and"
+ " implementation of AttributeConverter are required to be added in" + " implementation of AttributeConverter are required to be added in"
+ " persistence.xml.") + " persistence.xml.")

View file

@ -18,25 +18,21 @@ import static com.google.common.truth.Truth.assertThat;
import com.googlecode.objectify.Key; import com.googlecode.objectify.Key;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import google.registry.testing.TestObject; import google.registry.testing.TestObject;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) /** Unit tests for {@link VKey}. */
public class VKeyTest { class VKeyTest {
@Rule @RegisterExtension
public final AppEngineRule appEngineRule = final AppEngineRule appEngineRule =
AppEngineRule.builder() AppEngineRule.builder()
.withDatastoreAndCloudSql() .withDatastoreAndCloudSql()
.withOfyTestEntities(TestObject.class) .withOfyTestEntities(TestObject.class)
.build(); .build();
public VKeyTest() {}
@Test @Test
public void testOptionalAccessors() { void testOptionalAccessors() {
VKey<TestObject> key = VKey<TestObject> key =
VKey.create(TestObject.class, "foo", Key.create(TestObject.create("foo"))); VKey.create(TestObject.class, "foo", Key.create(TestObject.create("foo")));
assertThat(key.maybeGetSqlKey().isPresent()).isTrue(); assertThat(key.maybeGetSqlKey().isPresent()).isTrue();

View file

@ -17,16 +17,13 @@ package google.registry.persistence.transaction;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertThrows;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** JUnit test for {@link DummyJpaTransactionManager} */ /** JUnit test for {@link DummyJpaTransactionManager} */
@RunWith(JUnit4.class) class DummyJpaTransactionManagerTest {
public class DummyJpaTransactionManagerTest {
@Test @Test
public void throwsExceptionWhenAnyMethodIsInvoked() { void throwsExceptionWhenAnyMethodIsInvoked() {
assertThrows(UnsupportedOperationException.class, () -> jpaTm().transact(() -> null)); assertThrows(UnsupportedOperationException.class, () -> jpaTm().transact(() -> null));
assertThrows(UnsupportedOperationException.class, () -> jpaTm().getTransactionTime()); assertThrows(UnsupportedOperationException.class, () -> jpaTm().getTransactionTime());
} }

View file

@ -28,38 +28,35 @@ import javax.servlet.http.HttpServletRequest;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.LocalDate; import org.joda.time.LocalDate;
import org.joda.time.YearMonth; import org.joda.time.YearMonth;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link ReportingModule}. */ /** Unit tests for {@link ReportingModule}. */
@RunWith(JUnit4.class) class ReportingModuleTest {
public class ReportingModuleTest {
private HttpServletRequest req = mock(HttpServletRequest.class); private HttpServletRequest req = mock(HttpServletRequest.class);
private Clock clock; private Clock clock;
@Before @BeforeEach
public void setUp() { void beforeEach() {
clock = new FakeClock(DateTime.parse("2017-07-01TZ")); clock = new FakeClock(DateTime.parse("2017-07-01TZ"));
} }
@Test @Test
public void testEmptyYearMonthParameter_returnsEmptyYearMonthOptional() { void testEmptyYearMonthParameter_returnsEmptyYearMonthOptional() {
when(req.getParameter("yearMonth")).thenReturn(""); when(req.getParameter("yearMonth")).thenReturn("");
Truth8.assertThat(ReportingModule.provideYearMonthOptional(req)).isEmpty(); Truth8.assertThat(ReportingModule.provideYearMonthOptional(req)).isEmpty();
} }
@Test @Test
public void testValidYearMonthParameter_returnsThatMonth() { void testValidYearMonthParameter_returnsThatMonth() {
when(req.getParameter("yearMonth")).thenReturn("2017-05"); when(req.getParameter("yearMonth")).thenReturn("2017-05");
Truth8.assertThat(ReportingModule.provideYearMonthOptional(req)) Truth8.assertThat(ReportingModule.provideYearMonthOptional(req))
.hasValue(new YearMonth(2017, 5)); .hasValue(new YearMonth(2017, 5));
} }
@Test @Test
public void testInvalidYearMonthParameter_throwsException() { void testInvalidYearMonthParameter_throwsException() {
when(req.getParameter("yearMonth")).thenReturn("201705"); when(req.getParameter("yearMonth")).thenReturn("201705");
BadRequestException thrown = BadRequestException thrown =
assertThrows( assertThrows(
@ -70,13 +67,13 @@ public class ReportingModuleTest {
} }
@Test @Test
public void testEmptyYearMonth_returnsLastMonth() { void testEmptyYearMonth_returnsLastMonth() {
assertThat(ReportingModule.provideYearMonth(Optional.empty(), new LocalDate(2017, 1, 6))) assertThat(ReportingModule.provideYearMonth(Optional.empty(), new LocalDate(2017, 1, 6)))
.isEqualTo(new YearMonth(2016, 12)); .isEqualTo(new YearMonth(2016, 12));
} }
@Test @Test
public void testGivenYearMonth_returnsThatMonth() { void testGivenYearMonth_returnsThatMonth() {
assertThat( assertThat(
ReportingModule.provideYearMonth( ReportingModule.provideYearMonth(
Optional.of(new YearMonth(2017, 5)), new LocalDate(2017, 7, 6))) Optional.of(new YearMonth(2017, 5)), new LocalDate(2017, 7, 6)))
@ -84,20 +81,20 @@ public class ReportingModuleTest {
} }
@Test @Test
public void testEmptyDateParameter_returnsEmptyDateOptional() { void testEmptyDateParameter_returnsEmptyDateOptional() {
when(req.getParameter("date")).thenReturn(""); when(req.getParameter("date")).thenReturn("");
Truth8.assertThat(ReportingModule.provideDateOptional(req)).isEmpty(); Truth8.assertThat(ReportingModule.provideDateOptional(req)).isEmpty();
} }
@Test @Test
public void testValidDateParameter_returnsThatDate() { void testValidDateParameter_returnsThatDate() {
when(req.getParameter("date")).thenReturn("2017-05-13"); when(req.getParameter("date")).thenReturn("2017-05-13");
Truth8.assertThat(ReportingModule.provideDateOptional(req)) Truth8.assertThat(ReportingModule.provideDateOptional(req))
.hasValue(new LocalDate(2017, 5, 13)); .hasValue(new LocalDate(2017, 5, 13));
} }
@Test @Test
public void testInvalidDateParameter_throwsException() { void testInvalidDateParameter_throwsException() {
when(req.getParameter("date")).thenReturn("20170513"); when(req.getParameter("date")).thenReturn("20170513");
BadRequestException thrown = BadRequestException thrown =
assertThrows(BadRequestException.class, () -> ReportingModule.provideDateOptional(req)); assertThrows(BadRequestException.class, () -> ReportingModule.provideDateOptional(req));
@ -107,13 +104,13 @@ public class ReportingModuleTest {
} }
@Test @Test
public void testEmptyDate_returnsToday() { void testEmptyDate_returnsToday() {
when(req.getParameter("date")).thenReturn(null); when(req.getParameter("date")).thenReturn(null);
assertThat(ReportingModule.provideDate(req, clock)).isEqualTo(new LocalDate(2017, 7, 1)); assertThat(ReportingModule.provideDate(req, clock)).isEqualTo(new LocalDate(2017, 7, 1));
} }
@Test @Test
public void testGivenDate_returnsThatDate() { void testGivenDate_returnsThatDate() {
when(req.getParameter("date")).thenReturn("2017-07-02"); when(req.getParameter("date")).thenReturn("2017-07-02");
assertThat(ReportingModule.provideDate(req, clock)).isEqualTo(new LocalDate(2017, 7, 2)); assertThat(ReportingModule.provideDate(req, clock)).isEqualTo(new LocalDate(2017, 7, 2));
} }

View file

@ -35,23 +35,20 @@ import java.nio.charset.StandardCharsets;
import javax.mail.MessagingException; import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress; import javax.mail.internet.InternetAddress;
import org.joda.time.YearMonth; import org.joda.time.YearMonth;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
/** Unit tests for {@link google.registry.reporting.billing.BillingEmailUtils}. */ /** Unit tests for {@link google.registry.reporting.billing.BillingEmailUtils}. */
@RunWith(JUnit4.class) class BillingEmailUtilsTest {
public class BillingEmailUtilsTest {
private SendEmailService emailService; private SendEmailService emailService;
private BillingEmailUtils emailUtils; private BillingEmailUtils emailUtils;
private GcsUtils gcsUtils; private GcsUtils gcsUtils;
private ArgumentCaptor<EmailMessage> contentCaptor; private ArgumentCaptor<EmailMessage> contentCaptor;
@Before @BeforeEach
public void setUp() throws Exception { void beforeEach() throws Exception {
emailService = mock(SendEmailService.class); emailService = mock(SendEmailService.class);
gcsUtils = mock(GcsUtils.class); gcsUtils = mock(GcsUtils.class);
when(gcsUtils.openInputStream(new GcsFilename("test-bucket", "results/REG-INV-2017-10.csv"))) when(gcsUtils.openInputStream(new GcsFilename("test-bucket", "results/REG-INV-2017-10.csv")))
@ -74,7 +71,7 @@ public class BillingEmailUtilsTest {
} }
@Test @Test
public void testSuccess_emailOverallInvoice() throws MessagingException { void testSuccess_emailOverallInvoice() throws MessagingException {
emailUtils.emailOverallInvoice(); emailUtils.emailOverallInvoice();
verify(emailService).sendEmail(contentCaptor.capture()); verify(emailService).sendEmail(contentCaptor.capture());
@ -98,7 +95,7 @@ public class BillingEmailUtilsTest {
} }
@Test @Test
public void testFailure_emailsAlert() throws MessagingException { void testFailure_emailsAlert() throws MessagingException {
doThrow(new RuntimeException(new MessagingException("expected"))) doThrow(new RuntimeException(new MessagingException("expected")))
.doNothing() .doNothing()
.when(emailService) .when(emailService)
@ -116,7 +113,7 @@ public class BillingEmailUtilsTest {
} }
@Test @Test
public void testSuccess_sendAlertEmail() throws MessagingException { void testSuccess_sendAlertEmail() throws MessagingException {
emailUtils.sendAlertEmail("Alert!"); emailUtils.sendAlertEmail("Alert!");
verify(emailService).sendEmail(contentCaptor.capture()); verify(emailService).sendEmail(contentCaptor.capture());
validateAlertMessage(contentCaptor.getValue(), "Alert!"); validateAlertMessage(contentCaptor.getValue(), "Alert!");

View file

@ -41,18 +41,15 @@ import google.registry.testing.FakeResponse;
import google.registry.testing.FakeSleeper; import google.registry.testing.FakeSleeper;
import google.registry.util.Retrier; import google.registry.util.Retrier;
import java.io.IOException; import java.io.IOException;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link google.registry.reporting.billing.CopyDetailReportsAction}. */ /** Unit tests for {@link google.registry.reporting.billing.CopyDetailReportsAction}. */
@RunWith(JUnit4.class) class CopyDetailReportsActionTest {
public class CopyDetailReportsActionTest {
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
private final GcsService gcsService = GcsServiceFactory.createGcsService(); private final GcsService gcsService = GcsServiceFactory.createGcsService();
private final GcsUtils gcsUtils = new GcsUtils(gcsService, 1024); private final GcsUtils gcsUtils = new GcsUtils(gcsService, 1024);
@ -62,8 +59,8 @@ public class CopyDetailReportsActionTest {
private BillingEmailUtils emailUtils; private BillingEmailUtils emailUtils;
private CopyDetailReportsAction action; private CopyDetailReportsAction action;
@Before @BeforeEach
public void setUp() { void beforeEach() {
persistResource(loadRegistrar("TheRegistrar").asBuilder().setDriveFolderId("0B-12345").build()); persistResource(loadRegistrar("TheRegistrar").asBuilder().setDriveFolderId("0B-12345").build());
persistResource(loadRegistrar("NewRegistrar").asBuilder().setDriveFolderId("0B-54321").build()); persistResource(loadRegistrar("NewRegistrar").asBuilder().setDriveFolderId("0B-54321").build());
response = new FakeResponse(); response = new FakeResponse();
@ -81,7 +78,7 @@ public class CopyDetailReportsActionTest {
} }
@Test @Test
public void testSuccess() throws IOException { void testSuccess() throws IOException {
writeGcsFile( writeGcsFile(
gcsService, gcsService,
new GcsFilename("test-bucket", "results/invoice_details_2017-10_TheRegistrar_test.csv"), new GcsFilename("test-bucket", "results/invoice_details_2017-10_TheRegistrar_test.csv"),
@ -112,7 +109,7 @@ public class CopyDetailReportsActionTest {
} }
@Test @Test
public void testSuccess_nonDetailReportFiles_notSent() throws IOException{ void testSuccess_nonDetailReportFiles_notSent() throws IOException {
writeGcsFile( writeGcsFile(
gcsService, gcsService,
new GcsFilename("test-bucket", "results/invoice_details_2017-10_TheRegistrar_hello.csv"), new GcsFilename("test-bucket", "results/invoice_details_2017-10_TheRegistrar_hello.csv"),
@ -137,7 +134,7 @@ public class CopyDetailReportsActionTest {
} }
@Test @Test
public void testSuccess_transientIOException_retries() throws IOException { void testSuccess_transientIOException_retries() throws IOException {
writeGcsFile( writeGcsFile(
gcsService, gcsService,
new GcsFilename("test-bucket", "results/invoice_details_2017-10_TheRegistrar_hello.csv"), new GcsFilename("test-bucket", "results/invoice_details_2017-10_TheRegistrar_hello.csv"),
@ -159,7 +156,7 @@ public class CopyDetailReportsActionTest {
} }
@Test @Test
public void testFail_tooManyFailures_sendsAlertEmail_continues() throws IOException { void testFail_tooManyFailures_sendsAlertEmail_continues() throws IOException {
writeGcsFile( writeGcsFile(
gcsService, gcsService,
new GcsFilename("test-bucket", "results/invoice_details_2017-10_TheRegistrar_hello.csv"), new GcsFilename("test-bucket", "results/invoice_details_2017-10_TheRegistrar_hello.csv"),
@ -202,7 +199,7 @@ public class CopyDetailReportsActionTest {
} }
@Test @Test
public void testFail_registrarDoesntExist_doesntCopy() throws IOException { void testFail_registrarDoesntExist_doesntCopy() throws IOException {
writeGcsFile( writeGcsFile(
gcsService, gcsService,
new GcsFilename("test-bucket", "results/invoice_details_2017-10_notExistent_hello.csv"), new GcsFilename("test-bucket", "results/invoice_details_2017-10_notExistent_hello.csv"),
@ -212,12 +209,11 @@ public class CopyDetailReportsActionTest {
} }
@Test @Test
public void testFail_noRegistrarFolderId_doesntCopy() throws IOException { void testFail_noRegistrarFolderId_doesntCopy() throws IOException {
persistResource(loadRegistrar("TheRegistrar").asBuilder().setDriveFolderId(null).build()); persistResource(loadRegistrar("TheRegistrar").asBuilder().setDriveFolderId(null).build());
writeGcsFile( writeGcsFile(
gcsService, gcsService,
new GcsFilename( new GcsFilename("test-bucket", "results/invoice_details_2017-10_TheRegistrar_hello.csv"),
"test-bucket", "results/invoice_details_2017-10_TheRegistrar_hello.csv"),
"hola,mundo\n3,4".getBytes(UTF_8)); "hola,mundo\n3,4".getBytes(UTF_8));
action.run(); action.run();
verifyNoInteractions(driveConnection); verifyNoInteractions(driveConnection);

View file

@ -36,18 +36,15 @@ import google.registry.testing.FakeResponse;
import google.registry.testing.TaskQueueHelper.TaskMatcher; import google.registry.testing.TaskQueueHelper.TaskMatcher;
import java.io.IOException; import java.io.IOException;
import org.joda.time.YearMonth; import org.joda.time.YearMonth;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link google.registry.reporting.billing.GenerateInvoicesAction}. */ /** Unit tests for {@link google.registry.reporting.billing.GenerateInvoicesAction}. */
@RunWith(JUnit4.class) class GenerateInvoicesActionTest {
public class GenerateInvoicesActionTest {
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withTaskQueue().build(); final AppEngineRule appEngine = AppEngineRule.builder().withTaskQueue().build();
private Dataflow dataflow; private Dataflow dataflow;
private Projects projects; private Projects projects;
@ -55,10 +52,10 @@ public class GenerateInvoicesActionTest {
private Launch launch; private Launch launch;
private FakeResponse response; private FakeResponse response;
private BillingEmailUtils emailUtils; private BillingEmailUtils emailUtils;
GenerateInvoicesAction action; private GenerateInvoicesAction action;
@Before @BeforeEach
public void setUp() throws IOException { void beforeEach() throws IOException {
dataflow = mock(Dataflow.class); dataflow = mock(Dataflow.class);
projects = mock(Projects.class); projects = mock(Projects.class);
templates = mock(Templates.class); templates = mock(Templates.class);
@ -77,7 +74,7 @@ public class GenerateInvoicesActionTest {
} }
@Test @Test
public void testLaunchTemplateJob_withPublish() throws Exception { void testLaunchTemplateJob_withPublish() throws Exception {
action = action =
new GenerateInvoicesAction( new GenerateInvoicesAction(
"test-project", "test-project",
@ -113,7 +110,7 @@ public class GenerateInvoicesActionTest {
} }
@Test @Test
public void testLaunchTemplateJob_withoutPublish() throws Exception { void testLaunchTemplateJob_withoutPublish() throws Exception {
action = action =
new GenerateInvoicesAction( new GenerateInvoicesAction(
"test-project", "test-project",
@ -142,7 +139,7 @@ public class GenerateInvoicesActionTest {
} }
@Test @Test
public void testCaughtIOException() throws IOException { void testCaughtIOException() throws IOException {
when(launch.execute()).thenThrow(new IOException("expected")); when(launch.execute()).thenThrow(new IOException("expected"));
action = action =
new GenerateInvoicesAction( new GenerateInvoicesAction(

View file

@ -35,15 +35,12 @@ import google.registry.testing.FakeResponse;
import google.registry.testing.TaskQueueHelper.TaskMatcher; import google.registry.testing.TaskQueueHelper.TaskMatcher;
import java.io.IOException; import java.io.IOException;
import org.joda.time.YearMonth; import org.joda.time.YearMonth;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link PublishInvoicesAction}. */ /** Unit tests for {@link PublishInvoicesAction}. */
@RunWith(JUnit4.class) class PublishInvoicesActionTest {
public class PublishInvoicesActionTest {
private Get get; private Get get;
private BillingEmailUtils emailUtils; private BillingEmailUtils emailUtils;
@ -52,11 +49,11 @@ public class PublishInvoicesActionTest {
private FakeResponse response; private FakeResponse response;
private PublishInvoicesAction uploadAction; private PublishInvoicesAction uploadAction;
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withTaskQueue().build(); final AppEngineRule appEngine = AppEngineRule.builder().withTaskQueue().build();
@Before @BeforeEach
public void setUp() throws IOException { void beforeEach() throws IOException {
Dataflow dataflow = mock(Dataflow.class); Dataflow dataflow = mock(Dataflow.class);
Projects projects = mock(Projects.class); Projects projects = mock(Projects.class);
Jobs jobs = mock(Jobs.class); Jobs jobs = mock(Jobs.class);
@ -74,7 +71,7 @@ public class PublishInvoicesActionTest {
} }
@Test @Test
public void testJobDone_enqueuesCopyAction_emailsResults() { void testJobDone_enqueuesCopyAction_emailsResults() {
expectedJob.setCurrentState("JOB_STATE_DONE"); expectedJob.setCurrentState("JOB_STATE_DONE");
uploadAction.run(); uploadAction.run();
assertThat(response.getStatus()).isEqualTo(SC_OK); assertThat(response.getStatus()).isEqualTo(SC_OK);
@ -88,7 +85,7 @@ public class PublishInvoicesActionTest {
} }
@Test @Test
public void testJobFailed_returnsNonRetriableResponse() { void testJobFailed_returnsNonRetriableResponse() {
expectedJob.setCurrentState("JOB_STATE_FAILED"); expectedJob.setCurrentState("JOB_STATE_FAILED");
uploadAction.run(); uploadAction.run();
assertThat(response.getStatus()).isEqualTo(SC_NO_CONTENT); assertThat(response.getStatus()).isEqualTo(SC_NO_CONTENT);
@ -96,14 +93,14 @@ public class PublishInvoicesActionTest {
} }
@Test @Test
public void testJobIndeterminate_returnsRetriableResponse() { void testJobIndeterminate_returnsRetriableResponse() {
expectedJob.setCurrentState("JOB_STATE_RUNNING"); expectedJob.setCurrentState("JOB_STATE_RUNNING");
uploadAction.run(); uploadAction.run();
assertThat(response.getStatus()).isEqualTo(SC_NOT_MODIFIED); assertThat(response.getStatus()).isEqualTo(SC_NOT_MODIFIED);
} }
@Test @Test
public void testIOException_returnsFailureMessage() throws IOException { void testIOException_returnsFailureMessage() throws IOException {
when(get.execute()).thenThrow(new IOException("expected")); when(get.execute()).thenThrow(new IOException("expected"));
uploadAction.run(); uploadAction.run();
assertThat(response.getStatus()).isEqualTo(SC_INTERNAL_SERVER_ERROR); assertThat(response.getStatus()).isEqualTo(SC_INTERNAL_SERVER_ERROR);

View file

@ -19,13 +19,10 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import org.joda.time.YearMonth; import org.joda.time.YearMonth;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link ActivityReportingQueryBuilder}. */ /** Unit tests for {@link ActivityReportingQueryBuilder}. */
@RunWith(JUnit4.class) class ActivityReportingQueryBuilderTest {
public class ActivityReportingQueryBuilderTest {
private final YearMonth yearMonth = new YearMonth(2017, 9); private final YearMonth yearMonth = new YearMonth(2017, 9);
@ -39,7 +36,7 @@ public class ActivityReportingQueryBuilderTest {
} }
@Test @Test
public void testAggregateQueryMatch() { void testAggregateQueryMatch() {
ActivityReportingQueryBuilder queryBuilder = getQueryBuilder(); ActivityReportingQueryBuilder queryBuilder = getQueryBuilder();
assertThat(queryBuilder.getReportQuery(yearMonth)) assertThat(queryBuilder.getReportQuery(yearMonth))
.isEqualTo( .isEqualTo(
@ -48,7 +45,7 @@ public class ActivityReportingQueryBuilderTest {
} }
@Test @Test
public void testIntermediaryQueryMatch() { void testIntermediaryQueryMatch() {
ImmutableList<String> expectedQueryNames = ImmutableList<String> expectedQueryNames =
ImmutableList.of( ImmutableList.of(
ActivityReportingQueryBuilder.REGISTRAR_OPERATING_STATUS, ActivityReportingQueryBuilder.REGISTRAR_OPERATING_STATUS,

View file

@ -33,17 +33,12 @@ import google.registry.testing.AppEngineRule;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** /** Unit tests for {@link IcannHttpReporter}. */
* Unit tests for {@link IcannHttpReporter}. class IcannHttpReporterTest {
*/
@RunWith(JUnit4.class)
public class IcannHttpReporterTest {
private static final ByteSource IIRDEA_GOOD_XML = ReportingTestData.loadBytes("iirdea_good.xml"); private static final ByteSource IIRDEA_GOOD_XML = ReportingTestData.loadBytes("iirdea_good.xml");
private static final ByteSource IIRDEA_BAD_XML = ReportingTestData.loadBytes("iirdea_bad.xml"); private static final ByteSource IIRDEA_BAD_XML = ReportingTestData.loadBytes("iirdea_bad.xml");
@ -51,15 +46,15 @@ public class IcannHttpReporterTest {
private MockLowLevelHttpRequest mockRequest; private MockLowLevelHttpRequest mockRequest;
@Rule @RegisterExtension
public AppEngineRule appEngineRule = AppEngineRule appEngineRule = new AppEngineRule.Builder().withDatastoreAndCloudSql().build();
new AppEngineRule.Builder().withDatastoreAndCloudSql().build();
private MockHttpTransport createMockTransport(final ByteSource iirdeaResponse) { private MockHttpTransport createMockTransport(final ByteSource iirdeaResponse) {
return new MockHttpTransport() { return new MockHttpTransport() {
@Override @Override
public LowLevelHttpRequest buildRequest(String method, String url) { public LowLevelHttpRequest buildRequest(String method, String url) {
mockRequest = new MockLowLevelHttpRequest() { mockRequest =
new MockLowLevelHttpRequest() {
@Override @Override
public LowLevelHttpResponse execute() throws IOException { public LowLevelHttpResponse execute() throws IOException {
MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
@ -75,8 +70,8 @@ public class IcannHttpReporterTest {
}; };
} }
@Before @BeforeEach
public void setUp() { void beforeEach() {
createTld("test"); createTld("test");
createTld("xn--abc123"); createTld("xn--abc123");
} }
@ -91,7 +86,7 @@ public class IcannHttpReporterTest {
} }
@Test @Test
public void testSuccess() throws Exception { void testSuccess() throws Exception {
IcannHttpReporter reporter = createReporter(); IcannHttpReporter reporter = createReporter();
reporter.send(FAKE_PAYLOAD, "test-transactions-201706.csv"); reporter.send(FAKE_PAYLOAD, "test-transactions-201706.csv");
@ -105,7 +100,7 @@ public class IcannHttpReporterTest {
} }
@Test @Test
public void testSuccess_internationalTld() throws Exception { void testSuccess_internationalTld() throws Exception {
IcannHttpReporter reporter = createReporter(); IcannHttpReporter reporter = createReporter();
reporter.send(FAKE_PAYLOAD, "xn--abc123-transactions-201706.csv"); reporter.send(FAKE_PAYLOAD, "xn--abc123-transactions-201706.csv");
@ -119,14 +114,14 @@ public class IcannHttpReporterTest {
} }
@Test @Test
public void testFail_BadIirdeaResponse() throws Exception { void testFail_BadIirdeaResponse() throws Exception {
IcannHttpReporter reporter = createReporter(); IcannHttpReporter reporter = createReporter();
reporter.httpTransport = createMockTransport(IIRDEA_BAD_XML); reporter.httpTransport = createMockTransport(IIRDEA_BAD_XML);
assertThat(reporter.send(FAKE_PAYLOAD, "test-transactions-201706.csv")).isFalse(); assertThat(reporter.send(FAKE_PAYLOAD, "test-transactions-201706.csv")).isFalse();
} }
@Test @Test
public void testFail_invalidFilename_nonSixDigitYearMonth() { void testFail_invalidFilename_nonSixDigitYearMonth() {
IcannHttpReporter reporter = createReporter(); IcannHttpReporter reporter = createReporter();
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
@ -140,7 +135,7 @@ public class IcannHttpReporterTest {
} }
@Test @Test
public void testFail_invalidFilename_notActivityOrTransactions() { void testFail_invalidFilename_notActivityOrTransactions() {
IcannHttpReporter reporter = createReporter(); IcannHttpReporter reporter = createReporter();
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
@ -153,7 +148,7 @@ public class IcannHttpReporterTest {
} }
@Test @Test
public void testFail_invalidFilename_invalidTldName() { void testFail_invalidFilename_invalidTldName() {
IcannHttpReporter reporter = createReporter(); IcannHttpReporter reporter = createReporter();
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
@ -167,7 +162,7 @@ public class IcannHttpReporterTest {
} }
@Test @Test
public void testFail_invalidFilename_tldDoesntExist() { void testFail_invalidFilename_tldDoesntExist() {
IcannHttpReporter reporter = createReporter(); IcannHttpReporter reporter = createReporter();
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(

View file

@ -19,16 +19,13 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link google.registry.reporting.icann.IcannReportingModule}. */ /** Unit tests for {@link google.registry.reporting.icann.IcannReportingModule}. */
@RunWith(JUnit4.class) class IcannReportingModuleTest {
public class IcannReportingModuleTest {
@Test @Test
public void testProvideReportTypes() { void testProvideReportTypes() {
HttpServletRequest req = mock(HttpServletRequest.class); HttpServletRequest req = mock(HttpServletRequest.class);
when(req.getParameter("reportTypes")).thenReturn(null); when(req.getParameter("reportTypes")).thenReturn(null);

View file

@ -38,23 +38,20 @@ import google.registry.testing.FakeResponse;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.joda.time.YearMonth; import org.joda.time.YearMonth;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link google.registry.reporting.icann.IcannReportingStager}. */ /** Unit tests for {@link google.registry.reporting.icann.IcannReportingStager}. */
@RunWith(JUnit4.class) class IcannReportingStagerTest {
public class IcannReportingStagerTest {
BigqueryConnection bigquery = mock(BigqueryConnection.class); private BigqueryConnection bigquery = mock(BigqueryConnection.class);
FakeResponse response = new FakeResponse(); FakeResponse response = new FakeResponse();
GcsService gcsService = GcsServiceFactory.createGcsService(); private GcsService gcsService = GcsServiceFactory.createGcsService();
YearMonth yearMonth = new YearMonth(2017, 6); private YearMonth yearMonth = new YearMonth(2017, 6);
String subdir = "icann/monthly/2017-06"; private String subdir = "icann/monthly/2017-06";
@Rule @RegisterExtension
public final AppEngineRule appEngine = final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withLocalModules().build(); AppEngineRule.builder().withDatastoreAndCloudSql().withLocalModules().build();
private IcannReportingStager createStager() { private IcannReportingStager createStager() {
@ -74,7 +71,8 @@ public class IcannReportingStagerTest {
private void setUpBigquery() { private void setUpBigquery() {
when(bigquery.query(any(String.class), any(DestinationTable.class))).thenReturn(fakeFuture()); when(bigquery.query(any(String.class), any(DestinationTable.class))).thenReturn(fakeFuture());
DestinationTable.Builder tableBuilder = new DestinationTable.Builder() DestinationTable.Builder tableBuilder =
new DestinationTable.Builder()
.datasetId("testdataset") .datasetId("testdataset")
.type(TableType.TABLE) .type(TableType.TABLE)
.name("tablename") .name("tablename")
@ -83,7 +81,7 @@ public class IcannReportingStagerTest {
} }
@Test @Test
public void testRunSuccess_activityReport() throws Exception { void testRunSuccess_activityReport() throws Exception {
setUpBigquery(); setUpBigquery();
ImmutableTable<Integer, TableFieldSchema, Object> activityReportTable = ImmutableTable<Integer, TableFieldSchema, Object> activityReportTable =
new ImmutableTable.Builder<Integer, TableFieldSchema, Object>() new ImmutableTable.Builder<Integer, TableFieldSchema, Object>()
@ -113,7 +111,7 @@ public class IcannReportingStagerTest {
} }
@Test @Test
public void testRunSuccess_transactionsReport() throws Exception { void testRunSuccess_transactionsReport() throws Exception {
setUpBigquery(); setUpBigquery();
/* /*
The fake table result looks like: The fake table result looks like:
@ -157,7 +155,7 @@ public class IcannReportingStagerTest {
} }
@Test @Test
public void testRunSuccess_createAndUploadManifest() throws Exception { void testRunSuccess_createAndUploadManifest() throws Exception {
IcannReportingStager stager = createStager(); IcannReportingStager stager = createStager();
ImmutableList<String> filenames = ImmutableList<String> filenames =
ImmutableList.of("fooTld-transactions-201706.csv", "barTld-activity-201706.csv"); ImmutableList.of("fooTld-transactions-201706.csv", "barTld-activity-201706.csv");
@ -204,4 +202,3 @@ public class IcannReportingStagerTest {
}; };
} }
} }

View file

@ -39,28 +39,25 @@ import google.registry.util.SendEmailService;
import java.util.Optional; import java.util.Optional;
import javax.mail.internet.InternetAddress; import javax.mail.internet.InternetAddress;
import org.joda.time.YearMonth; import org.joda.time.YearMonth;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link google.registry.reporting.icann.IcannReportingStagingAction}. */ /** Unit tests for {@link google.registry.reporting.icann.IcannReportingStagingAction}. */
@RunWith(JUnit4.class) class IcannReportingStagingActionTest {
public class IcannReportingStagingActionTest {
FakeResponse response = new FakeResponse(); private FakeResponse response = new FakeResponse();
IcannReportingStager stager = mock(IcannReportingStager.class); private IcannReportingStager stager = mock(IcannReportingStager.class);
YearMonth yearMonth = new YearMonth(2017, 6); private YearMonth yearMonth = new YearMonth(2017, 6);
String subdir = "default/dir"; private String subdir = "default/dir";
IcannReportingStagingAction action; private IcannReportingStagingAction action;
@Rule @RegisterExtension
public final AppEngineRule appEngine = final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withLocalModules().withTaskQueue().build(); AppEngineRule.builder().withDatastoreAndCloudSql().withLocalModules().withTaskQueue().build();
@Before @BeforeEach
public void setUp() throws Exception { void beforeEach() throws Exception {
action = new IcannReportingStagingAction(); action = new IcannReportingStagingAction();
action.yearMonth = yearMonth; action.yearMonth = yearMonth;
action.overrideSubdir = Optional.of(subdir); action.overrideSubdir = Optional.of(subdir);
@ -84,7 +81,7 @@ public class IcannReportingStagingActionTest {
} }
@Test @Test
public void testActivityReportingMode_onlyStagesActivityReports() throws Exception { void testActivityReportingMode_onlyStagesActivityReports() throws Exception {
action.reportTypes = ImmutableSet.of(ReportType.ACTIVITY); action.reportTypes = ImmutableSet.of(ReportType.ACTIVITY);
action.run(); action.run();
verify(stager).stageReports(yearMonth, subdir, ReportType.ACTIVITY); verify(stager).stageReports(yearMonth, subdir, ReportType.ACTIVITY);
@ -100,7 +97,7 @@ public class IcannReportingStagingActionTest {
} }
@Test @Test
public void testAbsentReportingMode_stagesBothReports() throws Exception { void testAbsentReportingMode_stagesBothReports() throws Exception {
action.run(); action.run();
verify(stager).stageReports(yearMonth, subdir, ReportType.ACTIVITY); verify(stager).stageReports(yearMonth, subdir, ReportType.ACTIVITY);
verify(stager).stageReports(yearMonth, subdir, ReportType.TRANSACTIONS); verify(stager).stageReports(yearMonth, subdir, ReportType.TRANSACTIONS);
@ -116,7 +113,7 @@ public class IcannReportingStagingActionTest {
} }
@Test @Test
public void testRetryOnBigqueryException() throws Exception { void testRetryOnBigqueryException() throws Exception {
when(stager.stageReports(yearMonth, subdir, ReportType.TRANSACTIONS)) when(stager.stageReports(yearMonth, subdir, ReportType.TRANSACTIONS))
.thenThrow(new BigqueryJobFailureException("Expected failure", null, null, null)) .thenThrow(new BigqueryJobFailureException("Expected failure", null, null, null))
.thenReturn(ImmutableList.of("c", "d")); .thenReturn(ImmutableList.of("c", "d"));
@ -135,7 +132,7 @@ public class IcannReportingStagingActionTest {
} }
@Test @Test
public void testEmailEng_onMoreThanRetriableFailure() throws Exception { void testEmailEng_onMoreThanRetriableFailure() throws Exception {
action.reportTypes = ImmutableSet.of(ReportType.ACTIVITY); action.reportTypes = ImmutableSet.of(ReportType.ACTIVITY);
when(stager.stageReports(yearMonth, subdir, ReportType.ACTIVITY)) when(stager.stageReports(yearMonth, subdir, ReportType.ACTIVITY))
.thenThrow(new BigqueryJobFailureException("Expected failure", null, null, null)); .thenThrow(new BigqueryJobFailureException("Expected failure", null, null, null));
@ -160,25 +157,22 @@ public class IcannReportingStagingActionTest {
} }
@Test @Test
public void testEmptySubDir_returnsDefaultSubdir() { void testEmptySubDir_returnsDefaultSubdir() {
action.overrideSubdir = Optional.empty(); action.overrideSubdir = Optional.empty();
assertThat(action.getSubdir(new YearMonth(2017, 6))).isEqualTo("icann/monthly/2017-06"); assertThat(action.getSubdir(new YearMonth(2017, 6))).isEqualTo("icann/monthly/2017-06");
} }
@Test @Test
public void testGivenSubdir_returnsManualSubdir() { void testGivenSubdir_returnsManualSubdir() {
action.overrideSubdir = Optional.of("manual/dir"); action.overrideSubdir = Optional.of("manual/dir");
assertThat(action.getSubdir(new YearMonth(2017, 6))).isEqualTo("manual/dir"); assertThat(action.getSubdir(new YearMonth(2017, 6))).isEqualTo("manual/dir");
} }
@Test @Test
public void testInvalidSubdir_throwsException() { void testInvalidSubdir_throwsException() {
action.overrideSubdir = Optional.of("/whoops"); action.overrideSubdir = Optional.of("/whoops");
BadRequestException thrown = BadRequestException thrown =
assertThrows( assertThrows(BadRequestException.class, () -> action.getSubdir(new YearMonth(2017, 6)));
BadRequestException.class,
() ->
action.getSubdir(new YearMonth(2017, 6)));
assertThat(thrown) assertThat(thrown)
.hasMessageThat() .hasMessageThat()
.contains("subdir must not start or end with a \"/\", got /whoops instead."); .contains("subdir must not start or end with a \"/\", got /whoops instead.");

View file

@ -50,18 +50,15 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.mail.internet.InternetAddress; import javax.mail.internet.InternetAddress;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link google.registry.reporting.icann.IcannReportingUploadAction} */ /** Unit tests for {@link google.registry.reporting.icann.IcannReportingUploadAction} */
@RunWith(JUnit4.class) class IcannReportingUploadActionTest {
public class IcannReportingUploadActionTest {
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
private static final byte[] PAYLOAD_SUCCESS = "test,csv\n13,37".getBytes(UTF_8); private static final byte[] PAYLOAD_SUCCESS = "test,csv\n13,37".getBytes(UTF_8);
private static final byte[] PAYLOAD_FAIL = "ahah,csv\n12,34".getBytes(UTF_8); private static final byte[] PAYLOAD_FAIL = "ahah,csv\n12,34".getBytes(UTF_8);
@ -89,8 +86,8 @@ public class IcannReportingUploadActionTest {
return action; return action;
} }
@Before @BeforeEach
public void before() throws Exception { void beforeEach() throws Exception {
createTlds("tld", "foo"); createTlds("tld", "foo");
writeGcsFile( writeGcsFile(
gcsService, gcsService,
@ -129,7 +126,7 @@ public class IcannReportingUploadActionTest {
} }
@Test @Test
public void testSuccess() throws Exception { void testSuccess() throws Exception {
IcannReportingUploadAction action = createAction(); IcannReportingUploadAction action = createAction();
action.run(); action.run();
verify(mockReporter).send(PAYLOAD_SUCCESS, "foo-activity-200606.csv"); verify(mockReporter).send(PAYLOAD_SUCCESS, "foo-activity-200606.csv");
@ -152,7 +149,7 @@ public class IcannReportingUploadActionTest {
} }
@Test @Test
public void testSuccess_january() throws Exception { void testSuccess_january() throws Exception {
clock.setTo(DateTime.parse("2006-01-22T00:30:00Z")); clock.setTo(DateTime.parse("2006-01-22T00:30:00Z"));
persistResource( persistResource(
Cursor.create( Cursor.create(
@ -189,7 +186,7 @@ public class IcannReportingUploadActionTest {
} }
@Test @Test
public void testSuccess_advancesCursor() throws Exception { void testSuccess_advancesCursor() throws Exception {
writeGcsFile( writeGcsFile(
gcsService, gcsService,
new GcsFilename("basin/icann/monthly/2006-06", "tld-activity-200606.csv"), new GcsFilename("basin/icann/monthly/2006-06", "tld-activity-200606.csv"),
@ -207,7 +204,7 @@ public class IcannReportingUploadActionTest {
} }
@Test @Test
public void testSuccess_noUploadsNeeded() throws Exception { void testSuccess_noUploadsNeeded() throws Exception {
clock.setTo(DateTime.parse("2006-5-01T00:30:00Z")); clock.setTo(DateTime.parse("2006-5-01T00:30:00Z"));
IcannReportingUploadAction action = createAction(); IcannReportingUploadAction action = createAction();
action.run(); action.run();
@ -223,7 +220,7 @@ public class IcannReportingUploadActionTest {
} }
@Test @Test
public void testSuccess_withRetry() throws Exception { void testSuccess_withRetry() throws Exception {
IcannReportingUploadAction action = createAction(); IcannReportingUploadAction action = createAction();
when(mockReporter.send(PAYLOAD_SUCCESS, "tld-transactions-200606.csv")) when(mockReporter.send(PAYLOAD_SUCCESS, "tld-transactions-200606.csv"))
.thenThrow(new IOException("Expected exception.")) .thenThrow(new IOException("Expected exception."))
@ -248,7 +245,7 @@ public class IcannReportingUploadActionTest {
} }
@Test @Test
public void testFailure_quicklySkipsOverNonRetryableUploadException() throws Exception { void testFailure_quicklySkipsOverNonRetryableUploadException() throws Exception {
runTest_nonRetryableException( runTest_nonRetryableException(
new IOException( new IOException(
"<msg>A report for that month already exists, the cut-off date already" "<msg>A report for that month already exists, the cut-off date already"
@ -256,13 +253,13 @@ public class IcannReportingUploadActionTest {
} }
@Test @Test
public void testFailure_quicklySkipsOverIpAllowListException() throws Exception { void testFailure_quicklySkipsOverIpAllowListException() throws Exception {
runTest_nonRetryableException( runTest_nonRetryableException(
new IOException("Your IP address 25.147.130.158 is not allowed to connect")); new IOException("Your IP address 25.147.130.158 is not allowed to connect"));
} }
@Test @Test
public void testFailure_cursorIsNotAdvancedForward() throws Exception { void testFailure_cursorIsNotAdvancedForward() throws Exception {
runTest_nonRetryableException( runTest_nonRetryableException(
new IOException("Your IP address 25.147.130.158 is not allowed to connect")); new IOException("Your IP address 25.147.130.158 is not allowed to connect"));
ofy().clearSessionCache(); ofy().clearSessionCache();
@ -275,7 +272,7 @@ public class IcannReportingUploadActionTest {
} }
@Test @Test
public void testNotRunIfCursorDateIsAfterToday() throws Exception { void testNotRunIfCursorDateIsAfterToday() throws Exception {
clock.setTo(DateTime.parse("2006-05-01T00:30:00Z")); clock.setTo(DateTime.parse("2006-05-01T00:30:00Z"));
IcannReportingUploadAction action = createAction(); IcannReportingUploadAction action = createAction();
action.run(); action.run();
@ -316,7 +313,7 @@ public class IcannReportingUploadActionTest {
} }
@Test @Test
public void testFail_fileNotFound() throws Exception { void testFail_fileNotFound() throws Exception {
clock.setTo(DateTime.parse("2006-01-22T00:30:00Z")); clock.setTo(DateTime.parse("2006-01-22T00:30:00Z"));
persistResource( persistResource(
Cursor.create( Cursor.create(
@ -332,7 +329,7 @@ public class IcannReportingUploadActionTest {
} }
@Test @Test
public void testWarning_fileNotStagedYet() throws Exception { void testWarning_fileNotStagedYet() throws Exception {
persistResource( persistResource(
Cursor.create( Cursor.create(
CursorType.ICANN_UPLOAD_ACTIVITY, DateTime.parse("2006-08-01TZ"), Registry.get("foo"))); CursorType.ICANN_UPLOAD_ACTIVITY, DateTime.parse("2006-08-01TZ"), Registry.get("foo")));
@ -349,7 +346,7 @@ public class IcannReportingUploadActionTest {
} }
@Test @Test
public void testFailure_lockIsntAvailable() throws Exception { void testFailure_lockIsntAvailable() throws Exception {
IcannReportingUploadAction action = createAction(); IcannReportingUploadAction action = createAction();
action.lockHandler = new FakeLockHandler(false); action.lockHandler = new FakeLockHandler(false);
ServiceUnavailableException thrown = ServiceUnavailableException thrown =
@ -360,7 +357,7 @@ public class IcannReportingUploadActionTest {
} }
@Test @Test
public void testSuccess_nullCursorsInitiatedToFirstOfNextMonth() throws Exception { void testSuccess_nullCursorsInitiatedToFirstOfNextMonth() throws Exception {
createTlds("new"); createTlds("new");
IcannReportingUploadAction action = createAction(); IcannReportingUploadAction action = createAction();

View file

@ -19,13 +19,10 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import org.joda.time.YearMonth; import org.joda.time.YearMonth;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link ActivityReportingQueryBuilder}. */ /** Unit tests for {@link ActivityReportingQueryBuilder}. */
@RunWith(JUnit4.class) class TransactionsReportingQueryBuilderTest {
public class TransactionsReportingQueryBuilderTest {
private final YearMonth yearMonth = new YearMonth(2017, 9); private final YearMonth yearMonth = new YearMonth(2017, 9);
@ -36,7 +33,7 @@ public class TransactionsReportingQueryBuilderTest {
} }
@Test @Test
public void testAggregateQueryMatch() { void testAggregateQueryMatch() {
TransactionsReportingQueryBuilder queryBuilder = getQueryBuilder(); TransactionsReportingQueryBuilder queryBuilder = getQueryBuilder();
assertThat(queryBuilder.getReportQuery(yearMonth)) assertThat(queryBuilder.getReportQuery(yearMonth))
.isEqualTo( .isEqualTo(
@ -45,7 +42,7 @@ public class TransactionsReportingQueryBuilderTest {
} }
@Test @Test
public void testIntermediaryQueryMatch() { void testIntermediaryQueryMatch() {
ImmutableList<String> expectedQueryNames = ImmutableList<String> expectedQueryNames =
ImmutableList.of( ImmutableList.of(
TransactionsReportingQueryBuilder.TRANSACTIONS_REPORT_AGGREGATION, TransactionsReportingQueryBuilder.TRANSACTIONS_REPORT_AGGREGATION,

View file

@ -36,18 +36,15 @@ import google.registry.testing.FakeResponse;
import google.registry.testing.TaskQueueHelper.TaskMatcher; import google.registry.testing.TaskQueueHelper.TaskMatcher;
import java.io.IOException; import java.io.IOException;
import org.joda.time.LocalDate; import org.joda.time.LocalDate;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link google.registry.reporting.spec11.GenerateSpec11ReportAction}. */ /** Unit tests for {@link google.registry.reporting.spec11.GenerateSpec11ReportAction}. */
@RunWith(JUnit4.class) class GenerateSpec11ReportActionTest {
public class GenerateSpec11ReportActionTest {
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withTaskQueue().build(); final AppEngineRule appEngine = AppEngineRule.builder().withTaskQueue().build();
private FakeResponse response; private FakeResponse response;
private Dataflow dataflow; private Dataflow dataflow;
@ -57,8 +54,8 @@ public class GenerateSpec11ReportActionTest {
private GenerateSpec11ReportAction action; private GenerateSpec11ReportAction action;
@Before @BeforeEach
public void setUp() throws IOException { void beforeEach() throws IOException {
response = new FakeResponse(); response = new FakeResponse();
dataflow = mock(Dataflow.class); dataflow = mock(Dataflow.class);
@ -79,7 +76,7 @@ public class GenerateSpec11ReportActionTest {
} }
@Test @Test
public void testLaunch_success() throws IOException { void testLaunch_success() throws IOException {
action = action =
new GenerateSpec11ReportAction( new GenerateSpec11ReportAction(
"test", "test",

View file

@ -41,14 +41,11 @@ import google.registry.testing.FakeResponse;
import java.io.IOException; import java.io.IOException;
import java.util.Optional; import java.util.Optional;
import org.joda.time.LocalDate; import org.joda.time.LocalDate;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link PublishSpec11ReportAction}. */ /** Unit tests for {@link PublishSpec11ReportAction}. */
@RunWith(JUnit4.class) class PublishSpec11ReportActionTest {
public class PublishSpec11ReportActionTest {
private final LocalDate date = new LocalDate(2018, 6, 5); private final LocalDate date = new LocalDate(2018, 6, 5);
@ -63,8 +60,8 @@ public class PublishSpec11ReportActionTest {
private FakeResponse response; private FakeResponse response;
private PublishSpec11ReportAction publishAction; private PublishSpec11ReportAction publishAction;
@Before @BeforeEach
public void setUp() throws Exception { void beforeEach() throws Exception {
dataflow = mock(Dataflow.class); dataflow = mock(Dataflow.class);
projects = mock(Projects.class); projects = mock(Projects.class);
jobs = mock(Jobs.class); jobs = mock(Jobs.class);
@ -91,7 +88,7 @@ public class PublishSpec11ReportActionTest {
} }
@Test @Test
public void testJobDone_emailsOnlyMonthlyResultsOnSecondOfMonth() throws Exception { void testJobDone_emailsOnlyMonthlyResultsOnSecondOfMonth() throws Exception {
LocalDate secondOfMonth = date.withDayOfMonth(2); LocalDate secondOfMonth = date.withDayOfMonth(2);
when(parser.getRegistrarThreatMatches(secondOfMonth)).thenReturn(sampleThreatMatches()); when(parser.getRegistrarThreatMatches(secondOfMonth)).thenReturn(sampleThreatMatches());
expectedJob.setCurrentState("JOB_STATE_DONE"); expectedJob.setCurrentState("JOB_STATE_DONE");
@ -117,7 +114,7 @@ public class PublishSpec11ReportActionTest {
} }
@Test @Test
public void testJobFailed_returnsNonRetriableResponse() { void testJobFailed_returnsNonRetriableResponse() {
expectedJob.setCurrentState("JOB_STATE_FAILED"); expectedJob.setCurrentState("JOB_STATE_FAILED");
publishAction.run(); publishAction.run();
assertThat(response.getStatus()).isEqualTo(SC_NO_CONTENT); assertThat(response.getStatus()).isEqualTo(SC_NO_CONTENT);
@ -128,7 +125,7 @@ public class PublishSpec11ReportActionTest {
} }
@Test @Test
public void testJobIndeterminate_returnsRetriableResponse() { void testJobIndeterminate_returnsRetriableResponse() {
expectedJob.setCurrentState("JOB_STATE_RUNNING"); expectedJob.setCurrentState("JOB_STATE_RUNNING");
publishAction.run(); publishAction.run();
assertThat(response.getStatus()).isEqualTo(SC_NOT_MODIFIED); assertThat(response.getStatus()).isEqualTo(SC_NOT_MODIFIED);
@ -136,7 +133,7 @@ public class PublishSpec11ReportActionTest {
} }
@Test @Test
public void testIOException_returnsFailureMessage() throws IOException { void testIOException_returnsFailureMessage() throws IOException {
when(get.execute()).thenThrow(new IOException("expected")); when(get.execute()).thenThrow(new IOException("expected"));
publishAction.run(); publishAction.run();
assertThat(response.getStatus()).isEqualTo(SC_INTERNAL_SERVER_ERROR); assertThat(response.getStatus()).isEqualTo(SC_INTERNAL_SERVER_ERROR);
@ -149,7 +146,7 @@ public class PublishSpec11ReportActionTest {
} }
@Test @Test
public void testJobDone_onlyDailyResults() throws Exception { void testJobDone_onlyDailyResults() throws Exception {
LocalDate yesterday = date.minusDays(1); LocalDate yesterday = date.minusDays(1);
when(parser.getPreviousDateWithMatches(date)).thenReturn(Optional.of(yesterday)); when(parser.getPreviousDateWithMatches(date)).thenReturn(Optional.of(yesterday));
when(parser.getRegistrarThreatMatches(date)).thenReturn(sampleThreatMatches()); when(parser.getRegistrarThreatMatches(date)).thenReturn(sampleThreatMatches());
@ -167,7 +164,7 @@ public class PublishSpec11ReportActionTest {
} }
@Test @Test
public void testJobDone_multipleEntriesWithSameEmail() throws Exception { void testJobDone_multipleEntriesWithSameEmail() throws Exception {
LocalDate yesterday = date.minusDays(1); LocalDate yesterday = date.minusDays(1);
when(parser.getPreviousDateWithMatches(date)).thenReturn(Optional.of(yesterday)); when(parser.getPreviousDateWithMatches(date)).thenReturn(Optional.of(yesterday));
when(parser.getRegistrarThreatMatches(yesterday)).thenReturn(ImmutableSet.of()); when(parser.getRegistrarThreatMatches(yesterday)).thenReturn(ImmutableSet.of());
@ -200,7 +197,7 @@ public class PublishSpec11ReportActionTest {
} }
@Test @Test
public void testJobDone_noDifferentResults() throws Exception { void testJobDone_noDifferentResults() throws Exception {
LocalDate yesterday = date.minusDays(1); LocalDate yesterday = date.minusDays(1);
when(parser.getPreviousDateWithMatches(date)).thenReturn(Optional.of(yesterday)); when(parser.getPreviousDateWithMatches(date)).thenReturn(Optional.of(yesterday));
when(parser.getRegistrarThreatMatches(date)).thenReturn(sampleThreatMatches()); when(parser.getRegistrarThreatMatches(date)).thenReturn(sampleThreatMatches());
@ -218,7 +215,7 @@ public class PublishSpec11ReportActionTest {
} }
@Test @Test
public void testJobDone_failsDueToNoPreviousResults() { void testJobDone_failsDueToNoPreviousResults() {
when(parser.getPreviousDateWithMatches(date)).thenReturn(Optional.empty()); when(parser.getPreviousDateWithMatches(date)).thenReturn(Optional.empty());
expectedJob.setCurrentState("JOB_STATE_DONE"); expectedJob.setCurrentState("JOB_STATE_DONE");
publishAction.run(); publishAction.run();

View file

@ -47,16 +47,13 @@ import java.util.Optional;
import javax.mail.MessagingException; import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress; import javax.mail.internet.InternetAddress;
import org.joda.time.LocalDate; import org.joda.time.LocalDate;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
/** Unit tests for {@link Spec11EmailUtils}. */ /** Unit tests for {@link Spec11EmailUtils}. */
@RunWith(JUnit4.class) class Spec11EmailUtilsTest {
public class Spec11EmailUtilsTest {
private static final ImmutableList<String> FAKE_RESOURCES = ImmutableList.of("foo"); private static final ImmutableList<String> FAKE_RESOURCES = ImmutableList.of("foo");
private static final String DAILY_EMAIL_FORMAT = private static final String DAILY_EMAIL_FORMAT =
@ -95,8 +92,8 @@ public class Spec11EmailUtilsTest {
+ " domains are added to these lists.</p><p>If you have any questions regarding this" + " domains are added to these lists.</p><p>If you have any questions regarding this"
+ " notice, please contact abuse@test.com.</p>"; + " notice, please contact abuse@test.com.</p>";
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
private SendEmailService emailService; private SendEmailService emailService;
private Spec11EmailUtils emailUtils; private Spec11EmailUtils emailUtils;
@ -107,8 +104,8 @@ public class Spec11EmailUtilsTest {
private DomainBase aDomain; private DomainBase aDomain;
private DomainBase bDomain; private DomainBase bDomain;
@Before @BeforeEach
public void setUp() throws Exception { void beforeEach() throws Exception {
emailService = mock(SendEmailService.class); emailService = mock(SendEmailService.class);
parser = mock(Spec11RegistrarThreatMatchesParser.class); parser = mock(Spec11RegistrarThreatMatchesParser.class);
when(parser.getRegistrarThreatMatches(date)).thenReturn(sampleThreatMatches()); when(parser.getRegistrarThreatMatches(date)).thenReturn(sampleThreatMatches());
@ -131,7 +128,7 @@ public class Spec11EmailUtilsTest {
} }
@Test @Test
public void testSuccess_emailMonthlySpec11Reports() throws Exception { void testSuccess_emailMonthlySpec11Reports() throws Exception {
emailUtils.emailSpec11Reports( emailUtils.emailSpec11Reports(
date, date,
Spec11EmailSoyInfo.MONTHLY_SPEC_11_EMAIL, Spec11EmailSoyInfo.MONTHLY_SPEC_11_EMAIL,
@ -169,7 +166,7 @@ public class Spec11EmailUtilsTest {
} }
@Test @Test
public void testSuccess_emailDailySpec11Reports() throws Exception { void testSuccess_emailDailySpec11Reports() throws Exception {
emailUtils.emailSpec11Reports( emailUtils.emailSpec11Reports(
date, date,
Spec11EmailSoyInfo.DAILY_SPEC_11_EMAIL, Spec11EmailSoyInfo.DAILY_SPEC_11_EMAIL,
@ -207,14 +204,12 @@ public class Spec11EmailUtilsTest {
} }
@Test @Test
public void testSuccess_skipsInactiveDomain() throws Exception { void testSuccess_skipsInactiveDomain() throws Exception {
// CLIENT_HOLD and SERVER_HOLD mean no DNS so we don't need to email it out // CLIENT_HOLD and SERVER_HOLD mean no DNS so we don't need to email it out
persistResource( persistResource(
ofy().load().entity(aDomain).now().asBuilder().addStatusValue(SERVER_HOLD) ofy().load().entity(aDomain).now().asBuilder().addStatusValue(SERVER_HOLD).build());
.build());
persistResource( persistResource(
ofy().load().entity(bDomain).now().asBuilder().addStatusValue(CLIENT_HOLD) ofy().load().entity(bDomain).now().asBuilder().addStatusValue(CLIENT_HOLD).build());
.build());
emailUtils.emailSpec11Reports( emailUtils.emailSpec11Reports(
date, date,
Spec11EmailSoyInfo.MONTHLY_SPEC_11_EMAIL, Spec11EmailSoyInfo.MONTHLY_SPEC_11_EMAIL,
@ -242,7 +237,7 @@ public class Spec11EmailUtilsTest {
} }
@Test @Test
public void testOneFailure_sendsAlert() throws Exception { void testOneFailure_sendsAlert() throws Exception {
// If there is one failure, we should still send the other message and then an alert email // If there is one failure, we should still send the other message and then an alert email
LinkedHashSet<RegistrarThreatMatches> matches = new LinkedHashSet<>(); LinkedHashSet<RegistrarThreatMatches> matches = new LinkedHashSet<>();
matches.add(getMatchA()); matches.add(getMatchA());
@ -297,7 +292,7 @@ public class Spec11EmailUtilsTest {
} }
@Test @Test
public void testSuccess_sendAlertEmail() throws Exception { void testSuccess_sendAlertEmail() throws Exception {
emailUtils.sendAlertEmail("Spec11 Pipeline Alert: 2018-07", "Alert!"); emailUtils.sendAlertEmail("Spec11 Pipeline Alert: 2018-07", "Alert!");
verify(emailService).sendEmail(contentCaptor.capture()); verify(emailService).sendEmail(contentCaptor.capture());
validateMessage( validateMessage(
@ -311,7 +306,7 @@ public class Spec11EmailUtilsTest {
} }
@Test @Test
public void testSuccess_useWhoisAbuseEmailIfAvailable() throws Exception { void testSuccess_useWhoisAbuseEmailIfAvailable() throws Exception {
// if John Doe is the whois abuse contact, email them instead of the regular email // if John Doe is the whois abuse contact, email them instead of the regular email
persistResource( persistResource(
AppEngineRule.makeRegistrarContact2() AppEngineRule.makeRegistrarContact2()
@ -330,7 +325,7 @@ public class Spec11EmailUtilsTest {
} }
@Test @Test
public void testFailure_badClientId() { void testFailure_badClientId() {
RuntimeException thrown = RuntimeException thrown =
assertThrows( assertThrows(
RuntimeException.class, RuntimeException.class,

View file

@ -30,14 +30,11 @@ import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import org.joda.time.LocalDate; import org.joda.time.LocalDate;
import org.json.JSONObject; import org.json.JSONObject;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link Spec11RegistrarThreatMatchesParser}. */ /** Unit tests for {@link Spec11RegistrarThreatMatchesParser}. */
@RunWith(JUnit4.class) class Spec11RegistrarThreatMatchesParserTest {
public class Spec11RegistrarThreatMatchesParserTest {
private static final String TODAY = "2018-07-21"; private static final String TODAY = "2018-07-21";
private static final String YESTERDAY = "2018-07-20"; private static final String YESTERDAY = "2018-07-20";
@ -46,31 +43,31 @@ public class Spec11RegistrarThreatMatchesParserTest {
private final Spec11RegistrarThreatMatchesParser parser = private final Spec11RegistrarThreatMatchesParser parser =
new Spec11RegistrarThreatMatchesParser(gcsUtils, "test-bucket"); new Spec11RegistrarThreatMatchesParser(gcsUtils, "test-bucket");
@Before @BeforeEach
public void setUp() { void beforeEach() {
setupFile("spec11_fake_report", TODAY); setupFile("spec11_fake_report", TODAY);
} }
@Test @Test
public void testSuccess_retrievesReport() throws Exception { void testSuccess_retrievesReport() throws Exception {
assertThat(parser.getRegistrarThreatMatches(LocalDate.parse(TODAY))) assertThat(parser.getRegistrarThreatMatches(LocalDate.parse(TODAY)))
.isEqualTo(sampleThreatMatches()); .isEqualTo(sampleThreatMatches());
} }
@Test @Test
public void testFindPrevious_exists() throws Exception { void testFindPrevious_exists() throws Exception {
setupFile("spec11_fake_report_previous_day", YESTERDAY); setupFile("spec11_fake_report_previous_day", YESTERDAY);
assertThat(parser.getPreviousDateWithMatches(LocalDate.parse(TODAY))) assertThat(parser.getPreviousDateWithMatches(LocalDate.parse(TODAY)))
.hasValue(LocalDate.parse(YESTERDAY)); .hasValue(LocalDate.parse(YESTERDAY));
} }
@Test @Test
public void testFindPrevious_notFound() { void testFindPrevious_notFound() {
assertThat(parser.getPreviousDateWithMatches(LocalDate.parse(TODAY))).isEmpty(); assertThat(parser.getPreviousDateWithMatches(LocalDate.parse(TODAY))).isEmpty();
} }
@Test @Test
public void testFindPrevious_olderThanYesterdayFound() throws Exception { void testFindPrevious_olderThanYesterdayFound() throws Exception {
setupFile("spec11_fake_report_previous_day", "2018-07-14"); setupFile("spec11_fake_report_previous_day", "2018-07-14");
assertThat(parser.getPreviousDateWithMatches(LocalDate.parse(TODAY))) assertThat(parser.getPreviousDateWithMatches(LocalDate.parse(TODAY)))
@ -78,7 +75,7 @@ public class Spec11RegistrarThreatMatchesParserTest {
} }
@Test @Test
public void testSuccess_ignoreExtraFields() throws Exception { void testSuccess_ignoreExtraFields() throws Exception {
ThreatMatch objectWithExtraFields = ThreatMatch objectWithExtraFields =
ThreatMatch.fromJSON( ThreatMatch.fromJSON(
new JSONObject( new JSONObject(

View file

@ -21,25 +21,22 @@ import com.google.common.collect.ImmutableMap;
import google.registry.testing.FakeResponse; import google.registry.testing.FakeResponse;
import java.util.Map; import java.util.Map;
import org.json.simple.JSONValue; import org.json.simple.JSONValue;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link JsonResponse}. */ /** Unit tests for {@link JsonResponse}. */
@RunWith(JUnit4.class) class JsonResponseTest {
public class JsonResponseTest {
FakeResponse fakeResponse = new FakeResponse(); private FakeResponse fakeResponse = new FakeResponse();
JsonResponse jsonResponse = new JsonResponse(fakeResponse); private JsonResponse jsonResponse = new JsonResponse(fakeResponse);
@Test @Test
public void testSetStatus() { void testSetStatus() {
jsonResponse.setStatus(666); jsonResponse.setStatus(666);
assertThat(fakeResponse.getStatus()).isEqualTo(666); assertThat(fakeResponse.getStatus()).isEqualTo(666);
} }
@Test @Test
public void testSetResponseValue() { void testSetResponseValue() {
ImmutableMap<String, String> responseValues = ImmutableMap.of( ImmutableMap<String, String> responseValues = ImmutableMap.of(
"hello", "world", "hello", "world",
"goodbye", "cruel world"); "goodbye", "cruel world");
@ -53,7 +50,7 @@ public class JsonResponseTest {
} }
@Test @Test
public void testSetHeader() { void testSetHeader() {
jsonResponse.setHeader("header", "value"); jsonResponse.setHeader("header", "value");
Map<String, Object> headerMap = fakeResponse.getHeaders(); Map<String, Object> headerMap = fakeResponse.getHeaders();
assertThat(headerMap.size()).isEqualTo(1); assertThat(headerMap.size()).isEqualTo(1);

View file

@ -42,19 +42,16 @@ import java.io.StringWriter;
import java.util.Optional; import java.util.Optional;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RequestHandler}. */ /** Unit tests for {@link RequestHandler}. */
@RunWith(JUnit4.class)
public final class RequestHandlerTest { public final class RequestHandlerTest {
@Rule @RegisterExtension
public final AppEngineRule appEngine = final AppEngineRule appEngine =
AppEngineRule.builder() AppEngineRule.builder()
.withDatastoreAndCloudSql() .withDatastoreAndCloudSql()
.withUserService(UserInfo.create("test@example.com", "test@example.com")) .withUserService(UserInfo.create("test@example.com", "test@example.com"))
@ -102,7 +99,7 @@ public final class RequestHandlerTest {
@Action(service = Action.Service.DEFAULT, path = "/failAtConstruction", auth = AUTH_PUBLIC) @Action(service = Action.Service.DEFAULT, path = "/failAtConstruction", auth = AUTH_PUBLIC)
public static final class FailAtConstructionTask implements Runnable { public static final class FailAtConstructionTask implements Runnable {
public FailAtConstructionTask() { FailAtConstructionTask() {
throw new ServiceUnavailableException("Fail at construction"); throw new ServiceUnavailableException("Fail at construction");
} }
@ -207,8 +204,8 @@ public final class RequestHandlerTest {
private AuthResult providedAuthResult = null; private AuthResult providedAuthResult = null;
private final User testUser = new User("test@example.com", "test@example.com"); private final User testUser = new User("test@example.com", "test@example.com");
@Before @BeforeEach
public void before() throws Exception { void beforeEach() throws Exception {
// Initialize here, not inline, so that we pick up the mocked UserService. // Initialize here, not inline, so that we pick up the mocked UserService.
handler = handler =
RequestHandler.createForTest( RequestHandler.createForTest(
@ -226,8 +223,8 @@ public final class RequestHandlerTest {
handler.requestMetrics = requestMetrics; handler.requestMetrics = requestMetrics;
} }
@After @AfterEach
public void after() { void afterEach() {
verifyNoMoreInteractions(rsp, bumblebeeTask, slothTask, safeSlothTask, requestMetrics); verifyNoMoreInteractions(rsp, bumblebeeTask, slothTask, safeSlothTask, requestMetrics);
} }
@ -237,7 +234,7 @@ public final class RequestHandlerTest {
} }
@Test @Test
public void testHandleRequest_normalRequest_works() throws Exception { void testHandleRequest_normalRequest_works() throws Exception {
when(req.getMethod()).thenReturn("GET"); when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/bumblebee"); when(req.getRequestURI()).thenReturn("/bumblebee");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req)) when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -251,7 +248,7 @@ public final class RequestHandlerTest {
} }
@Test @Test
public void testHandleRequest_multipleMethodMappings_works() throws Exception { void testHandleRequest_multipleMethodMappings_works() throws Exception {
when(req.getMethod()).thenReturn("POST"); when(req.getMethod()).thenReturn("POST");
when(req.getRequestURI()).thenReturn("/bumblebee"); when(req.getRequestURI()).thenReturn("/bumblebee");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req)) when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -264,7 +261,7 @@ public final class RequestHandlerTest {
} }
@Test @Test
public void testHandleRequest_prefixEnabled_subpathsWork() throws Exception { void testHandleRequest_prefixEnabled_subpathsWork() throws Exception {
when(req.getMethod()).thenReturn("GET"); when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/bumblebee/hive"); when(req.getRequestURI()).thenReturn("/bumblebee/hive");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req)) when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -277,7 +274,7 @@ public final class RequestHandlerTest {
} }
@Test @Test
public void testHandleRequest_taskHasAutoPrintOk_printsOk() throws Exception { void testHandleRequest_taskHasAutoPrintOk_printsOk() throws Exception {
when(req.getMethod()).thenReturn("POST"); when(req.getMethod()).thenReturn("POST");
when(req.getRequestURI()).thenReturn("/sloth"); when(req.getRequestURI()).thenReturn("/sloth");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req)) when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -293,7 +290,7 @@ public final class RequestHandlerTest {
} }
@Test @Test
public void testHandleRequest_prefixDisabled_subpathsReturn404NotFound() throws Exception { void testHandleRequest_prefixDisabled_subpathsReturn404NotFound() throws Exception {
when(req.getMethod()).thenReturn("POST"); when(req.getMethod()).thenReturn("POST");
when(req.getRequestURI()).thenReturn("/sloth/nest"); when(req.getRequestURI()).thenReturn("/sloth/nest");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req)) when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -305,7 +302,7 @@ public final class RequestHandlerTest {
} }
@Test @Test
public void testHandleRequest_taskThrowsHttpException_getsHandledByHandler() throws Exception { void testHandleRequest_taskThrowsHttpException_getsHandledByHandler() throws Exception {
when(req.getMethod()).thenReturn("GET"); when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/fail"); when(req.getRequestURI()).thenReturn("/fail");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req)) when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -319,7 +316,7 @@ public final class RequestHandlerTest {
/** Test for a regression of the issue in b/21377705. */ /** Test for a regression of the issue in b/21377705. */
@Test @Test
public void testHandleRequest_taskThrowsHttpException_atConstructionTime_getsHandledByHandler() void testHandleRequest_taskThrowsHttpException_atConstructionTime_getsHandledByHandler()
throws Exception { throws Exception {
when(req.getMethod()).thenReturn("GET"); when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/failAtConstruction"); when(req.getRequestURI()).thenReturn("/failAtConstruction");
@ -333,7 +330,7 @@ public final class RequestHandlerTest {
} }
@Test @Test
public void testHandleRequest_notFound_returns404NotFound() throws Exception { void testHandleRequest_notFound_returns404NotFound() throws Exception {
when(req.getMethod()).thenReturn("GET"); when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/bogus"); when(req.getRequestURI()).thenReturn("/bogus");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req)) when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -345,7 +342,7 @@ public final class RequestHandlerTest {
} }
@Test @Test
public void testHandleRequest_methodNotAllowed_returns405MethodNotAllowed() throws Exception { void testHandleRequest_methodNotAllowed_returns405MethodNotAllowed() throws Exception {
when(req.getMethod()).thenReturn("POST"); when(req.getMethod()).thenReturn("POST");
when(req.getRequestURI()).thenReturn("/fail"); when(req.getRequestURI()).thenReturn("/fail");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req)) when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -357,7 +354,7 @@ public final class RequestHandlerTest {
} }
@Test @Test
public void testHandleRequest_insaneMethod_returns405MethodNotAllowed() throws Exception { void testHandleRequest_insaneMethod_returns405MethodNotAllowed() throws Exception {
when(req.getMethod()).thenReturn("FIREAWAY"); when(req.getMethod()).thenReturn("FIREAWAY");
when(req.getRequestURI()).thenReturn("/fail"); when(req.getRequestURI()).thenReturn("/fail");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req)) when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -368,10 +365,12 @@ public final class RequestHandlerTest {
verify(rsp).sendError(405); verify(rsp).sendError(405);
} }
/** @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.1"> /**
* RFC2616 - HTTP/1.1 - Method</a> */ * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.1">RFC2616 -
* HTTP/1.1 - Method</a>
*/
@Test @Test
public void testHandleRequest_lowercaseMethod_notRecognized() throws Exception { void testHandleRequest_lowercaseMethod_notRecognized() throws Exception {
when(req.getMethod()).thenReturn("get"); when(req.getMethod()).thenReturn("get");
when(req.getRequestURI()).thenReturn("/bumblebee"); when(req.getRequestURI()).thenReturn("/bumblebee");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req)) when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -382,8 +381,9 @@ public final class RequestHandlerTest {
verify(rsp).sendError(405); verify(rsp).sendError(405);
} }
@SuppressWarnings("UnstableApiUsage")
@Test @Test
public void testNullness() { void testNullness() {
NullPointerTester tester = new NullPointerTester(); NullPointerTester tester = new NullPointerTester();
tester.setDefault(Class.class, Component.class); tester.setDefault(Class.class, Component.class);
tester.setDefault(RequestAuthenticator.class, requestAuthenticator); tester.setDefault(RequestAuthenticator.class, requestAuthenticator);
@ -392,7 +392,7 @@ public final class RequestHandlerTest {
} }
@Test @Test
public void testXsrfProtection_validTokenProvided_runsAction() throws Exception { void testXsrfProtection_validTokenProvided_runsAction() throws Exception {
when(req.getMethod()).thenReturn("POST"); when(req.getMethod()).thenReturn("POST");
when(req.getRequestURI()).thenReturn("/safe-sloth"); when(req.getRequestURI()).thenReturn("/safe-sloth");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req)) when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -405,7 +405,7 @@ public final class RequestHandlerTest {
} }
@Test @Test
public void testXsrfProtection_GETMethodWithoutToken_doesntCheckToken() throws Exception { void testXsrfProtection_GETMethodWithoutToken_doesntCheckToken() throws Exception {
when(req.getMethod()).thenReturn("GET"); when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/safe-sloth"); when(req.getRequestURI()).thenReturn("/safe-sloth");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req)) when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -418,7 +418,7 @@ public final class RequestHandlerTest {
} }
@Test @Test
public void testNoAuthNeeded_success() throws Exception { void testNoAuthNeeded_success() throws Exception {
when(req.getMethod()).thenReturn("GET"); when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/auth/none"); when(req.getRequestURI()).thenReturn("/auth/none");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req)) when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -433,7 +433,7 @@ public final class RequestHandlerTest {
} }
@Test @Test
public void testAuthNeeded_failure() throws Exception { void testAuthNeeded_failure() throws Exception {
when(req.getMethod()).thenReturn("GET"); when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/auth/adminUser"); when(req.getRequestURI()).thenReturn("/auth/adminUser");
when(requestAuthenticator.authorize(AUTH_INTERNAL_OR_ADMIN.authSettings(), req)) when(requestAuthenticator.authorize(AUTH_INTERNAL_OR_ADMIN.authSettings(), req))
@ -446,7 +446,7 @@ public final class RequestHandlerTest {
} }
@Test @Test
public void testAuthNeeded_success() throws Exception { void testAuthNeeded_success() throws Exception {
when(req.getMethod()).thenReturn("GET"); when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/auth/adminUser"); when(req.getRequestURI()).thenReturn("/auth/adminUser");
when(requestAuthenticator.authorize(AUTH_INTERNAL_OR_ADMIN.authSettings(), req)) when(requestAuthenticator.authorize(AUTH_INTERNAL_OR_ADMIN.authSettings(), req))
@ -462,5 +462,4 @@ public final class RequestHandlerTest {
assertThat(providedAuthResult.userAuthInfo().get().oauthTokenInfo()).isEmpty(); assertThat(providedAuthResult.userAuthInfo().get().oauthTokenInfo()).isEmpty();
assertMetric("/auth/adminUser", GET, AuthLevel.USER, true); assertMetric("/auth/adminUser", GET, AuthLevel.USER, true);
} }
} }

View file

@ -21,27 +21,24 @@ import static org.junit.Assert.assertThrows;
import com.google.common.net.MediaType; import com.google.common.net.MediaType;
import google.registry.request.HttpException.BadRequestException; import google.registry.request.HttpException.BadRequestException;
import google.registry.request.HttpException.UnsupportedMediaTypeException; import google.registry.request.HttpException.UnsupportedMediaTypeException;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RequestModule}. */ /** Unit tests for {@link RequestModule}. */
@RunWith(JUnit4.class) final class RequestModuleTest {
public final class RequestModuleTest {
@Test @Test
public void testProvideJsonPayload() { void testProvideJsonPayload() {
assertThat(provideJsonPayload(MediaType.JSON_UTF_8, "{\"k\":\"v\"}")) assertThat(provideJsonPayload(MediaType.JSON_UTF_8, "{\"k\":\"v\"}")).containsExactly("k", "v");
.containsExactly("k", "v");
} }
@Test @Test
public void testProvideJsonPayload_contentTypeWithoutCharsetAllowed() { void testProvideJsonPayload_contentTypeWithoutCharsetAllowed() {
assertThat(provideJsonPayload(MediaType.JSON_UTF_8.withoutParameters(), "{\"k\":\"v\"}")) assertThat(provideJsonPayload(MediaType.JSON_UTF_8.withoutParameters(), "{\"k\":\"v\"}"))
.containsExactly("k", "v"); .containsExactly("k", "v");
} }
@Test @Test
public void testProvideJsonPayload_malformedInput_throws500() { void testProvideJsonPayload_malformedInput_throws500() {
BadRequestException thrown = BadRequestException thrown =
assertThrows( assertThrows(
BadRequestException.class, () -> provideJsonPayload(MediaType.JSON_UTF_8, "{\"k\":")); BadRequestException.class, () -> provideJsonPayload(MediaType.JSON_UTF_8, "{\"k\":"));
@ -49,21 +46,21 @@ public final class RequestModuleTest {
} }
@Test @Test
public void testProvideJsonPayload_emptyInput_throws500() { void testProvideJsonPayload_emptyInput_throws500() {
BadRequestException thrown = BadRequestException thrown =
assertThrows(BadRequestException.class, () -> provideJsonPayload(MediaType.JSON_UTF_8, "")); assertThrows(BadRequestException.class, () -> provideJsonPayload(MediaType.JSON_UTF_8, ""));
assertThat(thrown).hasMessageThat().contains("Malformed JSON"); assertThat(thrown).hasMessageThat().contains("Malformed JSON");
} }
@Test @Test
public void testProvideJsonPayload_nonJsonContentType_throws415() { void testProvideJsonPayload_nonJsonContentType_throws415() {
assertThrows( assertThrows(
UnsupportedMediaTypeException.class, UnsupportedMediaTypeException.class,
() -> provideJsonPayload(MediaType.PLAIN_TEXT_UTF_8, "{}")); () -> provideJsonPayload(MediaType.PLAIN_TEXT_UTF_8, "{}"));
} }
@Test @Test
public void testProvideJsonPayload_contentTypeWithWeirdParam_throws415() { void testProvideJsonPayload_contentTypeWithWeirdParam_throws415() {
assertThrows( assertThrows(
UnsupportedMediaTypeException.class, UnsupportedMediaTypeException.class,
() -> provideJsonPayload(MediaType.JSON_UTF_8.withParameter("omg", "handel"), "{}")); () -> provideJsonPayload(MediaType.JSON_UTF_8.withParameter("omg", "handel"), "{}"));

View file

@ -33,30 +33,28 @@ import com.google.common.collect.ImmutableMap;
import google.registry.request.HttpException.BadRequestException; import google.registry.request.HttpException.BadRequestException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RequestParameters}. */ /** Unit tests for {@link RequestParameters}. */
@RunWith(JUnit4.class) class RequestParametersTest {
public class RequestParametersTest {
private final HttpServletRequest req = mock(HttpServletRequest.class); private final HttpServletRequest req = mock(HttpServletRequest.class);
@Test @Test
public void testExtractRequiredParameter_valuePresent_returnsValue() { void testExtractRequiredParameter_valuePresent_returnsValue() {
when(req.getParameter("spin")).thenReturn("bog"); when(req.getParameter("spin")).thenReturn("bog");
assertThat(extractRequiredParameter(req, "spin")).isEqualTo("bog"); assertThat(extractRequiredParameter(req, "spin")).isEqualTo("bog");
} }
@Test @Test
public void testExtractRequiredParameter_notPresent_throwsBadRequest() { void testExtractRequiredParameter_notPresent_throwsBadRequest() {
BadRequestException thrown = BadRequestException thrown =
assertThrows(BadRequestException.class, () -> extractRequiredParameter(req, "spin")); assertThrows(BadRequestException.class, () -> extractRequiredParameter(req, "spin"));
assertThat(thrown).hasMessageThat().contains("spin"); assertThat(thrown).hasMessageThat().contains("spin");
} }
@Test @Test
public void testExtractRequiredParameter_empty_throwsBadRequest() { void testExtractRequiredParameter_empty_throwsBadRequest() {
when(req.getParameter("spin")).thenReturn(""); when(req.getParameter("spin")).thenReturn("");
BadRequestException thrown = BadRequestException thrown =
assertThrows(BadRequestException.class, () -> extractRequiredParameter(req, "spin")); assertThrows(BadRequestException.class, () -> extractRequiredParameter(req, "spin"));
@ -64,53 +62,53 @@ public class RequestParametersTest {
} }
@Test @Test
public void testExtractOptionalParameter_valuePresent_returnsValue() { void testExtractOptionalParameter_valuePresent_returnsValue() {
when(req.getParameter("spin")).thenReturn("bog"); when(req.getParameter("spin")).thenReturn("bog");
assertThat(extractOptionalParameter(req, "spin")).hasValue("bog"); assertThat(extractOptionalParameter(req, "spin")).hasValue("bog");
} }
@Test @Test
public void testExtractOptionalParameter_notPresent_returnsEmpty() { void testExtractOptionalParameter_notPresent_returnsEmpty() {
assertThat(extractOptionalParameter(req, "spin")).isEmpty(); assertThat(extractOptionalParameter(req, "spin")).isEmpty();
} }
@Test @Test
public void testExtractOptionalParameter_empty_returnsEmpty() { void testExtractOptionalParameter_empty_returnsEmpty() {
when(req.getParameter("spin")).thenReturn(""); when(req.getParameter("spin")).thenReturn("");
assertThat(extractOptionalParameter(req, "spin")).isEmpty(); assertThat(extractOptionalParameter(req, "spin")).isEmpty();
} }
@Test @Test
public void testExtractSetOfParameters_notPresent_returnsEmpty() { void testExtractSetOfParameters_notPresent_returnsEmpty() {
assertThat(extractSetOfParameters(req, "spin")).isEmpty(); assertThat(extractSetOfParameters(req, "spin")).isEmpty();
} }
@Test @Test
public void testExtractSetOfParameters_empty_returnsEmpty() { void testExtractSetOfParameters_empty_returnsEmpty() {
when(req.getParameter("spin")).thenReturn(""); when(req.getParameter("spin")).thenReturn("");
assertThat(extractSetOfParameters(req, "spin")).isEmpty(); assertThat(extractSetOfParameters(req, "spin")).isEmpty();
} }
@Test @Test
public void testExtractSetOfParameters_oneValue_returnsValue() { void testExtractSetOfParameters_oneValue_returnsValue() {
when(req.getParameter("spin")).thenReturn("bog"); when(req.getParameter("spin")).thenReturn("bog");
assertThat(extractSetOfParameters(req, "spin")).containsExactly("bog"); assertThat(extractSetOfParameters(req, "spin")).containsExactly("bog");
} }
@Test @Test
public void testExtractSetOfParameters_multipleValues_returnsAll() { void testExtractSetOfParameters_multipleValues_returnsAll() {
when(req.getParameter("spin")).thenReturn("bog,gob"); when(req.getParameter("spin")).thenReturn("bog,gob");
assertThat(extractSetOfParameters(req, "spin")).containsExactly("bog", "gob"); assertThat(extractSetOfParameters(req, "spin")).containsExactly("bog", "gob");
} }
@Test @Test
public void testExtractSetOfParameters_multipleValuesWithEmpty_removesEmpty() { void testExtractSetOfParameters_multipleValuesWithEmpty_removesEmpty() {
when(req.getParameter("spin")).thenReturn(",bog,,gob,"); when(req.getParameter("spin")).thenReturn(",bog,,gob,");
assertThat(extractSetOfParameters(req, "spin")).containsExactly("bog", "gob"); assertThat(extractSetOfParameters(req, "spin")).containsExactly("bog", "gob");
} }
@Test @Test
public void testExtractSetOfParameters_multipleParameters_error() { void testExtractSetOfParameters_multipleParameters_error() {
when(req.getParameterValues("spin")).thenReturn(new String[] {"bog", "gob"}); when(req.getParameterValues("spin")).thenReturn(new String[] {"bog", "gob"});
BadRequestException thrown = BadRequestException thrown =
assertThrows(BadRequestException.class, () -> extractSetOfParameters(req, "spin")); assertThrows(BadRequestException.class, () -> extractSetOfParameters(req, "spin"));
@ -118,45 +116,45 @@ public class RequestParametersTest {
} }
@Test @Test
public void testExtractSetOfEnumParameters_notPresent_returnsEmpty() { void testExtractSetOfEnumParameters_notPresent_returnsEmpty() {
assertThat(extractSetOfEnumParameters(req, Club.class, "spin")).isEmpty(); assertThat(extractSetOfEnumParameters(req, Club.class, "spin")).isEmpty();
} }
@Test @Test
public void testExtractSetOfEnumParameters_empty_returnsEmpty() { void testExtractSetOfEnumParameters_empty_returnsEmpty() {
when(req.getParameter("spin")).thenReturn(""); when(req.getParameter("spin")).thenReturn("");
assertThat(extractSetOfEnumParameters(req, Club.class, "spin")).isEmpty(); assertThat(extractSetOfEnumParameters(req, Club.class, "spin")).isEmpty();
} }
@Test @Test
public void testExtractSetOfEnumParameters_oneValue_returnsValue() { void testExtractSetOfEnumParameters_oneValue_returnsValue() {
when(req.getParameter("spin")).thenReturn("DANCE"); when(req.getParameter("spin")).thenReturn("DANCE");
assertThat(extractSetOfEnumParameters(req, Club.class, "spin")).containsExactly(Club.DANCE); assertThat(extractSetOfEnumParameters(req, Club.class, "spin")).containsExactly(Club.DANCE);
} }
@Test @Test
public void testExtractSetOfEnumParameters_multipleValues_returnsAll() { void testExtractSetOfEnumParameters_multipleValues_returnsAll() {
when(req.getParameter("spin")).thenReturn("DANCE,FLOOR"); when(req.getParameter("spin")).thenReturn("DANCE,FLOOR");
assertThat(extractSetOfEnumParameters(req, Club.class, "spin")) assertThat(extractSetOfEnumParameters(req, Club.class, "spin"))
.containsExactly(Club.DANCE, Club.FLOOR); .containsExactly(Club.DANCE, Club.FLOOR);
} }
@Test @Test
public void testExtractSetOfEnumParameters_multipleValuesWithEmpty_removesEmpty() { void testExtractSetOfEnumParameters_multipleValuesWithEmpty_removesEmpty() {
when(req.getParameter("spin")).thenReturn(",DANCE,,FLOOR,"); when(req.getParameter("spin")).thenReturn(",DANCE,,FLOOR,");
assertThat(extractSetOfEnumParameters(req, Club.class, "spin")) assertThat(extractSetOfEnumParameters(req, Club.class, "spin"))
.containsExactly(Club.DANCE, Club.FLOOR); .containsExactly(Club.DANCE, Club.FLOOR);
} }
@Test @Test
public void testExtractSetOfEnumParameters_multipleValues_caseInsensitive() { void testExtractSetOfEnumParameters_multipleValues_caseInsensitive() {
when(req.getParameter("spin")).thenReturn("danCE,FlooR"); when(req.getParameter("spin")).thenReturn("danCE,FlooR");
assertThat(extractSetOfEnumParameters(req, Club.class, "spin")) assertThat(extractSetOfEnumParameters(req, Club.class, "spin"))
.containsExactly(Club.DANCE, Club.FLOOR); .containsExactly(Club.DANCE, Club.FLOOR);
} }
@Test @Test
public void testExtractSetOfEnumParameters_multipleParameters_error() { void testExtractSetOfEnumParameters_multipleParameters_error() {
when(req.getParameterValues("spin")).thenReturn(new String[] {"DANCE", "FLOOR"}); when(req.getParameterValues("spin")).thenReturn(new String[] {"DANCE", "FLOOR"});
BadRequestException thrown = BadRequestException thrown =
assertThrows( assertThrows(
@ -165,67 +163,70 @@ public class RequestParametersTest {
} }
@Test @Test
public void testExtractBooleanParameter_notPresent_returnsFalse() { void testExtractBooleanParameter_notPresent_returnsFalse() {
assertThat(extractBooleanParameter(req, "love")).isFalse(); assertThat(extractBooleanParameter(req, "love")).isFalse();
} }
@Test @Test
public void testExtractBooleanParameter_presentWithoutValue_returnsTrue() { void testExtractBooleanParameter_presentWithoutValue_returnsTrue() {
when(req.getParameterMap()).thenReturn(ImmutableMap.of("love", "")); when(req.getParameterMap()).thenReturn(ImmutableMap.of("love", ""));
assertThat(extractBooleanParameter(req, "love")).isTrue(); assertThat(extractBooleanParameter(req, "love")).isTrue();
} }
@Test @Test
public void testExtractBooleanParameter_empty_returnsTrue() { void testExtractBooleanParameter_empty_returnsTrue() {
when(req.getParameterMap()).thenReturn(ImmutableMap.of("love", "")); when(req.getParameterMap()).thenReturn(ImmutableMap.of("love", ""));
when(req.getParameter("love")).thenReturn(""); when(req.getParameter("love")).thenReturn("");
assertThat(extractBooleanParameter(req, "love")).isTrue(); assertThat(extractBooleanParameter(req, "love")).isTrue();
} }
@Test @Test
public void testExtractBooleanParameter_presentStringArbitrary_returnsTrue() { void testExtractBooleanParameter_presentStringArbitrary_returnsTrue() {
when(req.getParameterMap()).thenReturn(ImmutableMap.of("love", "lol")); when(req.getParameterMap()).thenReturn(ImmutableMap.of("love", "lol"));
when(req.getParameter("love")).thenReturn("lol"); when(req.getParameter("love")).thenReturn("lol");
assertThat(extractBooleanParameter(req, "love")).isTrue(); assertThat(extractBooleanParameter(req, "love")).isTrue();
} }
@Test @Test
public void testExtractBooleanParameter_presentStringTrue_returnsTrue() { void testExtractBooleanParameter_presentStringTrue_returnsTrue() {
when(req.getParameterMap()).thenReturn(ImmutableMap.of("love", "true")); when(req.getParameterMap()).thenReturn(ImmutableMap.of("love", "true"));
when(req.getParameter("love")).thenReturn("true"); when(req.getParameter("love")).thenReturn("true");
assertThat(extractBooleanParameter(req, "love")).isTrue(); assertThat(extractBooleanParameter(req, "love")).isTrue();
} }
@Test @Test
public void testExtractBooleanParameter_presentStringFalse_returnsFalse() { void testExtractBooleanParameter_presentStringFalse_returnsFalse() {
when(req.getParameterMap()).thenReturn(ImmutableMap.of("love", "false")); when(req.getParameterMap()).thenReturn(ImmutableMap.of("love", "false"));
when(req.getParameter("love")).thenReturn("false"); when(req.getParameter("love")).thenReturn("false");
assertThat(extractBooleanParameter(req, "love")).isFalse(); assertThat(extractBooleanParameter(req, "love")).isFalse();
} }
@Test @Test
public void testExtractBooleanParameter_presentStringFalse_caseInsensitive() { void testExtractBooleanParameter_presentStringFalse_caseInsensitive() {
when(req.getParameterMap()).thenReturn(ImmutableMap.of("love", "FaLsE")); when(req.getParameterMap()).thenReturn(ImmutableMap.of("love", "FaLsE"));
when(req.getParameter("love")).thenReturn("FaLsE"); when(req.getParameter("love")).thenReturn("FaLsE");
assertThat(extractBooleanParameter(req, "love")).isFalse(); assertThat(extractBooleanParameter(req, "love")).isFalse();
} }
enum Club { DANCE, FLOOR } enum Club {
DANCE,
FLOOR
}
@Test @Test
public void testExtractEnumValue_correctValue_works() { void testExtractEnumValue_correctValue_works() {
when(req.getParameter("spin")).thenReturn("DANCE"); when(req.getParameter("spin")).thenReturn("DANCE");
assertThat(extractEnumParameter(req, Club.class, "spin")).isEqualTo(Club.DANCE); assertThat(extractEnumParameter(req, Club.class, "spin")).isEqualTo(Club.DANCE);
} }
@Test @Test
public void testExtractEnumValue_weirdCasing_isCaseInsensitive() { void testExtractEnumValue_weirdCasing_isCaseInsensitive() {
when(req.getParameter("spin")).thenReturn("DaNcE"); when(req.getParameter("spin")).thenReturn("DaNcE");
assertThat(extractEnumParameter(req, Club.class, "spin")).isEqualTo(Club.DANCE); assertThat(extractEnumParameter(req, Club.class, "spin")).isEqualTo(Club.DANCE);
} }
@Test @Test
public void testExtractEnumValue_nonExistentValue_throwsBadRequest() { void testExtractEnumValue_nonExistentValue_throwsBadRequest() {
when(req.getParameter("spin")).thenReturn("sing"); when(req.getParameter("spin")).thenReturn("sing");
BadRequestException thrown = BadRequestException thrown =
assertThrows( assertThrows(
@ -234,19 +235,19 @@ public class RequestParametersTest {
} }
@Test @Test
public void testOptionalExtractEnumValue_givenValue_returnsValue() { void testOptionalExtractEnumValue_givenValue_returnsValue() {
when(req.getParameter("spin")).thenReturn("DANCE"); when(req.getParameter("spin")).thenReturn("DANCE");
assertThat(extractOptionalEnumParameter(req, Club.class, "spin")).hasValue(Club.DANCE); assertThat(extractOptionalEnumParameter(req, Club.class, "spin")).hasValue(Club.DANCE);
} }
@Test @Test
public void testOptionalExtractEnumValue_noValue_returnsEmpty() { void testOptionalExtractEnumValue_noValue_returnsEmpty() {
when(req.getParameter("spin")).thenReturn(""); when(req.getParameter("spin")).thenReturn("");
assertThat(extractOptionalEnumParameter(req, Club.class, "spin")).isEmpty(); assertThat(extractOptionalEnumParameter(req, Club.class, "spin")).isEmpty();
} }
@Test @Test
public void testOptionalExtractEnumValue_nonExistentValue_throwsBadRequest() { void testOptionalExtractEnumValue_nonExistentValue_throwsBadRequest() {
when(req.getParameter("spin")).thenReturn("sing"); when(req.getParameter("spin")).thenReturn("sing");
BadRequestException thrown = BadRequestException thrown =
assertThrows( assertThrows(
@ -255,14 +256,14 @@ public class RequestParametersTest {
} }
@Test @Test
public void testExtractRequiredDatetimeParameter_correctValue_works() { void testExtractRequiredDatetimeParameter_correctValue_works() {
when(req.getParameter("timeParam")).thenReturn("2015-08-27T13:25:34.123Z"); when(req.getParameter("timeParam")).thenReturn("2015-08-27T13:25:34.123Z");
assertThat(extractRequiredDatetimeParameter(req, "timeParam")) assertThat(extractRequiredDatetimeParameter(req, "timeParam"))
.isEqualTo(DateTime.parse("2015-08-27T13:25:34.123Z")); .isEqualTo(DateTime.parse("2015-08-27T13:25:34.123Z"));
} }
@Test @Test
public void testExtractRequiredDatetimeParameter_badValue_throwsBadRequest() { void testExtractRequiredDatetimeParameter_badValue_throwsBadRequest() {
when(req.getParameter("timeParam")).thenReturn("Tuesday at three o'clock"); when(req.getParameter("timeParam")).thenReturn("Tuesday at three o'clock");
BadRequestException thrown = BadRequestException thrown =
assertThrows( assertThrows(
@ -271,14 +272,14 @@ public class RequestParametersTest {
} }
@Test @Test
public void testExtractOptionalDatetimeParameter_correctValue_works() { void testExtractOptionalDatetimeParameter_correctValue_works() {
when(req.getParameter("timeParam")).thenReturn("2015-08-27T13:25:34.123Z"); when(req.getParameter("timeParam")).thenReturn("2015-08-27T13:25:34.123Z");
assertThat(extractOptionalDatetimeParameter(req, "timeParam")) assertThat(extractOptionalDatetimeParameter(req, "timeParam"))
.hasValue(DateTime.parse("2015-08-27T13:25:34.123Z")); .hasValue(DateTime.parse("2015-08-27T13:25:34.123Z"));
} }
@Test @Test
public void testExtractOptionalDatetimeParameter_badValue_throwsBadRequest() { void testExtractOptionalDatetimeParameter_badValue_throwsBadRequest() {
when(req.getParameter("timeParam")).thenReturn("Tuesday at three o'clock"); when(req.getParameter("timeParam")).thenReturn("Tuesday at three o'clock");
BadRequestException thrown = BadRequestException thrown =
assertThrows( assertThrows(
@ -287,13 +288,13 @@ public class RequestParametersTest {
} }
@Test @Test
public void testExtractOptionalDatetimeParameter_empty_returnsEmpty() { void testExtractOptionalDatetimeParameter_empty_returnsEmpty() {
when(req.getParameter("timeParam")).thenReturn(""); when(req.getParameter("timeParam")).thenReturn("");
assertThat(extractOptionalDatetimeParameter(req, "timeParam")).isEmpty(); assertThat(extractOptionalDatetimeParameter(req, "timeParam")).isEmpty();
} }
@Test @Test
public void testExtractRequiredDatetimeParameter_noValue_throwsBadRequest() { void testExtractRequiredDatetimeParameter_noValue_throwsBadRequest() {
BadRequestException thrown = BadRequestException thrown =
assertThrows( assertThrows(
BadRequestException.class, () -> extractRequiredDatetimeParameter(req, "timeParam")); BadRequestException.class, () -> extractRequiredDatetimeParameter(req, "timeParam"));

View file

@ -24,32 +24,29 @@ import static org.mockito.Mockito.when;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link ResponseImpl}. */ /** Unit tests for {@link ResponseImpl}. */
@RunWith(JUnit4.class) class ResponseImplTest {
public class ResponseImplTest {
private final HttpServletResponse rsp = mock(HttpServletResponse.class); private final HttpServletResponse rsp = mock(HttpServletResponse.class);
@Test @Test
public void testSetStatus() { void testSetStatus() {
new ResponseImpl(rsp).setStatus(666); new ResponseImpl(rsp).setStatus(666);
verify(rsp).setStatus(666); verify(rsp).setStatus(666);
verifyNoMoreInteractions(rsp); verifyNoMoreInteractions(rsp);
} }
@Test @Test
public void testSetContentType() { void testSetContentType() {
new ResponseImpl(rsp).setContentType(PLAIN_TEXT_UTF_8); new ResponseImpl(rsp).setContentType(PLAIN_TEXT_UTF_8);
verify(rsp).setContentType("text/plain; charset=utf-8"); verify(rsp).setContentType("text/plain; charset=utf-8");
verifyNoMoreInteractions(rsp); verifyNoMoreInteractions(rsp);
} }
@Test @Test
public void testSetPayload() throws Exception { void testSetPayload() throws Exception {
StringWriter httpOutput = new StringWriter(); StringWriter httpOutput = new StringWriter();
when(rsp.getWriter()).thenReturn(new PrintWriter(httpOutput)); when(rsp.getWriter()).thenReturn(new PrintWriter(httpOutput));
new ResponseImpl(rsp).setPayload("hello world"); new ResponseImpl(rsp).setPayload("hello world");

View file

@ -22,12 +22,9 @@ import static org.junit.Assert.assertThrows;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.function.Function; import java.util.function.Function;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link Router}. */ /** Unit tests for {@link Router}. */
@RunWith(JUnit4.class)
public final class RouterTest { public final class RouterTest {
//////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////
@ -35,7 +32,7 @@ public final class RouterTest {
public interface Empty {} public interface Empty {}
@Test @Test
public void testRoute_noRoutes_throws() { void testRoute_noRoutes_throws() {
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows(IllegalArgumentException.class, () -> Router.create(Empty.class)); assertThrows(IllegalArgumentException.class, () -> Router.create(Empty.class));
assertThat(thrown) assertThat(thrown)
@ -56,7 +53,7 @@ public final class RouterTest {
} }
@Test @Test
public void testRoute_pathMatch_returnsRoute() { void testRoute_pathMatch_returnsRoute() {
Optional<Route> route = Router.create(SlothComponent.class).route("/sloth"); Optional<Route> route = Router.create(SlothComponent.class).route("/sloth");
assertThat(route).isPresent(); assertThat(route).isPresent();
assertThat(route.get().action().path()).isEqualTo("/sloth"); assertThat(route.get().action().path()).isEqualTo("/sloth");
@ -64,12 +61,12 @@ public final class RouterTest {
} }
@Test @Test
public void testRoute_pathMismatch_returnsEmpty() { void testRoute_pathMismatch_returnsEmpty() {
assertThat(Router.create(SlothComponent.class).route("/doge")).isEmpty(); assertThat(Router.create(SlothComponent.class).route("/doge")).isEmpty();
} }
@Test @Test
public void testRoute_pathIsAPrefix_notAllowedByDefault() { void testRoute_pathIsAPrefix_notAllowedByDefault() {
assertThat(Router.create(SlothComponent.class).route("/sloth/extra")).isEmpty(); assertThat(Router.create(SlothComponent.class).route("/sloth/extra")).isEmpty();
} }
@ -90,13 +87,13 @@ public final class RouterTest {
} }
@Test @Test
public void testRoute_prefixMatches_returnsRoute() { void testRoute_prefixMatches_returnsRoute() {
assertThat(Router.create(PrefixComponent.class).route("/prefix")).isPresent(); assertThat(Router.create(PrefixComponent.class).route("/prefix")).isPresent();
assertThat(Router.create(PrefixComponent.class).route("/prefix/extra")).isPresent(); assertThat(Router.create(PrefixComponent.class).route("/prefix/extra")).isPresent();
} }
@Test @Test
public void testRoute_prefixDoesNotMatch_returnsEmpty() { void testRoute_prefixDoesNotMatch_returnsEmpty() {
assertThat(Router.create(PrefixComponent.class).route("")).isEmpty(); assertThat(Router.create(PrefixComponent.class).route("")).isEmpty();
assertThat(Router.create(PrefixComponent.class).route("/")).isEmpty(); assertThat(Router.create(PrefixComponent.class).route("/")).isEmpty();
assertThat(Router.create(PrefixComponent.class).route("/ulysses")).isEmpty(); assertThat(Router.create(PrefixComponent.class).route("/ulysses")).isEmpty();
@ -121,21 +118,21 @@ public final class RouterTest {
} }
@Test @Test
public void testRoute_prefixAndLongPathMatch_returnsLongerPath() { void testRoute_prefixAndLongPathMatch_returnsLongerPath() {
Optional<Route> route = Router.create(LongPathComponent.class).route("/prefix/long"); Optional<Route> route = Router.create(LongPathComponent.class).route("/prefix/long");
assertThat(route).isPresent(); assertThat(route).isPresent();
assertThat(route.get().action().path()).isEqualTo("/prefix/long"); assertThat(route.get().action().path()).isEqualTo("/prefix/long");
} }
@Test @Test
public void testRoute_prefixAndLongerPrefixMatch_returnsLongerPrefix() { void testRoute_prefixAndLongerPrefixMatch_returnsLongerPrefix() {
Optional<Route> route = Router.create(LongPathComponent.class).route("/prefix/longer"); Optional<Route> route = Router.create(LongPathComponent.class).route("/prefix/longer");
assertThat(route).isPresent(); assertThat(route).isPresent();
assertThat(route.get().action().path()).isEqualTo("/prefix/long"); assertThat(route.get().action().path()).isEqualTo("/prefix/long");
} }
@Test @Test
public void testRoute_onlyShortPrefixMatches_returnsShortPrefix() { void testRoute_onlyShortPrefixMatches_returnsShortPrefix() {
Optional<Route> route = Router.create(LongPathComponent.class).route("/prefix/cat"); Optional<Route> route = Router.create(LongPathComponent.class).route("/prefix/cat");
assertThat(route).isPresent(); assertThat(route).isPresent();
assertThat(route.get().action().path()).isEqualTo("/prefix"); assertThat(route.get().action().path()).isEqualTo("/prefix");
@ -149,7 +146,7 @@ public final class RouterTest {
} }
@Test @Test
public void testRoute_methodsInComponentAreIgnored_throws() { void testRoute_methodsInComponentAreIgnored_throws() {
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
IllegalArgumentException.class, () -> Router.create(WeirdMethodsComponent.class)); IllegalArgumentException.class, () -> Router.create(WeirdMethodsComponent.class));
@ -185,7 +182,7 @@ public final class RouterTest {
} }
@Test @Test
public void testCreate_twoTasksWithSameMethodAndPath_resultsInError() { void testCreate_twoTasksWithSameMethodAndPath_resultsInError() {
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows(IllegalArgumentException.class, () -> Router.create(DuplicateComponent.class)); assertThrows(IllegalArgumentException.class, () -> Router.create(DuplicateComponent.class));
assertThat(thrown).hasMessageThat().contains("Multiple entries with same key"); assertThat(thrown).hasMessageThat().contains("Multiple entries with same key");

View file

@ -14,16 +14,13 @@
package google.registry.request.auth; package google.registry.request.auth;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link Auth}. */ /** Unit tests for {@link Auth}. */
@RunWith(JUnit4.class) final class AuthTest {
public final class AuthTest {
@Test @Test
public void testAuthValues_validConfig() { void testAuthValues_validConfig() {
for (Auth auth : Auth.values()) { for (Auth auth : Auth.values()) {
RequestAuthenticator.checkAuthConfig(auth.authSettings()); RequestAuthenticator.checkAuthConfig(auth.authSettings());
} }

View file

@ -43,25 +43,25 @@ import java.util.Optional;
import java.util.logging.Level; import java.util.logging.Level;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runners.JUnit4;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit; import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.MockitoRule; import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
/** Unit tests for {@link AuthenticatedRegistrarAccessor}. */ /** Unit tests for {@link AuthenticatedRegistrarAccessor}. */
@RunWith(JUnit4.class) @ExtendWith(MockitoExtension.class)
public class AuthenticatedRegistrarAccessorTest { @MockitoSettings(strictness = Strictness.LENIENT)
class AuthenticatedRegistrarAccessorTest {
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Rule public final InjectRule inject = new InjectRule(); @RegisterExtension final InjectRule inject = new InjectRule();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@Mock private HttpServletRequest req; @Mock private HttpServletRequest req;
@Mock private HttpServletResponse rsp; @Mock private HttpServletResponse rsp;
@ -86,7 +86,7 @@ public class AuthenticatedRegistrarAccessorTest {
/** /**
* Creates an AuthResult for a fake user. * Creates an AuthResult for a fake user.
* *
* The user will be a RegistrarContact for "TheRegistrar", but not for "NewRegistrar". * <p>The user will be a RegistrarContact for "TheRegistrar", but not for "NewRegistrar".
* *
* @param isAdmin if true, the user is an administrator for the app-engine project. * @param isAdmin if true, the user is an administrator for the app-engine project.
*/ */
@ -103,8 +103,8 @@ public class AuthenticatedRegistrarAccessorTest {
isAdmin)); isAdmin));
} }
@Before @BeforeEach
public void before() { void beforeEach() {
when(lazyGroupsConnection.get()).thenReturn(groupsConnection); when(lazyGroupsConnection.get()).thenReturn(groupsConnection);
LoggerConfig.getConfig(AuthenticatedRegistrarAccessor.class).addHandler(testLogHandler); LoggerConfig.getConfig(AuthenticatedRegistrarAccessor.class).addHandler(testLogHandler);
// persistResource(loadRegistrar(ADMIN_CLIENT_ID)); // persistResource(loadRegistrar(ADMIN_CLIENT_ID));
@ -125,14 +125,14 @@ public class AuthenticatedRegistrarAccessorTest {
when(groupsConnection.isMemberOfGroup(any(), any())).thenReturn(false); when(groupsConnection.isMemberOfGroup(any(), any())).thenReturn(false);
} }
@After @AfterEach
public void after() { void afterEach() {
LoggerConfig.getConfig(AuthenticatedRegistrarAccessor.class).removeHandler(testLogHandler); LoggerConfig.getConfig(AuthenticatedRegistrarAccessor.class).removeHandler(testLogHandler);
} }
/** Users are owners for registrars if and only if they are in the contacts for that registrar. */ /** Users are owners for registrars if and only if they are in the contacts for that registrar. */
@Test @Test
public void getAllClientIdWithAccess_user() { void getAllClientIdWithAccess_user() {
AuthenticatedRegistrarAccessor registrarAccessor = AuthenticatedRegistrarAccessor registrarAccessor =
new AuthenticatedRegistrarAccessor( new AuthenticatedRegistrarAccessor(
USER, ADMIN_CLIENT_ID, SUPPORT_GROUP, lazyGroupsConnection); USER, ADMIN_CLIENT_ID, SUPPORT_GROUP, lazyGroupsConnection);
@ -144,7 +144,7 @@ public class AuthenticatedRegistrarAccessorTest {
/** Logged out users don't have access to anything. */ /** Logged out users don't have access to anything. */
@Test @Test
public void getAllClientIdWithAccess_loggedOutUser() { void getAllClientIdWithAccess_loggedOutUser() {
AuthenticatedRegistrarAccessor registrarAccessor = AuthenticatedRegistrarAccessor registrarAccessor =
new AuthenticatedRegistrarAccessor( new AuthenticatedRegistrarAccessor(
NO_USER, ADMIN_CLIENT_ID, SUPPORT_GROUP, lazyGroupsConnection); NO_USER, ADMIN_CLIENT_ID, SUPPORT_GROUP, lazyGroupsConnection);
@ -165,7 +165,7 @@ public class AuthenticatedRegistrarAccessorTest {
* <p>(in other words - they don't have OWNER access only to REAL registrars owned by others) * <p>(in other words - they don't have OWNER access only to REAL registrars owned by others)
*/ */
@Test @Test
public void getAllClientIdWithAccess_gaeAdmin() { void getAllClientIdWithAccess_gaeAdmin() {
AuthenticatedRegistrarAccessor registrarAccessor = AuthenticatedRegistrarAccessor registrarAccessor =
new AuthenticatedRegistrarAccessor( new AuthenticatedRegistrarAccessor(
GAE_ADMIN, ADMIN_CLIENT_ID, SUPPORT_GROUP, lazyGroupsConnection); GAE_ADMIN, ADMIN_CLIENT_ID, SUPPORT_GROUP, lazyGroupsConnection);
@ -197,7 +197,7 @@ public class AuthenticatedRegistrarAccessorTest {
* <p>(in other words - they don't have OWNER access only to REAL registrars owned by others) * <p>(in other words - they don't have OWNER access only to REAL registrars owned by others)
*/ */
@Test @Test
public void getAllClientIdWithAccess_userInSupportGroup() { void getAllClientIdWithAccess_userInSupportGroup() {
when(groupsConnection.isMemberOfGroup("user@gmail.com", SUPPORT_GROUP.get())).thenReturn(true); when(groupsConnection.isMemberOfGroup("user@gmail.com", SUPPORT_GROUP.get())).thenReturn(true);
AuthenticatedRegistrarAccessor registrarAccessor = AuthenticatedRegistrarAccessor registrarAccessor =
new AuthenticatedRegistrarAccessor( new AuthenticatedRegistrarAccessor(
@ -220,7 +220,7 @@ public class AuthenticatedRegistrarAccessorTest {
/** Empty Support group email - skips check and doesn't generate the lazy. */ /** Empty Support group email - skips check and doesn't generate the lazy. */
@Test @Test
public void getAllClientIdWithAccess_emptySupportEmail_works() { void getAllClientIdWithAccess_emptySupportEmail_works() {
AuthenticatedRegistrarAccessor registrarAccessor = AuthenticatedRegistrarAccessor registrarAccessor =
new AuthenticatedRegistrarAccessor( new AuthenticatedRegistrarAccessor(
USER, ADMIN_CLIENT_ID, Optional.empty(), lazyGroupsConnection); USER, ADMIN_CLIENT_ID, Optional.empty(), lazyGroupsConnection);
@ -233,7 +233,7 @@ public class AuthenticatedRegistrarAccessorTest {
/** Support group check throws - continue anyway. */ /** Support group check throws - continue anyway. */
@Test @Test
public void getAllClientIdWithAccess_throwingGroupCheck_stillWorks() { void getAllClientIdWithAccess_throwingGroupCheck_stillWorks() {
when(groupsConnection.isMemberOfGroup(any(), any())).thenThrow(new RuntimeException("blah")); when(groupsConnection.isMemberOfGroup(any(), any())).thenThrow(new RuntimeException("blah"));
AuthenticatedRegistrarAccessor registrarAccessor = AuthenticatedRegistrarAccessor registrarAccessor =
new AuthenticatedRegistrarAccessor( new AuthenticatedRegistrarAccessor(
@ -247,7 +247,7 @@ public class AuthenticatedRegistrarAccessorTest {
/** Fail loading registrar if user doesn't have access to it. */ /** Fail loading registrar if user doesn't have access to it. */
@Test @Test
public void testGetRegistrarForUser_noAccess_isNotAdmin() { void testGetRegistrarForUser_noAccess_isNotAdmin() {
expectGetRegistrarFailure( expectGetRegistrarFailure(
REAL_CLIENT_ID_WITHOUT_CONTACT, REAL_CLIENT_ID_WITHOUT_CONTACT,
USER, USER,
@ -256,7 +256,7 @@ public class AuthenticatedRegistrarAccessorTest {
} }
@Test @Test
public void testGetRegistrarForUser_registrarIsDisabled_isNotAdmin() { void testGetRegistrarForUser_registrarIsDisabled_isNotAdmin() {
persistResource( persistResource(
Registrar.loadByClientId("TheRegistrar") Registrar.loadByClientId("TheRegistrar")
.get() .get()
@ -272,7 +272,7 @@ public class AuthenticatedRegistrarAccessorTest {
/** Fail loading registrar if user doesn't have access to it, even if it's not REAL. */ /** Fail loading registrar if user doesn't have access to it, even if it's not REAL. */
@Test @Test
public void testGetRegistrarForUser_noAccess_isNotAdmin_notReal() { void testGetRegistrarForUser_noAccess_isNotAdmin_notReal() {
expectGetRegistrarFailure( expectGetRegistrarFailure(
OTE_CLIENT_ID_WITHOUT_CONTACT, OTE_CLIENT_ID_WITHOUT_CONTACT,
USER, USER,
@ -282,7 +282,7 @@ public class AuthenticatedRegistrarAccessorTest {
/** Fail loading registrar if there's no user associated with the request. */ /** Fail loading registrar if there's no user associated with the request. */
@Test @Test
public void testGetRegistrarForUser_noUser() { void testGetRegistrarForUser_noUser() {
expectGetRegistrarFailure( expectGetRegistrarFailure(
CLIENT_ID_WITH_CONTACT, CLIENT_ID_WITH_CONTACT,
NO_USER, NO_USER,
@ -292,7 +292,7 @@ public class AuthenticatedRegistrarAccessorTest {
/** Succeed loading registrar if user has access to it. */ /** Succeed loading registrar if user has access to it. */
@Test @Test
public void testGetRegistrarForUser_inContacts_isNotAdmin() throws Exception { void testGetRegistrarForUser_inContacts_isNotAdmin() throws Exception {
expectGetRegistrarSuccess( expectGetRegistrarSuccess(
CLIENT_ID_WITH_CONTACT, CLIENT_ID_WITH_CONTACT,
USER, USER,
@ -302,7 +302,7 @@ public class AuthenticatedRegistrarAccessorTest {
/** Succeed loading registrar if admin with access. */ /** Succeed loading registrar if admin with access. */
@Test @Test
public void testGetRegistrarForUser_inContacts_isAdmin() throws Exception { void testGetRegistrarForUser_inContacts_isAdmin() throws Exception {
expectGetRegistrarSuccess( expectGetRegistrarSuccess(
CLIENT_ID_WITH_CONTACT, CLIENT_ID_WITH_CONTACT,
GAE_ADMIN, GAE_ADMIN,
@ -312,7 +312,7 @@ public class AuthenticatedRegistrarAccessorTest {
/** Succeed loading registrar for admin even if they aren't on the approved contacts list. */ /** Succeed loading registrar for admin even if they aren't on the approved contacts list. */
@Test @Test
public void testGetRegistrarForUser_notInContacts_isAdmin() throws Exception { void testGetRegistrarForUser_notInContacts_isAdmin() throws Exception {
expectGetRegistrarSuccess( expectGetRegistrarSuccess(
REAL_CLIENT_ID_WITHOUT_CONTACT, REAL_CLIENT_ID_WITHOUT_CONTACT,
GAE_ADMIN, GAE_ADMIN,
@ -321,7 +321,7 @@ public class AuthenticatedRegistrarAccessorTest {
} }
@Test @Test
public void testGetRegistrarForUser_registrarIsDisabled_isAdmin() throws Exception { void testGetRegistrarForUser_registrarIsDisabled_isAdmin() throws Exception {
persistResource( persistResource(
Registrar.loadByClientId("NewRegistrar") Registrar.loadByClientId("NewRegistrar")
.get() .get()
@ -337,7 +337,7 @@ public class AuthenticatedRegistrarAccessorTest {
/** Succeed loading non-REAL registrar for admin. */ /** Succeed loading non-REAL registrar for admin. */
@Test @Test
public void testGetRegistrarForUser_notInContacts_isAdmin_notReal() throws Exception { void testGetRegistrarForUser_notInContacts_isAdmin_notReal() throws Exception {
expectGetRegistrarSuccess( expectGetRegistrarSuccess(
OTE_CLIENT_ID_WITHOUT_CONTACT, OTE_CLIENT_ID_WITHOUT_CONTACT,
GAE_ADMIN, GAE_ADMIN,
@ -347,7 +347,7 @@ public class AuthenticatedRegistrarAccessorTest {
/** Fail loading registrar even if admin, if registrar doesn't exist. */ /** Fail loading registrar even if admin, if registrar doesn't exist. */
@Test @Test
public void testGetRegistrarForUser_doesntExist_isAdmin() { void testGetRegistrarForUser_doesntExist_isAdmin() {
expectGetRegistrarFailure( expectGetRegistrarFailure(
"BadClientId", "BadClientId",
GAE_ADMIN, GAE_ADMIN,
@ -382,7 +382,7 @@ public class AuthenticatedRegistrarAccessorTest {
/** guessClientIdForUser returns the first clientId in getAllClientIdWithRoles. */ /** guessClientIdForUser returns the first clientId in getAllClientIdWithRoles. */
@Test @Test
public void testGuessClientIdForUser_hasAccess_returnsFirst() throws Exception { void testGuessClientIdForUser_hasAccess_returnsFirst() throws Exception {
AuthenticatedRegistrarAccessor registrarAccessor = AuthenticatedRegistrarAccessor registrarAccessor =
AuthenticatedRegistrarAccessor.createForTesting( AuthenticatedRegistrarAccessor.createForTesting(
ImmutableSetMultimap.of( ImmutableSetMultimap.of(
@ -395,7 +395,7 @@ public class AuthenticatedRegistrarAccessorTest {
/** If a user doesn't have access to any registrars, guess fails. */ /** If a user doesn't have access to any registrars, guess fails. */
@Test @Test
public void testGuessClientIdForUser_noAccess_fails() { void testGuessClientIdForUser_noAccess_fails() {
AuthenticatedRegistrarAccessor registrarAccessor = AuthenticatedRegistrarAccessor registrarAccessor =
AuthenticatedRegistrarAccessor.createForTesting(ImmutableSetMultimap.of()); AuthenticatedRegistrarAccessor.createForTesting(ImmutableSetMultimap.of());
@ -405,7 +405,7 @@ public class AuthenticatedRegistrarAccessorTest {
} }
@Test @Test
public void testNullness() { void testNullness() {
new NullPointerTester() new NullPointerTester()
.setDefault(HttpServletRequest.class, req) .setDefault(HttpServletRequest.class, req)
.setDefault(HttpServletResponse.class, rsp) .setDefault(HttpServletResponse.class, rsp)

View file

@ -28,23 +28,22 @@ import google.registry.security.XsrfTokenManager;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock; import google.registry.testing.FakeClock;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runners.JUnit4;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit; import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.MockitoRule; import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
@RunWith(JUnit4.class) /** Unit tests for {@link LegacyAuthenticationMechanism}. */
public final class LegacyAuthenticationMechanismTest { @ExtendWith(MockitoExtension.class)
final class LegacyAuthenticationMechanismTest {
@Rule @RegisterExtension
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build(); final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@Mock private UserService userService; @Mock private UserService userService;
@Mock private HttpServletRequest req; @Mock private HttpServletRequest req;
@ -54,8 +53,8 @@ public final class LegacyAuthenticationMechanismTest {
private LegacyAuthenticationMechanism legacyAuthenticationMechanism; private LegacyAuthenticationMechanism legacyAuthenticationMechanism;
private String goodToken; private String goodToken;
@Before @BeforeEach
public void setUp() { void beforeEach() {
xsrfTokenManager = new XsrfTokenManager(clock, userService); xsrfTokenManager = new XsrfTokenManager(clock, userService);
legacyAuthenticationMechanism = legacyAuthenticationMechanism =
new LegacyAuthenticationMechanism(userService, xsrfTokenManager); new LegacyAuthenticationMechanism(userService, xsrfTokenManager);
@ -64,8 +63,8 @@ public final class LegacyAuthenticationMechanismTest {
goodToken = xsrfTokenManager.generateToken("email@example.com"); goodToken = xsrfTokenManager.generateToken("email@example.com");
} }
@After @AfterEach
public void tearDown() { void afterEach() {
// Make sure we didn't use getParameter or getInputStream or any of the other "with side // Make sure we didn't use getParameter or getInputStream or any of the other "with side
// effects" getters unexpectedly. But allow "no side effect" getters. // effects" getters unexpectedly. But allow "no side effect" getters.
// //
@ -83,14 +82,15 @@ public final class LegacyAuthenticationMechanismTest {
} }
@Test @Test
public void testAuthenticate_notLoggedIn() { @MockitoSettings(strictness = Strictness.LENIENT)
void testAuthenticate_notLoggedIn() {
when(userService.isUserLoggedIn()).thenReturn(false); when(userService.isUserLoggedIn()).thenReturn(false);
assertThat(legacyAuthenticationMechanism.authenticate(req).authLevel()) assertThat(legacyAuthenticationMechanism.authenticate(req).authLevel())
.isEqualTo(AuthLevel.NONE); .isEqualTo(AuthLevel.NONE);
} }
@Test @Test
public void testAuthenticate_loggedInSafeMethod_get() { void testAuthenticate_loggedInSafeMethod_get() {
when(userService.isUserLoggedIn()).thenReturn(true); when(userService.isUserLoggedIn()).thenReturn(true);
when(req.getMethod()).thenReturn("GET"); when(req.getMethod()).thenReturn("GET");
assertThat(legacyAuthenticationMechanism.authenticate(req).authLevel()) assertThat(legacyAuthenticationMechanism.authenticate(req).authLevel())
@ -98,7 +98,7 @@ public final class LegacyAuthenticationMechanismTest {
} }
@Test @Test
public void testAuthenticate_loggedInSafeMethod_head() { void testAuthenticate_loggedInSafeMethod_head() {
when(userService.isUserLoggedIn()).thenReturn(true); when(userService.isUserLoggedIn()).thenReturn(true);
when(req.getMethod()).thenReturn("HEAD"); when(req.getMethod()).thenReturn("HEAD");
assertThat(legacyAuthenticationMechanism.authenticate(req).authLevel()) assertThat(legacyAuthenticationMechanism.authenticate(req).authLevel())
@ -106,7 +106,8 @@ public final class LegacyAuthenticationMechanismTest {
} }
@Test @Test
public void testAuthenticate_loggedInUnsafeMethod_post_noXsrfToken() { @MockitoSettings(strictness = Strictness.LENIENT)
void testAuthenticate_loggedInUnsafeMethod_post_noXsrfToken() {
when(userService.isUserLoggedIn()).thenReturn(true); when(userService.isUserLoggedIn()).thenReturn(true);
when(req.getMethod()).thenReturn("POST"); when(req.getMethod()).thenReturn("POST");
assertThat(legacyAuthenticationMechanism.authenticate(req).authLevel()) assertThat(legacyAuthenticationMechanism.authenticate(req).authLevel())
@ -118,7 +119,7 @@ public final class LegacyAuthenticationMechanismTest {
} }
@Test @Test
public void testAuthenticate_loggedInUnsafeMethod_post_goodTokenInHeader() { void testAuthenticate_loggedInUnsafeMethod_post_goodTokenInHeader() {
when(userService.isUserLoggedIn()).thenReturn(true); when(userService.isUserLoggedIn()).thenReturn(true);
when(req.getMethod()).thenReturn("POST"); when(req.getMethod()).thenReturn("POST");
when(req.getHeader("X-CSRF-Token")).thenReturn(goodToken); when(req.getHeader("X-CSRF-Token")).thenReturn(goodToken);
@ -131,7 +132,8 @@ public final class LegacyAuthenticationMechanismTest {
} }
@Test @Test
public void testAuthenticate_loggedInUnsafeMethod_post_badTokenInHeader() { @MockitoSettings(strictness = Strictness.LENIENT)
void testAuthenticate_loggedInUnsafeMethod_post_badTokenInHeader() {
when(userService.isUserLoggedIn()).thenReturn(true); when(userService.isUserLoggedIn()).thenReturn(true);
when(req.getMethod()).thenReturn("POST"); when(req.getMethod()).thenReturn("POST");
when(req.getHeader("X-CSRF-Token")).thenReturn("bad"); when(req.getHeader("X-CSRF-Token")).thenReturn("bad");
@ -144,7 +146,7 @@ public final class LegacyAuthenticationMechanismTest {
} }
@Test @Test
public void testAuthenticate_loggedInUnsafeMethod_post_goodTokenInParam() { void testAuthenticate_loggedInUnsafeMethod_post_goodTokenInParam() {
when(userService.isUserLoggedIn()).thenReturn(true); when(userService.isUserLoggedIn()).thenReturn(true);
when(req.getMethod()).thenReturn("POST"); when(req.getMethod()).thenReturn("POST");
when(req.getParameter("xsrfToken")).thenReturn(goodToken); when(req.getParameter("xsrfToken")).thenReturn(goodToken);
@ -157,7 +159,8 @@ public final class LegacyAuthenticationMechanismTest {
} }
@Test @Test
public void testAuthenticate_loggedInUnsafeMethod_post_badTokenInParam() { @MockitoSettings(strictness = Strictness.LENIENT)
void testAuthenticate_loggedInUnsafeMethod_post_badTokenInParam() {
when(userService.isUserLoggedIn()).thenReturn(true); when(userService.isUserLoggedIn()).thenReturn(true);
when(req.getMethod()).thenReturn("POST"); when(req.getMethod()).thenReturn("POST");
when(req.getParameter("xsrfToken")).thenReturn("bad"); when(req.getParameter("xsrfToken")).thenReturn("bad");

View file

@ -36,18 +36,15 @@ import google.registry.testing.FakeOAuthService;
import google.registry.testing.FakeUserService; import google.registry.testing.FakeUserService;
import java.util.Optional; import java.util.Optional;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RequestAuthenticator}. */ /** Unit tests for {@link RequestAuthenticator}. */
@RunWith(JUnit4.class) class RequestAuthenticatorTest {
public class RequestAuthenticatorTest {
@RegisterExtension final AppEngineRule appEngine = AppEngineRule.builder().build();
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder().build();
private static final AuthSettings AUTH_NONE = AuthSettings.create( private static final AuthSettings AUTH_NONE = AuthSettings.create(
ImmutableList.of(AuthMethod.INTERNAL), ImmutableList.of(AuthMethod.INTERNAL),
AuthLevel.NONE, AuthLevel.NONE,
@ -112,8 +109,8 @@ public class RequestAuthenticatorTest {
"test-client-id", "test-client-id",
ImmutableList.of("test-scope1", "test-scope2", "nontest-scope")); ImmutableList.of("test-scope1", "test-scope2", "nontest-scope"));
@Before @BeforeEach
public void before() { void beforeEach() {
when(req.getMethod()).thenReturn("POST"); when(req.getMethod()).thenReturn("POST");
} }
@ -135,7 +132,7 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testNoAuthNeeded_noneFound() { void testNoAuthNeeded_noneFound() {
Optional<AuthResult> authResult = runTest(mockUserService, AUTH_NONE); Optional<AuthResult> authResult = runTest(mockUserService, AUTH_NONE);
verifyNoInteractions(mockUserService); verifyNoInteractions(mockUserService);
@ -144,7 +141,7 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testNoAuthNeeded_internalFound() { void testNoAuthNeeded_internalFound() {
when(req.getHeader("X-AppEngine-QueueName")).thenReturn("__cron"); when(req.getHeader("X-AppEngine-QueueName")).thenReturn("__cron");
Optional<AuthResult> authResult = runTest(mockUserService, AUTH_NONE); Optional<AuthResult> authResult = runTest(mockUserService, AUTH_NONE);
@ -156,7 +153,7 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testInternalAuth_notInvokedInternally() { void testInternalAuth_notInvokedInternally() {
Optional<AuthResult> authResult = runTest(mockUserService, AUTH_INTERNAL_OR_ADMIN); Optional<AuthResult> authResult = runTest(mockUserService, AUTH_INTERNAL_OR_ADMIN);
verifyNoInteractions(mockUserService); verifyNoInteractions(mockUserService);
@ -164,7 +161,7 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testInternalAuth_success() { void testInternalAuth_success() {
when(req.getHeader("X-AppEngine-QueueName")).thenReturn("__cron"); when(req.getHeader("X-AppEngine-QueueName")).thenReturn("__cron");
Optional<AuthResult> authResult = runTest(mockUserService, AUTH_INTERNAL_OR_ADMIN); Optional<AuthResult> authResult = runTest(mockUserService, AUTH_INTERNAL_OR_ADMIN);
@ -176,14 +173,14 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testAnyUserAnyMethod_notLoggedIn() { void testAnyUserAnyMethod_notLoggedIn() {
Optional<AuthResult> authResult = runTest(fakeUserService, AUTH_ANY_USER_ANY_METHOD); Optional<AuthResult> authResult = runTest(fakeUserService, AUTH_ANY_USER_ANY_METHOD);
assertThat(authResult).isEmpty(); assertThat(authResult).isEmpty();
} }
@Test @Test
public void testAnyUserAnyMethod_xsrfFailure() { void testAnyUserAnyMethod_xsrfFailure() {
fakeUserService.setUser(testUser, false); fakeUserService.setUser(testUser, false);
Optional<AuthResult> authResult = runTest(fakeUserService, AUTH_ANY_USER_ANY_METHOD); Optional<AuthResult> authResult = runTest(fakeUserService, AUTH_ANY_USER_ANY_METHOD);
@ -192,7 +189,7 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testAnyUserAnyMethod_success() { void testAnyUserAnyMethod_success() {
fakeUserService.setUser(testUser, false /* isAdmin */); fakeUserService.setUser(testUser, false /* isAdmin */);
when(req.getHeader(XsrfTokenManager.X_CSRF_TOKEN)) when(req.getHeader(XsrfTokenManager.X_CSRF_TOKEN))
.thenReturn(xsrfTokenManager.generateToken(testUser.getEmail())); .thenReturn(xsrfTokenManager.generateToken(testUser.getEmail()));
@ -208,7 +205,7 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testAnyUserAnyMethod_xsrfNotRequiredForGet() { void testAnyUserAnyMethod_xsrfNotRequiredForGet() {
fakeUserService.setUser(testUser, false); fakeUserService.setUser(testUser, false);
when(req.getMethod()).thenReturn("GET"); when(req.getMethod()).thenReturn("GET");
@ -222,14 +219,14 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testAdminUserAnyMethod_notLoggedIn() { void testAdminUserAnyMethod_notLoggedIn() {
Optional<AuthResult> authResult = runTest(fakeUserService, AUTH_ADMIN_USER_ANY_METHOD); Optional<AuthResult> authResult = runTest(fakeUserService, AUTH_ADMIN_USER_ANY_METHOD);
assertThat(authResult).isEmpty(); assertThat(authResult).isEmpty();
} }
@Test @Test
public void testAdminUserAnyMethod_notAdminUser() { void testAdminUserAnyMethod_notAdminUser() {
fakeUserService.setUser(testUser, false /* isAdmin */); fakeUserService.setUser(testUser, false /* isAdmin */);
Optional<AuthResult> authResult = runTest(fakeUserService, AUTH_ADMIN_USER_ANY_METHOD); Optional<AuthResult> authResult = runTest(fakeUserService, AUTH_ADMIN_USER_ANY_METHOD);
@ -238,7 +235,7 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testAdminUserAnyMethod_xsrfFailure() { void testAdminUserAnyMethod_xsrfFailure() {
fakeUserService.setUser(testUser, true); fakeUserService.setUser(testUser, true);
Optional<AuthResult> authResult = runTest(fakeUserService, AUTH_ADMIN_USER_ANY_METHOD); Optional<AuthResult> authResult = runTest(fakeUserService, AUTH_ADMIN_USER_ANY_METHOD);
@ -247,7 +244,7 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testAdminUserAnyMethod_success() { void testAdminUserAnyMethod_success() {
fakeUserService.setUser(testUser, true /* isAdmin */); fakeUserService.setUser(testUser, true /* isAdmin */);
when(req.getHeader(XsrfTokenManager.X_CSRF_TOKEN)) when(req.getHeader(XsrfTokenManager.X_CSRF_TOKEN))
.thenReturn(xsrfTokenManager.generateToken(testUser.getEmail())); .thenReturn(xsrfTokenManager.generateToken(testUser.getEmail()));
@ -263,7 +260,7 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testOAuth_success() { void testOAuth_success() {
fakeOAuthService.setUser(testUser); fakeOAuthService.setUser(testUser);
fakeOAuthService.setOAuthEnabled(true); fakeOAuthService.setOAuthEnabled(true);
when(req.getHeader(AUTHORIZATION)).thenReturn("Bearer TOKEN"); when(req.getHeader(AUTHORIZATION)).thenReturn("Bearer TOKEN");
@ -285,7 +282,7 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testOAuthAdmin_success() { void testOAuthAdmin_success() {
fakeOAuthService.setUser(testUser); fakeOAuthService.setUser(testUser);
fakeOAuthService.setUserAdmin(true); fakeOAuthService.setUserAdmin(true);
fakeOAuthService.setOAuthEnabled(true); fakeOAuthService.setOAuthEnabled(true);
@ -308,7 +305,7 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testOAuthMissingAuthenticationToken_failure() { void testOAuthMissingAuthenticationToken_failure() {
fakeOAuthService.setUser(testUser); fakeOAuthService.setUser(testUser);
fakeOAuthService.setOAuthEnabled(true); fakeOAuthService.setOAuthEnabled(true);
@ -318,7 +315,7 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testOAuthClientIdMismatch_failure() { void testOAuthClientIdMismatch_failure() {
fakeOAuthService.setUser(testUser); fakeOAuthService.setUser(testUser);
fakeOAuthService.setOAuthEnabled(true); fakeOAuthService.setOAuthEnabled(true);
fakeOAuthService.setClientId("wrong-client-id"); fakeOAuthService.setClientId("wrong-client-id");
@ -330,7 +327,7 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testOAuthNoScopes_failure() { void testOAuthNoScopes_failure() {
fakeOAuthService.setUser(testUser); fakeOAuthService.setUser(testUser);
fakeOAuthService.setOAuthEnabled(true); fakeOAuthService.setOAuthEnabled(true);
fakeOAuthService.setAuthorizedScopes(); fakeOAuthService.setAuthorizedScopes();
@ -342,7 +339,7 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testOAuthMissingScope_failure() { void testOAuthMissingScope_failure() {
fakeOAuthService.setUser(testUser); fakeOAuthService.setUser(testUser);
fakeOAuthService.setOAuthEnabled(true); fakeOAuthService.setOAuthEnabled(true);
fakeOAuthService.setAuthorizedScopes("test-scope1", "test-scope3"); fakeOAuthService.setAuthorizedScopes("test-scope1", "test-scope3");
@ -354,7 +351,7 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testOAuthExtraScope_success() { void testOAuthExtraScope_success() {
fakeOAuthService.setUser(testUser); fakeOAuthService.setUser(testUser);
fakeOAuthService.setOAuthEnabled(true); fakeOAuthService.setOAuthEnabled(true);
fakeOAuthService.setAuthorizedScopes("test-scope1", "test-scope2", "test-scope3"); fakeOAuthService.setAuthorizedScopes("test-scope1", "test-scope2", "test-scope3");
@ -377,7 +374,7 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testAnyUserNoLegacy_failureWithLegacyUser() { void testAnyUserNoLegacy_failureWithLegacyUser() {
fakeUserService.setUser(testUser, false /* isAdmin */); fakeUserService.setUser(testUser, false /* isAdmin */);
Optional<AuthResult> authResult = runTest(fakeUserService, AUTH_ANY_USER_NO_LEGACY); Optional<AuthResult> authResult = runTest(fakeUserService, AUTH_ANY_USER_NO_LEGACY);
@ -386,7 +383,7 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testCheckAuthConfig_NoMethods_failure() { void testCheckAuthConfig_NoMethods_failure() {
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
@ -395,7 +392,7 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testCheckAuthConfig_WrongMethodOrdering_failure() { void testCheckAuthConfig_WrongMethodOrdering_failure() {
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
@ -406,7 +403,7 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testCheckAuthConfig_DuplicateMethods_failure() { void testCheckAuthConfig_DuplicateMethods_failure() {
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
@ -417,7 +414,7 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testCheckAuthConfig_InternalWithUser_failure() { void testCheckAuthConfig_InternalWithUser_failure() {
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
@ -428,7 +425,7 @@ public class RequestAuthenticatorTest {
} }
@Test @Test
public void testCheckAuthConfig_WronglyIgnoringUser_failure() { void testCheckAuthConfig_WronglyIgnoringUser_failure() {
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,

View file

@ -60,11 +60,10 @@ import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
public final class ConsoleRegistrarCreatorActionTest { final class ConsoleRegistrarCreatorActionTest {
@RegisterExtension @RegisterExtension
public final AppEngineRule appEngineRule = final AppEngineRule appEngineRule = AppEngineRule.builder().withDatastoreAndCloudSql().build();
AppEngineRule.builder().withDatastoreAndCloudSql().build();
@RegisterExtension @RegisterExtension
@Order(value = Integer.MAX_VALUE) @Order(value = Integer.MAX_VALUE)