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

View file

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

View file

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

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

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

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

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.ConfigModule.provideReservedTermsExportDisclaimer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
@RunWith(JUnit4.class)
public class RegistryConfigTest {
/** Unit tests for {@link RegistryConfig}. */
class RegistryConfigTest {
@Test
public void test_reservedTermsExportDisclaimer_isPrependedWithOctothorpes() {
void test_reservedTermsExportDisclaimer_isPrependedWithOctothorpes() {
assertThat(provideReservedTermsExportDisclaimer(CONFIG_SETTINGS.get()))
.isEqualTo("# Disclaimer line 1.\n" + "# Line 2 is this 1.");
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -49,16 +49,12 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import google.registry.groups.GroupsConnection.Role;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link DirectoryGroupsConnection}. */
class DirectoryGroupsConnectionTest {
/**
* Unit tests for {@link DirectoryGroupsConnection}.
*/
@RunWith(JUnit4.class)
public class DirectoryGroupsConnectionTest {
private final Directory directory = mock(Directory.class);
private final Groupssettings groupsSettings = mock(Groupssettings.class);
private final Directory.Members members = mock(Directory.Members.class);
@ -75,8 +71,8 @@ public class DirectoryGroupsConnectionTest {
private DirectoryGroupsConnection connection;
private Member expectedOwner = new Member();
@Before
public void init() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
when(directory.members()).thenReturn(members);
when(members.insert(anyString(), any(Member.class))).thenReturn(membersInsert);
when(members.get(anyString(), anyString())).thenReturn(membersGet);
@ -94,12 +90,12 @@ public class DirectoryGroupsConnectionTest {
}
@Test
public void test_addMemberToGroup_succeeds() throws Exception {
void test_addMemberToGroup_succeeds() throws Exception {
runAddMemberTest();
}
@Test
public void test_addMemberToGroup_isIdempotent_whenMemberAlreadyExists() throws Exception {
void test_addMemberToGroup_isIdempotent_whenMemberAlreadyExists() throws Exception {
Member expected = runAddMemberTest();
when(membersInsert.execute())
.thenThrow(makeResponseException(SC_CONFLICT, "Member already exists."));
@ -109,14 +105,14 @@ public class DirectoryGroupsConnectionTest {
}
@Test
public void test_addMemberToGroup_handlesExceptionThrownByDirectoryService() throws Exception {
void test_addMemberToGroup_handlesExceptionThrownByDirectoryService() throws Exception {
when(membersInsert.execute()).thenThrow(
makeResponseException(SC_INTERNAL_SERVER_ERROR, "Could not contact Directory server."));
assertThrows(GoogleJsonResponseException.class, this::runAddMemberTest);
}
@Test
public void test_addMemberToGroup_handlesMemberKeyNotFoundException() throws Exception {
void test_addMemberToGroup_handlesMemberKeyNotFoundException() throws Exception {
when(membersInsert.execute()).thenThrow(
makeResponseException(SC_NOT_FOUND, "Resource Not Found: memberKey"));
RuntimeException thrown =
@ -131,7 +127,7 @@ public class DirectoryGroupsConnectionTest {
}
@Test
public void test_addMemberToGroup_createsGroupWhenNonexistent() throws Exception {
void test_addMemberToGroup_createsGroupWhenNonexistent() throws Exception {
Member expected = new Member();
expected.setEmail("tim@example.com");
expected.setRole("MEMBER");
@ -157,12 +153,12 @@ public class DirectoryGroupsConnectionTest {
}
@Test
public void test_createGroup_succeeds() throws Exception {
void test_createGroup_succeeds() throws Exception {
runCreateGroupTest();
}
@Test
public void test_createGroup_isIdempotent_whenGroupAlreadyExists() throws Exception {
void test_createGroup_isIdempotent_whenGroupAlreadyExists() throws Exception {
Group expected = runCreateGroupTest();
when(groupsInsert.execute())
.thenThrow(makeResponseException(SC_CONFLICT, "Entity already exists."));
@ -173,14 +169,14 @@ public class DirectoryGroupsConnectionTest {
}
@Test
public void test_createGroup_handlesExceptionThrownByDirectoryService() throws Exception {
void test_createGroup_handlesExceptionThrownByDirectoryService() throws Exception {
when(groupsInsert.execute()).thenThrow(
makeResponseException(SC_INTERNAL_SERVER_ERROR, "Could not contact Directory server."));
assertThrows(GoogleJsonResponseException.class, this::runCreateGroupTest);
}
@Test
public void test_getMembersOfGroup_succeeds() throws Exception {
void test_getMembersOfGroup_succeeds() throws Exception {
Member member1 = new Member();
member1.setEmail("john@example.com");
Member member2 = new Member();
@ -208,7 +204,7 @@ public class DirectoryGroupsConnectionTest {
}
@Test
public void test_getMembersOfNonexistentGroup_returnsEmptySet() throws Exception {
void test_getMembersOfNonexistentGroup_returnsEmptySet() throws Exception {
when(members.list("nonexistent_group@fake.notreal")).thenReturn(membersList);
when(membersList.setRoles("MEMBER")).thenReturn(membersList);
when(membersList.execute())
@ -217,7 +213,7 @@ public class DirectoryGroupsConnectionTest {
}
@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(membersGet.execute()).thenReturn(new Member());
assertThat(connection.isMemberOfGroup("user@example.com", "support@domain-registry.example"))
@ -225,7 +221,7 @@ public class DirectoryGroupsConnectionTest {
}
@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"))
.thenThrow(makeResponseException(0, "Resource Not Found: memberKey"));
when(membersGet.execute()).thenReturn(new Member());
@ -234,7 +230,7 @@ public class DirectoryGroupsConnectionTest {
}
@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"))
.thenThrow(makeResponseException(0, "Missing required field: memberKey"));
when(membersGet.execute()).thenReturn(new Member());
@ -243,7 +239,7 @@ public class DirectoryGroupsConnectionTest {
}
@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"))
.thenThrow(makeResponseException(0, "some error"));
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.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link ComparatorKeyring}. */
@RunWith(JUnit4.class)
public class ComparatorKeyringTest {
class ComparatorKeyringTest {
private static final String PUBLIC_KEY_FINGERPRINT = "fingerprint";
private static final String PUBLIC_KEY_TO_STRING =
@ -79,18 +76,18 @@ public class ComparatorKeyringTest {
private final TestLogHandler testLogHandler = new TestLogHandler();
@Before
public void setUp() {
@BeforeEach
void beforeEach() {
LoggerConfig.getConfig(ComparatorKeyring.class).addHandler(testLogHandler);
}
@After
public void tearDown() {
@AfterEach
void afterEach() {
LoggerConfig.getConfig(ComparatorKeyring.class).removeHandler(testLogHandler);
}
@Test
public void testPublicKeyToString() throws Exception {
void testPublicKeyToString() throws Exception {
assertThat(
ComparatorKeyring.stringify(
mockPublicKey(false, false)))
@ -98,7 +95,7 @@ public class ComparatorKeyringTest {
}
@Test
public void testPublicKeyEquals() throws Exception {
void testPublicKeyEquals() throws Exception {
assertThat(
ComparatorKeyring.compare(
mockPublicKey(false, false),
@ -107,7 +104,7 @@ public class ComparatorKeyringTest {
}
@Test
public void testPublicKeyDifferFingerprint_notEqual() throws Exception {
void testPublicKeyDifferFingerprint_notEqual() throws Exception {
assertThat(
ComparatorKeyring.compare(
mockPublicKey(false, false),
@ -116,7 +113,7 @@ public class ComparatorKeyringTest {
}
@Test
public void testPublicKeyDifferEncoded_notEqual() throws Exception {
void testPublicKeyDifferEncoded_notEqual() throws Exception {
assertThat(
ComparatorKeyring.compare(
mockPublicKey(false, false),
@ -125,7 +122,7 @@ public class ComparatorKeyringTest {
}
@Test
public void testPrivateKeyToString() throws Exception {
void testPrivateKeyToString() throws Exception {
assertThat(
ComparatorKeyring.stringify(
mockPrivateKey(false, false, false, false)))
@ -133,7 +130,7 @@ public class ComparatorKeyringTest {
}
@Test
public void testPrivateKeyEquals() throws Exception {
void testPrivateKeyEquals() throws Exception {
assertThat(
ComparatorKeyring.compare(
mockPrivateKey(false, false, false, false),
@ -142,7 +139,7 @@ public class ComparatorKeyringTest {
}
@Test
public void testPrivateKeyDifferId_notEquals() throws Exception {
void testPrivateKeyDifferId_notEquals() throws Exception {
assertThat(
ComparatorKeyring.compare(
mockPrivateKey(false, false, false, false),
@ -151,7 +148,7 @@ public class ComparatorKeyringTest {
}
@Test
public void testPrivateKeyDifferBcpgFormat_notEquals() throws Exception {
void testPrivateKeyDifferBcpgFormat_notEquals() throws Exception {
assertThat(
ComparatorKeyring.compare(
mockPrivateKey(false, false, false, false),
@ -160,7 +157,7 @@ public class ComparatorKeyringTest {
}
@Test
public void testPrivateKeyDifferBcpgEncoding_notEquals() throws Exception {
void testPrivateKeyDifferBcpgEncoding_notEquals() throws Exception {
assertThat(
ComparatorKeyring.compare(
mockPrivateKey(false, false, false, false),
@ -169,7 +166,7 @@ public class ComparatorKeyringTest {
}
@Test
public void testPrivateKeyDifferPublicKeyEncoding_notEquals() throws Exception {
void testPrivateKeyDifferPublicKeyEncoding_notEquals() throws Exception {
assertThat(
ComparatorKeyring.compare(
mockPrivateKey(false, false, false, false),
@ -178,7 +175,7 @@ public class ComparatorKeyringTest {
}
@Test
public void testKeyPairToString() throws Exception {
void testKeyPairToString() throws Exception {
assertThat(
ComparatorKeyring.stringify(
new PGPKeyPair(
@ -188,7 +185,7 @@ public class ComparatorKeyringTest {
}
@Test
public void testKeyPairEquals() throws Exception {
void testKeyPairEquals() throws Exception {
assertThat(
ComparatorKeyring.compare(
new PGPKeyPair(
@ -201,7 +198,7 @@ public class ComparatorKeyringTest {
}
@Test
public void testKeyPairDifferPublicKey_notEqual() throws Exception {
void testKeyPairDifferPublicKey_notEqual() throws Exception {
assertThat(
ComparatorKeyring.compare(
new PGPKeyPair(
@ -214,7 +211,7 @@ public class ComparatorKeyringTest {
}
@Test
public void testKeyPairDifferPrivateKey_notEqual() throws Exception {
void testKeyPairDifferPrivateKey_notEqual() throws Exception {
assertThat(
ComparatorKeyring.compare(
new PGPKeyPair(
@ -232,7 +229,7 @@ public class ComparatorKeyringTest {
// We will fully test a single method just to make sure everything is "connected" correctly.
@Test
public void testRdeSigningKey_actualThrows() throws Exception {
void testRdeSigningKey_actualThrows() throws Exception {
Keyring actualKeyring = mock(Keyring.class);
Keyring secondKeyring = mock(Keyring.class);
PGPKeyPair keyPair =
@ -252,7 +249,7 @@ public class ComparatorKeyringTest {
}
@Test
public void testRdeSigningKey_secondThrows() throws Exception {
void testRdeSigningKey_secondThrows() throws Exception {
Keyring actualKeyring = mock(Keyring.class);
Keyring secondKeyring = mock(Keyring.class);
PGPKeyPair keyPair =
@ -272,7 +269,7 @@ public class ComparatorKeyringTest {
}
@Test
public void testRdeSigningKey_bothThrow() {
void testRdeSigningKey_bothThrow() {
Keyring actualKeyring = mock(Keyring.class);
Keyring secondKeyring = mock(Keyring.class);
when(actualKeyring.getRdeSigningKey()).thenThrow(new KeyringException("message"));
@ -285,7 +282,7 @@ public class ComparatorKeyringTest {
}
@Test
public void testRdeSigningKey_same() throws Exception {
void testRdeSigningKey_same() throws Exception {
Keyring actualKeyring = mock(Keyring.class);
Keyring secondKeyring = mock(Keyring.class);
PGPKeyPair keyPair =
@ -306,7 +303,7 @@ public class ComparatorKeyringTest {
}
@Test
public void testRdeSigningKey_different() throws Exception {
void testRdeSigningKey_different() throws Exception {
Keyring actualKeyring = mock(Keyring.class);
Keyring secondKeyring = mock(Keyring.class);
PGPKeyPair keyPair =

View file

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

View file

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

View file

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

View file

@ -44,19 +44,16 @@ import java.io.ObjectOutputStream;
import java.util.HashSet;
import java.util.NoSuchElementException;
import java.util.Set;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Tests {@link EppResourceInputs} */
@RunWith(JUnit4.class)
public class EppResourceInputsTest {
class EppResourceInputsTest {
private static final double EPSILON = 0.0001;
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@RegisterExtension
final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@SuppressWarnings("unchecked")
private <T> T serializeAndDeserialize(T obj) throws Exception {
@ -71,12 +68,12 @@ public class EppResourceInputsTest {
}
@Test
public void testSuccess_keyInputType_polymorphicBaseType() {
void testSuccess_keyInputType_polymorphicBaseType() {
createKeyInput(EppResource.class);
}
@Test
public void testFailure_keyInputType_noInheritanceBetweenTypes_eppResource() {
void testFailure_keyInputType_noInheritanceBetweenTypes_eppResource() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@ -85,7 +82,7 @@ public class EppResourceInputsTest {
}
@Test
public void testFailure_entityInputType_noInheritanceBetweenTypes_eppResource() {
void testFailure_entityInputType_noInheritanceBetweenTypes_eppResource() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@ -94,7 +91,7 @@ public class EppResourceInputsTest {
}
@Test
public void testFailure_entityInputType_noInheritanceBetweenTypes_subclasses() {
void testFailure_entityInputType_noInheritanceBetweenTypes_subclasses() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@ -103,13 +100,13 @@ public class EppResourceInputsTest {
}
@Test
public void testReaderCountMatchesBucketCount() throws Exception {
void testReaderCountMatchesBucketCount() throws Exception {
assertThat(createKeyInput(DomainBase.class).createReaders()).hasSize(3);
assertThat(createEntityInput(DomainBase.class).createReaders()).hasSize(3);
}
@Test
public void testKeyInput_oneReaderPerBucket() throws Exception {
void testKeyInput_oneReaderPerBucket() throws Exception {
createTld("tld");
Set<Key<DomainBase>> domains = new HashSet<>();
for (int i = 1; i <= 3; i++) {
@ -132,7 +129,7 @@ public class EppResourceInputsTest {
}
@Test
public void testEntityInput_oneReaderPerBucket() throws Exception {
void testEntityInput_oneReaderPerBucket() throws Exception {
createTld("tld");
Set<DomainBase> domains = new HashSet<>();
for (int i = 1; i <= 3; i++) {
@ -142,8 +139,7 @@ public class EppResourceInputsTest {
persistResource(EppResourceIndex.create(getBucketKey(i), Key.create(domain)));
}
Set<DomainBase> seen = new HashSet<>();
for (InputReader<DomainBase> reader
: createEntityInput(DomainBase.class).createReaders()) {
for (InputReader<DomainBase> reader : createEntityInput(DomainBase.class).createReaders()) {
reader.beginShard();
reader.beginSlice();
seen.add(reader.next());
@ -157,7 +153,7 @@ public class EppResourceInputsTest {
}
@Test
public void testSuccess_keyReader_survivesAcrossSerialization() throws Exception {
void testSuccess_keyReader_survivesAcrossSerialization() throws Exception {
createTld("tld");
DomainBase domainA = persistEppResourceInFirstBucket(newDomainBase("a.tld"));
DomainBase domainB = persistEppResourceInFirstBucket(newDomainBase("b.tld"));
@ -181,15 +177,14 @@ public class EppResourceInputsTest {
}
@Test
public void testSuccess_entityReader_survivesAcrossSerialization() throws Exception {
void testSuccess_entityReader_survivesAcrossSerialization() throws Exception {
createTld("tld");
DomainBase domainA = persistEppResourceInFirstBucket(newDomainBase("a.tld"));
DomainBase domainB = persistEppResourceInFirstBucket(newDomainBase("b.tld"));
// Should be ignored. We'll know if it isn't because the progress counts will be off.
persistActiveContact("contact");
Set<DomainBase> seen = new HashSet<>();
InputReader<DomainBase> reader =
createEntityInput(DomainBase.class).createReaders().get(0);
InputReader<DomainBase> reader = createEntityInput(DomainBase.class).createReaders().get(0);
reader.beginShard();
reader.beginSlice();
assertThat(reader.getProgress()).isWithin(EPSILON).of(0);
@ -208,15 +203,16 @@ public class EppResourceInputsTest {
}
@Test
public void testSuccess_entityReader_filtersOnMultipleTypes() throws Exception {
void testSuccess_entityReader_filtersOnMultipleTypes() throws Exception {
createTld("tld");
DomainBase domain = persistEppResourceInFirstBucket(newDomainBase("a.tld"));
HostResource host = persistEppResourceInFirstBucket(newHostResource("ns1.example.com"));
persistEppResourceInFirstBucket(newContactResource("contact"));
Set<EppResource> seen = new HashSet<>();
InputReader<EppResource> reader =
EppResourceInputs.<EppResource>createEntityInput(
DomainBase.class, HostResource.class).createReaders().get(0);
EppResourceInputs.<EppResource>createEntityInput(DomainBase.class, HostResource.class)
.createReaders()
.get(0);
reader.beginShard();
reader.beginSlice();
assertThat(reader.getProgress()).isWithin(EPSILON).of(0);
@ -229,7 +225,7 @@ public class EppResourceInputsTest {
}
@Test
public void testSuccess_entityReader_noFilteringWhenUsingEppResource() throws Exception {
void testSuccess_entityReader_noFilteringWhenUsingEppResource() throws Exception {
createTld("tld");
ContactResource contact = persistEppResourceInFirstBucket(newContactResource("contact"));
// 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 org.joda.time.DateTime;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link RdeNamingUtils}. */
@RunWith(JUnit4.class)
public class RdeNamingUtilsTest {
class RdeNamingUtilsTest {
@Test
public void testMakeRydeFilename_rdeDeposit() {
void testMakeRydeFilename_rdeDeposit() {
assertThat(makeRydeFilename("numbness", DateTime.parse("1984-12-18TZ"), FULL, 1, 0))
.isEqualTo("numbness_1984-12-18_full_S1_R0");
}
@Test
public void testMakeRydeFilename_brdaDeposit() {
void testMakeRydeFilename_brdaDeposit() {
assertThat(makeRydeFilename("dreary", DateTime.parse("2000-12-18TZ"), THIN, 1, 0))
.isEqualTo("dreary_2000-12-18_thin_S1_R0");
}
@Test
public void testMakeRydeFilename_revisionNumber() {
void testMakeRydeFilename_revisionNumber() {
assertThat(makeRydeFilename("wretched", DateTime.parse("2000-12-18TZ"), THIN, 1, 123))
.isEqualTo("wretched_2000-12-18_thin_S1_R123");
}
@Test
public void testMakeRydeFilename_timestampNotAtTheWitchingHour_throwsIae() {
void testMakeRydeFilename_timestampNotAtTheWitchingHour_throwsIae() {
assertThrows(
IllegalArgumentException.class,
() -> makeRydeFilename("wretched", DateTime.parse("2000-12-18T04:20Z"), THIN, 1, 0));
}
@Test
public void testMakePartialName() {
void testMakePartialName() {
assertThat(makePartialName("unholy", DateTime.parse("2000-12-18TZ"), 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 google.registry.testing.AppEngineRule;
import org.joda.time.DateTime;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link RdeRevision}. */
@RunWith(JUnit4.class)
public class RdeRevisionTest {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@RegisterExtension
final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Test
public void testGetNextRevision_objectDoesntExist_returnsZero() {
assertThat(getNextRevision("torment", DateTime.parse("1984-12-18TZ"), FULL))
.isEqualTo(0);
void testGetNextRevision_objectDoesntExist_returnsZero() {
assertThat(getNextRevision("torment", DateTime.parse("1984-12-18TZ"), FULL)).isEqualTo(0);
}
@Test
public void testGetNextRevision_objectExistsAtZero_returnsOne() {
void testGetNextRevision_objectExistsAtZero_returnsOne() {
save("sorrow", DateTime.parse("1984-12-18TZ"), FULL, 0);
assertThat(getNextRevision("sorrow", DateTime.parse("1984-12-18TZ"), FULL))
.isEqualTo(1);
assertThat(getNextRevision("sorrow", DateTime.parse("1984-12-18TZ"), FULL)).isEqualTo(1);
}
@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(
tm().transact(
() ->
assertThat(getNextRevision("despondency", DateTime.parse("1984-12-18TZ"), FULL))
.isEqualTo(1));
}
@Test
public void testSaveRevision_objectDoesntExist_newRevisionIsOne_throwsVe() {
void testSaveRevision_objectDoesntExist_newRevisionIsOne_throwsVe() {
VerifyException thrown =
assertThrows(
VerifyException.class,
() ->
tm()
.transact(
tm().transact(
() ->
saveRevision("despondency", DateTime.parse("1984-12-18TZ"), FULL, 1)));
assertThat(thrown).hasMessageThat().contains("object missing");
}
@Test
public void testSaveRevision_objectExistsAtZero_newRevisionIsZero_throwsVe() {
void testSaveRevision_objectExistsAtZero_newRevisionIsZero_throwsVe() {
save("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0);
VerifyException thrown =
assertThrows(
VerifyException.class,
() ->
tm()
.transact(
tm().transact(
() -> saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0)));
assertThat(thrown).hasMessageThat().contains("object already created");
}
@Test
public void testSaveRevision_objectExistsAtZero_newRevisionIsOne_nextRevIsTwo() {
void testSaveRevision_objectExistsAtZero_newRevisionIsOne_nextRevIsTwo() {
save("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0);
tm().transact(() -> saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 1));
tm()
.transact(
tm().transact(
() ->
assertThat(getNextRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL))
.isEqualTo(2));
}
@Test
public void testSaveRevision_objectExistsAtZero_newRevisionIsTwo_throwsVe() {
void testSaveRevision_objectExistsAtZero_newRevisionIsTwo_throwsVe() {
save("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0);
VerifyException thrown =
assertThrows(
VerifyException.class,
() ->
tm()
.transact(
tm().transact(
() -> saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 2)));
assertThat(thrown).hasMessageThat().contains("should be at 1 ");
}
@Test
public void testSaveRevision_negativeRevision_throwsIae() {
void testSaveRevision_negativeRevision_throwsIae() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
() ->
tm()
.transact(
tm().transact(
() ->
saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, -1)));
assertThat(thrown).hasMessageThat().contains("Negative revision");
}
@Test
public void testSaveRevision_callerNotInTransaction_throwsIse() {
void testSaveRevision_callerNotInTransaction_throwsIse() {
IllegalStateException thrown =
assertThrows(
IllegalStateException.class,

View file

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

View file

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

View file

@ -24,23 +24,20 @@ import com.google.common.reflect.ClassPath.ResourceInfo;
import google.registry.testing.AppEngineRule;
import java.net.URL;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Presubmit tests for {@link ReservedList} configuration files. */
@RunWith(JUnit4.class)
public class GenruleReservedListTest {
class GenruleReservedListTest {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final String LISTS_DIRECTORY = "google/registry/config/files/reserved/";
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@RegisterExtension
final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Test
public void testParse_allReservedLists() throws Exception {
void testParse_allReservedLists() throws Exception {
ClassPath classpath = ClassPath.from(getClass().getClassLoader());
int numParsed = 0;
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.InjectRule;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link ReservedList}. */
@RunWith(JUnit4.class)
public class ReservedListTest {
class ReservedListTest {
@Rule
public final InjectRule inject = new InjectRule();
@RegisterExtension final InjectRule inject = new InjectRule();
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@RegisterExtension
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
public void before() {
@BeforeEach
void beforeEach() {
inject.setStaticField(Ofy.class, "clock", clock);
createTld("tld");
reservedListChecks.reset();
@ -79,7 +75,7 @@ public class ReservedListTest {
}
@Test
public void testGetReservationTypes_allLabelsAreUnreserved_withNoReservedLists() {
void testGetReservationTypes_allLabelsAreUnreserved_withNoReservedLists() {
assertThat(Registry.get("tld").getReservedLists()).isEmpty();
assertThat(getReservationTypes("doodle", "tld")).isEmpty();
assertThat(getReservationTypes("access", "tld")).isEmpty();
@ -88,13 +84,13 @@ public class ReservedListTest {
}
@Test
public void testZeroReservedLists_doesNotCauseError() {
void testZeroReservedLists_doesNotCauseError() {
assertThat(getReservationTypes("doodle", "tld")).isEmpty();
verifyUnreservedCheckCount(1);
}
@Test
public void testGetReservationTypes_twoLetterCodesAreAvailable() {
void testGetReservationTypes_twoLetterCodesAreAvailable() {
for (String sld : ImmutableList.of("aa", "az", "zz", "91", "1n", "j5")) {
assertThat(getReservationTypes(sld, "tld")).isEmpty();
}
@ -102,7 +98,7 @@ public class ReservedListTest {
}
@Test
public void testGetReservationTypes_singleCharacterDomainsAreAllowed() {
void testGetReservationTypes_singleCharacterDomainsAreAllowed() {
// This isn't quite exhaustive but it's close.
for (char c = 'a'; c <= 'z'; c++) {
assertThat(getReservationTypes("" + c, "tld")).isEmpty();
@ -111,7 +107,7 @@ public class ReservedListTest {
}
@Test
public void testGetReservationTypes_concatsMultipleListsCorrectly() {
void testGetReservationTypes_concatsMultipleListsCorrectly() {
ReservedList rl1 = persistReservedList(
"reserved1",
"lol,FULLY_BLOCKED # yup",
@ -153,7 +149,7 @@ public class ReservedListTest {
}
@Test
public void testGetReservationTypes_returnsAllReservationTypesFromMultipleListsForTheSameLabel() {
void testGetReservationTypes_returnsAllReservationTypesFromMultipleListsForTheSameLabel() {
ReservedList rl1 =
persistReservedList("reserved1", "lol,NAME_COLLISION # yup", "cat,FULLY_BLOCKED");
ReservedList rl2 =
@ -167,9 +163,8 @@ public class ReservedListTest {
assertThat(getReservationTypes("snowcrash", "tld")).containsExactly(FULLY_BLOCKED);
}
@Test
public void testGetReservationTypes_worksAfterReservedListRemovedUsingSet() {
void testGetReservationTypes_worksAfterReservedListRemovedUsingSet() {
ReservedList rl1 = persistReservedList(
"reserved1", "lol,FULLY_BLOCKED", "cat,FULLY_BLOCKED");
ReservedList rl2 = persistReservedList(
@ -202,7 +197,7 @@ public class ReservedListTest {
}
@Test
public void testGetReservationTypes_combinesMultipleLists() {
void testGetReservationTypes_combinesMultipleLists() {
ReservedList rl1 = persistReservedList(
"reserved1", "lol,NAME_COLLISION", "roflcopter,ALLOWED_IN_SUNRISE");
ReservedList rl2 = persistReservedList("reserved2", "lol,FULLY_BLOCKED");
@ -233,7 +228,7 @@ public class ReservedListTest {
}
@Test
public void testSave() {
void testSave() {
ReservedList rl = persistReservedList("tld-reserved", "lol,FULLY_BLOCKED # yup");
createTld("tld");
persistResource(Registry.get("tld").asBuilder().setReservedLists(rl).build());
@ -241,7 +236,7 @@ public class ReservedListTest {
}
@Test
public void testSave_commentsArePersistedCorrectly() {
void testSave_commentsArePersistedCorrectly() {
ReservedList reservedList = persistReservedList(
"reserved",
"trombone,FULLY_BLOCKED # yup",
@ -266,20 +261,20 @@ public class ReservedListTest {
}
@Test
public void testIsInUse_returnsTrueWhenInUse() {
void testIsInUse_returnsTrueWhenInUse() {
ReservedList rl = persistReservedList("reserved", "trombone,FULLY_BLOCKED");
persistResource(Registry.get("tld").asBuilder().setReservedLists(ImmutableSet.of(rl)).build());
assertThat(rl.isInUse()).isTrue();
}
@Test
public void testIsInUse_returnsFalseWhenNotInUse() {
void testIsInUse_returnsFalseWhenNotInUse() {
ReservedList rl = persistReservedList("reserved", "trombone,FULLY_BLOCKED");
assertThat(rl.isInUse()).isFalse();
}
@Test
public void testSetFromInputLines() {
void testSetFromInputLines() {
ReservedList reservedList = persistReservedList("reserved", "trombone,FULLY_BLOCKED");
assertThat(ReservedList.get("reserved").get().getReservedListEntries()).hasSize(1);
reservedList = reservedList.asBuilder()
@ -290,7 +285,7 @@ public class ReservedListTest {
}
@Test
public void testAsBuilderReturnsIdenticalReservedList() {
void testAsBuilderReturnsIdenticalReservedList() {
ReservedList original = persistReservedList("tld-reserved-cloning", "trombone,FULLY_BLOCKED");
ReservedList clone = original.asBuilder().build();
assertThat(clone.getName()).isEqualTo("tld-reserved-cloning");
@ -301,7 +296,7 @@ public class ReservedListTest {
}
@Test
public void testSave_badSyntax() {
void testSave_badSyntax() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
@ -310,13 +305,13 @@ public class ReservedListTest {
}
@Test
public void testSave_badReservationType() {
void testSave_badReservationType() {
assertThrows(
IllegalArgumentException.class, () -> persistReservedList("tld", "lol,FULLY_BLOCKZ # yup"));
}
@Test
public void testParse_cannotIncludeDuplicateLabels() {
void testParse_cannotIncludeDuplicateLabels() {
ReservedList rl = new ReservedList.Builder().setName("blah").build();
IllegalStateException thrown =
assertThrows(
@ -336,7 +331,7 @@ public class ReservedListTest {
}
@Test
public void testValidation_labelMustBeLowercase() {
void testValidation_labelMustBeLowercase() {
Exception e =
assertThrows(
IllegalArgumentException.class,
@ -345,7 +340,7 @@ public class ReservedListTest {
}
@Test
public void testValidation_labelMustBePunyCoded() {
void testValidation_labelMustBePunyCoded() {
Exception e =
assertThrows(
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.RouterDisplayHelper;
import google.registry.testing.GoldenFileTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link BackendRequestComponent}. */
@RunWith(JUnit4.class)
public class BackendRequestComponentTest {
class BackendRequestComponentTest {
@Test
public void testRoutingMap() {
void testRoutingMap() {
GoldenFileTestHelper.assertThatRoutesFromComponent(BackendRequestComponent.class)
.describedAs("backend routing map")
.isEqualToGolden(BackendRequestComponentTest.class, "backend_routing.txt");
}
@Test
public void testRoutingService() {
void testRoutingService() {
assertThat(
RouterDisplayHelper.extractHumanReadableRoutesWithWrongService(
BackendRequestComponent.class, Action.Service.BACKEND))

View file

@ -21,24 +21,21 @@ import static org.mockito.Mockito.when;
import google.registry.testing.AppEngineRule;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link BackendServlet}. */
@RunWith(JUnit4.class)
public class BackendServletTest {
class BackendServletTest {
@Rule
public final AppEngineRule appEngine =
@RegisterExtension
final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withLocalModules().build();
private final HttpServletRequest req = mock(HttpServletRequest.class);
private final HttpServletResponse rsp = mock(HttpServletResponse.class);
@Test
public void testService_unknownPath_returnsNotFound() throws Exception {
void testService_unknownPath_returnsNotFound() throws Exception {
when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/lol");
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.RouterDisplayHelper;
import google.registry.testing.GoldenFileTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link FrontendRequestComponent}. */
@RunWith(JUnit4.class)
public class FrontendRequestComponentTest {
class FrontendRequestComponentTest {
@Test
public void testRoutingMap() {
void testRoutingMap() {
GoldenFileTestHelper.assertThatRoutesFromComponent(FrontendRequestComponent.class)
.describedAs("frontend routing map")
.isEqualToGolden(FrontendRequestComponentTest.class, "frontend_routing.txt");
}
@Test
public void testRoutingService() {
void testRoutingService() {
assertThat(
RouterDisplayHelper.extractHumanReadableRoutesWithWrongService(
FrontendRequestComponent.class, Action.Service.DEFAULT))

View file

@ -21,24 +21,21 @@ import static org.mockito.Mockito.when;
import google.registry.testing.AppEngineRule;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link FrontendServlet}. */
@RunWith(JUnit4.class)
public class FrontendServletTest {
class FrontendServletTest {
@Rule
public final AppEngineRule appEngine =
@RegisterExtension
final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withLocalModules().build();
private final HttpServletRequest req = mock(HttpServletRequest.class);
private final HttpServletResponse rsp = mock(HttpServletResponse.class);
@Test
public void testService_unknownPath_returnNotFound() throws Exception {
void testService_unknownPath_returnNotFound() throws Exception {
when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/lol");
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.RouterDisplayHelper;
import google.registry.testing.GoldenFileTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link PubApiRequestComponent}. */
@RunWith(JUnit4.class)
public class PubApiRequestComponentTest {
class PubApiRequestComponentTest {
@Test
public void testRoutingMap() {
void testRoutingMap() {
GoldenFileTestHelper.assertThatRoutesFromComponent(PubApiRequestComponent.class)
.describedAs("pubapi routing map")
.isEqualToGolden(PubApiRequestComponentTest.class, "pubapi_routing.txt");
}
@Test
public void testRoutingService() {
void testRoutingService() {
assertThat(
RouterDisplayHelper.extractHumanReadableRoutesWithWrongService(
PubApiRequestComponent.class, Action.Service.PUBAPI))

View file

@ -21,24 +21,21 @@ import static org.mockito.Mockito.when;
import google.registry.testing.AppEngineRule;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link PubApiServlet}. */
@RunWith(JUnit4.class)
public class PubApiServletTest {
class PubApiServletTest {
@Rule
public final AppEngineRule appEngine =
@RegisterExtension
final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withLocalModules().build();
private final HttpServletRequest req = mock(HttpServletRequest.class);
private final HttpServletResponse rsp = mock(HttpServletResponse.class);
@Test
public void testService_unknownPath_returnNotFound() throws Exception {
void testService_unknownPath_returnNotFound() throws Exception {
when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/lol");
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.RouterDisplayHelper;
import google.registry.testing.GoldenFileTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link ToolsRequestComponent}. */
@RunWith(JUnit4.class)
public class ToolsRequestComponentTest {
class ToolsRequestComponentTest {
@Test
public void testRoutingMap() {
void testRoutingMap() {
GoldenFileTestHelper.assertThatRoutesFromComponent(ToolsRequestComponent.class)
.describedAs("tools routing map")
.isEqualToGolden(ToolsRequestComponentTest.class, "tools_routing.txt");
}
@Test
public void testRoutingService() {
void testRoutingService() {
assertThat(
RouterDisplayHelper.extractHumanReadableRoutesWithWrongService(
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.HttpServletResponse;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link ToolsServlet}. */
@RunWith(JUnit4.class)
public class ToolsServletTest {
class ToolsServletTest {
private final HttpServletRequest req = mock(HttpServletRequest.class);
private final HttpServletResponse rsp = mock(HttpServletResponse.class);
@Test
public void testService_unknownPath_returnsNotFound() throws Exception {
void testService_unknownPath_returnsNotFound() throws Exception {
when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/lol");
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.testing.FakeClock;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link CheckApiMetric}. */
@RunWith(JUnit4.class)
public class CheckApiMetricTest {
class CheckApiMetricTest {
private static final DateTime START_TIME = DateTime.parse("2000-01-01T00:00:00.0Z");
private final FakeClock clock = new FakeClock(START_TIME);
private CheckApiMetric.Builder metricBuilder;
@Before
public void setup() {
@BeforeEach
void beforeEach() {
metricBuilder = CheckApiMetric.builder(clock);
}
@Test
public void testSuccess_timestampsAreSet() {
void testSuccess_timestampsAreSet() {
clock.advanceOneMilli();
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 google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link EppMetric}. */
@RunWith(JUnit4.class)
public class EppMetricTest {
class EppMetricTest {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@RegisterExtension
final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@Test
public void test_invalidTld_isRecordedAsInvalid() {
void test_invalidTld_isRecordedAsInvalid() {
EppMetric metric =
EppMetric.builderForRequest(new FakeClock())
.setTlds(ImmutableSet.of("notarealtld"))
@ -43,7 +40,7 @@ public class EppMetricTest {
}
@Test
public void test_validTld_isRecorded() {
void test_validTld_isRecorded() {
createTld("example");
EppMetric metric =
EppMetric.builderForRequest(new FakeClock()).setTlds(ImmutableSet.of("example")).build();
@ -51,7 +48,7 @@ public class EppMetricTest {
}
@Test
public void test_multipleTlds_areRecordedAsVarious() {
void test_multipleTlds_areRecordedAsVarious() {
createTlds("foo", "bar");
EppMetric metric =
EppMetric.builderForRequest(new FakeClock())
@ -61,7 +58,7 @@ public class EppMetricTest {
}
@Test
public void test_zeroTlds_areRecordedAsAbsent() {
void test_zeroTlds_areRecordedAsAbsent() {
EppMetric metric =
EppMetric.builderForRequest(new FakeClock()).setTlds(ImmutableSet.of()).build();
assertThat(metric.getTld()).isEmpty();

View file

@ -21,40 +21,42 @@ import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.joda.money.CurrencyUnit;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
/** Unit tests for {@link HibernateSchemaExporter}. */
@RunWith(JUnit4.class)
public class HibernateSchemaExporterTest {
@ClassRule
public static final PostgreSQLContainer database =
@Testcontainers
class HibernateSchemaExporterTest {
@Container
private static final PostgreSQLContainer database =
new PostgreSQLContainer(NomulusPostgreSql.getDockerTag());
private static HibernateSchemaExporter exporter;
@Rule public final TemporaryFolder tempFolder = new TemporaryFolder();
@SuppressWarnings("WeakerAccess")
@TempDir
Path tmpDir;
@BeforeClass
public static void init() {
@BeforeAll
static void beforeAll() {
exporter =
HibernateSchemaExporter.create(
database.getJdbcUrl(), database.getUsername(), database.getPassword());
}
@Test
public void export_succeeds() throws IOException {
File sqlFile = tempFolder.newFile();
exporter.export(ImmutableList.of(TestEntity.class), sqlFile);
void export_succeeds() throws IOException {
File sqlFile = Files.createFile(tmpDir.resolve("tempfile.dat")).toFile();
exporter.export(ImmutableList.of(HibernateSchemaTestEntity.class), sqlFile);
assertThat(Files.readAllBytes(sqlFile.toPath()))
.isEqualTo(
("\n"
@ -67,7 +69,7 @@ public class HibernateSchemaExporterTest {
}
@Entity(name = "TestEntity") // Override entity name to avoid the nested class reference.
private static class TestEntity {
private static class HibernateSchemaTestEntity {
@Id String name;
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.ImmutableSet.toImmutableSet;
import static com.google.common.truth.Truth.assertWithMessage;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.truth.Expect;
import java.util.Collections;
import javax.persistence.AttributeConverter;
import javax.persistence.Entity;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests to verify persistence.xml is valid. */
@RunWith(JUnit4.class)
public class PersistenceXmlTest {
@ClassRule public static final Expect expect = Expect.create();
class PersistenceXmlTest {
@Test
public void verifyClassTags_containOnlyRequiredClasses() {
void verifyClassTags_containOnlyRequiredClasses() {
ImmutableList<Class> managedClassed = PersistenceXmlUtility.getManagedClasses();
ImmutableList<Class> unnecessaryClasses =
@ -51,13 +45,11 @@ public class PersistenceXmlTest {
.filter(clazz -> Collections.frequency(managedClassed, clazz) > 1)
.collect(toImmutableSet());
expect
.withMessage("Found duplicate <class> tags defined in persistence.xml.")
assertWithMessage("Found duplicate <class> tags defined in persistence.xml.")
.that(duplicateClasses)
.isEmpty();
expect
.withMessage(
assertWithMessage(
"Found unnecessary <class> tags defined in persistence.xml. Only entity class and"
+ " implementation of AttributeConverter are required to be added in"
+ " persistence.xml.")

View file

@ -18,25 +18,21 @@ import static com.google.common.truth.Truth.assertThat;
import com.googlecode.objectify.Key;
import google.registry.testing.AppEngineRule;
import google.registry.testing.TestObject;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
@RunWith(JUnit4.class)
public class VKeyTest {
/** Unit tests for {@link VKey}. */
class VKeyTest {
@Rule
public final AppEngineRule appEngineRule =
@RegisterExtension
final AppEngineRule appEngineRule =
AppEngineRule.builder()
.withDatastoreAndCloudSql()
.withOfyTestEntities(TestObject.class)
.build();
public VKeyTest() {}
@Test
public void testOptionalAccessors() {
void testOptionalAccessors() {
VKey<TestObject> key =
VKey.create(TestObject.class, "foo", Key.create(TestObject.create("foo")));
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 org.junit.Assert.assertThrows;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** JUnit test for {@link DummyJpaTransactionManager} */
@RunWith(JUnit4.class)
public class DummyJpaTransactionManagerTest {
class DummyJpaTransactionManagerTest {
@Test
public void throwsExceptionWhenAnyMethodIsInvoked() {
void throwsExceptionWhenAnyMethodIsInvoked() {
assertThrows(UnsupportedOperationException.class, () -> jpaTm().transact(() -> null));
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.LocalDate;
import org.joda.time.YearMonth;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link ReportingModule}. */
@RunWith(JUnit4.class)
public class ReportingModuleTest {
class ReportingModuleTest {
private HttpServletRequest req = mock(HttpServletRequest.class);
private Clock clock;
@Before
public void setUp() {
@BeforeEach
void beforeEach() {
clock = new FakeClock(DateTime.parse("2017-07-01TZ"));
}
@Test
public void testEmptyYearMonthParameter_returnsEmptyYearMonthOptional() {
void testEmptyYearMonthParameter_returnsEmptyYearMonthOptional() {
when(req.getParameter("yearMonth")).thenReturn("");
Truth8.assertThat(ReportingModule.provideYearMonthOptional(req)).isEmpty();
}
@Test
public void testValidYearMonthParameter_returnsThatMonth() {
void testValidYearMonthParameter_returnsThatMonth() {
when(req.getParameter("yearMonth")).thenReturn("2017-05");
Truth8.assertThat(ReportingModule.provideYearMonthOptional(req))
.hasValue(new YearMonth(2017, 5));
}
@Test
public void testInvalidYearMonthParameter_throwsException() {
void testInvalidYearMonthParameter_throwsException() {
when(req.getParameter("yearMonth")).thenReturn("201705");
BadRequestException thrown =
assertThrows(
@ -70,13 +67,13 @@ public class ReportingModuleTest {
}
@Test
public void testEmptyYearMonth_returnsLastMonth() {
void testEmptyYearMonth_returnsLastMonth() {
assertThat(ReportingModule.provideYearMonth(Optional.empty(), new LocalDate(2017, 1, 6)))
.isEqualTo(new YearMonth(2016, 12));
}
@Test
public void testGivenYearMonth_returnsThatMonth() {
void testGivenYearMonth_returnsThatMonth() {
assertThat(
ReportingModule.provideYearMonth(
Optional.of(new YearMonth(2017, 5)), new LocalDate(2017, 7, 6)))
@ -84,20 +81,20 @@ public class ReportingModuleTest {
}
@Test
public void testEmptyDateParameter_returnsEmptyDateOptional() {
void testEmptyDateParameter_returnsEmptyDateOptional() {
when(req.getParameter("date")).thenReturn("");
Truth8.assertThat(ReportingModule.provideDateOptional(req)).isEmpty();
}
@Test
public void testValidDateParameter_returnsThatDate() {
void testValidDateParameter_returnsThatDate() {
when(req.getParameter("date")).thenReturn("2017-05-13");
Truth8.assertThat(ReportingModule.provideDateOptional(req))
.hasValue(new LocalDate(2017, 5, 13));
}
@Test
public void testInvalidDateParameter_throwsException() {
void testInvalidDateParameter_throwsException() {
when(req.getParameter("date")).thenReturn("20170513");
BadRequestException thrown =
assertThrows(BadRequestException.class, () -> ReportingModule.provideDateOptional(req));
@ -107,13 +104,13 @@ public class ReportingModuleTest {
}
@Test
public void testEmptyDate_returnsToday() {
void testEmptyDate_returnsToday() {
when(req.getParameter("date")).thenReturn(null);
assertThat(ReportingModule.provideDate(req, clock)).isEqualTo(new LocalDate(2017, 7, 1));
}
@Test
public void testGivenDate_returnsThatDate() {
void testGivenDate_returnsThatDate() {
when(req.getParameter("date")).thenReturn("2017-07-02");
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.internet.InternetAddress;
import org.joda.time.YearMonth;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
/** Unit tests for {@link google.registry.reporting.billing.BillingEmailUtils}. */
@RunWith(JUnit4.class)
public class BillingEmailUtilsTest {
class BillingEmailUtilsTest {
private SendEmailService emailService;
private BillingEmailUtils emailUtils;
private GcsUtils gcsUtils;
private ArgumentCaptor<EmailMessage> contentCaptor;
@Before
public void setUp() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
emailService = mock(SendEmailService.class);
gcsUtils = mock(GcsUtils.class);
when(gcsUtils.openInputStream(new GcsFilename("test-bucket", "results/REG-INV-2017-10.csv")))
@ -74,7 +71,7 @@ public class BillingEmailUtilsTest {
}
@Test
public void testSuccess_emailOverallInvoice() throws MessagingException {
void testSuccess_emailOverallInvoice() throws MessagingException {
emailUtils.emailOverallInvoice();
verify(emailService).sendEmail(contentCaptor.capture());
@ -98,7 +95,7 @@ public class BillingEmailUtilsTest {
}
@Test
public void testFailure_emailsAlert() throws MessagingException {
void testFailure_emailsAlert() throws MessagingException {
doThrow(new RuntimeException(new MessagingException("expected")))
.doNothing()
.when(emailService)
@ -116,7 +113,7 @@ public class BillingEmailUtilsTest {
}
@Test
public void testSuccess_sendAlertEmail() throws MessagingException {
void testSuccess_sendAlertEmail() throws MessagingException {
emailUtils.sendAlertEmail("Alert!");
verify(emailService).sendEmail(contentCaptor.capture());
validateAlertMessage(contentCaptor.getValue(), "Alert!");

View file

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

View file

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

View file

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

View file

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

View file

@ -19,16 +19,13 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import javax.servlet.http.HttpServletRequest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link google.registry.reporting.icann.IcannReportingModule}. */
@RunWith(JUnit4.class)
public class IcannReportingModuleTest {
class IcannReportingModuleTest {
@Test
public void testProvideReportTypes() {
void testProvideReportTypes() {
HttpServletRequest req = mock(HttpServletRequest.class);
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.TimeUnit;
import org.joda.time.YearMonth;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link google.registry.reporting.icann.IcannReportingStager}. */
@RunWith(JUnit4.class)
public class IcannReportingStagerTest {
class IcannReportingStagerTest {
BigqueryConnection bigquery = mock(BigqueryConnection.class);
private BigqueryConnection bigquery = mock(BigqueryConnection.class);
FakeResponse response = new FakeResponse();
GcsService gcsService = GcsServiceFactory.createGcsService();
YearMonth yearMonth = new YearMonth(2017, 6);
String subdir = "icann/monthly/2017-06";
private GcsService gcsService = GcsServiceFactory.createGcsService();
private YearMonth yearMonth = new YearMonth(2017, 6);
private String subdir = "icann/monthly/2017-06";
@Rule
public final AppEngineRule appEngine =
@RegisterExtension
final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withLocalModules().build();
private IcannReportingStager createStager() {
@ -74,16 +71,17 @@ public class IcannReportingStagerTest {
private void setUpBigquery() {
when(bigquery.query(any(String.class), any(DestinationTable.class))).thenReturn(fakeFuture());
DestinationTable.Builder tableBuilder = new DestinationTable.Builder()
.datasetId("testdataset")
.type(TableType.TABLE)
.name("tablename")
.overwrite(true);
DestinationTable.Builder tableBuilder =
new DestinationTable.Builder()
.datasetId("testdataset")
.type(TableType.TABLE)
.name("tablename")
.overwrite(true);
when(bigquery.buildDestinationTable(any(String.class))).thenReturn(tableBuilder);
}
@Test
public void testRunSuccess_activityReport() throws Exception {
void testRunSuccess_activityReport() throws Exception {
setUpBigquery();
ImmutableTable<Integer, TableFieldSchema, Object> activityReportTable =
new ImmutableTable.Builder<Integer, TableFieldSchema, Object>()
@ -113,7 +111,7 @@ public class IcannReportingStagerTest {
}
@Test
public void testRunSuccess_transactionsReport() throws Exception {
void testRunSuccess_transactionsReport() throws Exception {
setUpBigquery();
/*
The fake table result looks like:
@ -157,7 +155,7 @@ public class IcannReportingStagerTest {
}
@Test
public void testRunSuccess_createAndUploadManifest() throws Exception {
void testRunSuccess_createAndUploadManifest() throws Exception {
IcannReportingStager stager = createStager();
ImmutableList<String> filenames =
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 javax.mail.internet.InternetAddress;
import org.joda.time.YearMonth;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link google.registry.reporting.icann.IcannReportingStagingAction}. */
@RunWith(JUnit4.class)
public class IcannReportingStagingActionTest {
class IcannReportingStagingActionTest {
FakeResponse response = new FakeResponse();
IcannReportingStager stager = mock(IcannReportingStager.class);
YearMonth yearMonth = new YearMonth(2017, 6);
String subdir = "default/dir";
IcannReportingStagingAction action;
private FakeResponse response = new FakeResponse();
private IcannReportingStager stager = mock(IcannReportingStager.class);
private YearMonth yearMonth = new YearMonth(2017, 6);
private String subdir = "default/dir";
private IcannReportingStagingAction action;
@Rule
public final AppEngineRule appEngine =
@RegisterExtension
final AppEngineRule appEngine =
AppEngineRule.builder().withDatastoreAndCloudSql().withLocalModules().withTaskQueue().build();
@Before
public void setUp() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
action = new IcannReportingStagingAction();
action.yearMonth = yearMonth;
action.overrideSubdir = Optional.of(subdir);
@ -84,7 +81,7 @@ public class IcannReportingStagingActionTest {
}
@Test
public void testActivityReportingMode_onlyStagesActivityReports() throws Exception {
void testActivityReportingMode_onlyStagesActivityReports() throws Exception {
action.reportTypes = ImmutableSet.of(ReportType.ACTIVITY);
action.run();
verify(stager).stageReports(yearMonth, subdir, ReportType.ACTIVITY);
@ -100,7 +97,7 @@ public class IcannReportingStagingActionTest {
}
@Test
public void testAbsentReportingMode_stagesBothReports() throws Exception {
void testAbsentReportingMode_stagesBothReports() throws Exception {
action.run();
verify(stager).stageReports(yearMonth, subdir, ReportType.ACTIVITY);
verify(stager).stageReports(yearMonth, subdir, ReportType.TRANSACTIONS);
@ -116,7 +113,7 @@ public class IcannReportingStagingActionTest {
}
@Test
public void testRetryOnBigqueryException() throws Exception {
void testRetryOnBigqueryException() throws Exception {
when(stager.stageReports(yearMonth, subdir, ReportType.TRANSACTIONS))
.thenThrow(new BigqueryJobFailureException("Expected failure", null, null, null))
.thenReturn(ImmutableList.of("c", "d"));
@ -135,7 +132,7 @@ public class IcannReportingStagingActionTest {
}
@Test
public void testEmailEng_onMoreThanRetriableFailure() throws Exception {
void testEmailEng_onMoreThanRetriableFailure() throws Exception {
action.reportTypes = ImmutableSet.of(ReportType.ACTIVITY);
when(stager.stageReports(yearMonth, subdir, ReportType.ACTIVITY))
.thenThrow(new BigqueryJobFailureException("Expected failure", null, null, null));
@ -160,25 +157,22 @@ public class IcannReportingStagingActionTest {
}
@Test
public void testEmptySubDir_returnsDefaultSubdir() {
void testEmptySubDir_returnsDefaultSubdir() {
action.overrideSubdir = Optional.empty();
assertThat(action.getSubdir(new YearMonth(2017, 6))).isEqualTo("icann/monthly/2017-06");
}
@Test
public void testGivenSubdir_returnsManualSubdir() {
void testGivenSubdir_returnsManualSubdir() {
action.overrideSubdir = Optional.of("manual/dir");
assertThat(action.getSubdir(new YearMonth(2017, 6))).isEqualTo("manual/dir");
}
@Test
public void testInvalidSubdir_throwsException() {
void testInvalidSubdir_throwsException() {
action.overrideSubdir = Optional.of("/whoops");
BadRequestException thrown =
assertThrows(
BadRequestException.class,
() ->
action.getSubdir(new YearMonth(2017, 6)));
assertThrows(BadRequestException.class, () -> action.getSubdir(new YearMonth(2017, 6)));
assertThat(thrown)
.hasMessageThat()
.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 javax.mail.internet.InternetAddress;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link google.registry.reporting.icann.IcannReportingUploadAction} */
@RunWith(JUnit4.class)
public class IcannReportingUploadActionTest {
class IcannReportingUploadActionTest {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@RegisterExtension
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_FAIL = "ahah,csv\n12,34".getBytes(UTF_8);
@ -89,8 +86,8 @@ public class IcannReportingUploadActionTest {
return action;
}
@Before
public void before() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
createTlds("tld", "foo");
writeGcsFile(
gcsService,
@ -129,7 +126,7 @@ public class IcannReportingUploadActionTest {
}
@Test
public void testSuccess() throws Exception {
void testSuccess() throws Exception {
IcannReportingUploadAction action = createAction();
action.run();
verify(mockReporter).send(PAYLOAD_SUCCESS, "foo-activity-200606.csv");
@ -152,7 +149,7 @@ public class IcannReportingUploadActionTest {
}
@Test
public void testSuccess_january() throws Exception {
void testSuccess_january() throws Exception {
clock.setTo(DateTime.parse("2006-01-22T00:30:00Z"));
persistResource(
Cursor.create(
@ -189,7 +186,7 @@ public class IcannReportingUploadActionTest {
}
@Test
public void testSuccess_advancesCursor() throws Exception {
void testSuccess_advancesCursor() throws Exception {
writeGcsFile(
gcsService,
new GcsFilename("basin/icann/monthly/2006-06", "tld-activity-200606.csv"),
@ -207,7 +204,7 @@ public class IcannReportingUploadActionTest {
}
@Test
public void testSuccess_noUploadsNeeded() throws Exception {
void testSuccess_noUploadsNeeded() throws Exception {
clock.setTo(DateTime.parse("2006-5-01T00:30:00Z"));
IcannReportingUploadAction action = createAction();
action.run();
@ -223,7 +220,7 @@ public class IcannReportingUploadActionTest {
}
@Test
public void testSuccess_withRetry() throws Exception {
void testSuccess_withRetry() throws Exception {
IcannReportingUploadAction action = createAction();
when(mockReporter.send(PAYLOAD_SUCCESS, "tld-transactions-200606.csv"))
.thenThrow(new IOException("Expected exception."))
@ -248,7 +245,7 @@ public class IcannReportingUploadActionTest {
}
@Test
public void testFailure_quicklySkipsOverNonRetryableUploadException() throws Exception {
void testFailure_quicklySkipsOverNonRetryableUploadException() throws Exception {
runTest_nonRetryableException(
new IOException(
"<msg>A report for that month already exists, the cut-off date already"
@ -256,13 +253,13 @@ public class IcannReportingUploadActionTest {
}
@Test
public void testFailure_quicklySkipsOverIpAllowListException() throws Exception {
void testFailure_quicklySkipsOverIpAllowListException() throws Exception {
runTest_nonRetryableException(
new IOException("Your IP address 25.147.130.158 is not allowed to connect"));
}
@Test
public void testFailure_cursorIsNotAdvancedForward() throws Exception {
void testFailure_cursorIsNotAdvancedForward() throws Exception {
runTest_nonRetryableException(
new IOException("Your IP address 25.147.130.158 is not allowed to connect"));
ofy().clearSessionCache();
@ -275,7 +272,7 @@ public class IcannReportingUploadActionTest {
}
@Test
public void testNotRunIfCursorDateIsAfterToday() throws Exception {
void testNotRunIfCursorDateIsAfterToday() throws Exception {
clock.setTo(DateTime.parse("2006-05-01T00:30:00Z"));
IcannReportingUploadAction action = createAction();
action.run();
@ -316,7 +313,7 @@ public class IcannReportingUploadActionTest {
}
@Test
public void testFail_fileNotFound() throws Exception {
void testFail_fileNotFound() throws Exception {
clock.setTo(DateTime.parse("2006-01-22T00:30:00Z"));
persistResource(
Cursor.create(
@ -332,7 +329,7 @@ public class IcannReportingUploadActionTest {
}
@Test
public void testWarning_fileNotStagedYet() throws Exception {
void testWarning_fileNotStagedYet() throws Exception {
persistResource(
Cursor.create(
CursorType.ICANN_UPLOAD_ACTIVITY, DateTime.parse("2006-08-01TZ"), Registry.get("foo")));
@ -349,7 +346,7 @@ public class IcannReportingUploadActionTest {
}
@Test
public void testFailure_lockIsntAvailable() throws Exception {
void testFailure_lockIsntAvailable() throws Exception {
IcannReportingUploadAction action = createAction();
action.lockHandler = new FakeLockHandler(false);
ServiceUnavailableException thrown =
@ -360,7 +357,7 @@ public class IcannReportingUploadActionTest {
}
@Test
public void testSuccess_nullCursorsInitiatedToFirstOfNextMonth() throws Exception {
void testSuccess_nullCursorsInitiatedToFirstOfNextMonth() throws Exception {
createTlds("new");
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.ImmutableMap;
import org.joda.time.YearMonth;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link ActivityReportingQueryBuilder}. */
@RunWith(JUnit4.class)
public class TransactionsReportingQueryBuilderTest {
class TransactionsReportingQueryBuilderTest {
private final YearMonth yearMonth = new YearMonth(2017, 9);
@ -36,7 +33,7 @@ public class TransactionsReportingQueryBuilderTest {
}
@Test
public void testAggregateQueryMatch() {
void testAggregateQueryMatch() {
TransactionsReportingQueryBuilder queryBuilder = getQueryBuilder();
assertThat(queryBuilder.getReportQuery(yearMonth))
.isEqualTo(
@ -45,7 +42,7 @@ public class TransactionsReportingQueryBuilderTest {
}
@Test
public void testIntermediaryQueryMatch() {
void testIntermediaryQueryMatch() {
ImmutableList<String> expectedQueryNames =
ImmutableList.of(
TransactionsReportingQueryBuilder.TRANSACTIONS_REPORT_AGGREGATION,

View file

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

View file

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

View file

@ -47,16 +47,13 @@ import java.util.Optional;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import org.joda.time.LocalDate;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.ArgumentCaptor;
/** Unit tests for {@link Spec11EmailUtils}. */
@RunWith(JUnit4.class)
public class Spec11EmailUtilsTest {
class Spec11EmailUtilsTest {
private static final ImmutableList<String> FAKE_RESOURCES = ImmutableList.of("foo");
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"
+ " notice, please contact abuse@test.com.</p>";
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
@RegisterExtension
final AppEngineRule appEngine = AppEngineRule.builder().withDatastoreAndCloudSql().build();
private SendEmailService emailService;
private Spec11EmailUtils emailUtils;
@ -107,8 +104,8 @@ public class Spec11EmailUtilsTest {
private DomainBase aDomain;
private DomainBase bDomain;
@Before
public void setUp() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
emailService = mock(SendEmailService.class);
parser = mock(Spec11RegistrarThreatMatchesParser.class);
when(parser.getRegistrarThreatMatches(date)).thenReturn(sampleThreatMatches());
@ -131,7 +128,7 @@ public class Spec11EmailUtilsTest {
}
@Test
public void testSuccess_emailMonthlySpec11Reports() throws Exception {
void testSuccess_emailMonthlySpec11Reports() throws Exception {
emailUtils.emailSpec11Reports(
date,
Spec11EmailSoyInfo.MONTHLY_SPEC_11_EMAIL,
@ -169,7 +166,7 @@ public class Spec11EmailUtilsTest {
}
@Test
public void testSuccess_emailDailySpec11Reports() throws Exception {
void testSuccess_emailDailySpec11Reports() throws Exception {
emailUtils.emailSpec11Reports(
date,
Spec11EmailSoyInfo.DAILY_SPEC_11_EMAIL,
@ -207,14 +204,12 @@ public class Spec11EmailUtilsTest {
}
@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
persistResource(
ofy().load().entity(aDomain).now().asBuilder().addStatusValue(SERVER_HOLD)
.build());
ofy().load().entity(aDomain).now().asBuilder().addStatusValue(SERVER_HOLD).build());
persistResource(
ofy().load().entity(bDomain).now().asBuilder().addStatusValue(CLIENT_HOLD)
.build());
ofy().load().entity(bDomain).now().asBuilder().addStatusValue(CLIENT_HOLD).build());
emailUtils.emailSpec11Reports(
date,
Spec11EmailSoyInfo.MONTHLY_SPEC_11_EMAIL,
@ -242,7 +237,7 @@ public class Spec11EmailUtilsTest {
}
@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
LinkedHashSet<RegistrarThreatMatches> matches = new LinkedHashSet<>();
matches.add(getMatchA());
@ -297,7 +292,7 @@ public class Spec11EmailUtilsTest {
}
@Test
public void testSuccess_sendAlertEmail() throws Exception {
void testSuccess_sendAlertEmail() throws Exception {
emailUtils.sendAlertEmail("Spec11 Pipeline Alert: 2018-07", "Alert!");
verify(emailService).sendEmail(contentCaptor.capture());
validateMessage(
@ -311,7 +306,7 @@ public class Spec11EmailUtilsTest {
}
@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
persistResource(
AppEngineRule.makeRegistrarContact2()
@ -330,7 +325,7 @@ public class Spec11EmailUtilsTest {
}
@Test
public void testFailure_badClientId() {
void testFailure_badClientId() {
RuntimeException thrown =
assertThrows(
RuntimeException.class,

View file

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

View file

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

View file

@ -42,19 +42,16 @@ import java.io.StringWriter;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link RequestHandler}. */
@RunWith(JUnit4.class)
public final class RequestHandlerTest {
@Rule
public final AppEngineRule appEngine =
@RegisterExtension
final AppEngineRule appEngine =
AppEngineRule.builder()
.withDatastoreAndCloudSql()
.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)
public static final class FailAtConstructionTask implements Runnable {
public FailAtConstructionTask() {
FailAtConstructionTask() {
throw new ServiceUnavailableException("Fail at construction");
}
@ -207,8 +204,8 @@ public final class RequestHandlerTest {
private AuthResult providedAuthResult = null;
private final User testUser = new User("test@example.com", "test@example.com");
@Before
public void before() throws Exception {
@BeforeEach
void beforeEach() throws Exception {
// Initialize here, not inline, so that we pick up the mocked UserService.
handler =
RequestHandler.createForTest(
@ -226,8 +223,8 @@ public final class RequestHandlerTest {
handler.requestMetrics = requestMetrics;
}
@After
public void after() {
@AfterEach
void afterEach() {
verifyNoMoreInteractions(rsp, bumblebeeTask, slothTask, safeSlothTask, requestMetrics);
}
@ -237,7 +234,7 @@ public final class RequestHandlerTest {
}
@Test
public void testHandleRequest_normalRequest_works() throws Exception {
void testHandleRequest_normalRequest_works() throws Exception {
when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/bumblebee");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -251,7 +248,7 @@ public final class RequestHandlerTest {
}
@Test
public void testHandleRequest_multipleMethodMappings_works() throws Exception {
void testHandleRequest_multipleMethodMappings_works() throws Exception {
when(req.getMethod()).thenReturn("POST");
when(req.getRequestURI()).thenReturn("/bumblebee");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -264,7 +261,7 @@ public final class RequestHandlerTest {
}
@Test
public void testHandleRequest_prefixEnabled_subpathsWork() throws Exception {
void testHandleRequest_prefixEnabled_subpathsWork() throws Exception {
when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/bumblebee/hive");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -277,7 +274,7 @@ public final class RequestHandlerTest {
}
@Test
public void testHandleRequest_taskHasAutoPrintOk_printsOk() throws Exception {
void testHandleRequest_taskHasAutoPrintOk_printsOk() throws Exception {
when(req.getMethod()).thenReturn("POST");
when(req.getRequestURI()).thenReturn("/sloth");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -293,7 +290,7 @@ public final class RequestHandlerTest {
}
@Test
public void testHandleRequest_prefixDisabled_subpathsReturn404NotFound() throws Exception {
void testHandleRequest_prefixDisabled_subpathsReturn404NotFound() throws Exception {
when(req.getMethod()).thenReturn("POST");
when(req.getRequestURI()).thenReturn("/sloth/nest");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -305,7 +302,7 @@ public final class RequestHandlerTest {
}
@Test
public void testHandleRequest_taskThrowsHttpException_getsHandledByHandler() throws Exception {
void testHandleRequest_taskThrowsHttpException_getsHandledByHandler() throws Exception {
when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/fail");
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
public void testHandleRequest_taskThrowsHttpException_atConstructionTime_getsHandledByHandler()
void testHandleRequest_taskThrowsHttpException_atConstructionTime_getsHandledByHandler()
throws Exception {
when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/failAtConstruction");
@ -333,7 +330,7 @@ public final class RequestHandlerTest {
}
@Test
public void testHandleRequest_notFound_returns404NotFound() throws Exception {
void testHandleRequest_notFound_returns404NotFound() throws Exception {
when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/bogus");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -345,7 +342,7 @@ public final class RequestHandlerTest {
}
@Test
public void testHandleRequest_methodNotAllowed_returns405MethodNotAllowed() throws Exception {
void testHandleRequest_methodNotAllowed_returns405MethodNotAllowed() throws Exception {
when(req.getMethod()).thenReturn("POST");
when(req.getRequestURI()).thenReturn("/fail");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -357,7 +354,7 @@ public final class RequestHandlerTest {
}
@Test
public void testHandleRequest_insaneMethod_returns405MethodNotAllowed() throws Exception {
void testHandleRequest_insaneMethod_returns405MethodNotAllowed() throws Exception {
when(req.getMethod()).thenReturn("FIREAWAY");
when(req.getRequestURI()).thenReturn("/fail");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -368,10 +365,12 @@ public final class RequestHandlerTest {
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
public void testHandleRequest_lowercaseMethod_notRecognized() throws Exception {
void testHandleRequest_lowercaseMethod_notRecognized() throws Exception {
when(req.getMethod()).thenReturn("get");
when(req.getRequestURI()).thenReturn("/bumblebee");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -382,8 +381,9 @@ public final class RequestHandlerTest {
verify(rsp).sendError(405);
}
@SuppressWarnings("UnstableApiUsage")
@Test
public void testNullness() {
void testNullness() {
NullPointerTester tester = new NullPointerTester();
tester.setDefault(Class.class, Component.class);
tester.setDefault(RequestAuthenticator.class, requestAuthenticator);
@ -392,7 +392,7 @@ public final class RequestHandlerTest {
}
@Test
public void testXsrfProtection_validTokenProvided_runsAction() throws Exception {
void testXsrfProtection_validTokenProvided_runsAction() throws Exception {
when(req.getMethod()).thenReturn("POST");
when(req.getRequestURI()).thenReturn("/safe-sloth");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -405,7 +405,7 @@ public final class RequestHandlerTest {
}
@Test
public void testXsrfProtection_GETMethodWithoutToken_doesntCheckToken() throws Exception {
void testXsrfProtection_GETMethodWithoutToken_doesntCheckToken() throws Exception {
when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/safe-sloth");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -418,7 +418,7 @@ public final class RequestHandlerTest {
}
@Test
public void testNoAuthNeeded_success() throws Exception {
void testNoAuthNeeded_success() throws Exception {
when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/auth/none");
when(requestAuthenticator.authorize(AUTH_PUBLIC.authSettings(), req))
@ -433,7 +433,7 @@ public final class RequestHandlerTest {
}
@Test
public void testAuthNeeded_failure() throws Exception {
void testAuthNeeded_failure() throws Exception {
when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/auth/adminUser");
when(requestAuthenticator.authorize(AUTH_INTERNAL_OR_ADMIN.authSettings(), req))
@ -446,7 +446,7 @@ public final class RequestHandlerTest {
}
@Test
public void testAuthNeeded_success() throws Exception {
void testAuthNeeded_success() throws Exception {
when(req.getMethod()).thenReturn("GET");
when(req.getRequestURI()).thenReturn("/auth/adminUser");
when(requestAuthenticator.authorize(AUTH_INTERNAL_OR_ADMIN.authSettings(), req))
@ -462,5 +462,4 @@ public final class RequestHandlerTest {
assertThat(providedAuthResult.userAuthInfo().get().oauthTokenInfo()).isEmpty();
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 google.registry.request.HttpException.BadRequestException;
import google.registry.request.HttpException.UnsupportedMediaTypeException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link RequestModule}. */
@RunWith(JUnit4.class)
public final class RequestModuleTest {
final class RequestModuleTest {
@Test
public void testProvideJsonPayload() {
assertThat(provideJsonPayload(MediaType.JSON_UTF_8, "{\"k\":\"v\"}"))
.containsExactly("k", "v");
void testProvideJsonPayload() {
assertThat(provideJsonPayload(MediaType.JSON_UTF_8, "{\"k\":\"v\"}")).containsExactly("k", "v");
}
@Test
public void testProvideJsonPayload_contentTypeWithoutCharsetAllowed() {
void testProvideJsonPayload_contentTypeWithoutCharsetAllowed() {
assertThat(provideJsonPayload(MediaType.JSON_UTF_8.withoutParameters(), "{\"k\":\"v\"}"))
.containsExactly("k", "v");
}
@Test
public void testProvideJsonPayload_malformedInput_throws500() {
void testProvideJsonPayload_malformedInput_throws500() {
BadRequestException thrown =
assertThrows(
BadRequestException.class, () -> provideJsonPayload(MediaType.JSON_UTF_8, "{\"k\":"));
@ -49,21 +46,21 @@ public final class RequestModuleTest {
}
@Test
public void testProvideJsonPayload_emptyInput_throws500() {
void testProvideJsonPayload_emptyInput_throws500() {
BadRequestException thrown =
assertThrows(BadRequestException.class, () -> provideJsonPayload(MediaType.JSON_UTF_8, ""));
assertThat(thrown).hasMessageThat().contains("Malformed JSON");
}
@Test
public void testProvideJsonPayload_nonJsonContentType_throws415() {
void testProvideJsonPayload_nonJsonContentType_throws415() {
assertThrows(
UnsupportedMediaTypeException.class,
() -> provideJsonPayload(MediaType.PLAIN_TEXT_UTF_8, "{}"));
}
@Test
public void testProvideJsonPayload_contentTypeWithWeirdParam_throws415() {
void testProvideJsonPayload_contentTypeWithWeirdParam_throws415() {
assertThrows(
UnsupportedMediaTypeException.class,
() -> 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 javax.servlet.http.HttpServletRequest;
import org.joda.time.DateTime;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link RequestParameters}. */
@RunWith(JUnit4.class)
public class RequestParametersTest {
class RequestParametersTest {
private final HttpServletRequest req = mock(HttpServletRequest.class);
@Test
public void testExtractRequiredParameter_valuePresent_returnsValue() {
void testExtractRequiredParameter_valuePresent_returnsValue() {
when(req.getParameter("spin")).thenReturn("bog");
assertThat(extractRequiredParameter(req, "spin")).isEqualTo("bog");
}
@Test
public void testExtractRequiredParameter_notPresent_throwsBadRequest() {
void testExtractRequiredParameter_notPresent_throwsBadRequest() {
BadRequestException thrown =
assertThrows(BadRequestException.class, () -> extractRequiredParameter(req, "spin"));
assertThat(thrown).hasMessageThat().contains("spin");
}
@Test
public void testExtractRequiredParameter_empty_throwsBadRequest() {
void testExtractRequiredParameter_empty_throwsBadRequest() {
when(req.getParameter("spin")).thenReturn("");
BadRequestException thrown =
assertThrows(BadRequestException.class, () -> extractRequiredParameter(req, "spin"));
@ -64,100 +62,100 @@ public class RequestParametersTest {
}
@Test
public void testExtractOptionalParameter_valuePresent_returnsValue() {
void testExtractOptionalParameter_valuePresent_returnsValue() {
when(req.getParameter("spin")).thenReturn("bog");
assertThat(extractOptionalParameter(req, "spin")).hasValue("bog");
}
@Test
public void testExtractOptionalParameter_notPresent_returnsEmpty() {
void testExtractOptionalParameter_notPresent_returnsEmpty() {
assertThat(extractOptionalParameter(req, "spin")).isEmpty();
}
@Test
public void testExtractOptionalParameter_empty_returnsEmpty() {
void testExtractOptionalParameter_empty_returnsEmpty() {
when(req.getParameter("spin")).thenReturn("");
assertThat(extractOptionalParameter(req, "spin")).isEmpty();
}
@Test
public void testExtractSetOfParameters_notPresent_returnsEmpty() {
void testExtractSetOfParameters_notPresent_returnsEmpty() {
assertThat(extractSetOfParameters(req, "spin")).isEmpty();
}
@Test
public void testExtractSetOfParameters_empty_returnsEmpty() {
void testExtractSetOfParameters_empty_returnsEmpty() {
when(req.getParameter("spin")).thenReturn("");
assertThat(extractSetOfParameters(req, "spin")).isEmpty();
}
@Test
public void testExtractSetOfParameters_oneValue_returnsValue() {
void testExtractSetOfParameters_oneValue_returnsValue() {
when(req.getParameter("spin")).thenReturn("bog");
assertThat(extractSetOfParameters(req, "spin")).containsExactly("bog");
}
@Test
public void testExtractSetOfParameters_multipleValues_returnsAll() {
void testExtractSetOfParameters_multipleValues_returnsAll() {
when(req.getParameter("spin")).thenReturn("bog,gob");
assertThat(extractSetOfParameters(req, "spin")).containsExactly("bog", "gob");
}
@Test
public void testExtractSetOfParameters_multipleValuesWithEmpty_removesEmpty() {
void testExtractSetOfParameters_multipleValuesWithEmpty_removesEmpty() {
when(req.getParameter("spin")).thenReturn(",bog,,gob,");
assertThat(extractSetOfParameters(req, "spin")).containsExactly("bog", "gob");
}
@Test
public void testExtractSetOfParameters_multipleParameters_error() {
when(req.getParameterValues("spin")).thenReturn(new String[]{"bog", "gob"});
void testExtractSetOfParameters_multipleParameters_error() {
when(req.getParameterValues("spin")).thenReturn(new String[] {"bog", "gob"});
BadRequestException thrown =
assertThrows(BadRequestException.class, () -> extractSetOfParameters(req, "spin"));
assertThat(thrown).hasMessageThat().contains("spin");
}
@Test
public void testExtractSetOfEnumParameters_notPresent_returnsEmpty() {
void testExtractSetOfEnumParameters_notPresent_returnsEmpty() {
assertThat(extractSetOfEnumParameters(req, Club.class, "spin")).isEmpty();
}
@Test
public void testExtractSetOfEnumParameters_empty_returnsEmpty() {
void testExtractSetOfEnumParameters_empty_returnsEmpty() {
when(req.getParameter("spin")).thenReturn("");
assertThat(extractSetOfEnumParameters(req, Club.class, "spin")).isEmpty();
}
@Test
public void testExtractSetOfEnumParameters_oneValue_returnsValue() {
void testExtractSetOfEnumParameters_oneValue_returnsValue() {
when(req.getParameter("spin")).thenReturn("DANCE");
assertThat(extractSetOfEnumParameters(req, Club.class, "spin")).containsExactly(Club.DANCE);
}
@Test
public void testExtractSetOfEnumParameters_multipleValues_returnsAll() {
void testExtractSetOfEnumParameters_multipleValues_returnsAll() {
when(req.getParameter("spin")).thenReturn("DANCE,FLOOR");
assertThat(extractSetOfEnumParameters(req, Club.class, "spin"))
.containsExactly(Club.DANCE, Club.FLOOR);
}
@Test
public void testExtractSetOfEnumParameters_multipleValuesWithEmpty_removesEmpty() {
void testExtractSetOfEnumParameters_multipleValuesWithEmpty_removesEmpty() {
when(req.getParameter("spin")).thenReturn(",DANCE,,FLOOR,");
assertThat(extractSetOfEnumParameters(req, Club.class, "spin"))
.containsExactly(Club.DANCE, Club.FLOOR);
}
@Test
public void testExtractSetOfEnumParameters_multipleValues_caseInsensitive() {
void testExtractSetOfEnumParameters_multipleValues_caseInsensitive() {
when(req.getParameter("spin")).thenReturn("danCE,FlooR");
assertThat(extractSetOfEnumParameters(req, Club.class, "spin"))
.containsExactly(Club.DANCE, Club.FLOOR);
}
@Test
public void testExtractSetOfEnumParameters_multipleParameters_error() {
when(req.getParameterValues("spin")).thenReturn(new String[]{"DANCE", "FLOOR"});
void testExtractSetOfEnumParameters_multipleParameters_error() {
when(req.getParameterValues("spin")).thenReturn(new String[] {"DANCE", "FLOOR"});
BadRequestException thrown =
assertThrows(
BadRequestException.class, () -> extractSetOfEnumParameters(req, Club.class, "spin"));
@ -165,67 +163,70 @@ public class RequestParametersTest {
}
@Test
public void testExtractBooleanParameter_notPresent_returnsFalse() {
void testExtractBooleanParameter_notPresent_returnsFalse() {
assertThat(extractBooleanParameter(req, "love")).isFalse();
}
@Test
public void testExtractBooleanParameter_presentWithoutValue_returnsTrue() {
void testExtractBooleanParameter_presentWithoutValue_returnsTrue() {
when(req.getParameterMap()).thenReturn(ImmutableMap.of("love", ""));
assertThat(extractBooleanParameter(req, "love")).isTrue();
}
@Test
public void testExtractBooleanParameter_empty_returnsTrue() {
void testExtractBooleanParameter_empty_returnsTrue() {
when(req.getParameterMap()).thenReturn(ImmutableMap.of("love", ""));
when(req.getParameter("love")).thenReturn("");
assertThat(extractBooleanParameter(req, "love")).isTrue();
}
@Test
public void testExtractBooleanParameter_presentStringArbitrary_returnsTrue() {
void testExtractBooleanParameter_presentStringArbitrary_returnsTrue() {
when(req.getParameterMap()).thenReturn(ImmutableMap.of("love", "lol"));
when(req.getParameter("love")).thenReturn("lol");
assertThat(extractBooleanParameter(req, "love")).isTrue();
}
@Test
public void testExtractBooleanParameter_presentStringTrue_returnsTrue() {
void testExtractBooleanParameter_presentStringTrue_returnsTrue() {
when(req.getParameterMap()).thenReturn(ImmutableMap.of("love", "true"));
when(req.getParameter("love")).thenReturn("true");
assertThat(extractBooleanParameter(req, "love")).isTrue();
}
@Test
public void testExtractBooleanParameter_presentStringFalse_returnsFalse() {
void testExtractBooleanParameter_presentStringFalse_returnsFalse() {
when(req.getParameterMap()).thenReturn(ImmutableMap.of("love", "false"));
when(req.getParameter("love")).thenReturn("false");
assertThat(extractBooleanParameter(req, "love")).isFalse();
}
@Test
public void testExtractBooleanParameter_presentStringFalse_caseInsensitive() {
void testExtractBooleanParameter_presentStringFalse_caseInsensitive() {
when(req.getParameterMap()).thenReturn(ImmutableMap.of("love", "FaLsE"));
when(req.getParameter("love")).thenReturn("FaLsE");
assertThat(extractBooleanParameter(req, "love")).isFalse();
}
enum Club { DANCE, FLOOR }
enum Club {
DANCE,
FLOOR
}
@Test
public void testExtractEnumValue_correctValue_works() {
void testExtractEnumValue_correctValue_works() {
when(req.getParameter("spin")).thenReturn("DANCE");
assertThat(extractEnumParameter(req, Club.class, "spin")).isEqualTo(Club.DANCE);
}
@Test
public void testExtractEnumValue_weirdCasing_isCaseInsensitive() {
void testExtractEnumValue_weirdCasing_isCaseInsensitive() {
when(req.getParameter("spin")).thenReturn("DaNcE");
assertThat(extractEnumParameter(req, Club.class, "spin")).isEqualTo(Club.DANCE);
}
@Test
public void testExtractEnumValue_nonExistentValue_throwsBadRequest() {
void testExtractEnumValue_nonExistentValue_throwsBadRequest() {
when(req.getParameter("spin")).thenReturn("sing");
BadRequestException thrown =
assertThrows(
@ -234,19 +235,19 @@ public class RequestParametersTest {
}
@Test
public void testOptionalExtractEnumValue_givenValue_returnsValue() {
void testOptionalExtractEnumValue_givenValue_returnsValue() {
when(req.getParameter("spin")).thenReturn("DANCE");
assertThat(extractOptionalEnumParameter(req, Club.class, "spin")).hasValue(Club.DANCE);
}
@Test
public void testOptionalExtractEnumValue_noValue_returnsEmpty() {
void testOptionalExtractEnumValue_noValue_returnsEmpty() {
when(req.getParameter("spin")).thenReturn("");
assertThat(extractOptionalEnumParameter(req, Club.class, "spin")).isEmpty();
}
@Test
public void testOptionalExtractEnumValue_nonExistentValue_throwsBadRequest() {
void testOptionalExtractEnumValue_nonExistentValue_throwsBadRequest() {
when(req.getParameter("spin")).thenReturn("sing");
BadRequestException thrown =
assertThrows(
@ -255,14 +256,14 @@ public class RequestParametersTest {
}
@Test
public void testExtractRequiredDatetimeParameter_correctValue_works() {
void testExtractRequiredDatetimeParameter_correctValue_works() {
when(req.getParameter("timeParam")).thenReturn("2015-08-27T13:25:34.123Z");
assertThat(extractRequiredDatetimeParameter(req, "timeParam"))
.isEqualTo(DateTime.parse("2015-08-27T13:25:34.123Z"));
}
@Test
public void testExtractRequiredDatetimeParameter_badValue_throwsBadRequest() {
void testExtractRequiredDatetimeParameter_badValue_throwsBadRequest() {
when(req.getParameter("timeParam")).thenReturn("Tuesday at three o'clock");
BadRequestException thrown =
assertThrows(
@ -271,14 +272,14 @@ public class RequestParametersTest {
}
@Test
public void testExtractOptionalDatetimeParameter_correctValue_works() {
void testExtractOptionalDatetimeParameter_correctValue_works() {
when(req.getParameter("timeParam")).thenReturn("2015-08-27T13:25:34.123Z");
assertThat(extractOptionalDatetimeParameter(req, "timeParam"))
.hasValue(DateTime.parse("2015-08-27T13:25:34.123Z"));
}
@Test
public void testExtractOptionalDatetimeParameter_badValue_throwsBadRequest() {
void testExtractOptionalDatetimeParameter_badValue_throwsBadRequest() {
when(req.getParameter("timeParam")).thenReturn("Tuesday at three o'clock");
BadRequestException thrown =
assertThrows(
@ -287,13 +288,13 @@ public class RequestParametersTest {
}
@Test
public void testExtractOptionalDatetimeParameter_empty_returnsEmpty() {
void testExtractOptionalDatetimeParameter_empty_returnsEmpty() {
when(req.getParameter("timeParam")).thenReturn("");
assertThat(extractOptionalDatetimeParameter(req, "timeParam")).isEmpty();
}
@Test
public void testExtractRequiredDatetimeParameter_noValue_throwsBadRequest() {
void testExtractRequiredDatetimeParameter_noValue_throwsBadRequest() {
BadRequestException thrown =
assertThrows(
BadRequestException.class, () -> extractRequiredDatetimeParameter(req, "timeParam"));

View file

@ -24,32 +24,29 @@ import static org.mockito.Mockito.when;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.http.HttpServletResponse;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link ResponseImpl}. */
@RunWith(JUnit4.class)
public class ResponseImplTest {
class ResponseImplTest {
private final HttpServletResponse rsp = mock(HttpServletResponse.class);
@Test
public void testSetStatus() {
void testSetStatus() {
new ResponseImpl(rsp).setStatus(666);
verify(rsp).setStatus(666);
verifyNoMoreInteractions(rsp);
}
@Test
public void testSetContentType() {
void testSetContentType() {
new ResponseImpl(rsp).setContentType(PLAIN_TEXT_UTF_8);
verify(rsp).setContentType("text/plain; charset=utf-8");
verifyNoMoreInteractions(rsp);
}
@Test
public void testSetPayload() throws Exception {
void testSetPayload() throws Exception {
StringWriter httpOutput = new StringWriter();
when(rsp.getWriter()).thenReturn(new PrintWriter(httpOutput));
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.concurrent.Callable;
import java.util.function.Function;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link Router}. */
@RunWith(JUnit4.class)
public final class RouterTest {
////////////////////////////////////////////////////////////////////////////////////////////////
@ -35,7 +32,7 @@ public final class RouterTest {
public interface Empty {}
@Test
public void testRoute_noRoutes_throws() {
void testRoute_noRoutes_throws() {
IllegalArgumentException thrown =
assertThrows(IllegalArgumentException.class, () -> Router.create(Empty.class));
assertThat(thrown)
@ -56,7 +53,7 @@ public final class RouterTest {
}
@Test
public void testRoute_pathMatch_returnsRoute() {
void testRoute_pathMatch_returnsRoute() {
Optional<Route> route = Router.create(SlothComponent.class).route("/sloth");
assertThat(route).isPresent();
assertThat(route.get().action().path()).isEqualTo("/sloth");
@ -64,12 +61,12 @@ public final class RouterTest {
}
@Test
public void testRoute_pathMismatch_returnsEmpty() {
void testRoute_pathMismatch_returnsEmpty() {
assertThat(Router.create(SlothComponent.class).route("/doge")).isEmpty();
}
@Test
public void testRoute_pathIsAPrefix_notAllowedByDefault() {
void testRoute_pathIsAPrefix_notAllowedByDefault() {
assertThat(Router.create(SlothComponent.class).route("/sloth/extra")).isEmpty();
}
@ -90,13 +87,13 @@ public final class RouterTest {
}
@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/extra")).isPresent();
}
@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("/ulysses")).isEmpty();
@ -121,21 +118,21 @@ public final class RouterTest {
}
@Test
public void testRoute_prefixAndLongPathMatch_returnsLongerPath() {
void testRoute_prefixAndLongPathMatch_returnsLongerPath() {
Optional<Route> route = Router.create(LongPathComponent.class).route("/prefix/long");
assertThat(route).isPresent();
assertThat(route.get().action().path()).isEqualTo("/prefix/long");
}
@Test
public void testRoute_prefixAndLongerPrefixMatch_returnsLongerPrefix() {
void testRoute_prefixAndLongerPrefixMatch_returnsLongerPrefix() {
Optional<Route> route = Router.create(LongPathComponent.class).route("/prefix/longer");
assertThat(route).isPresent();
assertThat(route.get().action().path()).isEqualTo("/prefix/long");
}
@Test
public void testRoute_onlyShortPrefixMatches_returnsShortPrefix() {
void testRoute_onlyShortPrefixMatches_returnsShortPrefix() {
Optional<Route> route = Router.create(LongPathComponent.class).route("/prefix/cat");
assertThat(route).isPresent();
assertThat(route.get().action().path()).isEqualTo("/prefix");
@ -149,7 +146,7 @@ public final class RouterTest {
}
@Test
public void testRoute_methodsInComponentAreIgnored_throws() {
void testRoute_methodsInComponentAreIgnored_throws() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class, () -> Router.create(WeirdMethodsComponent.class));
@ -185,7 +182,7 @@ public final class RouterTest {
}
@Test
public void testCreate_twoTasksWithSameMethodAndPath_resultsInError() {
void testCreate_twoTasksWithSameMethodAndPath_resultsInError() {
IllegalArgumentException thrown =
assertThrows(IllegalArgumentException.class, () -> Router.create(DuplicateComponent.class));
assertThat(thrown).hasMessageThat().contains("Multiple entries with same key");

View file

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

View file

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

View file

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

View file

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

View file

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