Resolved merge conflict

This commit is contained in:
Michael Muller 2018-10-31 14:41:05 -04:00
commit 02c75ee37e
237 changed files with 4148 additions and 3993 deletions

View file

@ -177,9 +177,7 @@ public class InvoicingPipelineTest {
"2017-10-01,2022-09-30,234,70.75,JPY,10125,1,PURCHASE,theRegistrar - hello,1,"
+ "CREATE | TLD: hello | TERM: 5-year,70.75,JPY,",
"2017-10-01,2018-09-30,456,20.50,USD,10125,1,PURCHASE,bestdomains - test,1,"
+ "RENEW | TLD: test | TERM: 1-year,20.50,USD,116688",
"2017-10-01,2018-09-30,789,0.00,USD,10125,1,PURCHASE,anotherRegistrar - test,1,"
+ "CREATE | TLD: test | TERM: 1-year,0.00,USD,");
+ "RENEW | TLD: test | TERM: 1-year,20.50,USD,116688");
}
@Test

View file

@ -47,6 +47,7 @@ java_library(
"@com_google_flogger_system_backend",
"@com_google_guava",
"@com_google_guava_testlib",
"@com_google_monitoring_client_contrib",
"@com_google_monitoring_client_metrics",
"@com_google_re2j",
"@com_google_truth",

View file

@ -70,7 +70,7 @@ public class EppCommitLogsTest extends ShardableTestCase {
sessionMetadata.setClientId("TheRegistrar");
DaggerEppTestComponent.builder()
.fakesAndMocksModule(
FakesAndMocksModule.create(clock, EppMetric.builderForRequest("request-id-1", clock)))
FakesAndMocksModule.create(clock, EppMetric.builderForRequest(clock)))
.build()
.startRequest()
.flowComponentBuilder()

View file

@ -16,7 +16,6 @@ package google.registry.flows;
import static com.google.common.io.BaseEncoding.base64;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import static google.registry.flows.EppXmlTransformer.marshal;
import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.LogsSubject.assertAboutLogs;
@ -40,7 +39,6 @@ import google.registry.model.eppoutput.EppOutput;
import google.registry.model.eppoutput.EppResponse;
import google.registry.model.eppoutput.Result;
import google.registry.model.eppoutput.Result.Code;
import google.registry.monitoring.whitebox.BigQueryMetricsEnqueuer;
import google.registry.monitoring.whitebox.EppMetric;
import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock;
@ -60,7 +58,6 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor;
import org.mockito.Matchers;
import org.mockito.Mock;
@ -74,7 +71,6 @@ public class EppControllerTest extends ShardableTestCase {
@Mock SessionMetadata sessionMetadata;
@Mock TransportCredentials transportCredentials;
@Mock EppMetrics eppMetrics;
@Mock BigQueryMetricsEnqueuer bigQueryMetricsEnqueuer;
@Mock FlowComponent.Builder flowComponentBuilder;
@Mock FlowComponent flowComponent;
@Mock FlowRunner flowRunner;
@ -111,9 +107,8 @@ public class EppControllerTest extends ShardableTestCase {
when(result.getCode()).thenReturn(Code.SUCCESS_WITH_NO_MESSAGES);
eppController = new EppController();
eppController.eppMetricBuilder = EppMetric.builderForRequest("request-id-1", clock);
eppController.eppMetricBuilder = EppMetric.builderForRequest(clock);
when(flowRunner.run(eppController.eppMetricBuilder)).thenReturn(eppOutput);
eppController.bigQueryMetricsEnqueuer = bigQueryMetricsEnqueuer;
eppController.flowComponentBuilder = flowComponentBuilder;
eppController.eppMetrics = eppMetrics;
eppController.serverTridProvider = new FakeServerTridProvider();
@ -132,49 +127,6 @@ public class EppControllerTest extends ShardableTestCase {
ValidationMode.STRICT);
}
@Test
public void testHandleEppCommand_unmarshallableData_exportsMetric() {
eppController.handleEppCommand(
sessionMetadata,
transportCredentials,
EppRequestSource.UNIT_TEST,
false,
false,
new byte[0]);
ArgumentCaptor<EppMetric> metricCaptor = ArgumentCaptor.forClass(EppMetric.class);
verify(bigQueryMetricsEnqueuer).export(metricCaptor.capture());
EppMetric metric = metricCaptor.getValue();
assertThat(metric.getRequestId()).isEqualTo("request-id-1");
assertThat(metric.getStartTimestamp()).isEqualTo(START_TIME);
assertThat(metric.getEndTimestamp()).isEqualTo(clock.nowUtc());
assertThat(metric.getClientId()).hasValue("some-client");
assertThat(metric.getPrivilegeLevel()).hasValue("NORMAL");
assertThat(metric.getStatus()).hasValue(Code.SYNTAX_ERROR);
}
@Test
public void testHandleEppCommand_regularEppCommand_exportsBigQueryMetric() {
eppController.handleEppCommand(
sessionMetadata,
transportCredentials,
EppRequestSource.UNIT_TEST,
false,
true,
domainCreateXml.getBytes(UTF_8));
ArgumentCaptor<EppMetric> metricCaptor = ArgumentCaptor.forClass(EppMetric.class);
verify(bigQueryMetricsEnqueuer).export(metricCaptor.capture());
EppMetric metric = metricCaptor.getValue();
assertThat(metric.getRequestId()).isEqualTo("request-id-1");
assertThat(metric.getStartTimestamp()).isEqualTo(START_TIME);
assertThat(metric.getEndTimestamp()).isEqualTo(clock.nowUtc());
assertThat(metric.getClientId()).hasValue("some-client");
assertThat(metric.getPrivilegeLevel()).hasValue("SUPERUSER");
assertThat(metric.getStatus()).hasValue(Code.SUCCESS_WITH_NO_MESSAGES);
assertThat(metric.getEppTarget()).hasValue("example.tld");
}
@Test
public void testHandleEppCommand_regularEppCommand_exportsEppMetrics() {
createTld("tld");
@ -182,12 +134,10 @@ public class EppControllerTest extends ShardableTestCase {
// FlowRunner, not EppController, and since FlowRunner is mocked out for these tests they won't
// actually get values.
EppMetric.Builder metricBuilder =
EppMetric.builderForRequest("request-id-1", clock)
EppMetric.builderForRequest(clock)
.setClientId("some-client")
.setEppTarget("example.tld")
.setStatus(Code.SUCCESS_WITH_NO_MESSAGES)
.setTld("tld")
.setPrivilegeLevel("SUPERUSER");
.setTld("tld");
eppController.handleEppCommand(
sessionMetadata,
transportCredentials,
@ -210,8 +160,6 @@ public class EppControllerTest extends ShardableTestCase {
true,
true,
domainCreateXml.getBytes(UTF_8));
verifyZeroInteractions(bigQueryMetricsEnqueuer);
verifyZeroInteractions(eppMetrics);
}

View file

@ -52,8 +52,6 @@ public class EppLifecycleContactTest extends EppTestCase {
.and()
.hasCommandName("ContactCreate")
.and()
.hasEppTarget("sh8013")
.and()
.hasStatus(SUCCESS);
assertThatCommand("contact_info.xml")
.atTime("2000-06-01T00:01:00Z")
@ -63,8 +61,6 @@ public class EppLifecycleContactTest extends EppTestCase {
.and()
.hasCommandName("ContactInfo")
.and()
.hasEppTarget("sh8013")
.and()
.hasStatus(SUCCESS);
assertThatCommand("contact_delete_sh8013.xml")
.hasResponse("contact_delete_response_sh8013.xml");
@ -73,8 +69,6 @@ public class EppLifecycleContactTest extends EppTestCase {
.and()
.hasCommandName("ContactDelete")
.and()
.hasEppTarget("sh8013")
.and()
.hasStatus(SUCCESS_WITH_ACTION_PENDING);
assertThatLogoutSucceeds();
}

View file

@ -440,8 +440,6 @@ public class EppLifecycleDomainTest extends EppTestCase {
.and()
.hasCommandName("HostUpdate")
.and()
.hasEppTarget("ns3.fakesite.example")
.and()
.hasStatus(SUCCESS);
// Delete the fakesite.example domain (which should succeed since it no longer has subords).
assertThatCommand("domain_delete.xml", ImmutableMap.of("DOMAIN", "fakesite.example"))
@ -454,8 +452,6 @@ public class EppLifecycleDomainTest extends EppTestCase {
.and()
.hasCommandName("DomainDelete")
.and()
.hasEppTarget("fakesite.example")
.and()
.hasStatus(SUCCESS_WITH_ACTION_PENDING);
// Check info on the renamed host and verify that it's still around and wasn't deleted.
assertThatCommand("host_info_ns9000_example.xml")
@ -466,8 +462,6 @@ public class EppLifecycleDomainTest extends EppTestCase {
.and()
.hasCommandName("HostInfo")
.and()
.hasEppTarget("ns9000.example.external")
.and()
.hasStatus(SUCCESS);
assertThatLogoutSucceeds();
assertThat(getRecordedEppMetric())
@ -575,8 +569,6 @@ public class EppLifecycleDomainTest extends EppTestCase {
.and()
.hasCommandName("DomainCheck")
.and()
.hasEppTarget("rich.example")
.and()
.hasTld("example")
.and()
.hasStatus(SUCCESS);

View file

@ -67,8 +67,6 @@ public class EppLifecycleHostTest extends EppTestCase {
.and()
.hasCommandName("HostCreate")
.and()
.hasEppTarget("ns1.example.tld")
.and()
.hasStatus(SUCCESS);
assertThatCommand("host_info.xml", ImmutableMap.of("HOSTNAME", "ns1.example.tld"))
.atTime("2000-06-02T00:02:00Z")
@ -81,8 +79,6 @@ public class EppLifecycleHostTest extends EppTestCase {
.and()
.hasCommandName("HostInfo")
.and()
.hasEppTarget("ns1.example.tld")
.and()
.hasStatus(SUCCESS);
assertThatCommand("host_delete.xml", ImmutableMap.of("HOSTNAME", "ns1.example.tld"))
.atTime("2000-06-02T00:03:00Z")
@ -92,8 +88,6 @@ public class EppLifecycleHostTest extends EppTestCase {
.and()
.hasCommandName("HostDelete")
.and()
.hasEppTarget("ns1.example.tld")
.and()
.hasStatus(SUCCESS_WITH_ACTION_PENDING);
assertThatLogoutSucceeds();
}

View file

@ -32,7 +32,6 @@ import google.registry.testing.FakeHttpSession;
import google.registry.testing.FakeResponse;
import google.registry.testing.InjectRule;
import google.registry.testing.ShardableTestCase;
import google.registry.tmch.TmchCertificateAuthority;
import java.util.Map;
import javax.annotation.Nullable;
import org.joda.time.DateTime;
@ -58,8 +57,6 @@ public class EppTestCase extends ShardableTestCase {
public void initTestCase() {
// For transactional flows
inject.setStaticField(Ofy.class, "clock", clock);
// For SignedMark signature validity
inject.setStaticField(TmchCertificateAuthority.class, "clock", clock);
}
/**
@ -167,7 +164,7 @@ public class EppTestCase extends ShardableTestCase {
EppRequestHandler handler = new EppRequestHandler();
FakeResponse response = new FakeResponse();
handler.response = response;
eppMetricBuilder = EppMetric.builderForRequest("request-id-1", clock);
eppMetricBuilder = EppMetric.builderForRequest(clock);
handler.eppController = DaggerEppTestComponent.builder()
.fakesAndMocksModule(FakesAndMocksModule.create(clock, eppMetricBuilder))
.build()

View file

@ -32,7 +32,6 @@ import google.registry.flows.async.AsyncFlowEnqueuer;
import google.registry.flows.custom.CustomLogicFactory;
import google.registry.flows.custom.TestCustomLogicFactory;
import google.registry.flows.domain.DomainFlowTmchUtils;
import google.registry.monitoring.whitebox.BigQueryMetricsEnqueuer;
import google.registry.monitoring.whitebox.EppMetric;
import google.registry.request.RequestScope;
import google.registry.request.lock.LockHandler;
@ -64,7 +63,6 @@ interface EppTestComponent {
class FakesAndMocksModule {
private AsyncFlowEnqueuer asyncFlowEnqueuer;
private BigQueryMetricsEnqueuer metricsEnqueuer;
private DnsQueue dnsQueue;
private DomainFlowTmchUtils domainFlowTmchUtils;
private EppMetric.Builder metricBuilder;
@ -75,14 +73,14 @@ interface EppTestComponent {
public static FakesAndMocksModule create() {
FakeClock clock = new FakeClock();
return create(clock, EppMetric.builderForRequest("request-id-1", clock));
return create(clock, EppMetric.builderForRequest(clock));
}
public static FakesAndMocksModule create(FakeClock clock, EppMetric.Builder metricBuilder) {
return create(
clock,
metricBuilder,
new TmchXmlSignature(new TmchCertificateAuthority(TmchCaMode.PILOT)));
new TmchXmlSignature(new TmchCertificateAuthority(TmchCaMode.PILOT, clock)));
}
public static FakesAndMocksModule create(
@ -106,7 +104,6 @@ interface EppTestComponent {
instance.dnsQueue = DnsQueue.create();
instance.metricBuilder = eppMetricBuilder;
instance.appEngineServiceUtils = appEngineServiceUtils;
instance.metricsEnqueuer = mock(BigQueryMetricsEnqueuer.class);
instance.lockHandler = new FakeLockHandler(true);
return instance;
}
@ -116,11 +113,6 @@ interface EppTestComponent {
return asyncFlowEnqueuer;
}
@Provides
BigQueryMetricsEnqueuer provideBigQueryMetricsEnqueuer() {
return metricsEnqueuer;
}
@Provides
Clock provideClock() {
return clock;

View file

@ -17,6 +17,7 @@ package google.registry.flows;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.flows.EppXmlSanitizer.sanitizeEppXml;
import static google.registry.testing.TestDataHelper.loadBytes;
import static java.nio.charset.StandardCharsets.UTF_16LE;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.collect.ImmutableMap;
@ -30,12 +31,12 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class EppXmlSanitizerTest {
private static final String XML_HEADER = "<?xml version=\"1.0\" ?>";
private static final String UTF8_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
@Test
public void testSanitize_noSensitiveData_noop() throws Exception {
byte[] inputXmlBytes = loadBytes(getClass(), "host_create.xml").read();
String expectedXml = XML_HEADER + new String(inputXmlBytes, UTF_8);
String expectedXml = UTF8_HEADER + new String(inputXmlBytes, UTF_8);
String sanitizedXml = sanitizeEppXml(inputXmlBytes);
assertThat(sanitizedXml).isEqualTo(expectedXml);
@ -50,7 +51,7 @@ public class EppXmlSanitizerTest {
ImmutableMap.of("PW", "oldpass", "NEWPW", "newPw"))
.getEppXml();
String expectedXml =
XML_HEADER
UTF8_HEADER
+ new EppLoader(
this,
"login_update_password.xml",
@ -68,7 +69,7 @@ public class EppXmlSanitizerTest {
this, "login_wrong_case.xml", ImmutableMap.of("PW", "oldpass", "NEWPW", "newPw"))
.getEppXml();
String expectedXml =
XML_HEADER
UTF8_HEADER
+ new EppLoader(
this,
"login_wrong_case.xml",
@ -83,7 +84,7 @@ public class EppXmlSanitizerTest {
public void testSanitize_contactAuthInfo_sanitized() throws Exception {
byte[] inputXmlBytes = loadBytes(getClass(), "contact_info.xml").read();
String expectedXml =
XML_HEADER
UTF8_HEADER
+ new EppLoader(this, "contact_info_sanitized.xml", ImmutableMap.of()).getEppXml();
String sanitizedXml = sanitizeEppXml(inputXmlBytes);
@ -94,7 +95,7 @@ public class EppXmlSanitizerTest {
public void testSanitize_contactCreateResponseAuthInfo_sanitized() throws Exception {
byte[] inputXmlBytes = loadBytes(getClass(), "contact_info_from_create_response.xml").read();
String expectedXml =
XML_HEADER
UTF8_HEADER
+ new EppLoader(
this, "contact_info_from_create_response_sanitized.xml", ImmutableMap.of())
.getEppXml();
@ -106,7 +107,7 @@ public class EppXmlSanitizerTest {
@Test
public void testSanitize_emptyElement_transformedToLongForm() {
byte[] inputXmlBytes = "<pw/>".getBytes(UTF_8);
assertThat(sanitizeEppXml(inputXmlBytes)).isEqualTo(XML_HEADER + "<pw></pw>\n");
assertThat(sanitizeEppXml(inputXmlBytes)).isEqualTo(UTF8_HEADER + "<pw></pw>\n");
}
@Test
@ -119,7 +120,22 @@ public class EppXmlSanitizerTest {
@Test
public void testSanitize_unicode_hasCorrectCharCount() {
byte[] inputXmlBytes = "<pw>\u007F\u4E43x</pw>".getBytes(UTF_8);
String expectedXml = XML_HEADER + "<pw>C**</pw>\n";
String expectedXml = UTF8_HEADER + "<pw>C**</pw>\n";
assertThat(sanitizeEppXml(inputXmlBytes)).isEqualTo(expectedXml);
}
@Test
public void testSanitize_emptyString_encodedToBase64() {
byte[] inputXmlBytes = "".getBytes(UTF_8);
assertThat(sanitizeEppXml(inputXmlBytes)).isEqualTo("");
}
@Test
public void testSanitize_utf16_encodingPreserved() {
// Test data should specify an endian-specific UTF-16 scheme for easy assertion. If 'UTF-16' is
// used, the XMLEventReader in sanitizer may resolve it to an endian-specific one.
String inputXml = "<?xml version=\"1.0\" encoding=\"UTF-16LE\"?><p>\u03bc</p>\n";
String sanitizedXml = sanitizeEppXml(inputXml.getBytes(UTF_16LE));
assertThat(sanitizedXml).isEqualTo(inputXml);
}
}

View file

@ -54,8 +54,7 @@ public class FlowRunnerTest extends ShardableTestCase {
public final AppEngineRule appEngineRule = new AppEngineRule.Builder().build();
private final FlowRunner flowRunner = new FlowRunner();
private final EppMetric.Builder eppMetricBuilder =
EppMetric.builderForRequest("request-id-1", new FakeClock());
private final EppMetric.Builder eppMetricBuilder = EppMetric.builderForRequest(new FakeClock());
private final TestLogHandler handler = new TestLogHandler();
@ -84,19 +83,6 @@ public class FlowRunnerTest extends ShardableTestCase {
flowRunner.flowReporter = Mockito.mock(FlowReporter.class);
}
@Test
public void testRun_nonTransactionalCommand_incrementsMetricAttempts() throws Exception {
flowRunner.run(eppMetricBuilder);
assertThat(eppMetricBuilder.build().getAttempts()).isEqualTo(1);
}
@Test
public void testRun_transactionalCommand_incrementsMetricAttempts() throws Exception {
flowRunner.isTransactional = true;
flowRunner.run(eppMetricBuilder);
assertThat(eppMetricBuilder.build().getAttempts()).isEqualTo(1);
}
@Test
public void testRun_nonTransactionalCommand_setsCommandNameOnMetric() throws Exception {
flowRunner.isTransactional = true;

View file

@ -110,8 +110,6 @@ public abstract class FlowTestCase<F extends Flow> extends ShardableTestCase {
ofy().saveWithoutBackup().entity(new ClaimsListSingleton()).now();
// For transactional flows
inject.setStaticField(Ofy.class, "clock", clock);
// For SignedMark signature validity
inject.setStaticField(TmchCertificateAuthority.class, "clock", clock);
}
protected void removeServiceExtensionUri(String uri) {
@ -278,7 +276,7 @@ public abstract class FlowTestCase<F extends Flow> extends ShardableTestCase {
private EppOutput runFlowInternal(CommitMode commitMode, UserPrivileges userPrivileges)
throws Exception {
eppMetricBuilder = EppMetric.builderForRequest("request-id-1", clock);
eppMetricBuilder = EppMetric.builderForRequest(clock);
// Assert that the xml triggers the flow we expect.
assertThat(FlowPicker.getFlowClass(eppLoader.getEpp()))
.isEqualTo(new TypeInstantiator<F>(getClass()){}.getExactType());
@ -286,7 +284,7 @@ public abstract class FlowTestCase<F extends Flow> extends ShardableTestCase {
TmchXmlSignature tmchXmlSignature =
testTmchXmlSignature != null
? testTmchXmlSignature
: new TmchXmlSignature(new TmchCertificateAuthority(tmchCaMode));
: new TmchXmlSignature(new TmchCertificateAuthority(tmchCaMode, clock));
return DaggerEppTestComponent.builder()
.fakesAndMocksModule(FakesAndMocksModule.create(clock, eppMetricBuilder, tmchXmlSignature))
.build()

View file

@ -14,19 +14,14 @@
package google.registry.flows.async;
import static com.google.monitoring.metrics.contrib.DistributionMetricSubject.assertThat;
import static com.google.monitoring.metrics.contrib.LongMetricSubject.assertThat;
import static google.registry.flows.async.AsyncFlowMetrics.OperationResult.SUCCESS;
import static google.registry.flows.async.AsyncFlowMetrics.OperationType.CONTACT_AND_HOST_DELETE;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import com.google.monitoring.metrics.EventMetric;
import com.google.monitoring.metrics.IncrementableMetric;
import com.google.common.collect.ImmutableSet;
import google.registry.testing.FakeClock;
import google.registry.testing.InjectRule;
import google.registry.testing.ShardableTestCase;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@ -35,26 +30,8 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class AsyncFlowMetricsTest extends ShardableTestCase {
@Rule public final InjectRule inject = new InjectRule();
private final IncrementableMetric asyncFlowOperationCounts = mock(IncrementableMetric.class);
private final EventMetric asyncFlowOperationProcessingTime = mock(EventMetric.class);
private final EventMetric asyncFlowBatchSize = mock(EventMetric.class);
private AsyncFlowMetrics asyncFlowMetrics;
private FakeClock clock;
@Before
public void setUp() {
clock = new FakeClock();
asyncFlowMetrics = new AsyncFlowMetrics(clock);
inject.setStaticField(
AsyncFlowMetrics.class, "asyncFlowOperationCounts", asyncFlowOperationCounts);
inject.setStaticField(
AsyncFlowMetrics.class,
"asyncFlowOperationProcessingTime",
asyncFlowOperationProcessingTime);
inject.setStaticField(AsyncFlowMetrics.class, "asyncFlowBatchSize", asyncFlowBatchSize);
}
private final FakeClock clock = new FakeClock();
private final AsyncFlowMetrics asyncFlowMetrics = new AsyncFlowMetrics(clock);
@Test
public void testRecordAsyncFlowResult_calculatesDurationMillisCorrectly() {
@ -62,9 +39,13 @@ public class AsyncFlowMetricsTest extends ShardableTestCase {
CONTACT_AND_HOST_DELETE,
SUCCESS,
clock.nowUtc().minusMinutes(10).minusSeconds(5).minusMillis(566));
verify(asyncFlowOperationCounts).increment("contactAndHostDelete", "success");
verify(asyncFlowOperationProcessingTime).record(605566.0, "contactAndHostDelete", "success");
verifyNoMoreInteractions(asyncFlowOperationCounts);
verifyNoMoreInteractions(asyncFlowOperationProcessingTime);
assertThat(AsyncFlowMetrics.asyncFlowOperationCounts)
.hasValueForLabels(1, "contactAndHostDelete", "success")
.and()
.hasNoOtherValues();
assertThat(AsyncFlowMetrics.asyncFlowOperationProcessingTime)
.hasDataSetForLabels(ImmutableSet.of(605566.0), "contactAndHostDelete", "success")
.and()
.hasNoOtherValues();
}
}

View file

@ -52,8 +52,8 @@ import static google.registry.testing.TaskQueueHelper.assertDnsTasksEnqueued;
import static google.registry.testing.TaskQueueHelper.assertNoDnsTasksEnqueued;
import static google.registry.testing.TaskQueueHelper.assertNoTasksEnqueued;
import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
import static google.registry.tmch.LordnTask.QUEUE_CLAIMS;
import static google.registry.tmch.LordnTask.QUEUE_SUNRISE;
import static google.registry.tmch.LordnTaskUtils.QUEUE_CLAIMS;
import static google.registry.tmch.LordnTaskUtils.QUEUE_SUNRISE;
import static google.registry.util.DateTimeUtils.END_OF_TIME;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static org.joda.money.CurrencyUnit.EUR;
@ -270,7 +270,8 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
new ImmutableSet.Builder<BillingEvent>().add(createBillingEvent).add(renewBillingEvent);
// If EAP is applied, a billing event for EAP should be present.
if (!eapFee.isZero()) {
// EAP fees are bypassed for anchor tenant domains.
if (!isAnchorTenant && !eapFee.isZero()) {
BillingEvent.OneTime eapBillingEvent =
new BillingEvent.OneTime.Builder()
.setReason(Reason.FEE_EARLY_ACCESS)
@ -1012,6 +1013,22 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
.isEqualTo(Key.create(getHistoryEntries(reloadResourceByForeignKey()).get(0)));
}
@Test
public void testSuccess_anchorTenant_bypassesEapFees() throws Exception {
setEapForTld("tld");
// This XML file does not contain EAP fees.
setEppInput("domain_create_anchor_allocationtoken.xml");
persistContactsAndHosts();
runFlowAssertResponse(loadFile("domain_create_anchor_response.xml"));
assertSuccessfulCreate("tld", ImmutableSet.of(ANCHOR_TENANT));
assertNoLordn();
AllocationToken reloadedToken =
ofy().load().key(Key.create(AllocationToken.class, "abcDEF23456")).now();
assertThat(reloadedToken.isRedeemed()).isTrue();
assertThat(reloadedToken.getRedemptionHistoryEntry())
.isEqualTo(Key.create(getHistoryEntries(reloadResourceByForeignKey()).get(0)));
}
@Test
public void testSuccess_anchorTenant_viaAuthCode_withClaims() throws Exception {
persistResource(
@ -1043,7 +1060,7 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
persistContactsAndHosts();
runFlowAssertResponse(
loadFile("domain_create_response.xml", ImmutableMap.of("DOMAIN", "resdom.tld")));
assertSuccessfulCreate("tld", ImmutableSet.of());
assertSuccessfulCreate("tld", ImmutableSet.of(Flag.RESERVED));
assertNoLordn();
AllocationToken reloadedToken = ofy().load().entity(token).now();
assertThat(reloadedToken.isRedeemed()).isTrue();
@ -1057,7 +1074,7 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
persistContactsAndHosts();
runFlowAssertResponse(
CommitMode.LIVE, SUPERUSER, loadFile("domain_create_reserved_response.xml"));
assertSuccessfulCreate("tld", ImmutableSet.of());
assertSuccessfulCreate("tld", ImmutableSet.of(Flag.RESERVED));
}
@Test
@ -2242,18 +2259,7 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
public void testFailure_eapFee_combined() {
setEppInput("domain_create_eap_combined_fee.xml", ImmutableMap.of("FEE_VERSION", "0.6"));
persistContactsAndHosts();
persistResource(
Registry.get("tld")
.asBuilder()
.setEapFeeSchedule(
ImmutableSortedMap.of(
START_OF_TIME,
Money.of(USD, 0),
clock.nowUtc().minusDays(1),
Money.of(USD, 100),
clock.nowUtc().plusDays(1),
Money.of(USD, 0)))
.build());
setEapForTld("tld");
EppException thrown = assertThrows(FeeDescriptionParseException.class, this::runFlow);
assertThat(thrown).hasMessageThat().contains("No fee description");
assertAboutEppExceptions().that(thrown).marshalsToXml();
@ -2271,18 +2277,7 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
"DESCRIPTION_2",
"create"));
persistContactsAndHosts();
persistResource(
Registry.get("tld")
.asBuilder()
.setEapFeeSchedule(
ImmutableSortedMap.of(
START_OF_TIME,
Money.of(USD, 0),
clock.nowUtc().minusDays(1),
Money.of(USD, 100),
clock.nowUtc().plusDays(1),
Money.of(USD, 0)))
.build());
setEapForTld("tld");
EppException thrown = assertThrows(FeesMismatchException.class, this::runFlow);
assertThat(thrown).hasMessageThat().contains("CREATE");
assertAboutEppExceptions().that(thrown).marshalsToXml();
@ -2302,18 +2297,7 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
.put("FEE_3", "55")
.build());
persistContactsAndHosts();
persistResource(
Registry.get("tld")
.asBuilder()
.setEapFeeSchedule(
ImmutableSortedMap.of(
START_OF_TIME,
Money.of(USD, 0),
clock.nowUtc().minusDays(1),
Money.of(USD, 100),
clock.nowUtc().plusDays(1),
Money.of(USD, 0)))
.build());
setEapForTld("tld");
EppException thrown = assertThrows(FeesMismatchException.class, this::runFlow);
assertThat(thrown).hasMessageThat().contains("expected total of USD 126.00");
assertAboutEppExceptions().that(thrown).marshalsToXml();
@ -2333,18 +2317,7 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
.put("FEE_3", "55")
.build());
persistContactsAndHosts();
persistResource(
Registry.get("tld")
.asBuilder()
.setEapFeeSchedule(
ImmutableSortedMap.of(
START_OF_TIME,
Money.of(USD, 0),
clock.nowUtc().minusDays(1),
Money.of(USD, 100),
clock.nowUtc().plusDays(1),
Money.of(USD, 0)))
.build());
setEapForTld("tld");
EppException thrown = assertThrows(FeesMismatchException.class, this::runFlow);
assertThat(thrown).hasMessageThat().contains("expected fee of USD 100.00");
assertAboutEppExceptions().that(thrown).marshalsToXml();
@ -2364,18 +2337,7 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
.put("FEE_3", "45")
.build());
persistContactsAndHosts();
persistResource(
Registry.get("tld")
.asBuilder()
.setEapFeeSchedule(
ImmutableSortedMap.of(
START_OF_TIME,
Money.of(USD, 0),
clock.nowUtc().minusDays(1),
Money.of(USD, 100),
clock.nowUtc().plusDays(1),
Money.of(USD, 0)))
.build());
setEapForTld("tld");
doSuccessfulTest(
"tld", "domain_create_response_eap_fee.xml", ImmutableMap.of("FEE_VERSION", "0.6"));
}
@ -2392,18 +2354,7 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
"DESCRIPTION_2",
"Early Access Period, fee expires: 2022-03-01T00:00:00.000Z"));
persistContactsAndHosts();
persistResource(
Registry.get("tld")
.asBuilder()
.setEapFeeSchedule(
ImmutableSortedMap.of(
START_OF_TIME,
Money.of(USD, 0),
clock.nowUtc().minusDays(1),
Money.of(USD, 100),
clock.nowUtc().plusDays(1),
Money.of(USD, 0)))
.build());
setEapForTld("tld");
doSuccessfulTest(
"tld", "domain_create_response_eap_fee.xml", ImmutableMap.of("FEE_VERSION", "0.6"));
}
@ -2415,18 +2366,7 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
ImmutableMap.of(
"FEE_VERSION", "0.6", "DESCRIPTION_1", "create", "DESCRIPTION_2", "renew transfer"));
persistContactsAndHosts();
persistResource(
Registry.get("tld")
.asBuilder()
.setEapFeeSchedule(
ImmutableSortedMap.of(
START_OF_TIME,
Money.of(USD, 0),
clock.nowUtc().minusDays(1),
Money.of(USD, 100),
clock.nowUtc().plusDays(1),
Money.of(USD, 0)))
.build());
setEapForTld("tld");
EppException thrown = assertThrows(FeeDescriptionMultipleMatchesException.class, this::runFlow);
assertThat(thrown).hasMessageThat().contains("RENEW, TRANSFER");
assertAboutEppExceptions().that(thrown).marshalsToXml();
@ -2444,18 +2384,7 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
"DESCRIPTION_2",
"Early Access Period"));
persistContactsAndHosts();
persistResource(
Registry.get("tld")
.asBuilder()
.setEapFeeSchedule(
ImmutableSortedMap.of(
START_OF_TIME,
Money.of(USD, 0),
clock.nowUtc().minusDays(1),
Money.of(USD, 100),
clock.nowUtc().plusDays(1),
Money.of(USD, 0)))
.build());
setEapForTld("tld");
doSuccessfulTest(
"tld", "domain_create_response_eap_fee.xml", ImmutableMap.of("FEE_VERSION", "0.6"));
}
@ -2472,18 +2401,7 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
"DESCRIPTION_2",
"Early Access Period"));
persistContactsAndHosts();
persistResource(
Registry.get("tld")
.asBuilder()
.setEapFeeSchedule(
ImmutableSortedMap.of(
START_OF_TIME,
Money.of(USD, 0),
clock.nowUtc().minusDays(1),
Money.of(USD, 100),
clock.nowUtc().plusDays(1),
Money.of(USD, 0)))
.build());
setEapForTld("tld");
doSuccessfulTest(
"tld", "domain_create_response_eap_fee.xml", ImmutableMap.of("FEE_VERSION", "0.11"));
}
@ -2500,18 +2418,7 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
"DESCRIPTION_2",
"Early Access Period"));
persistContactsAndHosts();
persistResource(
Registry.get("tld")
.asBuilder()
.setEapFeeSchedule(
ImmutableSortedMap.of(
START_OF_TIME,
Money.of(USD, 0),
clock.nowUtc().minusDays(1),
Money.of(USD, 100),
clock.nowUtc().plusDays(1),
Money.of(USD, 0)))
.build());
setEapForTld("tld");
doSuccessfulTest(
"tld", "domain_create_response_eap_fee.xml", ImmutableMap.of("FEE_VERSION", "0.12"));
}
@ -2519,8 +2426,18 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
@Test
public void testFailure_domainInEap_failsWithoutFeeExtension() {
persistContactsAndHosts();
setEapForTld("tld");
Exception e = assertThrows(FeesRequiredDuringEarlyAccessProgramException.class, this::runFlow);
assertThat(e)
.hasMessageThat()
.isEqualTo(
"Fees must be explicitly acknowledged when creating domains "
+ "during the Early Access Program. The EAP fee is: USD 100.00");
}
private void setEapForTld(String tld) {
persistResource(
Registry.get("tld")
Registry.get(tld)
.asBuilder()
.setEapFeeSchedule(
ImmutableSortedMap.of(
@ -2531,12 +2448,6 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
clock.nowUtc().plusDays(1),
Money.of(USD, 0)))
.build());
Exception e = assertThrows(FeesRequiredDuringEarlyAccessProgramException.class, this::runFlow);
assertThat(e)
.hasMessageThat()
.isEqualTo(
"Fees must be explicitly acknowledged when creating domains "
+ "during the Early Access Program. The EAP fee is: USD 100.00");
}
@Test
@ -2630,6 +2541,5 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
runFlow();
EppMetric eppMetric = getEppMetric();
assertThat(eppMetric.getCommandName()).hasValue("DomainCreate");
assertThat(eppMetric.getAttempts()).isEqualTo(1);
}
}

View file

@ -48,10 +48,12 @@ public class AllocationTokenTest extends EntityTestCase {
persistResource(
new AllocationToken.Builder()
.setToken("abc123")
.setRedemptionHistoryEntry(Key.create(HistoryEntry.class, 1L))
.setDomainName("blahdomain.fake")
.setCreationTimeForTest(DateTime.parse("2010-11-12T05:00:00Z"))
.build()),
"token",
"redemptionHistoryEntry",
"domainName");
}

View file

@ -21,6 +21,7 @@ enum google.registry.model.billing.BillingEvent$Flag {
ANCHOR_TENANT;
AUTO_RENEW;
LANDRUSH;
RESERVED;
SUNRISE;
SYNTHETIC;
}

View file

@ -26,12 +26,10 @@ import com.googlecode.objectify.Key;
import google.registry.model.tmch.ClaimsListShard.ClaimsListRevision;
import google.registry.model.tmch.ClaimsListShard.UnshardedSaveException;
import google.registry.testing.AppEngineRule;
import google.registry.testing.InjectRule;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -46,13 +44,7 @@ public class ClaimsListShardTest {
.withDatastore()
.build();
@Rule
public final InjectRule inject = new InjectRule();
@Before
public void before() {
inject.setStaticField(ClaimsListShard.class, "shardSize", 10);
}
private final int shardSize = 10;
@Test
public void test_unshardedSaveFails() {
@ -81,13 +73,13 @@ public class ClaimsListShardTest {
public void test_savesAndGets_withSharding() {
// Create a ClaimsList that will need 4 shards to save.
Map<String, String> labelsToKeys = new HashMap<>();
for (int i = 0; i <= ClaimsListShard.shardSize * 3; i++) {
for (int i = 0; i <= shardSize * 3; i++) {
labelsToKeys.put(Integer.toString(i), Integer.toString(i));
}
DateTime now = DateTime.now(UTC);
// Save it with sharding, and make sure that reloading it works.
ClaimsListShard unsharded = ClaimsListShard.create(now, ImmutableMap.copyOf(labelsToKeys));
unsharded.save();
unsharded.save(shardSize);
assertThat(ClaimsListShard.get().labelsToKeys).isEqualTo(unsharded.labelsToKeys);
List<ClaimsListShard> shards1 = ofy().load().type(ClaimsListShard.class).list();
assertThat(shards1).hasSize(4);
@ -97,11 +89,11 @@ public class ClaimsListShardTest {
// Create a smaller ClaimsList that will need only 2 shards to save.
labelsToKeys = new HashMap<>();
for (int i = 0; i <= ClaimsListShard.shardSize; i++) {
for (int i = 0; i <= shardSize; i++) {
labelsToKeys.put(Integer.toString(i), Integer.toString(i));
}
unsharded = ClaimsListShard.create(now.plusDays(1), ImmutableMap.copyOf(labelsToKeys));
unsharded.save();
unsharded.save(shardSize);
ofy().clearSessionCache();
assertThat(ClaimsListShard.get().labelsToKeys).hasSize(unsharded.labelsToKeys.size());
assertThat(ClaimsListShard.get().labelsToKeys).isEqualTo(unsharded.labelsToKeys);

View file

@ -26,7 +26,6 @@ PATH CLASS METHOD
/_dr/task/importRdeHosts RdeHostImportAction GET n INTERNAL APP IGNORED
/_dr/task/linkRdeHosts RdeHostLinkAction GET n INTERNAL APP IGNORED
/_dr/task/loadSnapshot LoadSnapshotAction POST n INTERNAL APP IGNORED
/_dr/task/metrics MetricsExportAction POST n INTERNAL APP IGNORED
/_dr/task/nordnUpload NordnUploadAction POST y INTERNAL APP IGNORED
/_dr/task/nordnVerify NordnVerifyAction POST y INTERNAL APP IGNORED
/_dr/task/pollBigqueryJob BigqueryPollJobAction GET,POST y INTERNAL APP IGNORED

View file

@ -1,111 +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.monitoring.whitebox;
import static com.google.appengine.api.taskqueue.QueueFactory.getQueue;
import static google.registry.bigquery.BigqueryUtils.toBigqueryTimestamp;
import static google.registry.monitoring.whitebox.BigQueryMetricsEnqueuer.QUEUE_BIGQUERY_STREAMING_METRICS;
import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
import static org.mockito.Mockito.when;
import com.google.api.services.bigquery.model.TableFieldSchema;
import com.google.auto.value.AutoValue;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import google.registry.testing.AppEngineRule;
import google.registry.testing.MockitoJUnitRule;
import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.util.AppEngineServiceUtils;
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.mockito.Mock;
/** Unit tests for {@link BigQueryMetricsEnqueuer}. */
@RunWith(JUnit4.class)
public class BigQueryMetricsEnqueuerTest {
@Rule
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastore().withLocalModules().withTaskQueue().build();
@Rule public final MockitoJUnitRule mocks = MockitoJUnitRule.create();
@Mock private AppEngineServiceUtils appEngineServiceUtils;
private BigQueryMetricsEnqueuer enqueuer;
@Before
public void setUp() {
enqueuer = new BigQueryMetricsEnqueuer();
enqueuer.idGenerator = Suppliers.ofInstance("laffo");
enqueuer.appEngineServiceUtils = appEngineServiceUtils;
enqueuer.queue = getQueue(QUEUE_BIGQUERY_STREAMING_METRICS);
when(appEngineServiceUtils.getCurrentVersionHostname("backend"))
.thenReturn("backend.test.localhost");
}
@Test
public void testExport() {
TestMetric metric =
TestMetric.create(
DateTime.parse("1984-12-18TZ"), DateTime.parse("1984-12-18TZ").plusMillis(1));
enqueuer.export(metric);
assertTasksEnqueued("bigquery-streaming-metrics",
new TaskMatcher()
.url("/_dr/task/metrics")
.header("Host", "backend.test.localhost")
.param("tableId", "test")
.param("startTime", "472176000.000000")
.param("endTime", "472176000.001000")
.param("insertId", "laffo"));
}
/** A stub implementation of {@link BigQueryMetric}. */
@AutoValue
abstract static class TestMetric implements BigQueryMetric {
static TestMetric create(DateTime startTimestamp, DateTime endTimestamp) {
return new AutoValue_BigQueryMetricsEnqueuerTest_TestMetric(startTimestamp, endTimestamp);
}
@Override
public String getTableId() {
return "test";
}
@Override
public ImmutableList<TableFieldSchema> getSchemaFields() {
return null;
}
@Override
public ImmutableMap<String, String> getBigQueryRowEncoding() {
return ImmutableMap.of(
"startTime", toBigqueryTimestamp(getStartTimestamp()),
"endTime", toBigqueryTimestamp(getEndTimestamp()));
}
abstract DateTime getStartTimestamp();
abstract DateTime getEndTimestamp();
}
}

View file

@ -14,18 +14,13 @@
package google.registry.monitoring.whitebox;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.createTlds;
import com.google.api.services.bigquery.model.TableFieldSchema;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import google.registry.model.eppoutput.Result.Code;
import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock;
import org.joda.time.DateTime;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -40,7 +35,7 @@ public class EppMetricTest {
@Test
public void test_invalidTld_isRecordedAsInvalid() {
EppMetric metric =
EppMetric.builderForRequest("request-id-1", new FakeClock())
EppMetric.builderForRequest(new FakeClock())
.setTlds(ImmutableSet.of("notarealtld"))
.build();
assertThat(metric.getTld()).hasValue("_invalid");
@ -50,9 +45,7 @@ public class EppMetricTest {
public void test_validTld_isRecorded() {
createTld("example");
EppMetric metric =
EppMetric.builderForRequest("request-id-1", new FakeClock())
.setTlds(ImmutableSet.of("example"))
.build();
EppMetric.builderForRequest(new FakeClock()).setTlds(ImmutableSet.of("example")).build();
assertThat(metric.getTld()).hasValue("example");
}
@ -60,7 +53,7 @@ public class EppMetricTest {
public void test_multipleTlds_areRecordedAsVarious() {
createTlds("foo", "bar");
EppMetric metric =
EppMetric.builderForRequest("request-id-1", new FakeClock())
EppMetric.builderForRequest(new FakeClock())
.setTlds(ImmutableSet.of("foo", "bar", "baz"))
.build();
assertThat(metric.getTld()).hasValue("_various");
@ -69,64 +62,7 @@ public class EppMetricTest {
@Test
public void test_zeroTlds_areRecordedAsAbsent() {
EppMetric metric =
EppMetric.builderForRequest("request-id-1", new FakeClock())
.setTlds(ImmutableSet.of())
.build();
EppMetric.builderForRequest(new FakeClock()).setTlds(ImmutableSet.of()).build();
assertThat(metric.getTld()).isEmpty();
}
@Test
public void testGetBigQueryRowEncoding_encodesCorrectly() {
EppMetric metric =
EppMetric.builder()
.setRequestId("request-id-1")
.setStartTimestamp(new DateTime(1337))
.setEndTimestamp(new DateTime(1338))
.setCommandName("command")
.setClientId("client")
.setTld("example")
.setPrivilegeLevel("level")
.setEppTarget("target")
.setStatus(Code.COMMAND_USE_ERROR)
.incrementAttempts()
.build();
assertThat(metric.getBigQueryRowEncoding())
.containsExactlyEntriesIn(
new ImmutableMap.Builder<String, String>()
.put("requestId", "request-id-1")
.put("startTime", "1.337000")
.put("endTime", "1.338000")
.put("commandName", "command")
.put("clientId", "client")
.put("tld", "example")
.put("privilegeLevel", "level")
.put("eppTarget", "target")
.put("eppStatus", "2002")
.put("attempts", "1")
.build());
}
@Test
public void testGetBigQueryRowEncoding_hasAllSchemaFields() {
EppMetric metric =
EppMetric.builder()
.setRequestId("request-id-1")
.setStartTimestamp(new DateTime(1337))
.setEndTimestamp(new DateTime(1338))
.setCommandName("command")
.setClientId("client")
.setTld("example")
.setPrivilegeLevel("level")
.setEppTarget("target")
.setStatus(Code.COMMAND_USE_ERROR)
.incrementAttempts()
.build();
ImmutableSet.Builder<String> schemaFieldNames = new ImmutableSet.Builder<>();
for (TableFieldSchema schemaField : metric.getSchemaFields()) {
schemaFieldNames.add(schemaField.getName());
}
assertThat(metric.getBigQueryRowEncoding().keySet()).isEqualTo(schemaFieldNames.build());
}
}

View file

@ -1,108 +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.monitoring.whitebox;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.api.services.bigquery.Bigquery;
import com.google.api.services.bigquery.Bigquery.Tabledata;
import com.google.api.services.bigquery.Bigquery.Tabledata.InsertAll;
import com.google.api.services.bigquery.model.TableDataInsertAllRequest;
import com.google.api.services.bigquery.model.TableDataInsertAllResponse;
import com.google.api.services.bigquery.model.TableDataInsertAllResponse.InsertErrors;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import google.registry.bigquery.CheckedBigquery;
import google.registry.testing.AppEngineRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Matchers;
/** Unit tests for {@link MetricsExportAction}. */
@RunWith(JUnit4.class)
public class MetricsExportActionTest {
@Rule
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastore().withTaskQueue().build();
private final CheckedBigquery checkedBigquery = mock(CheckedBigquery.class);
private final Bigquery bigquery = mock(Bigquery.class);
private final Tabledata tabledata = mock(Tabledata.class);
private final InsertAll insertAll = mock(InsertAll.class);
private TableDataInsertAllResponse response = new TableDataInsertAllResponse();
private long currentTimeMillis = 1000000000000L;
private ImmutableListMultimap<String, String> parameters =
new ImmutableListMultimap.Builder<String, String>()
.put("startTime", String.valueOf(MILLISECONDS.toSeconds(currentTimeMillis - 100)))
.put("endTime", String.valueOf(MILLISECONDS.toSeconds(currentTimeMillis)))
.put("jobname", "test job")
.put("status", "success")
.put("tld", "test")
.build();
MetricsExportAction action;
@Before
public void setup() throws Exception {
when(checkedBigquery.ensureDataSetAndTableExist(anyString(), anyString(), anyString()))
.thenReturn(bigquery);
when(bigquery.tabledata()).thenReturn(tabledata);
when(tabledata.insertAll(
anyString(),
anyString(),
anyString(),
Matchers.any(TableDataInsertAllRequest.class))).thenReturn(insertAll);
action = new MetricsExportAction();
action.checkedBigquery = checkedBigquery;
action.insertId = "insert id";
action.parameters = parameters;
action.projectId = "project id";
action.tableId = "eppMetrics";
}
@Test
public void testSuccess_nullErrors() throws Exception {
when(insertAll.execute()).thenReturn(response);
response.setInsertErrors(null);
action.run();
verify(insertAll).execute();
}
@Test
public void testSuccess_emptyErrors() throws Exception {
when(insertAll.execute()).thenReturn(response);
response.setInsertErrors(ImmutableList.of());
action.run();
verify(insertAll).execute();
}
@Test
public void testFailure_errors() throws Exception {
when(insertAll.execute()).thenReturn(response);
response.setInsertErrors(ImmutableList.of(new InsertErrors()));
action.run();
}
}

View file

@ -109,7 +109,11 @@ public class EppQuotaHandlerTest {
.thenReturn(QuotaResponse.create(false, clientCertHash, now));
OverQuotaException e =
assertThrows(OverQuotaException.class, () -> channel.writeInbound(message));
ChannelFuture unusedFuture = channel.close();
assertThat(e).hasMessageThat().contains(clientCertHash);
verify(quotaManager).acquireQuota(QuotaRequest.create(clientCertHash));
// Make sure that quotaManager.releaseQuota() is not called when the channel closes.
verifyNoMoreInteractions(quotaManager);
verify(metrics).registerQuotaRejection("epp", clientCertHash);
verifyNoMoreInteractions(metrics);
}

View file

@ -17,62 +17,37 @@ package google.registry.rdap;
import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.request.Action.Method.GET;
import static google.registry.request.Action.Method.HEAD;
import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.TestDataHelper.loadFile;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import com.google.appengine.api.users.User;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import google.registry.model.ofy.Ofy;
import google.registry.rdap.RdapJsonFormatter.BoilerplateType;
import google.registry.rdap.RdapMetrics.EndpointType;
import google.registry.rdap.RdapMetrics.SearchType;
import google.registry.rdap.RdapMetrics.WildcardType;
import google.registry.rdap.RdapSearchResults.IncompletenessWarningType;
import google.registry.request.Action;
import google.registry.request.auth.AuthLevel;
import google.registry.request.auth.AuthResult;
import google.registry.request.auth.UserAuthInfo;
import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock;
import google.registry.testing.FakeResponse;
import google.registry.testing.InjectRule;
import google.registry.ui.server.registrar.SessionUtils;
import java.util.Optional;
import org.joda.time.DateTime;
import org.json.simple.JSONValue;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RdapActionBase}. */
@RunWith(JUnit4.class)
public class RdapActionBaseTest {
public class RdapActionBaseTest extends RdapActionBaseTestCase<RdapActionBaseTest.RdapTestAction> {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore()
.build();
@Rule
public final InjectRule inject = new InjectRule();
private final FakeResponse response = new FakeResponse();
private final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01TZ"));
private final SessionUtils sessionUtils = mock(SessionUtils.class);
private final User user = new User("rdap.user@example.com", "gmail.com", "12345");
private final UserAuthInfo userAuthInfo = UserAuthInfo.create(user, false);
private final RdapMetrics rdapMetrics = mock(RdapMetrics.class);
public RdapActionBaseTest() {
super(RdapTestAction.class, RdapTestAction.PATH);
}
/**
* Dummy RdapActionBase subclass used for testing.
*/
static class RdapTestAction extends RdapActionBase {
public static class RdapTestAction extends RdapActionBase {
public static final String PATH = "/rdap/test/";
@ -112,37 +87,10 @@ public class RdapActionBaseTest {
}
}
private RdapTestAction action;
@Before
public void setUp() {
createTld("thing");
inject.setStaticField(Ofy.class, "clock", clock);
action = new RdapTestAction();
action.sessionUtils = sessionUtils;
action.authResult = AuthResult.create(AuthLevel.USER, userAuthInfo);
action.includeDeletedParam = Optional.empty();
action.registrarParam = Optional.empty();
action.formatOutputParam = Optional.empty();
action.response = response;
action.rdapJsonFormatter = RdapTestHelper.getTestRdapJsonFormatter();
action.rdapMetrics = rdapMetrics;
}
private Object generateActualJson(String domainName) {
action.requestPath = RdapTestAction.PATH + domainName;
action.fullServletPath = "http://myserver.example.com" + RdapTestAction.PATH;
action.requestMethod = GET;
action.run();
return JSONValue.parse(response.getPayload());
}
private String generateHeadPayload(String domainName) {
action.requestPath = RdapTestAction.PATH + domainName;
action.fullServletPath = "http://myserver.example.com" + RdapTestAction.PATH;
action.requestMethod = HEAD;
action.run();
return response.getPayload();
}
@Test
@ -241,7 +189,6 @@ public class RdapActionBaseTest {
@Test
public void testUnformatted() {
action.requestPath = RdapTestAction.PATH + "no.thing";
action.fullServletPath = "http://myserver.example.com" + RdapTestAction.PATH;
action.requestMethod = GET;
action.run();
assertThat(response.getPayload())
@ -251,7 +198,6 @@ public class RdapActionBaseTest {
@Test
public void testFormatted() {
action.requestPath = RdapTestAction.PATH + "no.thing?formatOutput=true";
action.fullServletPath = "http://myserver.example.com" + RdapTestAction.PATH;
action.requestMethod = GET;
action.formatOutputParam = Optional.of(true);
action.run();

View file

@ -0,0 +1,142 @@
// Copyright 2018 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.rdap;
import static google.registry.rdap.RdapAuthorization.Role.ADMINISTRATOR;
import static google.registry.rdap.RdapAuthorization.Role.PUBLIC;
import static google.registry.rdap.RdapAuthorization.Role.REGISTRAR;
import static google.registry.request.Action.Method.GET;
import static google.registry.request.Action.Method.HEAD;
import static google.registry.ui.server.registrar.AuthenticatedRegistrarAccessor.Role.OWNER;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.appengine.api.users.User;
import com.google.common.collect.ImmutableSetMultimap;
import google.registry.model.ofy.Ofy;
import google.registry.request.Action;
import google.registry.request.auth.AuthLevel;
import google.registry.request.auth.AuthResult;
import google.registry.request.auth.UserAuthInfo;
import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock;
import google.registry.testing.FakeResponse;
import google.registry.testing.InjectRule;
import google.registry.ui.server.registrar.AuthenticatedRegistrarAccessor;
import google.registry.util.TypeUtils;
import java.util.Optional;
import org.joda.time.DateTime;
import org.json.simple.JSONValue;
import org.junit.Before;
import org.junit.Rule;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Common unit test code for actions inheriting {@link RdapActionBase}. */
@RunWith(JUnit4.class)
public class RdapActionBaseTestCase<A extends RdapActionBase> {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore()
.build();
@Rule
public final InjectRule inject = new InjectRule();
protected static final AuthResult AUTH_RESULT =
AuthResult.create(
AuthLevel.USER,
UserAuthInfo.create(new User("rdap.user@user.com", "gmail.com", "12345"), false));
protected static final AuthResult AUTH_RESULT_ADMIN =
AuthResult.create(
AuthLevel.USER,
UserAuthInfo.create(new User("rdap.admin@google.com", "gmail.com", "12345"), true));
protected final AuthenticatedRegistrarAccessor registrarAccessor =
mock(AuthenticatedRegistrarAccessor.class);
protected FakeResponse response = new FakeResponse();
protected final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01TZ"));
protected final RdapMetrics rdapMetrics = mock(RdapMetrics.class);
protected RdapAuthorization.Role metricRole = PUBLIC;
protected A action;
protected final String actionPath;
protected final Class<A> rdapActionClass;
protected RdapActionBaseTestCase(Class<A> rdapActionClass, String actionPath) {
this.rdapActionClass = rdapActionClass;
this.actionPath = actionPath;
}
@Before
public void baseSetUp() {
inject.setStaticField(Ofy.class, "clock", clock);
action = TypeUtils.instantiate(rdapActionClass);
action.registrarAccessor = registrarAccessor;
action.clock = clock;
action.authResult = AUTH_RESULT;
action.includeDeletedParam = Optional.empty();
action.registrarParam = Optional.empty();
action.formatOutputParam = Optional.empty();
action.response = response;
action.rdapJsonFormatter = RdapTestHelper.getTestRdapJsonFormatter();
action.rdapMetrics = rdapMetrics;
action.requestMethod = Action.Method.GET;
action.fullServletPath = "https://example.tld/rdap";
action.rdapWhoisServer = null;
logout();
}
protected void login(String clientId) {
when(registrarAccessor.getAllClientIdWithRoles())
.thenReturn(ImmutableSetMultimap.of(clientId, OWNER));
action.authResult = AUTH_RESULT;
metricRole = REGISTRAR;
}
protected void logout() {
when(registrarAccessor.getAllClientIdWithRoles()).thenReturn(ImmutableSetMultimap.of());
action.authResult = AUTH_RESULT;
metricRole = PUBLIC;
}
protected void loginAsAdmin() {
// when admin, we don't actually check what they have access to - so it doesn't matter what we
// return.
// null isn't actually a legal value, we just want to make sure it's never actually used.
when(registrarAccessor.getAllClientIdWithRoles()).thenReturn(null);
action.authResult = AUTH_RESULT_ADMIN;
metricRole = ADMINISTRATOR;
}
protected Object generateActualJson(String domainName) {
action.requestPath = actionPath + domainName;
action.requestMethod = GET;
action.run();
return JSONValue.parse(response.getPayload());
}
protected String generateHeadPayload(String domainName) {
action.requestPath = actionPath + domainName;
action.fullServletPath = "http://myserver.example.com" + actionPath;
action.requestMethod = HEAD;
action.run();
return response.getPayload();
}
}

View file

@ -25,11 +25,8 @@ import static google.registry.testing.FullFieldsTestEntityHelper.makeHistoryEntr
import static google.registry.testing.FullFieldsTestEntityHelper.makeRegistrar;
import static google.registry.testing.FullFieldsTestEntityHelper.makeRegistrarContacts;
import static google.registry.testing.TestDataHelper.loadFile;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.appengine.api.users.User;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
@ -37,7 +34,6 @@ import google.registry.model.contact.ContactResource;
import google.registry.model.domain.DomainBase;
import google.registry.model.domain.Period;
import google.registry.model.host.HostResource;
import google.registry.model.ofy.Ofy;
import google.registry.model.registrar.Registrar;
import google.registry.model.registry.Registry;
import google.registry.model.reporting.HistoryEntry;
@ -46,55 +42,28 @@ import google.registry.rdap.RdapMetrics.SearchType;
import google.registry.rdap.RdapMetrics.WildcardType;
import google.registry.rdap.RdapSearchResults.IncompletenessWarningType;
import google.registry.request.Action;
import google.registry.request.auth.AuthLevel;
import google.registry.request.auth.AuthResult;
import google.registry.request.auth.UserAuthInfo;
import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock;
import google.registry.testing.FakeResponse;
import google.registry.testing.InjectRule;
import google.registry.ui.server.registrar.SessionUtils;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import org.joda.time.DateTime;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RdapDomainAction}. */
@RunWith(JUnit4.class)
public class RdapDomainActionTest {
public class RdapDomainActionTest extends RdapActionBaseTestCase<RdapDomainAction> {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore()
.build();
@Rule
public final InjectRule inject = new InjectRule();
private final HttpServletRequest request = mock(HttpServletRequest.class);
private final FakeResponse response = new FakeResponse();
private final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01TZ"));
private final SessionUtils sessionUtils = mock(SessionUtils.class);
private final User user = new User("rdap.user@example.com", "gmail.com", "12345");
private final UserAuthInfo userAuthInfo = UserAuthInfo.create(user, false);
private final UserAuthInfo adminUserAuthInfo = UserAuthInfo.create(user, true);
private final RdapMetrics rdapMetrics = mock(RdapMetrics.class);
private RdapDomainAction action;
public RdapDomainActionTest() {
super(RdapDomainAction.class, RdapDomainAction.PATH);
}
@Before
public void setUp() {
inject.setStaticField(Ofy.class, "clock", clock);
// lol
createTld("lol");
Registrar registrarLol = persistResource(makeRegistrar(
@ -259,38 +228,6 @@ public class RdapDomainActionTest {
Period.create(1, Period.Unit.YEARS),
"deleted",
clock.nowUtc().minusMonths(6)));
action = new RdapDomainAction();
action.clock = clock;
action.request = request;
action.requestMethod = Action.Method.GET;
action.fullServletPath = "https://example.com/rdap";
action.response = response;
action.registrarParam = Optional.empty();
action.includeDeletedParam = Optional.empty();
action.formatOutputParam = Optional.empty();
action.rdapJsonFormatter = RdapTestHelper.getTestRdapJsonFormatter();
action.rdapWhoisServer = null;
action.sessionUtils = sessionUtils;
action.authResult = AuthResult.create(AuthLevel.USER, userAuthInfo);
action.rdapMetrics = rdapMetrics;
}
private void login(String clientId) {
when(sessionUtils.checkRegistrarConsoleLogin(request, userAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn(clientId);
}
private void loginAsAdmin() {
when(sessionUtils.checkRegistrarConsoleLogin(request, adminUserAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn("irrelevant");
action.authResult = AuthResult.create(AuthLevel.USER, adminUserAuthInfo);
}
private Object generateActualJson(String domainName) {
action.requestPath = RdapDomainAction.PATH + domainName;
action.run();
return JSONValue.parse(response.getPayload());
}
private Object generateExpectedJson(
@ -397,7 +334,7 @@ public class RdapDomainActionTest {
builder,
false,
RdapTestHelper.createNotices(
"https://example.com/rdap/",
"https://example.tld/rdap/",
(contactRoids == null)
? RdapTestHelper.ContactNoticeType.DOMAIN
: RdapTestHelper.ContactNoticeType.NONE,

View file

@ -16,8 +16,6 @@ package google.registry.rdap;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.rdap.RdapAuthorization.Role.ADMINISTRATOR;
import static google.registry.rdap.RdapAuthorization.Role.REGISTRAR;
import static google.registry.request.Action.Method.POST;
import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistDomainAsDeleted;
@ -31,10 +29,7 @@ import static google.registry.testing.FullFieldsTestEntityHelper.makeHistoryEntr
import static google.registry.testing.FullFieldsTestEntityHelper.makeRegistrar;
import static google.registry.testing.FullFieldsTestEntityHelper.makeRegistrarContacts;
import static google.registry.testing.TestDataHelper.loadFile;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.appengine.api.users.User;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
@ -46,7 +41,6 @@ import google.registry.model.contact.ContactResource;
import google.registry.model.domain.DomainResource;
import google.registry.model.domain.Period;
import google.registry.model.host.HostResource;
import google.registry.model.ofy.Ofy;
import google.registry.model.registrar.Registrar;
import google.registry.model.registry.Registry;
import google.registry.model.reporting.HistoryEntry;
@ -54,15 +48,7 @@ import google.registry.rdap.RdapMetrics.EndpointType;
import google.registry.rdap.RdapMetrics.SearchType;
import google.registry.rdap.RdapMetrics.WildcardType;
import google.registry.rdap.RdapSearchResults.IncompletenessWarningType;
import google.registry.request.Action;
import google.registry.request.auth.AuthLevel;
import google.registry.request.auth.AuthResult;
import google.registry.request.auth.UserAuthInfo;
import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock;
import google.registry.testing.FakeResponse;
import google.registry.testing.InjectRule;
import google.registry.ui.server.registrar.SessionUtils;
import google.registry.util.Idn;
import java.net.IDN;
import java.net.URLDecoder;
@ -71,35 +57,22 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import org.joda.time.DateTime;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RdapDomainSearchAction}. */
@RunWith(JUnit4.class)
public class RdapDomainSearchActionTest extends RdapSearchActionTestCase {
public class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDomainSearchAction> {
@Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build();
@Rule public final InjectRule inject = new InjectRule();
private final HttpServletRequest request = mock(HttpServletRequest.class);
private final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01T00:00:00Z"));
private final SessionUtils sessionUtils = mock(SessionUtils.class);
private final User user = new User("rdap.user@example.com", "gmail.com", "12345");
private final UserAuthInfo userAuthInfo = UserAuthInfo.create(user, false);
private final UserAuthInfo adminUserAuthInfo = UserAuthInfo.create(user, true);
private final RdapDomainSearchAction action = new RdapDomainSearchAction();
private FakeResponse response = new FakeResponse();
public RdapDomainSearchActionTest() {
super(RdapDomainSearchAction.class, RdapDomainSearchAction.PATH);
}
private Registrar registrar;
private DomainResource domainCatLol;
@ -124,6 +97,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase {
private Object generateActualJson(
RequestType requestType, String paramValue, String cursor) {
action.requestPath = RdapDomainSearchAction.PATH;
action.requestMethod = POST;
String requestTypeParam = null;
switch (requestType) {
case NAME:
@ -173,7 +147,6 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase {
@Before
public void setUp() {
RdapDomainSearchAction.maxNameserversInFirstStage = 40;
inject.setStaticField(Ofy.class, "clock", clock);
// cat.lol and cat2.lol
createTld("lol");
@ -387,37 +360,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase {
"created",
clock.nowUtc()));
action.clock = clock;
action.request = request;
action.requestMethod = Action.Method.GET;
action.fullServletPath = "https://example.com/rdap";
action.requestUrl = "https://example.com/rdap/domains";
action.parameterMap = ImmutableListMultimap.of();
action.requestMethod = POST;
action.response = response;
action.registrarParam = Optional.empty();
action.includeDeletedParam = Optional.empty();
action.formatOutputParam = Optional.empty();
action.rdapJsonFormatter = RdapTestHelper.getTestRdapJsonFormatter();
action.rdapWhoisServer = null;
action.sessionUtils = sessionUtils;
action.authResult = AuthResult.create(AuthLevel.USER, userAuthInfo);
action.rdapMetrics = rdapMetrics;
action.cursorTokenParam = Optional.empty();
action.rdapResultSetMaxSize = 4;
}
private void login(String clientId) {
when(sessionUtils.checkRegistrarConsoleLogin(request, userAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn(clientId);
metricRole = REGISTRAR;
}
private void loginAsAdmin() {
when(sessionUtils.checkRegistrarConsoleLogin(request, adminUserAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn("irrelevant");
action.authResult = AuthResult.create(AuthLevel.USER, adminUserAuthInfo);
metricRole = ADMINISTRATOR;
}
private Object generateExpectedJsonForTwoDomains() {
@ -558,7 +501,7 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase {
builder.put("domainSearchResults", ImmutableList.of(obj));
builder.put("rdapConformance", ImmutableList.of("rdap_level_0"));
RdapTestHelper.addDomainBoilerplateNotices(
builder, RdapTestHelper.createNotices("https://example.com/rdap/"));
builder, RdapTestHelper.createNotices("https://example.tld/rdap/"));
return new JSONObject(builder.build());
}

View file

@ -25,65 +25,35 @@ import static google.registry.testing.FullFieldsTestEntityHelper.makeHostResourc
import static google.registry.testing.FullFieldsTestEntityHelper.makeRegistrar;
import static google.registry.testing.FullFieldsTestEntityHelper.makeRegistrarContacts;
import static google.registry.testing.TestDataHelper.loadFile;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.appengine.api.users.User;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import google.registry.model.contact.ContactResource;
import google.registry.model.host.HostResource;
import google.registry.model.ofy.Ofy;
import google.registry.model.registrar.Registrar;
import google.registry.rdap.RdapMetrics.EndpointType;
import google.registry.rdap.RdapMetrics.SearchType;
import google.registry.rdap.RdapMetrics.WildcardType;
import google.registry.rdap.RdapSearchResults.IncompletenessWarningType;
import google.registry.request.Action;
import google.registry.request.auth.AuthLevel;
import google.registry.request.auth.AuthResult;
import google.registry.request.auth.UserAuthInfo;
import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock;
import google.registry.testing.FakeResponse;
import google.registry.testing.InjectRule;
import google.registry.ui.server.registrar.SessionUtils;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import org.joda.time.DateTime;
import org.json.simple.JSONValue;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RdapEntityAction}. */
@RunWith(JUnit4.class)
public class RdapEntityActionTest {
public class RdapEntityActionTest extends RdapActionBaseTestCase<RdapEntityAction> {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore()
.build();
@Rule
public final InjectRule inject = new InjectRule();
private final HttpServletRequest request = mock(HttpServletRequest.class);
private final FakeResponse response = new FakeResponse();
private final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01TZ"));
private final SessionUtils sessionUtils = mock(SessionUtils.class);
private final User user = new User("rdap.user@example.com", "gmail.com", "12345");
private final UserAuthInfo userAuthInfo = UserAuthInfo.create(user, false);
private final UserAuthInfo adminUserAuthInfo = UserAuthInfo.create(user, true);
private final RdapMetrics rdapMetrics = mock(RdapMetrics.class);
private RdapEntityAction action;
public RdapEntityActionTest() {
super(RdapEntityAction.class, RdapEntityAction.PATH);
}
private Registrar registrarLol;
private ContactResource registrant;
@ -94,7 +64,6 @@ public class RdapEntityActionTest {
@Before
public void setUp() {
inject.setStaticField(Ofy.class, "clock", clock);
// lol
createTld("lol");
registrarLol = persistResource(makeRegistrar(
@ -161,37 +130,6 @@ public class RdapEntityActionTest {
clock.nowUtc().minusYears(1),
registrarLol,
clock.nowUtc().minusMonths(6));
action = new RdapEntityAction();
action.clock = clock;
action.request = request;
action.requestMethod = Action.Method.GET;
action.fullServletPath = "https://example.com/rdap";
action.response = response;
action.registrarParam = Optional.empty();
action.includeDeletedParam = Optional.empty();
action.formatOutputParam = Optional.empty();
action.rdapJsonFormatter = RdapTestHelper.getTestRdapJsonFormatter();
action.rdapWhoisServer = null;
action.sessionUtils = sessionUtils;
action.authResult = AuthResult.create(AuthLevel.USER, userAuthInfo);
action.rdapMetrics = rdapMetrics;
}
private void login(String registrar) {
when(sessionUtils.checkRegistrarConsoleLogin(request, userAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn(registrar);
}
private void loginAsAdmin() {
action.authResult = AuthResult.create(AuthLevel.USER, adminUserAuthInfo);
when(sessionUtils.checkRegistrarConsoleLogin(request, adminUserAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn("irrelevant");
}
private Object generateActualJson(String name) {
action.requestPath = RdapEntityAction.PATH + name;
action.run();
return JSONValue.parse(response.getPayload());
}
private Object generateExpectedJson(String handle, String expectedOutputFile) {
@ -259,7 +197,7 @@ public class RdapEntityActionTest {
RdapTestHelper.addNonDomainBoilerplateNotices(
builder,
RdapTestHelper.createNotices(
"https://example.com/rdap/",
"https://example.tld/rdap/",
addNoPersonalDataRemark
? RdapTestHelper.ContactNoticeType.CONTACT
: RdapTestHelper.ContactNoticeType.NONE,

View file

@ -16,8 +16,6 @@ package google.registry.rdap;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.rdap.RdapAuthorization.Role.ADMINISTRATOR;
import static google.registry.rdap.RdapAuthorization.Role.REGISTRAR;
import static google.registry.request.Action.Method.GET;
import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistResource;
@ -30,68 +28,44 @@ import static google.registry.testing.FullFieldsTestEntityHelper.makeHistoryEntr
import static google.registry.testing.FullFieldsTestEntityHelper.makeRegistrar;
import static google.registry.testing.FullFieldsTestEntityHelper.makeRegistrarContacts;
import static google.registry.testing.TestDataHelper.loadFile;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.appengine.api.users.User;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import google.registry.model.ImmutableObject;
import google.registry.model.contact.ContactResource;
import google.registry.model.ofy.Ofy;
import google.registry.model.registrar.Registrar;
import google.registry.model.reporting.HistoryEntry;
import google.registry.rdap.RdapMetrics.EndpointType;
import google.registry.rdap.RdapMetrics.SearchType;
import google.registry.rdap.RdapSearchResults.IncompletenessWarningType;
import google.registry.request.Action;
import google.registry.request.auth.AuthLevel;
import google.registry.request.auth.AuthResult;
import google.registry.request.auth.UserAuthInfo;
import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock;
import google.registry.testing.FakeResponse;
import google.registry.testing.InjectRule;
import google.registry.ui.server.registrar.SessionUtils;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import org.joda.time.DateTime;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RdapEntitySearchAction}. */
@RunWith(JUnit4.class)
public class RdapEntitySearchActionTest extends RdapSearchActionTestCase {
public class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEntitySearchAction> {
@Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build();
@Rule public final InjectRule inject = new InjectRule();
public RdapEntitySearchActionTest() {
super(RdapEntitySearchAction.class, RdapEntitySearchAction.PATH);
}
private enum QueryType {
FULL_NAME,
HANDLE
}
private final HttpServletRequest request = mock(HttpServletRequest.class);
private final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01T00:00:00Z"));
private final SessionUtils sessionUtils = mock(SessionUtils.class);
private final User user = new User("rdap.user@example.com", "gmail.com", "12345");
private final UserAuthInfo userAuthInfo = UserAuthInfo.create(user, false);
private final UserAuthInfo adminUserAuthInfo = UserAuthInfo.create(user, true);
private final RdapEntitySearchAction action = new RdapEntitySearchAction();
private FakeResponse response = new FakeResponse();
private Registrar registrarDeleted;
private Registrar registrarInactive;
private Registrar registrarTest;
@ -134,8 +108,6 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase {
@Before
public void setUp() {
inject.setStaticField(Ofy.class, "clock", clock);
createTld("tld");
// deleted
@ -181,40 +153,9 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase {
registrarDeleted,
clock.nowUtc().minusMonths(6));
action.clock = clock;
action.request = request;
action.requestMethod = Action.Method.GET;
action.fullServletPath = "https://example.com/rdap";
action.requestUrl = "https://example.com/rdap/entities";
action.requestPath = RdapEntitySearchAction.PATH;
action.parameterMap = ImmutableListMultimap.of();
action.response = response;
action.rdapJsonFormatter = RdapTestHelper.getTestRdapJsonFormatter();
action.rdapResultSetMaxSize = 4;
action.rdapWhoisServer = null;
action.fnParam = Optional.empty();
action.handleParam = Optional.empty();
action.subtypeParam = Optional.empty();
action.registrarParam = Optional.empty();
action.includeDeletedParam = Optional.empty();
action.formatOutputParam = Optional.empty();
action.sessionUtils = sessionUtils;
action.authResult = AuthResult.create(AuthLevel.USER, userAuthInfo);
action.rdapMetrics = rdapMetrics;
action.cursorTokenParam = Optional.empty();
}
private void login(String registrar) {
when(sessionUtils.checkRegistrarConsoleLogin(request, userAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn(registrar);
metricRole = REGISTRAR;
}
private void loginAsAdmin() {
action.authResult = AuthResult.create(AuthLevel.USER, adminUserAuthInfo);
when(sessionUtils.checkRegistrarConsoleLogin(request, adminUserAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn("noregistrar");
metricRole = ADMINISTRATOR;
}
private Object generateExpectedJson(String expectedOutputFile) {
@ -266,7 +207,7 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase {
builder.put("entitySearchResults", ImmutableList.of(obj));
builder.put("rdapConformance", ImmutableList.of("rdap_level_0"));
RdapTestHelper.addNonDomainBoilerplateNotices(
builder, RdapTestHelper.createNotices("https://example.com/rdap/"));
builder, RdapTestHelper.createNotices("https://example.tld/rdap/"));
return new JSONObject(builder.build());
}

View file

@ -16,72 +16,22 @@ package google.registry.rdap;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.TestDataHelper.loadFile;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import com.google.appengine.api.users.User;
import com.google.common.collect.ImmutableMap;
import google.registry.model.ofy.Ofy;
import google.registry.rdap.RdapMetrics.EndpointType;
import google.registry.rdap.RdapMetrics.SearchType;
import google.registry.rdap.RdapMetrics.WildcardType;
import google.registry.rdap.RdapSearchResults.IncompletenessWarningType;
import google.registry.request.Action;
import google.registry.request.auth.AuthLevel;
import google.registry.request.auth.AuthResult;
import google.registry.request.auth.UserAuthInfo;
import google.registry.testing.FakeClock;
import google.registry.testing.FakeResponse;
import google.registry.testing.InjectRule;
import google.registry.ui.server.registrar.SessionUtils;
import java.util.Optional;
import org.joda.time.DateTime;
import org.json.simple.JSONValue;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RdapHelpAction}. */
@RunWith(JUnit4.class)
public class RdapHelpActionTest {
public class RdapHelpActionTest extends RdapActionBaseTestCase<RdapHelpAction> {
@Rule
public final InjectRule inject = new InjectRule();
private final FakeResponse response = new FakeResponse();
private final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01TZ"));
private final SessionUtils sessionUtils = mock(SessionUtils.class);
private final User user = new User("rdap.user@example.com", "gmail.com", "12345");
private final UserAuthInfo userAuthInfo = UserAuthInfo.create(user, false);
private final RdapMetrics rdapMetrics = mock(RdapMetrics.class);
private RdapHelpAction action;
@Before
public void setUp() {
inject.setStaticField(Ofy.class, "clock", clock);
action = new RdapHelpAction();
action.clock = clock;
action.fullServletPath = "https://example.tld/rdap";
action.requestMethod = Action.Method.GET;
action.sessionUtils = sessionUtils;
action.authResult = AuthResult.create(AuthLevel.USER, userAuthInfo);
action.includeDeletedParam = Optional.empty();
action.registrarParam = Optional.empty();
action.formatOutputParam = Optional.empty();
action.response = response;
action.rdapJsonFormatter = RdapTestHelper.getTestRdapJsonFormatter();
action.rdapWhoisServer = null;
action.rdapMetrics = rdapMetrics;
}
private Object generateActualJson(String helpPath) {
action.requestPath = RdapHelpAction.PATH + helpPath;
action.run();
return JSONValue.parse(response.getPayload());
public RdapHelpActionTest() {
super(RdapHelpAction.class, RdapHelpAction.PATH);
}
private Object generateExpectedJson(String name, String expectedOutputFile) {

View file

@ -20,65 +20,36 @@ import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.FullFieldsTestEntityHelper.makeAndPersistHostResource;
import static google.registry.testing.FullFieldsTestEntityHelper.makeRegistrar;
import static google.registry.testing.TestDataHelper.loadFile;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.appengine.api.users.User;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import google.registry.model.ofy.Ofy;
import google.registry.model.registrar.Registrar;
import google.registry.rdap.RdapMetrics.EndpointType;
import google.registry.rdap.RdapMetrics.SearchType;
import google.registry.rdap.RdapMetrics.WildcardType;
import google.registry.rdap.RdapSearchResults.IncompletenessWarningType;
import google.registry.request.Action;
import google.registry.request.auth.AuthLevel;
import google.registry.request.auth.AuthResult;
import google.registry.request.auth.UserAuthInfo;
import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock;
import google.registry.testing.FakeResponse;
import google.registry.testing.InjectRule;
import google.registry.ui.server.registrar.SessionUtils;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import org.joda.time.DateTime;
import org.json.simple.JSONValue;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RdapNameserverAction}. */
@RunWith(JUnit4.class)
public class RdapNameserverActionTest {
public class RdapNameserverActionTest extends RdapActionBaseTestCase<RdapNameserverAction> {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore()
.build();
@Rule
public final InjectRule inject = new InjectRule();
private final HttpServletRequest request = mock(HttpServletRequest.class);
private final FakeResponse response = new FakeResponse();
private final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01TZ"));
private final SessionUtils sessionUtils = mock(SessionUtils.class);
private final User user = new User("rdap.user@example.com", "gmail.com", "12345");
private final UserAuthInfo userAuthInfo = UserAuthInfo.create(user, false);
private final UserAuthInfo adminUserAuthInfo = UserAuthInfo.create(user, true);
private final RdapMetrics rdapMetrics = mock(RdapMetrics.class);
public RdapNameserverActionTest() {
super(RdapNameserverAction.class, RdapNameserverAction.PATH);
}
@Before
public void setUp() {
inject.setStaticField(Ofy.class, "clock", clock);
// normal
createTld("lol");
makeAndPersistHostResource(
@ -104,45 +75,6 @@ public class RdapNameserverActionTest {
makeAndPersistHostResource("ns1.domain.external", "9.10.11.12", clock.nowUtc().minusYears(1));
}
private RdapNameserverAction newRdapNameserverAction(
String input, Optional<String> desiredRegistrar, Optional<Boolean> includeDeleted) {
return newRdapNameserverAction(
input, desiredRegistrar, includeDeleted, AuthResult.create(AuthLevel.USER, userAuthInfo));
}
private RdapNameserverAction newRdapNameserverAction(
String input,
Optional<String> desiredRegistrar,
Optional<Boolean> includeDeleted,
AuthResult authResult) {
RdapNameserverAction action = new RdapNameserverAction();
action.clock = clock;
action.request = request;
action.requestMethod = Action.Method.GET;
action.fullServletPath = "https://example.tld/rdap";
action.response = response;
action.requestPath = RdapNameserverAction.PATH.concat(input);
action.registrarParam = desiredRegistrar;
action.includeDeletedParam = includeDeleted;
action.formatOutputParam = Optional.empty();
action.rdapJsonFormatter = RdapTestHelper.getTestRdapJsonFormatter();
action.rdapWhoisServer = null;
action.authResult = authResult;
action.sessionUtils = sessionUtils;
action.rdapMetrics = rdapMetrics;
return action;
}
private Object generateActualJson(String name) {
return generateActualJson(name, Optional.empty(), Optional.empty());
}
private Object generateActualJson(
String name, Optional<String> desiredRegistrar, Optional<Boolean> includeDeleted) {
newRdapNameserverAction(name, desiredRegistrar, includeDeleted).run();
return JSONValue.parse(response.getPayload());
}
private Object generateExpectedJson(
String name,
@Nullable ImmutableMap<String, String> otherSubstitutions,
@ -323,9 +255,8 @@ public class RdapNameserverActionTest {
@Test
public void testNameserver_found_sameRegistrarRequested() {
assertThat(
generateActualJson(
"ns1.cat.lol", Optional.of("TheRegistrar"), Optional.empty()))
action.registrarParam = Optional.of("TheRegistrar");
assertThat(generateActualJson("ns1.cat.lol"))
.isEqualTo(
generateExpectedJsonWithTopLevelEntries(
"ns1.cat.lol",
@ -340,7 +271,9 @@ public class RdapNameserverActionTest {
@Test
public void testNameserver_notFound_differentRegistrarRequested() {
generateActualJson("ns1.cat.lol", Optional.of("otherregistrar"), Optional.of(false));
action.registrarParam = Optional.of("otherregistrar");
action.includeDeletedParam = Optional.of(false);
generateActualJson("ns1.cat.lol");
assertThat(response.getStatus()).isEqualTo(404);
}
@ -352,31 +285,32 @@ public class RdapNameserverActionTest {
@Test
public void testDeletedNameserver_notFound_includeDeletedSetFalse() {
generateActualJson("nsdeleted.cat.lol", Optional.empty(), Optional.of(false));
action.includeDeletedParam = Optional.of(false);
generateActualJson("nsdeleted.cat.lol");
assertThat(response.getStatus()).isEqualTo(404);
}
@Test
public void testDeletedNameserver_notFound_notLoggedIn() {
when(sessionUtils.checkRegistrarConsoleLogin(request, userAuthInfo)).thenReturn(false);
generateActualJson("nsdeleted.cat.lol", Optional.empty(), Optional.of(true));
logout();
action.includeDeletedParam = Optional.of(true);
generateActualJson("nsdeleted.cat.lol");
assertThat(response.getStatus()).isEqualTo(404);
}
@Test
public void testDeletedNameserver_notFound_loggedInAsDifferentRegistrar() {
when(sessionUtils.checkRegistrarConsoleLogin(request, userAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn("otherregistrar");
generateActualJson("nsdeleted.cat.lol", Optional.empty(), Optional.of(true));
login("otherregistrar");
action.includeDeletedParam = Optional.of(true);
generateActualJson("nsdeleted.cat.lol");
assertThat(response.getStatus()).isEqualTo(404);
}
@Test
public void testDeletedNameserver_found_loggedInAsCorrectRegistrar() {
when(sessionUtils.checkRegistrarConsoleLogin(request, userAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn("TheRegistrar");
assertThat(
generateActualJson("nsdeleted.cat.lol", Optional.empty(), Optional.of(true)))
login("TheRegistrar");
action.includeDeletedParam = Optional.of(true);
assertThat(generateActualJson("nsdeleted.cat.lol"))
.isEqualTo(
generateExpectedJsonWithTopLevelEntries(
"nsdeleted.cat.lol",
@ -391,15 +325,9 @@ public class RdapNameserverActionTest {
@Test
public void testDeletedNameserver_found_loggedInAsAdmin() {
when(sessionUtils.checkRegistrarConsoleLogin(request, adminUserAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn("irrelevant");
newRdapNameserverAction(
"nsdeleted.cat.lol",
Optional.empty(),
Optional.of(true),
AuthResult.create(AuthLevel.USER, adminUserAuthInfo))
.run();
assertThat(JSONValue.parse(response.getPayload()))
loginAsAdmin();
action.includeDeletedParam = Optional.of(true);
assertThat(generateActualJson("nsdeleted.cat.lol"))
.isEqualTo(
generateExpectedJsonWithTopLevelEntries(
"nsdeleted.cat.lol",
@ -414,10 +342,10 @@ public class RdapNameserverActionTest {
@Test
public void testDeletedNameserver_found_sameRegistrarRequested() {
when(sessionUtils.checkRegistrarConsoleLogin(request, userAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn("TheRegistrar");
assertThat(
generateActualJson("nsdeleted.cat.lol", Optional.of("TheRegistrar"), Optional.of(true)))
login("TheRegistrar");
action.registrarParam = Optional.of("TheRegistrar");
action.includeDeletedParam = Optional.of(true);
assertThat(generateActualJson("nsdeleted.cat.lol"))
.isEqualTo(
generateExpectedJsonWithTopLevelEntries(
"nsdeleted.cat.lol",
@ -432,9 +360,10 @@ public class RdapNameserverActionTest {
@Test
public void testDeletedNameserver_notFound_differentRegistrarRequested() {
when(sessionUtils.checkRegistrarConsoleLogin(request, userAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn("TheRegistrar");
generateActualJson("ns1.cat.lol", Optional.of("otherregistrar"), Optional.of(false));
login("TheRegistrar");
action.registrarParam = Optional.of("otherregistrar");
action.includeDeletedParam = Optional.of(false);
generateActualJson("ns1.cat.lol");
assertThat(response.getStatus()).isEqualTo(404);
}

View file

@ -15,8 +15,6 @@
package google.registry.rdap;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.rdap.RdapAuthorization.Role.ADMINISTRATOR;
import static google.registry.rdap.RdapAuthorization.Role.REGISTRAR;
import static google.registry.request.Action.Method.GET;
import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistResource;
@ -29,10 +27,7 @@ import static google.registry.testing.FullFieldsTestEntityHelper.makeHostResourc
import static google.registry.testing.FullFieldsTestEntityHelper.makeRegistrar;
import static google.registry.testing.FullFieldsTestEntityHelper.makeRegistrarContacts;
import static google.registry.testing.TestDataHelper.loadFile;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.appengine.api.users.User;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
@ -40,51 +35,31 @@ import com.google.common.collect.ImmutableSet;
import com.googlecode.objectify.Key;
import google.registry.model.domain.DomainResource;
import google.registry.model.host.HostResource;
import google.registry.model.ofy.Ofy;
import google.registry.model.registrar.Registrar;
import google.registry.rdap.RdapMetrics.EndpointType;
import google.registry.rdap.RdapMetrics.SearchType;
import google.registry.rdap.RdapMetrics.WildcardType;
import google.registry.rdap.RdapSearchResults.IncompletenessWarningType;
import google.registry.request.Action;
import google.registry.request.auth.AuthLevel;
import google.registry.request.auth.AuthResult;
import google.registry.request.auth.UserAuthInfo;
import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock;
import google.registry.testing.FakeResponse;
import google.registry.testing.InjectRule;
import google.registry.ui.server.registrar.SessionUtils;
import java.net.URLDecoder;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import org.joda.time.DateTime;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link RdapNameserverSearchAction}. */
@RunWith(JUnit4.class)
public class RdapNameserverSearchActionTest extends RdapSearchActionTestCase {
public class RdapNameserverSearchActionTest
extends RdapSearchActionTestCase<RdapNameserverSearchAction> {
@Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build();
@Rule public final InjectRule inject = new InjectRule();
private final HttpServletRequest request = mock(HttpServletRequest.class);
private FakeResponse response = new FakeResponse();
private final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01T00:00:00Z"));
private final SessionUtils sessionUtils = mock(SessionUtils.class);
private final User user = new User("rdap.user@example.com", "gmail.com", "12345");
private final UserAuthInfo userAuthInfo = UserAuthInfo.create(user, false);
private final UserAuthInfo adminUserAuthInfo = UserAuthInfo.create(user, true);
private final RdapNameserverSearchAction action = new RdapNameserverSearchAction();
public RdapNameserverSearchActionTest() {
super(RdapNameserverSearchAction.class, RdapNameserverSearchAction.PATH);
}
private DomainResource domainCatLol;
private HostResource hostNs1CatLol;
@ -177,40 +152,8 @@ public class RdapNameserverSearchActionTest extends RdapSearchActionTestCase {
persistResource(
hostNs2CatLol.asBuilder().setSuperordinateDomain(Key.create(domainCatLol)).build());
inject.setStaticField(Ofy.class, "clock", clock);
action.clock = clock;
action.fullServletPath = "https://example.tld/rdap";
action.requestUrl = "https://example.tld/rdap/nameservers";
action.requestPath = RdapNameserverSearchAction.PATH;
action.parameterMap = ImmutableListMultimap.of();
action.request = request;
action.requestMethod = Action.Method.GET;
action.response = response;
action.rdapJsonFormatter = RdapTestHelper.getTestRdapJsonFormatter();
action.rdapResultSetMaxSize = 4;
action.rdapWhoisServer = null;
action.ipParam = Optional.empty();
action.nameParam = Optional.empty();
action.registrarParam = Optional.empty();
action.includeDeletedParam = Optional.empty();
action.formatOutputParam = Optional.empty();
action.authResult = AuthResult.create(AuthLevel.USER, userAuthInfo);
action.sessionUtils = sessionUtils;
action.rdapMetrics = rdapMetrics;
action.cursorTokenParam = Optional.empty();
}
private void login(String clientId) {
when(sessionUtils.checkRegistrarConsoleLogin(request, userAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn(clientId);
metricRole = REGISTRAR;
}
private void loginAsAdmin() {
when(sessionUtils.checkRegistrarConsoleLogin(request, adminUserAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn("irrelevant");
action.authResult = AuthResult.create(AuthLevel.USER, adminUserAuthInfo);
metricRole = ADMINISTRATOR;
}
private Object generateExpectedJson(String expectedOutputFile) {

View file

@ -14,26 +14,39 @@
package google.registry.rdap;
import static google.registry.rdap.RdapAuthorization.Role.PUBLIC;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import com.google.common.collect.ImmutableListMultimap;
import google.registry.rdap.RdapMetrics.EndpointType;
import google.registry.rdap.RdapMetrics.SearchType;
import google.registry.rdap.RdapMetrics.WildcardType;
import google.registry.rdap.RdapSearchResults.IncompletenessWarningType;
import google.registry.request.Action;
import java.util.Optional;
import org.junit.Before;
public class RdapSearchActionTestCase {
/** Common unit test code for actions inheriting {@link RdapSearchActionBase}. */
public class RdapSearchActionTestCase<A extends RdapSearchActionBase>
extends RdapActionBaseTestCase<A> {
protected RdapSearchActionTestCase(Class<A> rdapActionClass, String path) {
super(rdapActionClass, path);
}
RdapAuthorization.Role metricRole = PUBLIC;
SearchType metricSearchType = SearchType.NONE;
WildcardType metricWildcardType = WildcardType.INVALID;
int metricPrefixLength = 0;
int metricStatusCode = SC_OK;
final RdapMetrics rdapMetrics = mock(RdapMetrics.class);
@Before
public void initRdapSearchActionTestCase() {
action.parameterMap = ImmutableListMultimap.of();
action.cursorTokenParam = Optional.empty();
action.rdapResultSetMaxSize = 4;
action.requestUrl = "https://example.tld" + actionPath;
action.requestPath = actionPath;
}
void rememberWildcardType(String queryString) {
try {

View file

@ -5,9 +5,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/%NAME%",
"value" : "https://example.tld/rdap/entity/%NAME%",
"rel" : "self",
"href": "https://example.com/rdap/entity/%NAME%",
"href": "https://example.tld/rdap/entity/%NAME%",
"type" : "application/rdap+json"
}
],

View file

@ -5,9 +5,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/%NAME%",
"value" : "https://example.tld/rdap/entity/%NAME%",
"rel" : "self",
"href": "https://example.com/rdap/entity/%NAME%",
"href": "https://example.tld/rdap/entity/%NAME%",
"type" : "application/rdap+json"
}
],

View file

@ -5,9 +5,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/%NAME%",
"value" : "https://example.tld/rdap/entity/%NAME%",
"rel" : "self",
"href": "https://example.com/rdap/entity/%NAME%",
"href": "https://example.tld/rdap/entity/%NAME%",
"type" : "application/rdap+json"
}
],

View file

@ -5,9 +5,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/%NAME%",
"value" : "https://example.tld/rdap/entity/%NAME%",
"rel" : "self",
"href": "https://example.com/rdap/entity/%NAME%",
"href": "https://example.tld/rdap/entity/%NAME%",
"type" : "application/rdap+json"
}
],

View file

@ -5,9 +5,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/%NAME%",
"value" : "https://example.tld/rdap/entity/%NAME%",
"rel" : "self",
"href": "https://example.com/rdap/entity/%NAME%",
"href": "https://example.tld/rdap/entity/%NAME%",
"type" : "application/rdap+json"
}
],

View file

@ -8,10 +8,10 @@
"handle": "%HANDLE%",
"links": [
{
"href": "https://example.com/rdap/domain/%NAME%",
"href": "https://example.tld/rdap/domain/%NAME%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%NAME%"
"value": "https://example.tld/rdap/domain/%NAME%"
}
],
"events": [
@ -42,10 +42,10 @@
"handle": "%NAMESERVER1ROID%",
"links": [
{
"href": "https://example.com/rdap/nameserver/%NAMESERVER1NAME%",
"href": "https://example.tld/rdap/nameserver/%NAMESERVER1NAME%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/nameserver/%NAMESERVER1NAME%"
"value": "https://example.tld/rdap/nameserver/%NAMESERVER1NAME%"
}
],
"ldhName": "%NAMESERVER1NAME%",
@ -74,10 +74,10 @@
"roles": [ "registrar" ],
"links": [
{
"href": "https://example.com/rdap/entity/1",
"href": "https://example.tld/rdap/entity/1",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/1"
"value": "https://example.tld/rdap/entity/1"
}
],
"vcardArray" : [
@ -129,10 +129,10 @@
"handle": "%NAMESERVER2ROID%",
"links": [
{
"href": "https://example.com/rdap/nameserver/%NAMESERVER2NAME%",
"href": "https://example.tld/rdap/nameserver/%NAMESERVER2NAME%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/nameserver/%NAMESERVER2NAME%"
"value": "https://example.tld/rdap/nameserver/%NAMESERVER2NAME%"
}
],
"ldhName": "%NAMESERVER2NAME%",
@ -161,10 +161,10 @@
"roles": [ "registrar" ],
"links": [
{
"href": "https://example.com/rdap/entity/1",
"href": "https://example.tld/rdap/entity/1",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/1"
"value": "https://example.tld/rdap/entity/1"
}
],
"vcardArray" : [
@ -222,10 +222,10 @@
],
"links": [
{
"href": "https://example.com/rdap/entity/%CONTACT1ROID%",
"href": "https://example.tld/rdap/entity/%CONTACT1ROID%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/%CONTACT1ROID%"
"value": "https://example.tld/rdap/entity/%CONTACT1ROID%"
}
],
"events": [
@ -315,10 +315,10 @@
],
"links": [
{
"href": "https://example.com/rdap/entity/%CONTACT2ROID%",
"href": "https://example.tld/rdap/entity/%CONTACT2ROID%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/%CONTACT2ROID%"
"value": "https://example.tld/rdap/entity/%CONTACT2ROID%"
}
],
"events": [
@ -408,10 +408,10 @@
],
"links": [
{
"href": "https://example.com/rdap/entity/%CONTACT3ROID%",
"href": "https://example.tld/rdap/entity/%CONTACT3ROID%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/%CONTACT3ROID%"
"value": "https://example.tld/rdap/entity/%CONTACT3ROID%"
}
],
"events": [
@ -497,10 +497,10 @@
"roles": [ "registrar" ],
"links": [
{
"href": "https://example.com/rdap/entity/1",
"href": "https://example.tld/rdap/entity/1",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/1"
"value": "https://example.tld/rdap/entity/1"
}
],
"vcardArray" : [

View file

@ -8,10 +8,10 @@
"handle": "%HANDLE%",
"links": [
{
"href": "https://example.com/rdap/domain/%NAME%",
"href": "https://example.tld/rdap/domain/%NAME%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%NAME%"
"value": "https://example.tld/rdap/domain/%NAME%"
}
],
"events": [
@ -42,10 +42,10 @@
"handle": "%NAMESERVER1ROID%",
"links": [
{
"href": "https://example.com/rdap/nameserver/%NAMESERVER1NAME%",
"href": "https://example.tld/rdap/nameserver/%NAMESERVER1NAME%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/nameserver/%NAMESERVER1NAME%"
"value": "https://example.tld/rdap/nameserver/%NAMESERVER1NAME%"
}
],
"ldhName": "%NAMESERVER1NAME%",
@ -74,10 +74,10 @@
"roles": [ "registrar" ],
"links": [
{
"href": "https://example.com/rdap/entity/1",
"href": "https://example.tld/rdap/entity/1",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/1"
"value": "https://example.tld/rdap/entity/1"
}
],
"vcardArray" : [
@ -129,10 +129,10 @@
"handle": "%NAMESERVER2ROID%",
"links": [
{
"href": "https://example.com/rdap/nameserver/%NAMESERVER2NAME%",
"href": "https://example.tld/rdap/nameserver/%NAMESERVER2NAME%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/nameserver/%NAMESERVER2NAME%"
"value": "https://example.tld/rdap/nameserver/%NAMESERVER2NAME%"
}
],
"ldhName": "%NAMESERVER2NAME%",
@ -161,10 +161,10 @@
"roles": [ "registrar" ],
"links": [
{
"href": "https://example.com/rdap/entity/1",
"href": "https://example.tld/rdap/entity/1",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/1"
"value": "https://example.tld/rdap/entity/1"
}
],
"vcardArray" : [
@ -222,10 +222,10 @@
],
"links": [
{
"href": "https://example.com/rdap/entity/%CONTACT1ROID%",
"href": "https://example.tld/rdap/entity/%CONTACT1ROID%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/%CONTACT1ROID%"
"value": "https://example.tld/rdap/entity/%CONTACT1ROID%"
}
],
"events": [
@ -315,10 +315,10 @@
],
"links": [
{
"href": "https://example.com/rdap/entity/%CONTACT2ROID%",
"href": "https://example.tld/rdap/entity/%CONTACT2ROID%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/%CONTACT2ROID%"
"value": "https://example.tld/rdap/entity/%CONTACT2ROID%"
}
],
"events": [
@ -408,10 +408,10 @@
],
"links": [
{
"href": "https://example.com/rdap/entity/%CONTACT3ROID%",
"href": "https://example.tld/rdap/entity/%CONTACT3ROID%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/%CONTACT3ROID%"
"value": "https://example.tld/rdap/entity/%CONTACT3ROID%"
}
],
"events": [
@ -497,10 +497,10 @@
"roles": [ "registrar" ],
"links": [
{
"href": "https://example.com/rdap/entity/1",
"href": "https://example.tld/rdap/entity/1",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/1"
"value": "https://example.tld/rdap/entity/1"
}
],
"vcardArray" : [

View file

@ -9,10 +9,10 @@
"handle": "%HANDLE%",
"links": [
{
"href": "https://example.com/rdap/domain/%NAME%",
"href": "https://example.tld/rdap/domain/%NAME%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%NAME%"
"value": "https://example.tld/rdap/domain/%NAME%"
}
],
"events": [
@ -48,10 +48,10 @@
"handle": "%NAMESERVER1ROID%",
"links": [
{
"href": "https://example.com/rdap/nameserver/%NAMESERVER1NAME%",
"href": "https://example.tld/rdap/nameserver/%NAMESERVER1NAME%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/nameserver/%NAMESERVER1NAME%"
"value": "https://example.tld/rdap/nameserver/%NAMESERVER1NAME%"
}
],
"ldhName": "%NAMESERVER1NAME%",
@ -80,10 +80,10 @@
"roles": [ "registrar" ],
"links": [
{
"href": "https://example.com/rdap/entity/1",
"href": "https://example.tld/rdap/entity/1",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/1"
"value": "https://example.tld/rdap/entity/1"
}
],
"vcardArray" : [
@ -134,10 +134,10 @@
"handle": "%NAMESERVER2ROID%",
"links": [
{
"href": "https://example.com/rdap/nameserver/%NAMESERVER2NAME%",
"href": "https://example.tld/rdap/nameserver/%NAMESERVER2NAME%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/nameserver/%NAMESERVER2NAME%"
"value": "https://example.tld/rdap/nameserver/%NAMESERVER2NAME%"
}
],
"ldhName": "%NAMESERVER2NAME%",
@ -166,10 +166,10 @@
"roles": [ "registrar" ],
"links": [
{
"href": "https://example.com/rdap/entity/1",
"href": "https://example.tld/rdap/entity/1",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/1"
"value": "https://example.tld/rdap/entity/1"
}
],
"vcardArray" : [
@ -226,10 +226,10 @@
],
"links": [
{
"href": "https://example.com/rdap/entity/%CONTACT1ROID%",
"href": "https://example.tld/rdap/entity/%CONTACT1ROID%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/%CONTACT1ROID%"
"value": "https://example.tld/rdap/entity/%CONTACT1ROID%"
}
],
"events": [
@ -318,10 +318,10 @@
],
"links": [
{
"href": "https://example.com/rdap/entity/%CONTACT2ROID%",
"href": "https://example.tld/rdap/entity/%CONTACT2ROID%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/%CONTACT2ROID%"
"value": "https://example.tld/rdap/entity/%CONTACT2ROID%"
}
],
"events": [
@ -410,10 +410,10 @@
],
"links": [
{
"href": "https://example.com/rdap/entity/%CONTACT3ROID%",
"href": "https://example.tld/rdap/entity/%CONTACT3ROID%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/%CONTACT3ROID%"
"value": "https://example.tld/rdap/entity/%CONTACT3ROID%"
}
],
"events": [
@ -499,10 +499,10 @@
"roles": [ "registrar" ],
"links": [
{
"href": "https://example.com/rdap/entity/1",
"href": "https://example.tld/rdap/entity/1",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/1"
"value": "https://example.tld/rdap/entity/1"
}
],
"vcardArray" : [

View file

@ -10,10 +10,10 @@
],
"links": [
{
"href": "https://example.com/rdap/domain/%NAME%",
"href": "https://example.tld/rdap/domain/%NAME%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%NAME%"
"value": "https://example.tld/rdap/domain/%NAME%"
}
],
"events": [
@ -44,10 +44,10 @@
"handle": "%NAMESERVER1ROID%",
"links": [
{
"href": "https://example.com/rdap/nameserver/%NAMESERVER1NAME%",
"href": "https://example.tld/rdap/nameserver/%NAMESERVER1NAME%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/nameserver/%NAMESERVER1NAME%"
"value": "https://example.tld/rdap/nameserver/%NAMESERVER1NAME%"
}
],
"ldhName": "%NAMESERVER1NAME%",
@ -76,10 +76,10 @@
"roles": [ "registrar" ],
"links": [
{
"href": "https://example.com/rdap/entity/1",
"href": "https://example.tld/rdap/entity/1",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/1"
"value": "https://example.tld/rdap/entity/1"
}
],
"vcardArray" : [
@ -131,10 +131,10 @@
"handle": "%NAMESERVER2ROID%",
"links": [
{
"href": "https://example.com/rdap/nameserver/%NAMESERVER2NAME%",
"href": "https://example.tld/rdap/nameserver/%NAMESERVER2NAME%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/nameserver/%NAMESERVER2NAME%"
"value": "https://example.tld/rdap/nameserver/%NAMESERVER2NAME%"
}
],
"ldhName": "%NAMESERVER2NAME%",
@ -163,10 +163,10 @@
"roles": [ "registrar" ],
"links": [
{
"href": "https://example.com/rdap/entity/1",
"href": "https://example.tld/rdap/entity/1",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/1"
"value": "https://example.tld/rdap/entity/1"
}
],
"vcardArray" : [
@ -220,9 +220,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/1",
"value" : "https://example.tld/rdap/entity/1",
"rel" : "self",
"href" : "https://example.com/rdap/entity/1",
"href" : "https://example.tld/rdap/entity/1",
"type" : "application/rdap+json"
}
],

View file

@ -10,10 +10,10 @@
],
"links": [
{
"href": "https://example.com/rdap/domain/%NAME%",
"href": "https://example.tld/rdap/domain/%NAME%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%NAME%"
"value": "https://example.tld/rdap/domain/%NAME%"
}
],
"events": [
@ -44,10 +44,10 @@
"handle": "%NAMESERVER1ROID%",
"links": [
{
"href": "https://example.com/rdap/nameserver/%NAMESERVER1NAME%",
"href": "https://example.tld/rdap/nameserver/%NAMESERVER1NAME%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/nameserver/%NAMESERVER1NAME%"
"value": "https://example.tld/rdap/nameserver/%NAMESERVER1NAME%"
}
],
"ldhName": "%NAMESERVER1NAME%",
@ -76,10 +76,10 @@
"roles": [ "registrar" ],
"links": [
{
"href": "https://example.com/rdap/entity/1",
"href": "https://example.tld/rdap/entity/1",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/1"
"value": "https://example.tld/rdap/entity/1"
}
],
"vcardArray" : [
@ -131,10 +131,10 @@
"handle": "%NAMESERVER2ROID%",
"links": [
{
"href": "https://example.com/rdap/nameserver/%NAMESERVER2NAME%",
"href": "https://example.tld/rdap/nameserver/%NAMESERVER2NAME%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/nameserver/%NAMESERVER2NAME%"
"value": "https://example.tld/rdap/nameserver/%NAMESERVER2NAME%"
}
],
"ldhName": "%NAMESERVER2NAME%",
@ -163,10 +163,10 @@
"roles": [ "registrar" ],
"links": [
{
"href": "https://example.com/rdap/entity/1",
"href": "https://example.tld/rdap/entity/1",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/1"
"value": "https://example.tld/rdap/entity/1"
}
],
"vcardArray" : [
@ -220,9 +220,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/1",
"value" : "https://example.tld/rdap/entity/1",
"rel" : "self",
"href" : "https://example.com/rdap/entity/1",
"href" : "https://example.tld/rdap/entity/1",
"type" : "application/rdap+json"
}
],

View file

@ -9,10 +9,10 @@
"handle": "%HANDLE%",
"links": [
{
"href": "https://example.com/rdap/domain/%PUNYCODENAME%",
"href": "https://example.tld/rdap/domain/%PUNYCODENAME%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%PUNYCODENAME%"
"value": "https://example.tld/rdap/domain/%PUNYCODENAME%"
}
],
"events": [
@ -44,11 +44,11 @@
"links": [
{
"href":
"https://example.com/rdap/nameserver/%NAMESERVER1PUNYCODENAME%",
"https://example.tld/rdap/nameserver/%NAMESERVER1PUNYCODENAME%",
"type": "application/rdap+json",
"rel": "self",
"value":
"https://example.com/rdap/nameserver/%NAMESERVER1PUNYCODENAME%"
"https://example.tld/rdap/nameserver/%NAMESERVER1PUNYCODENAME%"
}
],
"ldhName": "%NAMESERVER1PUNYCODENAME%",
@ -77,10 +77,10 @@
"roles": [ "registrar" ],
"links": [
{
"href": "https://example.com/rdap/entity/1",
"href": "https://example.tld/rdap/entity/1",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/1"
"value": "https://example.tld/rdap/entity/1"
}
],
"vcardArray" : [
@ -133,11 +133,11 @@
"links": [
{
"href":
"https://example.com/rdap/nameserver/%NAMESERVER2PUNYCODENAME%",
"https://example.tld/rdap/nameserver/%NAMESERVER2PUNYCODENAME%",
"type": "application/rdap+json",
"rel": "self",
"value":
"https://example.com/rdap/nameserver/%NAMESERVER2PUNYCODENAME%"
"https://example.tld/rdap/nameserver/%NAMESERVER2PUNYCODENAME%"
}
],
"ldhName": "%NAMESERVER2PUNYCODENAME%",
@ -166,10 +166,10 @@
"roles": [ "registrar" ],
"links": [
{
"href": "https://example.com/rdap/entity/1",
"href": "https://example.tld/rdap/entity/1",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/1"
"value": "https://example.tld/rdap/entity/1"
}
],
"vcardArray" : [
@ -227,10 +227,10 @@
],
"links": [
{
"href": "https://example.com/rdap/entity/%CONTACT1ROID%",
"href": "https://example.tld/rdap/entity/%CONTACT1ROID%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/%CONTACT1ROID%"
"value": "https://example.tld/rdap/entity/%CONTACT1ROID%"
}
],
"events": [
@ -320,10 +320,10 @@
],
"links": [
{
"href": "https://example.com/rdap/entity/%CONTACT2ROID%",
"href": "https://example.tld/rdap/entity/%CONTACT2ROID%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/%CONTACT2ROID%"
"value": "https://example.tld/rdap/entity/%CONTACT2ROID%"
}
],
"events": [
@ -413,10 +413,10 @@
],
"links": [
{
"href": "https://example.com/rdap/entity/%CONTACT3ROID%",
"href": "https://example.tld/rdap/entity/%CONTACT3ROID%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/%CONTACT3ROID%"
"value": "https://example.tld/rdap/entity/%CONTACT3ROID%"
}
],
"events": [
@ -502,10 +502,10 @@
"roles": [ "registrar" ],
"links": [
{
"href": "https://example.com/rdap/entity/1",
"href": "https://example.tld/rdap/entity/1",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/1"
"value": "https://example.tld/rdap/entity/1"
}
],
"vcardArray" : [

View file

@ -11,10 +11,10 @@
],
"links": [
{
"href": "https://example.com/rdap/domain/%PUNYCODENAME%",
"href": "https://example.tld/rdap/domain/%PUNYCODENAME%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%PUNYCODENAME%"
"value": "https://example.tld/rdap/domain/%PUNYCODENAME%"
}
],
"events": [
@ -45,10 +45,10 @@
"handle": "%NAMESERVER1ROID%",
"links": [
{
"href": "https://example.com/rdap/nameserver/%NAMESERVER1PUNYCODENAME%",
"href": "https://example.tld/rdap/nameserver/%NAMESERVER1PUNYCODENAME%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/nameserver/%NAMESERVER1PUNYCODENAME%"
"value": "https://example.tld/rdap/nameserver/%NAMESERVER1PUNYCODENAME%"
}
],
"ldhName": "%NAMESERVER1PUNYCODENAME%",
@ -78,10 +78,10 @@
"roles": [ "registrar" ],
"links": [
{
"href": "https://example.com/rdap/entity/1",
"href": "https://example.tld/rdap/entity/1",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/1"
"value": "https://example.tld/rdap/entity/1"
}
],
"vcardArray" : [
@ -133,10 +133,10 @@
"handle": "%NAMESERVER2ROID%",
"links": [
{
"href": "https://example.com/rdap/nameserver/%NAMESERVER2PUNYCODENAME%",
"href": "https://example.tld/rdap/nameserver/%NAMESERVER2PUNYCODENAME%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/nameserver/%NAMESERVER2PUNYCODENAME%"
"value": "https://example.tld/rdap/nameserver/%NAMESERVER2PUNYCODENAME%"
}
],
"ldhName": "%NAMESERVER2PUNYCODENAME%",
@ -166,10 +166,10 @@
"roles": [ "registrar" ],
"links": [
{
"href": "https://example.com/rdap/entity/1",
"href": "https://example.tld/rdap/entity/1",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/entity/1"
"value": "https://example.tld/rdap/entity/1"
}
],
"vcardArray" : [
@ -223,9 +223,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/1",
"value" : "https://example.tld/rdap/entity/1",
"rel" : "self",
"href" : "https://example.com/rdap/entity/1",
"href" : "https://example.tld/rdap/entity/1",
"type" : "application/rdap+json"
}
],

View file

@ -10,10 +10,10 @@
"handle": "%DOMAINHANDLE1%",
"links": [
{
"href": "https://example.com/rdap/domain/%DOMAINNAME1%",
"href": "https://example.tld/rdap/domain/%DOMAINNAME1%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%DOMAINNAME1%"
"value": "https://example.tld/rdap/domain/%DOMAINNAME1%"
}
],
"ldhName": "%DOMAINNAME1%",
@ -38,10 +38,10 @@
"handle": "%DOMAINHANDLE2%",
"links": [
{
"href": "https://example.com/rdap/domain/%DOMAINNAME2%",
"href": "https://example.tld/rdap/domain/%DOMAINNAME2%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%DOMAINNAME2%"
"value": "https://example.tld/rdap/domain/%DOMAINNAME2%"
}
],
"ldhName": "%DOMAINNAME2%",
@ -66,10 +66,10 @@
"handle": "%DOMAINHANDLE3%",
"links": [
{
"href": "https://example.com/rdap/domain/%DOMAINNAME3%",
"href": "https://example.tld/rdap/domain/%DOMAINNAME3%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%DOMAINNAME3%"
"value": "https://example.tld/rdap/domain/%DOMAINNAME3%"
}
],
"ldhName": "%DOMAINNAME3%",
@ -94,10 +94,10 @@
"handle": "%DOMAINHANDLE4%",
"links": [
{
"href": "https://example.com/rdap/domain/%DOMAINNAME4%",
"href": "https://example.tld/rdap/domain/%DOMAINNAME4%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%DOMAINNAME4%"
"value": "https://example.tld/rdap/domain/%DOMAINNAME4%"
}
],
"ldhName": "%DOMAINNAME4%",
@ -134,7 +134,7 @@
{
"type" : "application/rdap+json",
"rel" : "next",
"href" : "https://example.com/rdap/domains?%NEXT_QUERY%"
"href" : "https://example.tld/rdap/domains?%NEXT_QUERY%"
}
]
},
@ -156,7 +156,7 @@
"links" :
[
{
"value" : "https://example.com/rdap/help/tos",
"value" : "https://example.tld/rdap/help/tos",
"rel" : "alternate",
"href" : "https://www.registry.tld/about/rdap/tos.html",
"type" : "text/html"

View file

@ -10,10 +10,10 @@
"handle": "%DOMAINHANDLE1%",
"links": [
{
"href": "https://example.com/rdap/domain/%DOMAINNAME1%",
"href": "https://example.tld/rdap/domain/%DOMAINNAME1%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%DOMAINNAME1%"
"value": "https://example.tld/rdap/domain/%DOMAINNAME1%"
}
],
"ldhName": "%DOMAINNAME1%",
@ -38,10 +38,10 @@
"handle": "%DOMAINHANDLE2%",
"links": [
{
"href": "https://example.com/rdap/domain/%DOMAINNAME2%",
"href": "https://example.tld/rdap/domain/%DOMAINNAME2%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%DOMAINNAME2%"
"value": "https://example.tld/rdap/domain/%DOMAINNAME2%"
}
],
"ldhName": "%DOMAINNAME2%",
@ -66,10 +66,10 @@
"handle": "%DOMAINHANDLE3%",
"links": [
{
"href": "https://example.com/rdap/domain/%DOMAINNAME3%",
"href": "https://example.tld/rdap/domain/%DOMAINNAME3%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%DOMAINNAME3%"
"value": "https://example.tld/rdap/domain/%DOMAINNAME3%"
}
],
"ldhName": "%DOMAINNAME3%",
@ -94,10 +94,10 @@
"handle": "%DOMAINHANDLE4%",
"links": [
{
"href": "https://example.com/rdap/domain/%DOMAINPUNYCODENAME4%",
"href": "https://example.tld/rdap/domain/%DOMAINPUNYCODENAME4%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%DOMAINPUNYCODENAME4%"
"value": "https://example.tld/rdap/domain/%DOMAINPUNYCODENAME4%"
}
],
"ldhName": "%DOMAINPUNYCODENAME4%",
@ -137,7 +137,7 @@
"links" :
[
{
"value" : "https://example.com/rdap/help/tos",
"value" : "https://example.tld/rdap/help/tos",
"rel" : "alternate",
"href" : "https://www.registry.tld/about/rdap/tos.html",
"type" : "text/html"

View file

@ -10,10 +10,10 @@
"handle": "%DOMAINHANDLE1%",
"links": [
{
"href": "https://example.com/rdap/domain/%DOMAINPUNYCODENAME1%",
"href": "https://example.tld/rdap/domain/%DOMAINPUNYCODENAME1%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%DOMAINPUNYCODENAME1%"
"value": "https://example.tld/rdap/domain/%DOMAINPUNYCODENAME1%"
}
],
"ldhName": "%DOMAINPUNYCODENAME1%",
@ -38,10 +38,10 @@
"handle": "%DOMAINHANDLE2%",
"links": [
{
"href": "https://example.com/rdap/domain/%DOMAINPUNYCODENAME2%",
"href": "https://example.tld/rdap/domain/%DOMAINPUNYCODENAME2%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%DOMAINPUNYCODENAME2%"
"value": "https://example.tld/rdap/domain/%DOMAINPUNYCODENAME2%"
}
],
"ldhName": "%DOMAINPUNYCODENAME2%",
@ -66,10 +66,10 @@
"handle": "%DOMAINHANDLE3%",
"links": [
{
"href": "https://example.com/rdap/domain/%DOMAINPUNYCODENAME3%",
"href": "https://example.tld/rdap/domain/%DOMAINPUNYCODENAME3%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%DOMAINPUNYCODENAME3%"
"value": "https://example.tld/rdap/domain/%DOMAINPUNYCODENAME3%"
}
],
"ldhName": "%DOMAINPUNYCODENAME3%",
@ -94,10 +94,10 @@
"handle": "%DOMAINHANDLE4%",
"links": [
{
"href": "https://example.com/rdap/domain/%DOMAINPUNYCODENAME4%",
"href": "https://example.tld/rdap/domain/%DOMAINPUNYCODENAME4%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%DOMAINPUNYCODENAME4%"
"value": "https://example.tld/rdap/domain/%DOMAINPUNYCODENAME4%"
}
],
"ldhName": "%DOMAINPUNYCODENAME4%",
@ -135,7 +135,7 @@
{
"type" : "application/rdap+json",
"rel" : "next",
"href" : "https://example.com/rdap/domains?%NEXT_QUERY%"
"href" : "https://example.tld/rdap/domains?%NEXT_QUERY%"
}
]
},
@ -157,7 +157,7 @@
"links" :
[
{
"value" : "https://example.com/rdap/help/tos",
"value" : "https://example.tld/rdap/help/tos",
"rel" : "alternate",
"href" : "https://www.registry.tld/about/rdap/tos.html",
"type" : "text/html"

View file

@ -10,10 +10,10 @@
"handle": "%DOMAINHANDLE1%",
"links": [
{
"href": "https://example.com/rdap/domain/%DOMAINNAME1%",
"href": "https://example.tld/rdap/domain/%DOMAINNAME1%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%DOMAINNAME1%"
"value": "https://example.tld/rdap/domain/%DOMAINNAME1%"
}
],
"ldhName": "%DOMAINNAME1%",
@ -38,10 +38,10 @@
"handle": "%DOMAINHANDLE2%",
"links": [
{
"href": "https://example.com/rdap/domain/%DOMAINNAME2%",
"href": "https://example.tld/rdap/domain/%DOMAINNAME2%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%DOMAINNAME2%"
"value": "https://example.tld/rdap/domain/%DOMAINNAME2%"
}
],
"ldhName": "%DOMAINNAME2%",
@ -80,7 +80,7 @@
"links" :
[
{
"value" : "https://example.com/rdap/help/tos",
"value" : "https://example.tld/rdap/help/tos",
"rel" : "alternate",
"href" : "https://www.registry.tld/about/rdap/tos.html",
"type" : "text/html"

View file

@ -7,8 +7,8 @@
[
{
"rel":"self",
"href":"https://example.com/rdap/domain/%DOMAINNAME1%",
"value":"https://example.com/rdap/domain/%DOMAINNAME1%",
"href":"https://example.tld/rdap/domain/%DOMAINNAME1%",
"value":"https://example.tld/rdap/domain/%DOMAINNAME1%",
"type":"application/rdap+json"
}
],
@ -39,8 +39,8 @@
[
{
"rel":"self",
"href":"https://example.com/rdap/domain/%DOMAINNAME2%",
"value":"https://example.com/rdap/domain/%DOMAINNAME2%",
"href":"https://example.tld/rdap/domain/%DOMAINNAME2%",
"value":"https://example.tld/rdap/domain/%DOMAINNAME2%",
"type":"application/rdap+json"
}
],
@ -71,8 +71,8 @@
[
{
"rel":"self",
"href":"https://example.com/rdap/domain/%DOMAINNAME3%",
"value":"https://example.com/rdap/domain/%DOMAINNAME3%",
"href":"https://example.tld/rdap/domain/%DOMAINNAME3%",
"value":"https://example.tld/rdap/domain/%DOMAINNAME3%",
"type":"application/rdap+json"
}
],
@ -127,7 +127,7 @@
{
"rel":"alternate",
"href":"https://www.registry.tld/about/rdap/tos.html",
"value":"https://example.com/rdap/help/tos",
"value":"https://example.tld/rdap/help/tos",
"type":"text/html"
}
],

View file

@ -20,10 +20,10 @@
"handle":"%DOMAINHANDLE1%",
"links":[
{
"value":"https://example.com/rdap/domain/%DOMAINNAME1%",
"value":"https://example.tld/rdap/domain/%DOMAINNAME1%",
"type":"application/rdap+json",
"rel":"self",
"href":"https://example.com/rdap/domain/%DOMAINNAME1%"
"href":"https://example.tld/rdap/domain/%DOMAINNAME1%"
}
],
"objectClassName":"domain"
@ -48,10 +48,10 @@
"handle":"%DOMAINHANDLE2%",
"links":[
{
"value":"https://example.com/rdap/domain/%DOMAINNAME2%",
"value":"https://example.tld/rdap/domain/%DOMAINNAME2%",
"type":"application/rdap+json",
"rel":"self",
"href":"https://example.com/rdap/domain/%DOMAINNAME2%"
"href":"https://example.tld/rdap/domain/%DOMAINNAME2%"
}
],
"objectClassName":"domain"
@ -81,7 +81,7 @@
],
"links":[
{
"value":"https://example.com/rdap/help/tos",
"value":"https://example.tld/rdap/help/tos",
"type":"text/html",
"rel":"alternate",
"href":"https://www.registry.tld/about/rdap/tos.html"

View file

@ -8,9 +8,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/2-ROID",
"value" : "https://example.tld/rdap/entity/2-ROID",
"rel" : "self",
"href": "https://example.com/rdap/entity/2-ROID",
"href": "https://example.tld/rdap/entity/2-ROID",
"type" : "application/rdap+json"
}
],
@ -55,9 +55,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/2-Registrar",
"value" : "https://example.tld/rdap/entity/2-Registrar",
"rel" : "self",
"href": "https://example.com/rdap/entity/2-Registrar",
"href": "https://example.tld/rdap/entity/2-Registrar",
"type" : "application/rdap+json"
}
],
@ -122,7 +122,7 @@
"links" :
[
{
"value" : "https://example.com/rdap/help/tos",
"value" : "https://example.tld/rdap/help/tos",
"rel" : "alternate",
"href" : "https://www.registry.tld/about/rdap/tos.html",
"type" : "text/html"

View file

@ -8,9 +8,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/4-ROID",
"value" : "https://example.tld/rdap/entity/4-ROID",
"rel" : "self",
"href": "https://example.com/rdap/entity/4-ROID",
"href": "https://example.tld/rdap/entity/4-ROID",
"type" : "application/rdap+json"
}
],
@ -54,9 +54,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/2-ROID",
"value" : "https://example.tld/rdap/entity/2-ROID",
"rel" : "self",
"href": "https://example.com/rdap/entity/2-ROID",
"href": "https://example.tld/rdap/entity/2-ROID",
"type" : "application/rdap+json"
}
],
@ -115,7 +115,7 @@
"links" :
[
{
"value" : "https://example.com/rdap/help/tos",
"value" : "https://example.tld/rdap/help/tos",
"rel" : "alternate",
"href" : "https://www.registry.tld/about/rdap/tos.html",
"type" : "text/html"

View file

@ -8,9 +8,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/0001-ROID",
"value" : "https://example.tld/rdap/entity/0001-ROID",
"rel" : "self",
"href": "https://example.com/rdap/entity/0001-ROID",
"href": "https://example.tld/rdap/entity/0001-ROID",
"type" : "application/rdap+json"
}
],
@ -54,9 +54,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/0002-ROID",
"value" : "https://example.tld/rdap/entity/0002-ROID",
"rel" : "self",
"href": "https://example.com/rdap/entity/0002-ROID",
"href": "https://example.tld/rdap/entity/0002-ROID",
"type" : "application/rdap+json"
}
],
@ -100,9 +100,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/0003-ROID",
"value" : "https://example.tld/rdap/entity/0003-ROID",
"rel" : "self",
"href": "https://example.com/rdap/entity/0003-ROID",
"href": "https://example.tld/rdap/entity/0003-ROID",
"type" : "application/rdap+json"
}
],
@ -146,9 +146,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/0004-ROID",
"value" : "https://example.tld/rdap/entity/0004-ROID",
"rel" : "self",
"href": "https://example.com/rdap/entity/0004-ROID",
"href": "https://example.tld/rdap/entity/0004-ROID",
"type" : "application/rdap+json"
}
],
@ -207,7 +207,7 @@
"links" :
[
{
"value" : "https://example.com/rdap/help/tos",
"value" : "https://example.tld/rdap/help/tos",
"rel" : "alternate",
"href" : "https://www.registry.tld/about/rdap/tos.html",
"type" : "text/html"

View file

@ -10,10 +10,10 @@
"handle": "%DOMAINHANDLE1%",
"links": [
{
"href": "https://example.com/rdap/domain/%DOMAINNAME1%",
"href": "https://example.tld/rdap/domain/%DOMAINNAME1%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%DOMAINNAME1%"
"value": "https://example.tld/rdap/domain/%DOMAINNAME1%"
}
],
"ldhName": "%DOMAINNAME1%",
@ -38,10 +38,10 @@
"handle": "%DOMAINHANDLE2%",
"links": [
{
"href": "https://example.com/rdap/domain/%DOMAINNAME2%",
"href": "https://example.tld/rdap/domain/%DOMAINNAME2%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%DOMAINNAME2%"
"value": "https://example.tld/rdap/domain/%DOMAINNAME2%"
}
],
"ldhName": "%DOMAINNAME2%",
@ -66,10 +66,10 @@
"handle": "%DOMAINHANDLE3%",
"links": [
{
"href": "https://example.com/rdap/domain/%DOMAINNAME3%",
"href": "https://example.tld/rdap/domain/%DOMAINNAME3%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%DOMAINNAME3%"
"value": "https://example.tld/rdap/domain/%DOMAINNAME3%"
}
],
"ldhName": "%DOMAINNAME3%",
@ -94,10 +94,10 @@
"handle": "%DOMAINHANDLE4%",
"links": [
{
"href": "https://example.com/rdap/domain/%DOMAINNAME4%",
"href": "https://example.tld/rdap/domain/%DOMAINNAME4%",
"type": "application/rdap+json",
"rel": "self",
"value": "https://example.com/rdap/domain/%DOMAINNAME4%"
"value": "https://example.tld/rdap/domain/%DOMAINNAME4%"
}
],
"ldhName": "%DOMAINNAME4%",
@ -136,7 +136,7 @@
"links" :
[
{
"value" : "https://example.com/rdap/help/tos",
"value" : "https://example.tld/rdap/help/tos",
"rel" : "alternate",
"href" : "https://www.registry.tld/about/rdap/tos.html",
"type" : "text/html"

View file

@ -8,9 +8,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/301",
"value" : "https://example.tld/rdap/entity/301",
"rel" : "self",
"href": "https://example.com/rdap/entity/301",
"href": "https://example.tld/rdap/entity/301",
"type" : "application/rdap+json"
}
],
@ -61,9 +61,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/302",
"value" : "https://example.tld/rdap/entity/302",
"rel" : "self",
"href": "https://example.com/rdap/entity/302",
"href": "https://example.tld/rdap/entity/302",
"type" : "application/rdap+json"
}
],
@ -114,9 +114,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/303",
"value" : "https://example.tld/rdap/entity/303",
"rel" : "self",
"href": "https://example.com/rdap/entity/303",
"href": "https://example.tld/rdap/entity/303",
"type" : "application/rdap+json"
}
],
@ -167,9 +167,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/304",
"value" : "https://example.tld/rdap/entity/304",
"rel" : "self",
"href": "https://example.com/rdap/entity/304",
"href": "https://example.tld/rdap/entity/304",
"type" : "application/rdap+json"
}
],
@ -235,7 +235,7 @@
"links" :
[
{
"value" : "https://example.com/rdap/help/tos",
"value" : "https://example.tld/rdap/help/tos",
"rel" : "alternate",
"href" : "https://www.registry.tld/about/rdap/tos.html",
"type" : "text/html"

View file

@ -6,9 +6,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/%NAME%",
"value" : "https://example.tld/rdap/entity/%NAME%",
"rel" : "self",
"href": "https://example.com/rdap/entity/%NAME%",
"href": "https://example.tld/rdap/entity/%NAME%",
"type" : "application/rdap+json"
}
],

View file

@ -8,9 +8,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/0001-ROID",
"value" : "https://example.tld/rdap/entity/0001-ROID",
"rel" : "self",
"href": "https://example.com/rdap/entity/0001-ROID",
"href": "https://example.tld/rdap/entity/0001-ROID",
"type" : "application/rdap+json"
}
],
@ -54,9 +54,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/0002-ROID",
"value" : "https://example.tld/rdap/entity/0002-ROID",
"rel" : "self",
"href": "https://example.com/rdap/entity/0002-ROID",
"href": "https://example.tld/rdap/entity/0002-ROID",
"type" : "application/rdap+json"
}
],
@ -100,9 +100,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/0003-ROID",
"value" : "https://example.tld/rdap/entity/0003-ROID",
"rel" : "self",
"href": "https://example.com/rdap/entity/0003-ROID",
"href": "https://example.tld/rdap/entity/0003-ROID",
"type" : "application/rdap+json"
}
],
@ -146,9 +146,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/0004-ROID",
"value" : "https://example.tld/rdap/entity/0004-ROID",
"rel" : "self",
"href": "https://example.com/rdap/entity/0004-ROID",
"href": "https://example.tld/rdap/entity/0004-ROID",
"type" : "application/rdap+json"
}
],
@ -203,7 +203,7 @@
[
{
"type" : "application/rdap+json",
"href" : "https://example.com/rdap/entities?%NAME%",
"href" : "https://example.tld/rdap/entities?%NAME%",
"rel" : "next"
}
],
@ -227,7 +227,7 @@
"links" :
[
{
"value" : "https://example.com/rdap/help/tos",
"value" : "https://example.tld/rdap/help/tos",
"rel" : "alternate",
"href" : "https://www.registry.tld/about/rdap/tos.html",
"type" : "text/html"

View file

@ -8,9 +8,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/0001-ROID",
"value" : "https://example.tld/rdap/entity/0001-ROID",
"rel" : "self",
"href": "https://example.com/rdap/entity/0001-ROID",
"href": "https://example.tld/rdap/entity/0001-ROID",
"type" : "application/rdap+json"
}
],
@ -54,9 +54,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/0002-ROID",
"value" : "https://example.tld/rdap/entity/0002-ROID",
"rel" : "self",
"href": "https://example.com/rdap/entity/0002-ROID",
"href": "https://example.tld/rdap/entity/0002-ROID",
"type" : "application/rdap+json"
}
],
@ -100,9 +100,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/0003-ROID",
"value" : "https://example.tld/rdap/entity/0003-ROID",
"rel" : "self",
"href": "https://example.com/rdap/entity/0003-ROID",
"href": "https://example.tld/rdap/entity/0003-ROID",
"type" : "application/rdap+json"
}
],
@ -146,9 +146,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/301",
"value" : "https://example.tld/rdap/entity/301",
"rel" : "self",
"href": "https://example.com/rdap/entity/301",
"href": "https://example.tld/rdap/entity/301",
"type" : "application/rdap+json"
}
],
@ -210,7 +210,7 @@
[
{
"type" : "application/rdap+json",
"href" : "https://example.com/rdap/entities?%NAME%",
"href" : "https://example.tld/rdap/entities?%NAME%",
"rel" : "next"
}
],
@ -234,7 +234,7 @@
"links" :
[
{
"value" : "https://example.com/rdap/help/tos",
"value" : "https://example.tld/rdap/help/tos",
"rel" : "alternate",
"href" : "https://www.registry.tld/about/rdap/tos.html",
"type" : "text/html"

View file

@ -8,9 +8,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/301",
"value" : "https://example.tld/rdap/entity/301",
"rel" : "self",
"href": "https://example.com/rdap/entity/301",
"href": "https://example.tld/rdap/entity/301",
"type" : "application/rdap+json"
}
],
@ -61,9 +61,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/302",
"value" : "https://example.tld/rdap/entity/302",
"rel" : "self",
"href": "https://example.com/rdap/entity/302",
"href": "https://example.tld/rdap/entity/302",
"type" : "application/rdap+json"
}
],
@ -114,9 +114,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/303",
"value" : "https://example.tld/rdap/entity/303",
"rel" : "self",
"href": "https://example.com/rdap/entity/303",
"href": "https://example.tld/rdap/entity/303",
"type" : "application/rdap+json"
}
],
@ -167,9 +167,9 @@
"links" :
[
{
"value" : "https://example.com/rdap/entity/304",
"value" : "https://example.tld/rdap/entity/304",
"rel" : "self",
"href": "https://example.com/rdap/entity/304",
"href": "https://example.tld/rdap/entity/304",
"type" : "application/rdap+json"
}
],
@ -231,7 +231,7 @@
[
{
"type" : "application/rdap+json",
"href" : "https://example.com/rdap/entities?%NAME%",
"href" : "https://example.tld/rdap/entities?%NAME%",
"rel" : "next"
}
],
@ -255,7 +255,7 @@
"links" :
[
{
"value" : "https://example.com/rdap/help/tos",
"value" : "https://example.tld/rdap/help/tos",
"rel" : "alternate",
"href" : "https://www.registry.tld/about/rdap/tos.html",
"type" : "text/html"

View file

@ -50,9 +50,12 @@ import google.registry.model.transfer.TransferStatus;
import google.registry.request.Response;
import google.registry.testing.FakeResponse;
import google.registry.testing.mapreduce.MapreduceTestCase;
import google.registry.util.RandomStringGenerator;
import google.registry.util.StringGenerator;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
@ -91,12 +94,14 @@ public class RdeDomainImportActionTest extends MapreduceTestCase<RdeDomainImport
persistActiveContact("sh8013");
response = new FakeResponse();
mrRunner = makeDefaultRunner();
action = new RdeDomainImportAction(
mrRunner,
response,
IMPORT_BUCKET_NAME,
IMPORT_FILE_NAME,
Optional.of(3));
action =
new RdeDomainImportAction(
mrRunner,
response,
IMPORT_BUCKET_NAME,
IMPORT_FILE_NAME,
Optional.of(3),
new RandomStringGenerator(StringGenerator.Alphabets.BASE_64, new SecureRandom()));
}
@Test

View file

@ -51,7 +51,6 @@ import google.registry.model.transfer.TransferData;
import google.registry.model.transfer.TransferStatus;
import google.registry.testing.AppEngineRule;
import google.registry.testing.DeterministicStringGenerator;
import google.registry.testing.InjectRule;
import google.registry.util.StringGenerator;
import google.registry.xjc.rdedomain.XjcRdeDomain;
import google.registry.xjc.rdedomain.XjcRdeDomainElement;
@ -90,17 +89,16 @@ public class XjcToDomainResourceConverterTest {
"google.registry.xjc.smd"));
@Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build();
@Rule public final InjectRule inject = new InjectRule();
private Unmarshaller unmarshaller;
private DeterministicStringGenerator stringGenerator;
private final DeterministicStringGenerator stringGenerator =
new DeterministicStringGenerator(StringGenerator.Alphabets.BASE_64);
@Before
public void before() throws Exception {
createTld("example");
unmarshaller = JAXBContext.newInstance(JAXB_CONTEXT_PACKAGES).createUnmarshaller();
stringGenerator = new DeterministicStringGenerator(StringGenerator.Alphabets.BASE_64);
inject.setStaticField(XjcToDomainResourceConverter.class, "stringGenerator", stringGenerator);
}
@Test
@ -415,7 +413,7 @@ public class XjcToDomainResourceConverterTest {
// without that there's no way to actually test the capping of the projected registration here.
}
private static DomainResource convertDomainInTransaction(final XjcRdeDomain xjcDomain) {
private DomainResource convertDomainInTransaction(final XjcRdeDomain xjcDomain) {
return ofy()
.transact(
() -> {
@ -426,7 +424,7 @@ public class XjcToDomainResourceConverterTest {
createAutoRenewPollMessageForDomainImport(xjcDomain, historyEntry);
ofy().save().entities(historyEntry, autorenewBillingEvent, autorenewPollMessage);
return XjcToDomainResourceConverter.convertDomain(
xjcDomain, autorenewBillingEvent, autorenewPollMessage);
xjcDomain, autorenewBillingEvent, autorenewPollMessage, stringGenerator);
});
}

View file

@ -19,6 +19,7 @@ java_library(
"@com_google_apis_google_api_services_dataflow",
"@com_google_appengine_api_1_0_sdk",
"@com_google_appengine_tools_appengine_gcs_client",
"@com_google_code_findbugs_jsr305",
"@com_google_dagger",
"@com_google_guava",
"@com_google_truth",

View file

@ -36,7 +36,9 @@ import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Properties;
import javax.annotation.Nullable;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
@ -83,6 +85,8 @@ public class Spec11EmailUtilsTest {
new YearMonth(2018, 6),
"my-sender@test.com",
"my-receiver@test.com",
"my-reply-to@test.com",
"{LIST_OF_THREATS}\n{REPLY_TO_EMAIL}",
"test-bucket",
"icann/spec11/2018-06/SPEC11_MONTHLY_REPORT",
gcsUtils,
@ -99,27 +103,21 @@ public class Spec11EmailUtilsTest {
capturedMessages.get(0),
"my-sender@test.com",
"a@fake.com",
"my-reply-to@test.com",
"Google Registry Monthly Threat Detector [2018-06]",
"Hello registrar partner,\n"
+ "We have detected problems with the following domains:\n"
+ "a.com - MALWARE\n"
+ "At the moment, no action is required. This is purely informatory."
+ "Regards,\nGoogle Registry\n");
"a.com - MALWARE\n\nmy-reply-to@test.com");
validateMessage(
capturedMessages.get(1),
"my-sender@test.com",
"b@fake.com",
"my-reply-to@test.com",
"Google Registry Monthly Threat Detector [2018-06]",
"Hello registrar partner,\n"
+ "We have detected problems with the following domains:\n"
+ "b.com - MALWARE\n"
+ "c.com - MALWARE\n"
+ "At the moment, no action is required. This is purely informatory."
+ "Regards,\nGoogle Registry\n");
"b.com - MALWARE\nc.com - MALWARE\n\nmy-reply-to@test.com");
validateMessage(
capturedMessages.get(2),
"my-sender@test.com",
"my-receiver@test.com",
null,
"Spec11 Pipeline Success 2018-06",
"Spec11 reporting completed successfully.");
}
@ -163,6 +161,7 @@ public class Spec11EmailUtilsTest {
gotMessage.getValue(),
"my-sender@test.com",
"my-receiver@test.com",
null,
"Spec11 Emailing Failure 2018-06",
"Emailing spec11 reports failed due to expected");
}
@ -175,17 +174,31 @@ public class Spec11EmailUtilsTest {
gotMessage.getValue(),
"my-sender@test.com",
"my-receiver@test.com",
null,
"Spec11 Pipeline Alert: 2018-06",
"Alert!");
}
private void validateMessage(
Message message, String from, String recipient, String subject, String body)
Message message,
String from,
String recipient,
@Nullable String replyTo,
String subject,
String body)
throws MessagingException, IOException {
assertThat(message.getFrom()).asList().containsExactly(new InternetAddress(from));
assertThat(message.getAllRecipients())
assertThat(message.getRecipients(RecipientType.TO))
.asList()
.containsExactly(new InternetAddress(recipient));
if (replyTo == null) {
assertThat(message.getRecipients(RecipientType.BCC)).isNull();
} else {
assertThat(message.getRecipients(RecipientType.BCC))
.asList()
.containsExactly(new InternetAddress(replyTo));
}
assertThat(message.getRecipients(RecipientType.CC)).isNull();
assertThat(message.getSubject()).isEqualTo(subject);
assertThat(message.getContentType()).isEqualTo("text/plain");
assertThat(message.getContent().toString()).isEqualTo(body);

View file

@ -97,7 +97,7 @@ import google.registry.model.smd.EncodedSignedMark;
import google.registry.model.transfer.TransferData;
import google.registry.model.transfer.TransferData.Builder;
import google.registry.model.transfer.TransferStatus;
import google.registry.tmch.LordnTask;
import google.registry.tmch.LordnTaskUtils;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
@ -363,9 +363,10 @@ public class DatastoreHelper {
/** Persists a domain and enqueues a LORDN task of the appropriate type for it. */
public static DomainResource persistDomainAndEnqueueLordn(final DomainResource domain) {
final DomainResource persistedDomain = persistResource(domain);
// Calls {@link LordnTask#enqueueDomainResourceTask} wrapped in an ofy transaction so that the
// Calls {@link LordnTaskUtils#enqueueDomainResourceTask} wrapped in an ofy transaction so that
// the
// transaction time is set correctly.
ofy().transactNew(() -> LordnTask.enqueueDomainResourceTask(persistedDomain));
ofy().transactNew(() -> LordnTaskUtils.enqueueDomainResourceTask(persistedDomain));
return persistedDomain;
}
@ -453,7 +454,7 @@ public class DatastoreHelper {
registrar.asBuilder().setAllowedTlds(union(registrar.getAllowedTlds(), tld)).build());
}
private static void disallowRegistrarAccess(String clientId, String tld) {
public static void disallowRegistrarAccess(String clientId, String tld) {
Registrar registrar = loadRegistrar(clientId);
persistResource(
registrar.asBuilder().setAllowedTlds(difference(registrar.getAllowedTlds(), tld)).build());

View file

@ -44,10 +44,6 @@ public class EppMetricSubject extends Subject<EppMetricSubject, EppMetric> {
return hasValue(commandName, actual().getCommandName(), "has commandName");
}
public And<EppMetricSubject> hasEppTarget(String eppTarget) {
return hasValue(eppTarget, actual().getEppTarget(), "has eppTarget");
}
public And<EppMetricSubject> hasStatus(Code status) {
return hasValue(status, actual().getStatus(), "has status");
}

View file

@ -17,6 +17,7 @@ package google.registry.testing;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.truth.Truth.assertWithMessage;
import static java.nio.charset.StandardCharsets.UTF_8;
@ -84,9 +85,14 @@ public final class GpgSystemCommandRule extends ExternalResource {
@Override
protected void before() throws IOException, InterruptedException {
checkState(Objects.equals(cwd, DEV_NULL));
File tmpRoot = null;
tmpRoot = new File(System.getenv("TMPDIR"));
cwd = File.createTempFile(TEMP_FILE_PREFIX, "", tmpRoot);
String tmpRootDirString = System.getenv("TMPDIR");
// Create the working directory for the forked process on Temp file system. Create under the
// path specified by 'TMPDIR' envrionment variable if defined, otherwise create under the
// runtime's default (typically /tmp).
cwd =
isNullOrEmpty(tmpRootDirString)
? File.createTempFile(TEMP_FILE_PREFIX, "")
: File.createTempFile(TEMP_FILE_PREFIX, "", new File(tmpRootDirString));
cwd.delete();
cwd.mkdir();
conf = new File(cwd, ".gnupg");
@ -118,6 +124,7 @@ public final class GpgSystemCommandRule extends ExternalResource {
@Override
protected void after() {
// TODO(weiminyu): we should delete the cwd tree.
cwd = DEV_NULL;
conf = DEV_NULL;
}

View file

@ -23,7 +23,9 @@ import com.google.common.collect.ImmutableMap;
import com.google.common.io.ByteSource;
import com.google.common.io.MoreFiles;
import com.google.common.io.Resources;
import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystemAlreadyExistsException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
@ -93,7 +95,21 @@ public final class TestDataHelper {
/** Returns a recursive iterable of all files in the given directory. */
public static Iterable<Path> listFiles(Class<?> context, String directory) throws Exception {
URI dir = Resources.getResource(context, directory).toURI();
FileSystems.newFileSystem(dir, ImmutableMap.of("create", "true"));
ensureFileSystemPresentForUri(dir);
return MoreFiles.fileTraverser().breadthFirst(Paths.get(dir));
}
private static void ensureFileSystemPresentForUri(URI uri) throws IOException {
if (uri.getScheme().equals(FileSystems.getDefault().provider().getScheme())) {
// URI maps to default file system (file://...), which must be present. Besides, calling
// FileSystem.newFileSystem on this URI may trigger FileSystemAlreadyExistsException.
return;
}
try {
// URI maps to a special file system, e.g., jar:...
FileSystems.newFileSystem(uri, ImmutableMap.of("create", "true"));
} catch (FileSystemAlreadyExistsException e) {
// ignore.
}
}
}

View file

@ -17,6 +17,8 @@ java_library(
"@junit",
"@org_apache_ftpserver_core",
"@org_apache_sshd_core",
"@org_apache_sshd_scp",
"@org_apache_sshd_sftp",
"@org_bouncycastle_bcpkix_jdk15on",
],
)

View file

@ -31,11 +31,11 @@ import org.apache.sshd.common.NamedFactory;
import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory;
import org.apache.sshd.common.keyprovider.KeyPairProvider;
import org.apache.sshd.common.random.SingletonRandomFactory;
import org.apache.sshd.server.Command;
import org.apache.sshd.server.ServerBuilder;
import org.apache.sshd.server.SshServer;
import org.apache.sshd.server.auth.password.PasswordAuthenticator;
import org.apache.sshd.server.auth.pubkey.PublickeyAuthenticator;
import org.apache.sshd.server.command.Command;
import org.apache.sshd.server.scp.ScpCommandFactory;
import org.apache.sshd.server.session.ServerSession;
import org.apache.sshd.server.subsystem.sftp.SftpSubsystemFactory;

View file

@ -15,12 +15,9 @@
package google.registry.tldconfig.idn;
import static com.google.common.truth.Truth8.assertThat;
import static google.registry.tldconfig.idn.IdnLabelValidator.findValidIdnTableForTld;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import google.registry.testing.InjectRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@ -29,64 +26,63 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class IdnLabelValidatorTest {
@Rule
public final InjectRule inject = new InjectRule();
private IdnLabelValidator idnLabelValidator = IdnLabelValidator.createDefaultIdnLabelValidator();
private void doJapaneseLanguageTests(String tld) {
assertThat(findValidIdnTableForTld("foo", tld)).isPresent();
assertThat(findValidIdnTableForTld("12379foar", tld)).isPresent();
assertThat(findValidIdnTableForTld("みんな", tld)).isPresent();
assertThat(findValidIdnTableForTld("アシヨ", tld)).isPresent();
assertThat(findValidIdnTableForTld("わみけ", tld)).isPresent();
assertThat(findValidIdnTableForTld("みんなアシヨわみけabc", tld)).isPresent();
assertThat(findValidIdnTableForTld("-みんなアシヨわみけ-", tld)).isPresent();
assertThat(findValidIdnTableForTld("あいう〆", tld)).isPresent();
assertThat(findValidIdnTableForTld("〆わをん", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("foo", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("12379foar", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("みんな", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("アシヨ", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("わみけ", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("みんなアシヨわみけabc", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("-みんなアシヨわみけ-", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("あいう〆", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("〆わをん", tld)).isPresent();
// This should fail since it mixes Japanese characters with extended Latin characters. These are
// allowed individually, but not together, since they are in separate IDN tables.
assertThat(findValidIdnTableForTld("みんなアシヨわみけæ", tld)).isEmpty();
assertThat(idnLabelValidator.findValidIdnTableForTld("みんなアシヨわみけæ", tld)).isEmpty();
// This fails because it has Cyrillic characters, which just aren't allowed in either IDN table.
assertThat(findValidIdnTableForTld("З", tld)).isEmpty();
assertThat(idnLabelValidator.findValidIdnTableForTld("З", tld)).isEmpty();
assertThat(findValidIdnTableForTld("abcdefghæ", tld)).isPresent();
assertThat(findValidIdnTableForTld("happy", tld)).isPresent();
assertThat(findValidIdnTableForTld("ite-love-you", tld)).isPresent();
assertThat(findValidIdnTableForTld("凹凸商事", tld)).isPresent();
assertThat(findValidIdnTableForTld("いすゞ製鉄", tld)).isPresent();
assertThat(findValidIdnTableForTld("日々の生活", tld)).isPresent();
assertThat(findValidIdnTableForTld("1000万円", tld)).isPresent();
assertThat(findValidIdnTableForTld("たか--い", tld)).isPresent();
assertThat(findValidIdnTableForTld("ザ・セール", tld)).isPresent();
assertThat(findValidIdnTableForTld("example・例", tld)).isPresent();
assertThat(findValidIdnTableForTld("カレー・ライス", tld)).isPresent();
assertThat(findValidIdnTableForTld("〆切・明日", tld)).isPresent();
assertThat(findValidIdnTableForTld("そのスピードで", tld)).isPresent();
assertThat(findValidIdnTableForTld("visaクレジットカード", tld)).isPresent();
assertThat(findValidIdnTableForTld("cdケース", tld)).isPresent();
assertThat(findValidIdnTableForTld("らーめん", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("abcdefghæ", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("happy", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("ite-love-you", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("凹凸商事", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("いすゞ製鉄", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("日々の生活", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("1000万円", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("たか--い", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("ザ・セール", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("example・例", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("カレー・ライス", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("〆切・明日", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("そのスピードで", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("visaクレジットカード", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("cdケース", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("らーめん", tld)).isPresent();
// These fail because they have a KATAKANA MIDDLE DOT or IDEOGRAPHIC_CLOSING_MARK without any
// Japanese non-exception characters.
assertThat(findValidIdnTableForTld("eco・driving", tld)).isEmpty();
assertThat(findValidIdnTableForTld("・ー・", tld)).isEmpty();
assertThat(findValidIdnTableForTld("〆〆example・・", tld)).isEmpty();
assertThat(findValidIdnTableForTld("abc〆", tld)).isEmpty();
assertThat(findValidIdnTableForTld("〆xyz", tld)).isEmpty();
assertThat(findValidIdnTableForTld("〆bar・", tld)).isEmpty();
assertThat(idnLabelValidator.findValidIdnTableForTld("eco・driving", tld)).isEmpty();
assertThat(idnLabelValidator.findValidIdnTableForTld("・ー・", tld)).isEmpty();
assertThat(idnLabelValidator.findValidIdnTableForTld("〆〆example・・", tld)).isEmpty();
assertThat(idnLabelValidator.findValidIdnTableForTld("abc〆", tld)).isEmpty();
assertThat(idnLabelValidator.findValidIdnTableForTld("〆xyz", tld)).isEmpty();
assertThat(idnLabelValidator.findValidIdnTableForTld("〆bar・", tld)).isEmpty();
// This is a Japanese label with exactly 15 characters.
assertThat(findValidIdnTableForTld("カレー・ライスaaaaaaaa", tld)).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("カレー・ライスaaaaaaaa", tld)).isPresent();
// Should fail since it has Japanese characters but is more than 15 characters long.
assertThat(findValidIdnTableForTld("カレー・ライスaaaaaaaaa", tld)).isEmpty();
assertThat(idnLabelValidator.findValidIdnTableForTld("カレー・ライスaaaaaaaaa", tld)).isEmpty();
// Should fail since it has a prolonged sound mark that is not preceded by Hiragana or Katakana
// characters.
assertThat(findValidIdnTableForTld("aー", tld)).isEmpty();
assertThat(findValidIdnTableForTld("-ー", tld)).isEmpty();
assertThat(findValidIdnTableForTld("0ー", tld)).isEmpty();
assertThat(idnLabelValidator.findValidIdnTableForTld("aー", tld)).isEmpty();
assertThat(idnLabelValidator.findValidIdnTableForTld("-ー", tld)).isEmpty();
assertThat(idnLabelValidator.findValidIdnTableForTld("0ー", tld)).isEmpty();
}
@Test
@ -107,11 +103,10 @@ public class IdnLabelValidatorTest {
@Test
public void testOverridenTables() {
// Set .tld to have only the extended latin table and not japanese.
inject.setStaticField(
IdnLabelValidator.class,
"idnTableListsPerTld",
ImmutableMap.of("tld", ImmutableList.of(IdnTableEnum.EXTENDED_LATIN)));
assertThat(findValidIdnTableForTld("foo", "tld")).isPresent();
assertThat(findValidIdnTableForTld("みんな", "tld")).isEmpty();
idnLabelValidator =
new IdnLabelValidator(
ImmutableMap.of("tld", ImmutableList.of(IdnTableEnum.EXTENDED_LATIN)));
assertThat(idnLabelValidator.findValidIdnTableForTld("foo", "tld")).isPresent();
assertThat(idnLabelValidator.findValidIdnTableForTld("みんな", "tld")).isEmpty();
}
}

View file

@ -22,18 +22,7 @@ import static google.registry.testing.DatastoreHelper.persistActiveContact;
import static google.registry.testing.DatastoreHelper.persistDomainAndEnqueueLordn;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.appengine.api.taskqueue.LeaseOptions;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.TaskHandle;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;
import com.google.appengine.api.taskqueue.TransientFailureException;
import com.google.apphosting.api.DeadlineExceededException;
import com.google.common.collect.ImmutableList;
import com.googlecode.objectify.Key;
import google.registry.model.domain.DomainResource;
import google.registry.model.domain.launch.LaunchNotice;
@ -44,7 +33,6 @@ import google.registry.testing.FakeClock;
import google.registry.testing.InjectRule;
import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.util.Clock;
import java.util.List;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
@ -52,9 +40,9 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link LordnTask}. */
/** Unit tests for {@link LordnTaskUtils}. */
@RunWith(JUnit4.class)
public class LordnTaskTest {
public class LordnTaskUtilsTest {
private static final Clock clock = new FakeClock(DateTime.parse("2010-05-01T10:11:12Z"));
@ -70,32 +58,9 @@ public class LordnTaskTest {
public void before() {
createTld("example");
inject.setStaticField(Ofy.class, "clock", clock);
inject.setStaticField(LordnTask.class, "backOffMillis", 1L);
}
@Test
public void test_convertTasksToCsv() {
List<TaskHandle> tasks = ImmutableList.of(
makeTaskHandle("task1", "example", "csvLine1", "lordn-sunrise"),
makeTaskHandle("task2", "example", "csvLine2", "lordn-sunrise"),
makeTaskHandle("task3", "example", "ending", "lordn-sunrise"));
assertThat(LordnTask.convertTasksToCsv(tasks, clock.nowUtc(), "col1,col2"))
.isEqualTo("1,2010-05-01T10:11:12.000Z,3\ncol1,col2\ncsvLine1\ncsvLine2\nending\n");
}
@Test
public void test_convertTasksToCsv_doesntFailOnEmptyTasks() {
assertThat(
LordnTask.convertTasksToCsv(ImmutableList.of(), clock.nowUtc(), "col1,col2"))
.isEqualTo("1,2010-05-01T10:11:12.000Z,0\ncol1,col2\n");
}
@Test
public void test_convertTasksToCsv_throwsNpeOnNullTasks() {
assertThrows(
NullPointerException.class,
() -> LordnTask.convertTasksToCsv(null, clock.nowUtc(), "header"));
}
private DomainResource.Builder newDomainBuilder(DateTime applicationTime) {
return new DomainResource.Builder()
@ -173,38 +138,6 @@ public class LordnTaskTest {
public void test_enqueueDomainResourceTask_throwsNpeOnNullDomain() {
assertThrows(
NullPointerException.class,
() -> ofy().transactNew(() -> LordnTask.enqueueDomainResourceTask(null)));
}
@SuppressWarnings("unchecked")
@Test
public void test_loadAllTasks_retryLogic_thirdTrysTheCharm() {
Queue queue = mock(Queue.class);
TaskHandle task = new TaskHandle(TaskOptions.Builder.withTaskName("blah"), "blah");
when(queue.leaseTasks(any(LeaseOptions.class)))
.thenThrow(TransientFailureException.class)
.thenThrow(DeadlineExceededException.class)
.thenReturn(ImmutableList.of(task), ImmutableList.of());
assertThat(LordnTask.loadAllTasks(queue, "tld")).containsExactly(task);
}
@SuppressWarnings("unchecked")
@Test
public void test_loadAllTasks_retryLogic_allFailures() {
Queue queue = mock(Queue.class);
when(queue.leaseTasks(any(LeaseOptions.class))).thenThrow(TransientFailureException.class);
RuntimeException thrown =
assertThrows(RuntimeException.class, () -> LordnTask.loadAllTasks(queue, "tld"));
assertThat(thrown).hasMessageThat().contains("Error leasing tasks");
}
private static TaskHandle makeTaskHandle(
String taskName,
String tag,
String payload,
String queue) {
return new TaskHandle(
TaskOptions.Builder.withPayload(payload).method(Method.PULL).tag(tag).taskName(taskName),
queue);
() -> ofy().transactNew(() -> LordnTaskUtils.enqueueDomainResourceTask(null)));
}
}

View file

@ -32,13 +32,21 @@ import static java.nio.charset.StandardCharsets.UTF_8;
import static javax.servlet.http.HttpServletResponse.SC_ACCEPTED;
import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.appengine.api.taskqueue.LeaseOptions;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.TaskHandle;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;
import com.google.appengine.api.taskqueue.TransientFailureException;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.apphosting.api.DeadlineExceededException;
import com.google.common.base.VerifyException;
import com.google.common.collect.ImmutableList;
import google.registry.model.domain.DomainResource;
@ -55,7 +63,9 @@ import google.registry.util.Retrier;
import google.registry.util.TaskQueueUtils;
import google.registry.util.UrlFetchException;
import java.net.URL;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
@ -70,15 +80,15 @@ import org.mockito.Mock;
@RunWith(JUnit4.class)
public class NordnUploadActionTest {
private static final String CLAIMS_CSV = "1,2000-01-01T00:00:00.000Z,1\n"
private static final String CLAIMS_CSV = "1,2010-05-01T10:11:12.000Z,1\n"
+ "roid,domain-name,notice-id,registrar-id,registration-datetime,ack-datetime,"
+ "application-datetime\n"
+ "2-TLD,claims-landrush1.tld,landrush1tcn,99999,2000-01-01T00:00:00.000Z,"
+ "2-TLD,claims-landrush1.tld,landrush1tcn,99999,2010-05-01T10:11:12.000Z,"
+ "1969-12-31T23:00:00.000Z,1969-12-31T00:00:00.000Z\n";
private static final String SUNRISE_CSV = "1,2000-01-01T00:00:00.000Z,1\n"
private static final String SUNRISE_CSV = "1,2010-05-01T10:11:12.000Z,1\n"
+ "roid,domain-name,SMD-id,registrar-id,registration-datetime,application-datetime\n"
+ "2-TLD,sunrise1.tld,my-smdid,99999,2000-01-01T00:00:00.000Z,1969-12-31T00:00:00.000Z\n";
+ "2-TLD,sunrise1.tld,my-smdid,99999,2010-05-01T10:11:12.000Z,1969-12-31T00:00:00.000Z\n";
private static final String LOCATION_URL = "http://trololol";
@ -93,7 +103,7 @@ public class NordnUploadActionTest {
@Mock private HTTPResponse httpResponse;
@Captor private ArgumentCaptor<HTTPRequest> httpRequestCaptor;
private final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01TZ"));
private final FakeClock clock = new FakeClock(DateTime.parse("2010-05-01T10:11:12Z"));
private final LordnRequestInitializer lordnRequestInitializer = new LordnRequestInitializer();
private final NordnUploadAction action = new NordnUploadAction();
@ -115,6 +125,55 @@ public class NordnUploadActionTest {
action.taskQueueUtils = new TaskQueueUtils(new Retrier(new FakeSleeper(clock), 3));
action.tld = "tld";
action.tmchMarksdbUrl = "http://127.0.0.1";
action.random = new Random();
action.retrier = new Retrier(new FakeSleeper(clock), 3);
}
@Test
public void test_convertTasksToCsv() {
List<TaskHandle> tasks =
ImmutableList.of(
makeTaskHandle("task1", "example", "csvLine1", "lordn-sunrise"),
makeTaskHandle("task2", "example", "csvLine2", "lordn-sunrise"),
makeTaskHandle("task3", "example", "ending", "lordn-sunrise"));
assertThat(NordnUploadAction.convertTasksToCsv(tasks, clock.nowUtc(), "col1,col2"))
.isEqualTo("1,2010-05-01T10:11:12.000Z,3\ncol1,col2\ncsvLine1\ncsvLine2\nending\n");
}
@Test
public void test_convertTasksToCsv_doesntFailOnEmptyTasks() {
assertThat(NordnUploadAction.convertTasksToCsv(ImmutableList.of(), clock.nowUtc(), "col1,col2"))
.isEqualTo("1,2010-05-01T10:11:12.000Z,0\ncol1,col2\n");
}
@Test
public void test_convertTasksToCsv_throwsNpeOnNullTasks() {
assertThrows(
NullPointerException.class,
() -> NordnUploadAction.convertTasksToCsv(null, clock.nowUtc(), "header"));
}
@SuppressWarnings("unchecked")
@Test
public void test_loadAllTasks_retryLogic_thirdTrysTheCharm() {
Queue queue = mock(Queue.class);
TaskHandle task = new TaskHandle(TaskOptions.Builder.withTaskName("blah"), "blah");
when(queue.leaseTasks(any(LeaseOptions.class)))
.thenThrow(TransientFailureException.class)
.thenThrow(DeadlineExceededException.class)
.thenReturn(ImmutableList.of(task), ImmutableList.of());
assertThat(action.loadAllTasks(queue, "tld")).containsExactly(task);
}
@SuppressWarnings("unchecked")
@Test
public void test_loadAllTasks_retryLogic_allFailures() {
Queue queue = mock(Queue.class);
when(queue.leaseTasks(any(LeaseOptions.class)))
.thenThrow(new TransientFailureException("some transient error"));
RuntimeException thrown =
assertThrows(TransientFailureException.class, () -> action.loadAllTasks(queue, "tld"));
assertThat(thrown).hasMessageThat().isEqualTo("some transient error");
}
@Test
@ -228,4 +287,11 @@ public class NordnUploadActionTest {
.setApplicationTime(domain.getCreationTime().minusDays(1))
.build());
}
private static TaskHandle makeTaskHandle(
String taskName, String tag, String payload, String queue) {
return new TaskHandle(
TaskOptions.Builder.withPayload(payload).method(Method.PULL).tag(tag).taskName(taskName),
queue);
}
}

View file

@ -24,7 +24,6 @@ import com.google.appengine.api.urlfetch.URLFetchService;
import google.registry.testing.AppEngineRule;
import google.registry.testing.BouncyCastleProviderRule;
import google.registry.testing.FakeClock;
import google.registry.testing.InjectRule;
import google.registry.testing.MockitoJUnitRule;
import org.junit.Before;
import org.junit.Rule;
@ -44,7 +43,6 @@ public class TmchActionTestCase {
@Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build();
@Rule public final MockitoJUnitRule mocks = MockitoJUnitRule.create();
@Rule public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule();
@Rule public final InjectRule inject = new InjectRule();
@Mock URLFetchService fetchService;
@Mock HTTPResponse httpResponse;
@ -55,7 +53,6 @@ public class TmchActionTestCase {
@Before
public void commonBefore() throws Exception {
inject.setStaticField(TmchCertificateAuthority.class, "clock", clock);
marksdb.fetchService = fetchService;
marksdb.tmchMarksdbUrl = MARKSDB_URL;
marksdb.marksdbPublicKey = TmchData.loadPublicKey(TmchTestData.loadBytes("pubkey"));

View file

@ -25,13 +25,11 @@ import static google.registry.util.X509Utils.loadCertificate;
import google.registry.model.tmch.TmchCrl;
import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock;
import google.registry.testing.InjectRule;
import java.security.SignatureException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.CertificateRevokedException;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -48,38 +46,35 @@ public class TmchCertificateAuthorityTest {
public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore()
.build();
@Rule
public final InjectRule inject = new InjectRule();
private FakeClock clock = new FakeClock(DateTime.parse("2014-01-01T00:00:00Z"));
@Before
public void before() {
inject.setStaticField(TmchCertificateAuthority.class, "clock", clock);
}
@Test
public void testFailure_prodRootExpired() {
TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PRODUCTION);
TmchCertificateAuthority tmchCertificateAuthority =
new TmchCertificateAuthority(PRODUCTION, clock);
clock.setTo(DateTime.parse("2024-01-01T00:00:00Z"));
CertificateExpiredException e =
assertThrows(CertificateExpiredException.class, tmchCertificateAuthority::getRoot);
assertThrows(
CertificateExpiredException.class, tmchCertificateAuthority::getAndValidateRoot);
assertThat(e).hasMessageThat().containsMatch("NotAfter: Sun Jul 23 23:59:59 UTC 2023");
}
@Test
public void testFailure_prodRootNotYetValid() {
TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PRODUCTION);
TmchCertificateAuthority tmchCertificateAuthority =
new TmchCertificateAuthority(PRODUCTION, clock);
clock.setTo(DateTime.parse("2000-01-01T00:00:00Z"));
CertificateNotYetValidException e =
assertThrows(CertificateNotYetValidException.class, tmchCertificateAuthority::getRoot);
assertThrows(
CertificateNotYetValidException.class, tmchCertificateAuthority::getAndValidateRoot);
assertThat(e).hasMessageThat().containsMatch("NotBefore: Wed Jul 24 00:00:00 UTC 2013");
}
@Test
public void testFailure_crlDoesntMatchCerts() {
// Use the prod cl, which won't match our test certificate.
TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PILOT);
TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PILOT, clock);
TmchCrl.set(
readResourceUtf8(TmchCertificateAuthority.class, "icann-tmch.crl"), "http://cert.crl");
SignatureException e =
@ -91,13 +86,14 @@ public class TmchCertificateAuthorityTest {
@Test
public void testSuccess_verify() throws Exception {
TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PILOT);
TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PILOT, clock);
tmchCertificateAuthority.verify(loadCertificate(GOOD_TEST_CERTIFICATE));
}
@Test
public void testFailure_verifySignatureDoesntMatch() {
TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PRODUCTION);
TmchCertificateAuthority tmchCertificateAuthority =
new TmchCertificateAuthority(PRODUCTION, clock);
SignatureException e =
assertThrows(
SignatureException.class,
@ -107,7 +103,7 @@ public class TmchCertificateAuthorityTest {
@Test
public void testFailure_verifyRevoked() {
TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PILOT);
TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PILOT, clock);
CertificateRevokedException thrown =
assertThrows(
CertificateRevokedException.class,

View file

@ -36,7 +36,7 @@ public class TmchCrlActionTest extends TmchActionTestCase {
private TmchCrlAction newTmchCrlAction(TmchCaMode tmchCaMode) throws MalformedURLException {
TmchCrlAction action = new TmchCrlAction();
action.marksdb = marksdb;
action.tmchCertificateAuthority = new TmchCertificateAuthority(tmchCaMode);
action.tmchCertificateAuthority = new TmchCertificateAuthority(tmchCaMode, clock);
action.tmchCrlUrl = new URL("http://sloth.lol/tmch.crl");
return action;
}

View file

@ -24,6 +24,7 @@ import google.registry.flows.domain.DomainFlowTmchUtils;
import google.registry.model.smd.EncodedSignedMark;
import google.registry.testing.AppEngineRule;
import google.registry.util.ResourceUtils;
import google.registry.util.SystemClock;
import java.nio.file.Path;
import org.joda.time.DateTime;
import org.junit.Rule;
@ -43,7 +44,8 @@ public class TmchTestDataExpirationTest {
public void testActiveSignedMarkFiles_areValidAndNotExpired() throws Exception {
DomainFlowTmchUtils tmchUtils =
new DomainFlowTmchUtils(
new TmchXmlSignature(new TmchCertificateAuthority(TmchCaMode.PILOT)));
new TmchXmlSignature(
new TmchCertificateAuthority(TmchCaMode.PILOT, new SystemClock())));
for (Path path : listFiles(TmchTestDataExpirationTest.class, "testdata/active/")) {
if (path.toString().endsWith(".smd")) {

View file

@ -21,7 +21,7 @@ import org.junit.runners.Suite.SuiteClasses;
/** Convenience class to run all TMCH tests inside IDE with one keystroke. */
@RunWith(Suite.class)
@SuiteClasses({
LordnTaskTest.class,
LordnTaskUtilsTest.class,
NordnUploadAction.class,
NordnVerifyAction.class,
SmdrlCsvParserTest.class,

View file

@ -72,17 +72,17 @@ public class TmchXmlSignatureTest {
private final FakeClock clock = new FakeClock(DateTime.parse("2018-05-15T23:15:37.4Z"));
private byte[] smdData;
private TmchXmlSignature tmchXmlSignature;
private TmchXmlSignature tmchXmlSignature =
new TmchXmlSignature(new TmchCertificateAuthority(TmchCaMode.PILOT, clock));
@Before
public void before() {
inject.setStaticField(TmchCertificateAuthority.class, "clock", clock);
tmchXmlSignature = new TmchXmlSignature(new TmchCertificateAuthority(TmchCaMode.PILOT));
}
@Test
public void testWrongCertificateAuthority() {
tmchXmlSignature = new TmchXmlSignature(new TmchCertificateAuthority(TmchCaMode.PRODUCTION));
tmchXmlSignature =
new TmchXmlSignature(new TmchCertificateAuthority(TmchCaMode.PRODUCTION, clock));
smdData = loadSmd("active/Court-Agent-Arab-Active.smd");
CertificateSignatureException e =
assertThrows(CertificateSignatureException.class, () -> tmchXmlSignature.verify(smdData));

View file

@ -23,7 +23,6 @@ import com.google.common.collect.ImmutableMap;
import com.google.common.io.Files;
import com.google.common.net.MediaType;
import google.registry.testing.UriParameters;
import google.registry.tools.CommandWithConnection.Connection;
import java.io.File;
import java.nio.charset.StandardCharsets;
import org.mockito.ArgumentCaptor;
@ -46,13 +45,14 @@ public abstract class CreateOrUpdatePremiumListCommandTestCase<
}
void verifySentParams(
Connection connection, String path, ImmutableMap<String, String> parameterMap)
throws Exception {
verify(connection).send(
eq(path),
urlParamCaptor.capture(),
eq(MediaType.FORM_DATA),
requestBodyCaptor.capture());
AppEngineConnection connection, String path, ImmutableMap<String, String> parameterMap)
throws Exception {
verify(connection)
.sendPostRequest(
eq(path),
urlParamCaptor.capture(),
eq(MediaType.FORM_DATA),
requestBodyCaptor.capture());
assertThat(new ImmutableMap.Builder<String, String>()
.putAll(urlParamCaptor.getValue())
.putAll(UriParameters.parse(new String(requestBodyCaptor.getValue(), UTF_8)).entries())

View file

@ -28,7 +28,6 @@ import com.beust.jcommander.ParameterException;
import com.google.common.base.VerifyException;
import com.google.common.collect.ImmutableMap;
import com.google.common.net.MediaType;
import google.registry.tools.CommandWithConnection.Connection;
import google.registry.tools.server.CreatePremiumListAction;
import org.junit.Before;
import org.junit.Test;
@ -38,8 +37,7 @@ import org.mockito.Mock;
public class CreatePremiumListCommandTest<C extends CreatePremiumListCommand>
extends CreateOrUpdatePremiumListCommandTestCase<C> {
@Mock
Connection connection;
@Mock AppEngineConnection connection;
String premiumTermsPath;
String premiumTermsCsv;
@ -53,12 +51,12 @@ public class CreatePremiumListCommandTest<C extends CreatePremiumListCommand>
"example_premium_terms.csv",
loadFile(CreatePremiumListCommandTest.class, "example_premium_terms.csv"));
servletPath = "/_dr/admin/createPremiumList";
when(connection.send(
eq(CreatePremiumListAction.PATH),
anyMapOf(String.class, String.class),
any(MediaType.class),
any(byte[].class)))
.thenReturn(JSON_SAFETY_PREFIX + "{\"status\":\"success\",\"lines\":[]}");
when(connection.sendPostRequest(
eq(CreatePremiumListAction.PATH),
anyMapOf(String.class, String.class),
any(MediaType.class),
any(byte[].class)))
.thenReturn(JSON_SAFETY_PREFIX + "{\"status\":\"success\",\"lines\":[]}");
}
@Test
@ -86,13 +84,12 @@ public class CreatePremiumListCommandTest<C extends CreatePremiumListCommand>
public void testRun_errorResponse() throws Exception {
reset(connection);
command.setConnection(connection);
when(connection.send(
eq(CreatePremiumListAction.PATH),
anyMapOf(String.class, String.class),
any(MediaType.class),
any(byte[].class)))
.thenReturn(
JSON_SAFETY_PREFIX + "{\"status\":\"error\",\"error\":\"foo already exists\"}");
when(connection.sendPostRequest(
eq(CreatePremiumListAction.PATH),
anyMapOf(String.class, String.class),
any(MediaType.class),
any(byte[].class)))
.thenReturn(JSON_SAFETY_PREFIX + "{\"status\":\"error\",\"error\":\"foo already exists\"}");
VerifyException thrown =
assertThrows(
VerifyException.class, () -> runCommandForced("-i=" + premiumTermsPath, "-n=foo"));

View file

@ -34,7 +34,6 @@ import com.google.common.collect.Range;
import com.google.common.net.MediaType;
import google.registry.model.registrar.Registrar;
import google.registry.testing.CertificateSamples;
import google.registry.tools.CommandWithConnection.Connection;
import java.io.IOException;
import java.util.Optional;
import org.joda.money.CurrencyUnit;
@ -47,8 +46,7 @@ import org.mockito.Mockito;
/** Unit tests for {@link CreateRegistrarCommand}. */
public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarCommand> {
@Mock
private Connection connection;
@Mock private AppEngineConnection connection;
@Before
public void init() {
@ -93,11 +91,12 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
assertThat(registrar.getPremiumPriceAckRequired()).isFalse();
assertThat(registrar.getPoNumber()).isEmpty();
verify(connection).send(
eq("/_dr/admin/createGroups"),
eq(ImmutableMap.of("clientId", "clientz")),
eq(MediaType.PLAIN_TEXT_UTF_8),
eq(new byte[0]));
verify(connection)
.sendPostRequest(
eq("/_dr/admin/createGroups"),
eq(ImmutableMap.of("clientId", "clientz")),
eq(MediaType.PLAIN_TEXT_UTF_8),
eq(new byte[0]));
}
@Test
@ -210,12 +209,11 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
@SuppressWarnings("unchecked")
@Test
public void testFailure_groupCreationFails() throws Exception {
when(
connection.send(
Mockito.anyString(),
Mockito.anyMapOf(String.class, String.class),
Mockito.any(MediaType.class),
Mockito.any(byte[].class)))
when(connection.sendPostRequest(
Mockito.anyString(),
Mockito.anyMapOf(String.class, String.class),
Mockito.any(MediaType.class),
Mockito.any(byte[].class)))
.thenThrow(new IOException("BAD ROBOT NO COOKIE"));
runCommandForced(
"--name=blobio",

View file

@ -21,7 +21,6 @@ import static org.mockito.Mockito.verify;
import com.google.common.collect.ImmutableMap;
import com.google.common.net.MediaType;
import google.registry.tools.CommandWithConnection.Connection;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
@ -30,8 +29,7 @@ import org.mockito.Mock;
public class CreateRegistrarGroupsCommandTest extends
CommandTestCase<CreateRegistrarGroupsCommand> {
@Mock
private Connection connection;
@Mock private AppEngineConnection connection;
@Before
public void init() {
@ -41,16 +39,18 @@ public class CreateRegistrarGroupsCommandTest extends
@Test
public void test_createGroupsForTwoRegistrars() throws Exception {
runCommandForced("NewRegistrar", "TheRegistrar");
verify(connection).send(
eq("/_dr/admin/createGroups"),
eq(ImmutableMap.of("clientId", "NewRegistrar")),
eq(MediaType.PLAIN_TEXT_UTF_8),
eq(new byte[0]));
verify(connection).send(
eq("/_dr/admin/createGroups"),
eq(ImmutableMap.of("clientId", "TheRegistrar")),
eq(MediaType.PLAIN_TEXT_UTF_8),
eq(new byte[0]));
verify(connection)
.sendPostRequest(
eq("/_dr/admin/createGroups"),
eq(ImmutableMap.of("clientId", "NewRegistrar")),
eq(MediaType.PLAIN_TEXT_UTF_8),
eq(new byte[0]));
verify(connection)
.sendPostRequest(
eq("/_dr/admin/createGroups"),
eq(ImmutableMap.of("clientId", "TheRegistrar")),
eq(MediaType.PLAIN_TEXT_UTF_8),
eq(new byte[0]));
assertInStdout("Success!");
}

View file

@ -16,13 +16,19 @@ package google.registry.tools;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.tools.AppEngineConnection.Service.BACKEND;
import static google.registry.tools.AppEngineConnection.Service.DEFAULT;
import static google.registry.tools.AppEngineConnection.Service.PUBAPI;
import static google.registry.tools.AppEngineConnection.Service.TOOLS;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableMap;
import com.google.common.net.MediaType;
import google.registry.tools.CommandWithConnection.Connection;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
@ -31,34 +37,42 @@ import org.mockito.Mock;
/** Unit tests for {@link RefreshDnsForAllDomainsCommand}. */
public class CurlCommandTest extends CommandTestCase<CurlCommand> {
@Mock private Connection connection;
@Mock private AppEngineConnection connection;
@Mock private AppEngineConnection connectionForService;
@Before
public void init() {
command.setConnection(connection);
when(connection.withService(any())).thenReturn(connectionForService);
}
@Captor ArgumentCaptor<ImmutableMap<String, String>> urlParamCaptor;
@Test
public void testGetInvocation() throws Exception {
runCommand("--path=/foo/bar?a=1&b=2");
verify(connection)
runCommand("--path=/foo/bar?a=1&b=2", "--service=TOOLS");
verify(connection).withService(TOOLS);
verifyNoMoreInteractions(connection);
verify(connectionForService)
.sendGetRequest(eq("/foo/bar?a=1&b=2"), eq(ImmutableMap.<String, String>of()));
}
@Test
public void testExplicitGetInvocation() throws Exception {
runCommand("--path=/foo/bar?a=1&b=2", "--request=GET");
verify(connection)
runCommand("--path=/foo/bar?a=1&b=2", "--request=GET", "--service=BACKEND");
verify(connection).withService(BACKEND);
verifyNoMoreInteractions(connection);
verify(connectionForService)
.sendGetRequest(eq("/foo/bar?a=1&b=2"), eq(ImmutableMap.<String, String>of()));
}
@Test
public void testPostInvocation() throws Exception {
runCommand("--path=/foo/bar?a=1&b=2", "--data=some data");
verify(connection)
.send(
runCommand("--path=/foo/bar?a=1&b=2", "--data=some data", "--service=DEFAULT");
verify(connection).withService(DEFAULT);
verifyNoMoreInteractions(connection);
verify(connectionForService)
.sendPostRequest(
eq("/foo/bar?a=1&b=2"),
eq(ImmutableMap.<String, String>of()),
eq(MediaType.PLAIN_TEXT_UTF_8),
@ -67,9 +81,12 @@ public class CurlCommandTest extends CommandTestCase<CurlCommand> {
@Test
public void testMultiDataPost() throws Exception {
runCommand("--path=/foo/bar?a=1&b=2", "--data=first=100", "-d", "second=200");
verify(connection)
.send(
runCommand(
"--path=/foo/bar?a=1&b=2", "--data=first=100", "-d", "second=200", "--service=PUBAPI");
verify(connection).withService(PUBAPI);
verifyNoMoreInteractions(connection);
verify(connectionForService)
.sendPostRequest(
eq("/foo/bar?a=1&b=2"),
eq(ImmutableMap.<String, String>of()),
eq(MediaType.PLAIN_TEXT_UTF_8),
@ -78,9 +95,11 @@ public class CurlCommandTest extends CommandTestCase<CurlCommand> {
@Test
public void testExplicitPostInvocation() throws Exception {
runCommand("--path=/foo/bar?a=1&b=2", "--request=POST");
verify(connection)
.send(
runCommand("--path=/foo/bar?a=1&b=2", "--request=POST", "--service=TOOLS");
verify(connection).withService(TOOLS);
verifyNoMoreInteractions(connection);
verify(connectionForService)
.sendPostRequest(
eq("/foo/bar?a=1&b=2"),
eq(ImmutableMap.<String, String>of()),
eq(MediaType.PLAIN_TEXT_UTF_8),
@ -94,7 +113,10 @@ public class CurlCommandTest extends CommandTestCase<CurlCommand> {
IllegalArgumentException.class,
() ->
runCommand(
"--path=/foo/bar?a=1&b=2", "--request=GET", "--data=inappropriate data"));
"--path=/foo/bar?a=1&b=2",
"--request=GET",
"--data=inappropriate data",
"--service=TOOLS"));
assertThat(thrown).hasMessageThat().contains("You may not specify a body for a get method.");
}
}

View file

@ -20,7 +20,7 @@ import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.common.net.HostAndPort;
import google.registry.config.RegistryConfig;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -50,10 +50,8 @@ public class DefaultRequestFactoryModuleTest {
@Test
public void test_provideHttpRequestFactory_localhost() {
// Make sure that localhost creates a request factory with an initializer.
HttpRequestFactory factory =
module.provideHttpRequestFactory(
new AppEngineConnectionFlags(HostAndPort.fromParts("localhost", 1000)),
() -> FAKE_CREDENTIAL);
RegistryConfig.CONFIG_SETTINGS.get().appEngine.isLocal = true;
HttpRequestFactory factory = module.provideHttpRequestFactory(() -> FAKE_CREDENTIAL);
HttpRequestInitializer initializer = factory.getInitializer();
assertThat(initializer).isNotNull();
assertThat(initializer).isNotSameAs(FAKE_CREDENTIAL);
@ -62,11 +60,8 @@ public class DefaultRequestFactoryModuleTest {
@Test
public void test_provideHttpRequestFactory_remote() {
// Make sure that example.com creates a request factory with the UNITTEST client id but no
// initializer.
HttpRequestFactory factory =
module.provideHttpRequestFactory(
new AppEngineConnectionFlags(HostAndPort.fromParts("example.com", 1000)),
() -> FAKE_CREDENTIAL);
RegistryConfig.CONFIG_SETTINGS.get().appEngine.isLocal = false;
HttpRequestFactory factory = module.provideHttpRequestFactory(() -> FAKE_CREDENTIAL);
assertThat(factory.getInitializer()).isSameAs(FAKE_CREDENTIAL);
}
}

View file

@ -0,0 +1,140 @@
// Copyright 2018 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.tools;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.assertThrows;
import com.beust.jcommander.ParameterException;
import com.googlecode.objectify.Key;
import google.registry.model.domain.token.AllocationToken;
import google.registry.model.reporting.HistoryEntry;
import java.util.Collection;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Test;
/** Unit tests for {@link DeleteAllocationTokensCommand}. */
public class DeleteAllocationTokensCommandTest
extends CommandTestCase<DeleteAllocationTokensCommand> {
private AllocationToken preRed1;
private AllocationToken preRed2;
private AllocationToken preNot1;
private AllocationToken preNot2;
private AllocationToken othrRed;
private AllocationToken othrNot;
@Before
public void init() {
preRed1 = persistToken("prefix12345AA", null, true);
preRed2 = persistToken("prefixgh8907a", null, true);
preNot1 = persistToken("prefix2978204", null, false);
preNot2 = persistToken("prefix8ZZZhs8", null, false);
othrRed = persistToken("h97987sasdfhh", null, true);
othrNot = persistToken("asdgfho7HASDS", null, false);
}
@Test
public void test_deleteAllUnredeemedTokens_whenEmptyPrefixSpecified() throws Exception {
runCommandForced("--prefix", "");
assertThat(reloadTokens(preNot1, preNot2, othrNot)).isEmpty();
assertThat(reloadTokens(preRed1, preRed2, othrRed)).containsExactly(preRed1, preRed2, othrRed);
}
@Test
public void test_deleteOnlyUnredeemedTokensWithPrefix() throws Exception {
runCommandForced("--prefix", "prefix");
assertThat(reloadTokens(preNot1, preNot2)).isEmpty();
assertThat(reloadTokens(preRed1, preRed2, othrRed, othrNot))
.containsExactly(preRed1, preRed2, othrRed, othrNot);
}
@Test
public void test_deleteSingleAllocationToken() throws Exception {
runCommandForced("--prefix", "asdgfho7HASDS");
assertThat(reloadTokens(othrNot)).isEmpty();
assertThat(reloadTokens(preRed1, preRed2, preNot1, preNot2, othrRed))
.containsExactly(preRed1, preRed2, preNot1, preNot2, othrRed);
}
@Test
public void test_deleteTokensWithNonExistentPrefix_doesNothing() throws Exception {
runCommandForced("--prefix", "nonexistent");
assertThat(reloadTokens(preRed1, preRed2, preNot1, preNot2, othrRed, othrNot))
.containsExactly(preRed1, preRed2, preNot1, preNot2, othrRed, othrNot);
}
@Test
public void test_dryRun_deletesNothing() throws Exception {
runCommandForced("--prefix", "", "--dry_run");
assertThat(reloadTokens(preRed1, preRed2, preNot1, preNot2, othrRed, othrNot))
.containsExactly(preRed1, preRed2, preNot1, preNot2, othrRed, othrNot);
}
@Test
public void test_defaultOptions_doesntDeletePerDomainTokens() throws Exception {
AllocationToken preDom1 = persistToken("prefixasdfg897as", "foo.bar", false);
AllocationToken preDom2 = persistToken("prefix98HAZXadbn", "foo.bar", true);
runCommandForced("--prefix", "prefix");
assertThat(reloadTokens(preNot1, preNot2)).isEmpty();
assertThat(reloadTokens(preRed1, preRed2, preDom1, preDom2, othrRed, othrNot))
.containsExactly(preRed1, preRed2, preDom1, preDom2, othrRed, othrNot);
}
@Test
public void test_withDomains_doesDeletePerDomainTokens() throws Exception {
AllocationToken preDom1 = persistToken("prefixasdfg897as", "foo.bar", false);
AllocationToken preDom2 = persistToken("prefix98HAZXadbn", "foo.bar", true);
runCommandForced("--prefix", "prefix", "--with_domains");
assertThat(reloadTokens(preNot1, preNot2, preDom1)).isEmpty();
assertThat(reloadTokens(preRed1, preRed2, preDom2, othrRed, othrNot))
.containsExactly(preRed1, preRed2, preDom2, othrRed, othrNot);
}
@Test
public void test_batching() throws Exception {
for (int i = 0; i < 50; i++) {
persistToken(String.format("batch%2d", i), null, i % 2 == 0);
}
assertThat(ofy().load().type(AllocationToken.class).count()).isEqualTo(56);
runCommandForced("--prefix", "batch");
assertThat(ofy().load().type(AllocationToken.class).count()).isEqualTo(56 - 25);
}
@Test
public void test_prefixIsRequired() {
ParameterException thrown = assertThrows(ParameterException.class, () -> runCommandForced());
assertThat(thrown)
.hasMessageThat()
.isEqualTo("The following option is required: -p, --prefix ");
}
private static AllocationToken persistToken(
String token, @Nullable String domainName, boolean redeemed) {
AllocationToken.Builder builder =
new AllocationToken.Builder().setToken(token).setDomainName(domainName);
if (redeemed) {
builder.setRedemptionHistoryEntry(Key.create(HistoryEntry.class, 1051L));
}
return persistResource(builder.build());
}
private static Collection<AllocationToken> reloadTokens(AllocationToken ... tokens) {
return ofy().load().entities(tokens).values();
}
}

View file

@ -28,7 +28,6 @@ import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.net.MediaType;
import google.registry.tools.CommandWithConnection.Connection;
import google.registry.tools.server.ToolsTestData;
import java.net.URLDecoder;
import java.util.Map;
@ -49,7 +48,7 @@ import org.mockito.ArgumentCaptor;
*/
public class EppToolVerifier {
private final Connection connection = mock(Connection.class);
private final AppEngineConnection connection = mock(AppEngineConnection.class);
private String clientId;
private boolean superuser;
@ -167,11 +166,9 @@ public class EppToolVerifier {
return;
}
ArgumentCaptor<byte[]> params = ArgumentCaptor.forClass(byte[].class);
verify(connection, atLeast(0)).send(
eq("/_dr/epptool"),
eq(ImmutableMap.of()),
eq(MediaType.FORM_DATA),
params.capture());
verify(connection, atLeast(0))
.sendPostRequest(
eq("/_dr/epptool"), eq(ImmutableMap.of()), eq(MediaType.FORM_DATA), params.capture());
capturedParams = ImmutableList.copyOf(params.getAllValues());
paramIndex = 0;
}
@ -198,7 +195,7 @@ public class EppToolVerifier {
}
/** Returns the (mock) Connection that is being monitored by this verifier. */
private Connection getConnection() {
private AppEngineConnection getConnection() {
return connection;
}
}

View file

@ -18,19 +18,14 @@ import static google.registry.testing.JUnitBackports.assertThrows;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.beust.jcommander.ParameterException;
import google.registry.testing.InjectRule;
import google.registry.tools.server.ToolsTestData;
import java.io.ByteArrayInputStream;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
/** Unit tests for {@link ExecuteEppCommand}. */
public class ExecuteEppCommandTest extends EppToolCommandTestCase<ExecuteEppCommand> {
@Rule
public InjectRule inject = new InjectRule();
private String xmlInput;
private String eppFile;
@ -60,8 +55,7 @@ public class ExecuteEppCommandTest extends EppToolCommandTestCase<ExecuteEppComm
@Test
public void testSuccess_fromStdin() throws Exception {
inject.setStaticField(
ExecuteEppCommand.class, "stdin", new ByteArrayInputStream(xmlInput.getBytes(UTF_8)));
System.setIn(new ByteArrayInputStream(xmlInput.getBytes(UTF_8)));
runCommand("--client=NewRegistrar", "--force");
eppVerifier.verifySent("contact_create.xml");
}

View file

@ -15,6 +15,9 @@
package google.registry.tools;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.DatastoreHelper.createTlds;
import static google.registry.testing.DatastoreHelper.newRegistry;
import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.assertThrows;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
@ -22,6 +25,7 @@ import static org.mockito.Mockito.verify;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.net.MediaType;
import google.registry.model.registry.Registry.TldType;
import google.registry.tools.server.ListDomainsAction;
import org.junit.Test;
@ -56,10 +60,23 @@ public class ListDomainsCommandTest extends ListObjectsCommandTestCase<ListDomai
public void test_bothParamsSpecified() throws Exception {
runCommand("--tlds=foo,bar", "--limit=100");
verify(connection)
.send(
.sendPostRequest(
eq(getTaskPath()),
eq(ImmutableMap.of("tlds", "foo,bar", "limit", 100)),
eq(MediaType.PLAIN_TEXT_UTF_8),
eq(new byte[0]));
}
@Test
public void test_defaultsToAllRealTlds() throws Exception {
createTlds("tldone", "tldtwo");
persistResource(newRegistry("fake", "FAKE").asBuilder().setTldType(TldType.TEST).build());
runCommand();
verify(connection)
.sendPostRequest(
eq(getTaskPath()),
eq(ImmutableMap.of("tlds", "tldone,tldtwo", "limit", Integer.MAX_VALUE)),
eq(MediaType.PLAIN_TEXT_UTF_8),
eq(new byte[0]));
}
}

View file

@ -28,7 +28,6 @@ import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.net.MediaType;
import google.registry.tools.CommandWithConnection.Connection;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
@ -38,7 +37,7 @@ import org.mockito.Mock;
public abstract class ListObjectsCommandTestCase<C extends ListObjectsCommand>
extends CommandTestCase<C> {
@Mock Connection connection;
@Mock AppEngineConnection connection;
/** Where to find the servlet task; set by the subclass. */
abstract String getTaskPath();
@ -62,7 +61,7 @@ public abstract class ListObjectsCommandTestCase<C extends ListObjectsCommand>
.collect(toImmutableList());
}
command.setConnection(connection);
when(connection.send(
when(connection.sendPostRequest(
eq(getTaskPath()),
anyMapOf(String.class, Object.class),
eq(MediaType.PLAIN_TEXT_UTF_8),
@ -82,7 +81,7 @@ public abstract class ListObjectsCommandTestCase<C extends ListObjectsCommand>
fullFieldNames.ifPresent(aBoolean -> params.put(FULL_FIELD_NAMES_PARAM, aBoolean));
params.putAll(getOtherParameters());
verify(connection)
.send(
.sendPostRequest(
eq(getTaskPath()), eq(params.build()), eq(MediaType.PLAIN_TEXT_UTF_8), eq(new byte[0]));
}

View file

@ -24,7 +24,6 @@ import static org.mockito.Mockito.verifyZeroInteractions;
import com.google.common.collect.ImmutableMap;
import com.google.common.net.MediaType;
import google.registry.model.registrar.Registrar;
import google.registry.tools.CommandWithConnection.Connection;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -32,7 +31,7 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class LoadTestCommandTest extends CommandTestCase<LoadTestCommand> {
Connection connection = mock(Connection.class);
AppEngineConnection connection = mock(AppEngineConnection.class);
@Before
public void setUp() {
@ -55,11 +54,9 @@ public class LoadTestCommandTest extends CommandTestCase<LoadTestCommand> {
.put("contactInfos", 1)
.put("runSeconds", 4600)
.build();
verify(connection).send(
eq("/_dr/loadtest"),
eq(parms),
eq(MediaType.PLAIN_TEXT_UTF_8),
eq(new byte[0]));
verify(connection)
.sendPostRequest(
eq("/_dr/loadtest"), eq(parms), eq(MediaType.PLAIN_TEXT_UTF_8), eq(new byte[0]));
}
@Test
@ -86,11 +83,9 @@ public class LoadTestCommandTest extends CommandTestCase<LoadTestCommand> {
.put("contactInfos", 15)
.put("runSeconds", 16)
.build();
verify(connection).send(
eq("/_dr/loadtest"),
eq(parms),
eq(MediaType.PLAIN_TEXT_UTF_8),
eq(new byte[0]));
verify(connection)
.sendPostRequest(
eq("/_dr/loadtest"), eq(parms), eq(MediaType.PLAIN_TEXT_UTF_8), eq(new byte[0]));
}
@Test

View file

@ -30,6 +30,7 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import google.registry.model.registrar.Registrar;
import google.registry.model.registrar.RegistrarContact;
import google.registry.model.registry.Registry;
import google.registry.model.registry.Registry.TldState;
import google.registry.testing.DeterministicStringGenerator;
@ -57,6 +58,7 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
@Before
public void init() {
SetupOteCommand.interactive = false;
command.validDnsWriterNames = ImmutableSet.of("FooDnsWriter", "BarDnsWriter", "VoidDnsWriter");
command.passwordGenerator = passwordGenerator;
persistPremiumList("default_sandbox_list", "sandbox,USD 1000");
@ -144,11 +146,22 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
verifyRegistrarCreation(registrarName, allowedTld, password, ipWhitelist, false);
}
private void verifyRegistrarContactCreation(String registrarName, String email) {
ImmutableSet<RegistrarContact> registrarContacts =
loadRegistrar(registrarName).getContacts();
assertThat(registrarContacts).hasSize(1);
RegistrarContact registrarContact = registrarContacts.stream().findAny().get();
assertThat(registrarContact.getEmailAddress()).isEqualTo(email);
assertThat(registrarContact.getName()).isEqualTo(email);
assertThat(registrarContact.getGaeUserId()).isNotNull();
}
@Test
public void testSuccess() throws Exception {
runCommandForced(
"--ip_whitelist=1.1.1.1",
"--registrar=blobio",
"--email=contact@email.com",
"--dns_writers=VoidDnsWriter",
"--certfile=" + getCertFilename());
@ -189,6 +202,12 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
verifyRegistrarCreation("blobio-3", "blobio-ga", passwords.get(2), ipAddress);
verifyRegistrarCreation("blobio-4", "blobio-ga", passwords.get(3), ipAddress);
verifyRegistrarCreation("blobio-5", "blobio-eap", passwords.get(4), ipAddress);
verifyRegistrarContactCreation("blobio-1", "contact@email.com");
verifyRegistrarContactCreation("blobio-2", "contact@email.com");
verifyRegistrarContactCreation("blobio-3", "contact@email.com");
verifyRegistrarContactCreation("blobio-4", "contact@email.com");
verifyRegistrarContactCreation("blobio-5", "contact@email.com");
}
@Test
@ -196,6 +215,7 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
runCommandForced(
"--ip_whitelist=1.1.1.1",
"--registrar=abc",
"--email=abc@email.com",
"--dns_writers=VoidDnsWriter",
"--certfile=" + getCertFilename());
@ -236,6 +256,12 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
verifyRegistrarCreation("abc-3", "abc-ga", passwords.get(2), ipAddress);
verifyRegistrarCreation("abc-4", "abc-ga", passwords.get(3), ipAddress);
verifyRegistrarCreation("abc-5", "abc-eap", passwords.get(4), ipAddress);
verifyRegistrarContactCreation("abc-1", "abc@email.com");
verifyRegistrarContactCreation("abc-2", "abc@email.com");
verifyRegistrarContactCreation("abc-3", "abc@email.com");
verifyRegistrarContactCreation("abc-4", "abc@email.com");
verifyRegistrarContactCreation("abc-5", "abc@email.com");
}
@Test
@ -244,6 +270,7 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
"--eap_only",
"--ip_whitelist=1.1.1.1",
"--registrar=blobio",
"--email=contact@email.com",
"--dns_writers=VoidDnsWriter",
"--certhash=" + SAMPLE_CERT_HASH);
@ -262,6 +289,8 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
ImmutableList.of(CidrAddressBlock.create("1.1.1.1"));
verifyRegistrarCreation("blobio-5", "blobio-eap", passwords.get(0), ipAddress, true);
verifyRegistrarContactCreation("blobio-5", "contact@email.com");
}
@Test
@ -270,6 +299,7 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
"--eap_only",
"--ip_whitelist=1.1.1.1",
"--registrar=blobio",
"--email=contact@email.com",
"--dns_writers=VoidDnsWriter",
"--certfile=" + getCertFilename());
@ -288,6 +318,8 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
CidrAddressBlock.create("1.1.1.1"));
verifyRegistrarCreation("blobio-5", "blobio-eap", passwords.get(0), ipAddress);
verifyRegistrarContactCreation("blobio-5", "contact@email.com");
}
@Test
@ -295,6 +327,7 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
runCommandForced(
"--ip_whitelist=1.1.1.1,2.2.2.2",
"--registrar=blobio",
"--email=contact@email.com",
"--dns_writers=FooDnsWriter",
"--certfile=" + getCertFilename());
@ -336,6 +369,12 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
verifyRegistrarCreation("blobio-3", "blobio-ga", passwords.get(2), ipAddresses);
verifyRegistrarCreation("blobio-4", "blobio-ga", passwords.get(3), ipAddresses);
verifyRegistrarCreation("blobio-5", "blobio-eap", passwords.get(4), ipAddresses);
verifyRegistrarContactCreation("blobio-1", "contact@email.com");
verifyRegistrarContactCreation("blobio-2", "contact@email.com");
verifyRegistrarContactCreation("blobio-3", "contact@email.com");
verifyRegistrarContactCreation("blobio-4", "contact@email.com");
verifyRegistrarContactCreation("blobio-5", "contact@email.com");
}
@Test
@ -343,6 +382,7 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
runCommandForced(
"--ip_whitelist=1.1.1.1",
"--registrar=blobio",
"--email=contact@email.com",
"--certfile=" + getCertFilename(),
"--dns_writers=BarDnsWriter",
"--premium_list=alternate_list");
@ -384,6 +424,12 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
verifyRegistrarCreation("blobio-3", "blobio-ga", passwords.get(2), ipAddress);
verifyRegistrarCreation("blobio-4", "blobio-ga", passwords.get(3), ipAddress);
verifyRegistrarCreation("blobio-5", "blobio-eap", passwords.get(4), ipAddress);
verifyRegistrarContactCreation("blobio-1", "contact@email.com");
verifyRegistrarContactCreation("blobio-2", "contact@email.com");
verifyRegistrarContactCreation("blobio-3", "contact@email.com");
verifyRegistrarContactCreation("blobio-4", "contact@email.com");
verifyRegistrarContactCreation("blobio-5", "contact@email.com");
}
@Test
@ -394,6 +440,7 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
() ->
runCommandForced(
"--registrar=blobio",
"--email=contact@email.com",
"--dns_writers=VoidDnsWriter",
"--certfile=" + getCertFilename()));
assertThat(thrown).hasMessageThat().contains("option is required: -w, --ip_whitelist");
@ -407,6 +454,7 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
() ->
runCommandForced(
"--ip_whitelist=1.1.1.1",
"--email=contact@email.com",
"--dns_writers=VoidDnsWriter",
"--certfile=" + getCertFilename()));
assertThat(thrown).hasMessageThat().contains("option is required: -r, --registrar");
@ -419,7 +467,10 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
IllegalArgumentException.class,
() ->
runCommandForced(
"--ip_whitelist=1.1.1.1", "--dns_writers=VoidDnsWriter", "--registrar=blobio"));
"--ip_whitelist=1.1.1.1",
"--email=contact@email.com",
"--dns_writers=VoidDnsWriter",
"--registrar=blobio"));
assertThat(thrown)
.hasMessageThat()
.contains(
@ -434,6 +485,7 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
() ->
runCommandForced(
"--ip_whitelist=1.1.1.1",
"--email=contact@email.com",
"--dns_writers=VoidDnsWriter",
"--registrar=blobio",
"--certfile=" + getCertFilename(),
@ -452,11 +504,26 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
() ->
runCommandForced(
"--ip_whitelist=1.1.1.1",
"--email=contact@email.com",
"--certfile=" + getCertFilename(),
"--registrar=blobio"));
assertThat(thrown).hasMessageThat().contains("option is required: --dns_writers");
}
@Test
public void testFailure_missingEmail() {
ParameterException thrown =
assertThrows(
ParameterException.class,
() ->
runCommandForced(
"--ip_whitelist=1.1.1.1",
"--dns_writers=VoidDnsWriter",
"--certfile=" + getCertFilename(),
"--registrar=blobio"));
assertThat(thrown).hasMessageThat().contains("option is required: --email");
}
@Test
public void testFailure_invalidCert() {
CertificateParsingException thrown =
@ -466,6 +533,7 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
runCommandForced(
"--ip_whitelist=1.1.1.1",
"--registrar=blobio",
"--email=contact@email.com",
"--dns_writers=VoidDnsWriter",
"--certfile=/dev/null"));
assertThat(thrown).hasMessageThat().contains("No X509Certificate found");
@ -480,6 +548,7 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
runCommandForced(
"--ip_whitelist=1.1.1.1",
"--registrar=3blobio",
"--email=contact@email.com",
"--dns_writers=VoidDnsWriter",
"--certfile=" + getCertFilename()));
assertThat(thrown).hasMessageThat().contains("Registrar name is invalid");
@ -494,6 +563,7 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
runCommandForced(
"--ip_whitelist=1.1.1.1",
"--registrar=blobio",
"--email=contact@email.com",
"--dns_writers=InvalidDnsWriter",
"--certfile=" + getCertFilename()));
assertThat(thrown)
@ -510,6 +580,7 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
runCommandForced(
"--ip_whitelist=1.1.1.1",
"--registrar=bl",
"--email=contact@email.com",
"--dns_writers=VoidDnsWriter",
"--certfile=" + getCertFilename()));
assertThat(thrown).hasMessageThat().contains("Registrar name is invalid");
@ -524,6 +595,7 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
runCommandForced(
"--ip_whitelist=1.1.1.1",
"--registrar=blobiotoooolong",
"--email=contact@email.com",
"--dns_writers=VoidDnsWriter",
"--certfile=" + getCertFilename()));
assertThat(thrown).hasMessageThat().contains("Registrar name is invalid");
@ -538,6 +610,7 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
runCommandForced(
"--ip_whitelist=1.1.1.1",
"--registrar=blo#bio",
"--email=contact@email.com",
"--dns_writers=VoidDnsWriter",
"--certfile=" + getCertFilename()));
assertThat(thrown).hasMessageThat().contains("Registrar name is invalid");
@ -552,6 +625,7 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
runCommandForced(
"--ip_whitelist=1.1.1.1",
"--registrar=blobio",
"--email=contact@email.com",
"--dns_writers=VoidDnsWriter",
"--certfile=" + getCertFilename(),
"--premium_list=foo"));
@ -568,6 +642,7 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
runCommandForced(
"--ip_whitelist=1.1.1.1",
"--registrar=blobio",
"--email=contact@email.com",
"--dns_writers=VoidDnsWriter",
"--certfile=" + getCertFilename()));
assertThat(thrown).hasMessageThat().contains("TLD 'blobio-sunrise' already exists");
@ -587,6 +662,7 @@ public class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
runCommandForced(
"--ip_whitelist=1.1.1.1",
"--registrar=blobio",
"--email=contact@email.com",
"--dns_writers=VoidDnsWriter",
"--certfile=" + getCertFilename()));
assertThat(thrown).hasMessageThat().contains("Registrar blobio-1 already exists");

View file

@ -53,6 +53,9 @@ public class ShellCommandTest {
PrintStream orgStdout;
PrintStream orgStderr;
ByteArrayOutputStream stdout;
ByteArrayOutputStream stderr;
public ShellCommandTest() {}
@Before
@ -152,7 +155,6 @@ public class ShellCommandTest {
public void testMultipleCommandInvocations() throws Exception {
try (RegistryCli cli =
new RegistryCli("unittest", ImmutableMap.of("test_command", TestCommand.class))) {
cli.uploadMetrics = false;
RegistryToolEnvironment.UNITTEST.setup();
cli.setEnvironment(RegistryToolEnvironment.UNITTEST);
cli.run(new String[] {"test_command", "-x", "xval", "arg1", "arg2"});
@ -170,7 +172,7 @@ public class ShellCommandTest {
public void testNonExistentCommand() {
try (RegistryCli cli =
new RegistryCli("unittest", ImmutableMap.of("test_command", TestCommand.class))) {
cli.uploadMetrics = false;
cli.setEnvironment(RegistryToolEnvironment.UNITTEST);
assertThrows(MissingCommandException.class, () -> cli.run(new String[] {"bad_command"}));
}
@ -270,14 +272,7 @@ public class ShellCommandTest {
@Test
public void testEncapsulatedOutput_command() throws Exception {
RegistryToolEnvironment.ALPHA.setup();
// capture output (have to do this before the shell command is created)
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
ByteArrayOutputStream stderr = new ByteArrayOutputStream();
System.setOut(new PrintStream(stdout));
System.setErr(new PrintStream(stderr));
System.setIn(new ByteArrayInputStream("command1\n".getBytes(UTF_8)));
captureOutput();
ShellCommand shellCommand =
new ShellCommand(
args -> {
@ -297,6 +292,33 @@ public class ShellCommandTest {
+ "SUCCESS\n");
}
@Test
public void testEncapsulatedOutput_noCommand() throws Exception {
captureOutput();
ShellCommand shellCommand =
createShellCommand(
args -> {
System.out.println("first line");
},
Duration.ZERO,
"",
"do something");
shellCommand.encapsulateOutput = true;
shellCommand.run();
assertThat(stderr.toString()).isEmpty();
assertThat(stdout.toString())
.isEqualTo("out: first line\nSUCCESS\n");
}
void captureOutput() {
// capture output (have to do this before the shell command is created)
stdout = new ByteArrayOutputStream();
stderr = new ByteArrayOutputStream();
System.setOut(new PrintStream(stdout));
System.setErr(new PrintStream(stderr));
System.setIn(new ByteArrayInputStream("command1\n".getBytes(UTF_8)));
}
@Parameters(commandDescription = "Test command")
static class TestCommand implements Command {
enum OrgType {

View file

@ -23,7 +23,6 @@ import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableMap;
import com.google.common.net.MediaType;
import google.registry.tools.CommandWithConnection.Connection;
import google.registry.tools.server.UpdatePremiumListAction;
import org.junit.Before;
import org.junit.Test;
@ -33,8 +32,7 @@ import org.mockito.Mock;
public class UpdatePremiumListCommandTest<C extends UpdatePremiumListCommand>
extends CreateOrUpdatePremiumListCommandTestCase<C> {
@Mock
Connection connection;
@Mock AppEngineConnection connection;
String premiumTermsPath;
String premiumTermsCsv;
@ -48,12 +46,12 @@ public class UpdatePremiumListCommandTest<C extends UpdatePremiumListCommand>
writeToNamedTmpFile(
"example_premium_terms.csv",
loadFile(UpdatePremiumListCommandTest.class, "example_premium_terms.csv"));
when(connection.send(
eq(UpdatePremiumListAction.PATH),
anyMapOf(String.class, String.class),
any(MediaType.class),
any(byte[].class)))
.thenReturn(JSON_SAFETY_PREFIX + "{\"status\":\"success\",\"lines\":[]}");
when(connection.sendPostRequest(
eq(UpdatePremiumListAction.PATH),
anyMapOf(String.class, String.class),
any(MediaType.class),
any(byte[].class)))
.thenReturn(JSON_SAFETY_PREFIX + "{\"status\":\"success\",\"lines\":[]}");
}
@Test

View file

@ -75,8 +75,6 @@ public class UpdateSmdCommandTest extends CommandTestCase<UpdateSmdCommand> {
@Before
public void init() {
// For SignedMark signature validity
inject.setStaticField(TmchCertificateAuthority.class, "clock", clock);
inject.setStaticField(Ofy.class, "clock", clock);
createTld("xn--q9jyb4c");
clock.advanceOneMilli();
@ -87,7 +85,7 @@ public class UpdateSmdCommandTest extends CommandTestCase<UpdateSmdCommand> {
.build());
clock.advanceOneMilli();
command.tmchUtils =
new DomainFlowTmchUtils(new TmchXmlSignature(new TmchCertificateAuthority(PILOT)));
new DomainFlowTmchUtils(new TmchXmlSignature(new TmchCertificateAuthority(PILOT, clock)));
}
private DomainApplication reloadDomainApplication() {

View file

@ -27,7 +27,6 @@ import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import google.registry.model.registrar.Registrar;
import google.registry.tools.CommandWithConnection.Connection;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
@ -35,7 +34,7 @@ import org.mockito.Mock;
/** Unit tests for {@link VerifyOteCommand}. */
public class VerifyOteCommandTest extends CommandTestCase<VerifyOteCommand> {
@Mock private Connection connection;
@Mock private AppEngineConnection connection;
@Before
public void init() throws Exception {

View file

@ -13,6 +13,7 @@ closure_js_library(
deps = [
"//java/google/registry/ui/js",
"//java/google/registry/ui/js/registrar",
"//java/google/registry/ui/soy/registrar",
"@io_bazel_rules_closure//closure/library",
"@io_bazel_rules_closure//closure/library:testing",
],
@ -28,7 +29,6 @@ closure_js_test(
":console_test_util",
"//java/google/registry/ui/js",
"//java/google/registry/ui/js/registrar",
"//java/google/registry/ui/soy/registrar",
"//javatests/google/registry/ui/js:testing",
"@io_bazel_rules_closure//closure/library",
"@io_bazel_rules_closure//closure/library:testing",

View file

@ -17,7 +17,6 @@ goog.setTestOnly();
goog.require('goog.dom');
goog.require('goog.dom.classlist');
goog.require('goog.json');
goog.require('goog.soy');
goog.require('goog.testing.MockControl');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.asserts');
@ -25,15 +24,14 @@ goog.require('goog.testing.jsunit');
goog.require('goog.testing.mockmatchers');
goog.require('goog.testing.net.XhrIo');
goog.require('registry.registrar.ConsoleTestUtil');
goog.require('registry.soy.registrar.console');
goog.require('registry.testing');
goog.require('registry.util');
var $ = goog.dom.getRequiredElement;
var stubs = new goog.testing.PropertyReplacer();
const $ = goog.dom.getRequiredElement;
const stubs = new goog.testing.PropertyReplacer();
var test = {
const test = {
testXsrfToken: 'testToken',
testClientId: 'daddy',
mockControl: new goog.testing.MockControl()
@ -44,24 +42,13 @@ function setUp() {
registry.testing.addToDocument('<div id="test"/>');
registry.testing.addToDocument('<div class="kd-butterbar"/>');
stubs.setPath('goog.net.XhrIo', goog.testing.net.XhrIo);
var testElt = goog.dom.getElement('test');
goog.soy.renderElement(testElt, registry.soy.registrar.console.main, {
registry.registrar.ConsoleTestUtil.renderConsoleMain($('test'), {
xsrfToken: test.testXsrfToken,
username: 'blah',
logoutUrl: 'omg',
isAdmin: true,
clientId: test.testClientId,
logoFilename: 'logo.png',
productName: 'Nomulus',
integrationEmail: 'integration@example.com',
supportEmail: 'support@example.com',
announcementsEmail: 'announcement@example.com',
supportPhoneNumber: '+1 (888) 555 0123',
technicalDocsUrl: 'http://example.com/techdocs',
});
registry.registrar.ConsoleTestUtil.setup(test);
var regNavlist = $('reg-navlist');
var active = regNavlist.querySelector('a[href="/registrar#contact-us"]');
const regNavlist = $('reg-navlist');
const active = regNavlist.querySelector('a[href="#contact-us"]');
assertTrue(active != null);
}
@ -78,7 +65,7 @@ function testButter() {
productName: 'Foo Registry'
});
registry.util.butter('butter msg');
var butter = goog.dom.getElementByClass(goog.getCssName('kd-butterbar'));
const butter = goog.dom.getElementByClass(goog.getCssName('kd-butterbar'));
assertNotNull(butter.innerHTML.match(/.*butter msg.*/));
assertTrue(goog.dom.classlist.contains(butter, goog.getCssName('shown')));
}
@ -131,7 +118,7 @@ function testNavToResources() {
premiumPriceAckRequired: false,
readonly: true,
});
var xhr = goog.testing.net.XhrIo.getSendInstances().pop();
const xhr = goog.testing.net.XhrIo.getSendInstances().pop();
assertTrue(xhr.isActive());
assertEquals('/registrar-settings', xhr.getLastUri());
assertEquals(test.testXsrfToken,
@ -157,12 +144,12 @@ function testNavToContactUs() {
announcementsEmail: 'announcement@example.com',
supportPhoneNumber: '+1 (888) 555 0123'
});
var xhr = goog.testing.net.XhrIo.getSendInstances().pop();
const xhr = goog.testing.net.XhrIo.getSendInstances().pop();
assertTrue(xhr.isActive());
assertEquals('/registrar-settings', xhr.getLastUri());
assertEquals(test.testXsrfToken,
xhr.getLastRequestHeaders()['X-CSRF-Token']);
var passcode = '5-5-5-5-5';
const passcode = '5-5-5-5-5';
xhr.simulateResponse(200, goog.json.serialize({
status: 'SUCCESS',
message: 'OK',

View file

@ -18,9 +18,11 @@ goog.setTestOnly('registry.registrar.ConsoleTestUtil');
goog.require('goog.History');
goog.require('goog.asserts');
goog.require('goog.dom.xml');
goog.require('goog.soy');
goog.require('goog.testing.mockmatchers');
goog.require('registry.registrar.Console');
goog.require('registry.registrar.EppSession');
goog.require('registry.soy.registrar.console');
goog.require('registry.xml');
@ -28,7 +30,7 @@ goog.require('registry.xml');
* Utility method that attaches mocks to a `TestCase`. This was
* originally in the ctor for ConsoleTest and should simply be
* inherited but jstd_test breaks inheritance in test cases.
* @param {Object} test the test case to configure.
* @param {!Object} test the test case to configure.
*/
registry.registrar.ConsoleTestUtil.setup = function(test) {
test.historyMock = test.mockControl.createLooseMock(goog.History, true);
@ -42,13 +44,42 @@ registry.registrar.ConsoleTestUtil.setup = function(test) {
.$returns(test.sessionMock);
};
/**
* Utility method that renders the registry.soy.registrar.console.main element.
*
* This element has a lot of parameters. We use defaults everywhere, but you can
* override them with 'opt_args'.
*
* @param {!Element} element the element whose content we are rendering into.
* @param {?Object=} opt_args override for the default values of the soy params.
*/
registry.registrar.ConsoleTestUtil.renderConsoleMain = function(
element, opt_args) {
const args = opt_args || {};
goog.soy.renderElement(element, registry.soy.registrar.console.main, {
xsrfToken: args.xsrfToken || 'ignore',
username: args.username || 'jart',
logoutUrl: args.logoutUrl || 'https://logout.url.com',
isAdmin: goog.isDefAndNotNull(args.isAdmin) ? args.isAdmin : true,
clientId: args.clientId || 'ignore',
allClientIds: args.allClientIds || ['clientId1', 'clientId2'],
logoFilename: args.logoFilename || 'logo.png',
productName: args.productName || 'Nomulus',
integrationEmail: args.integrationEmail || 'integration@example.com',
supportEmail: args.supportEmail || 'support@example.com',
announcementsEmail: args.announcementsEmail || 'announcement@example.com',
supportPhoneNumber: args.supportPhoneNumber || '+1 (888) 555 0123',
technicalDocsUrl: args.technicalDocsUrl || 'http://example.com/techdocs',
});
};
/**
* Simulates visiting a page on the console. Sets path, then mocks
* session and calls `handleHashChange_`.
* @param {Object} test the test case to configure.
* @param {Object=} opt_args may include path, isEppLoggedIn.
* @param {Function=} opt_moar extra setup after called just before
* @param {!Object} test the test case to configure.
* @param {?Object=} opt_args may include path, isEppLoggedIn.
* @param {?Function=} opt_moar extra setup after called just before
* `$replayAll`. See memegen/3437690.
*/
registry.registrar.ConsoleTestUtil.visit = function(
@ -72,7 +103,7 @@ registry.registrar.ConsoleTestUtil.visit = function(
goog.testing.mockmatchers.isFunction)
.$does(function(args, cb) {
// XXX: Args should be checked.
var xml = goog.dom.xml.loadXml(opt_args.rspXml);
const xml = goog.dom.xml.loadXml(opt_args.rspXml);
goog.asserts.assert(xml != null);
cb(registry.xml.convertToJson(xml));
}).$anyTimes();

View file

@ -17,23 +17,21 @@ goog.setTestOnly();
goog.require('goog.array');
goog.require('goog.dispose');
goog.require('goog.dom');
goog.require('goog.soy');
goog.require('goog.testing.MockControl');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.asserts');
goog.require('goog.testing.jsunit');
goog.require('goog.testing.net.XhrIo');
goog.require('registry.registrar.ConsoleTestUtil');
goog.require('registry.soy.registrar.console');
goog.require('registry.testing');
goog.require('registry.util');
var $ = goog.dom.getRequiredElement;
var stubs = new goog.testing.PropertyReplacer();
var testContact = null;
const $ = goog.dom.getRequiredElement;
const stubs = new goog.testing.PropertyReplacer();
let testContact = null;
var test = {
const test = {
testXsrfToken: '༼༎෴ ༎༽',
testClientId: 'testClientId',
mockControl: new goog.testing.MockControl()
@ -44,19 +42,9 @@ function setUp() {
registry.testing.addToDocument('<div id="test"/>');
registry.testing.addToDocument('<div class="kd-butterbar"/>');
testContact = createTestContact();
goog.soy.renderElement($('test'), registry.soy.registrar.console.main, {
registry.registrar.ConsoleTestUtil.renderConsoleMain($('test'), {
xsrfToken: test.testXsrfToken,
username: 'blah',
logoutUrl: 'omg',
isAdmin: true,
clientId: test.testClientId,
logoFilename: 'logo.png',
productName: 'Nomulus',
integrationEmail: 'integration@google.com',
supportEmail: 'support@google.com',
announcementsEmail: 'announcements@google.com',
supportPhoneNumber: '123 456 7890',
technicalDocsUrl: 'http://example.com/techdocs'
});
stubs.setPath('goog.net.XhrIo', goog.testing.net.XhrIo);
registry.registrar.ConsoleTestUtil.setup(test);
@ -82,7 +70,7 @@ function testCollectionView() {
registry.testing.assertReqMockRsp(
test.testXsrfToken,
'/registrar-settings',
{op: 'read', args: {}},
{op: 'read', id: 'testClientId', args: {}},
{
status: 'SUCCESS',
message: 'OK',
@ -106,7 +94,7 @@ function testItemView() {
registry.testing.assertReqMockRsp(
test.testXsrfToken,
'/registrar-settings',
{op: 'read', args: {}},
{op: 'read', id: 'testClientId', args: {}},
{
status: 'SUCCESS',
message: 'OK',
@ -149,6 +137,7 @@ function testItemEdit() {
'/registrar-settings',
{
op: 'update',
id: 'testClientId',
args: {
contacts: [testContact],
readonly: false
@ -181,6 +170,7 @@ function testChangeContactTypes() {
'/registrar-settings',
{
op: 'update',
id: 'testClientId',
args: {
contacts: [testContact],
readonly: false
@ -204,9 +194,9 @@ function testOneOfManyUpdate() {
registry.registrar.ConsoleTestUtil.visit(test, {
path: 'contact-settings/test@example.com',
xsrfToken: test.testXsrfToken,
testClientId: test.testClientId
clientId: test.testClientId
});
var testContacts = [
const testContacts = [
createTestContact('new1@asdf.com'),
testContact,
createTestContact('new2@asdf.com')
@ -214,7 +204,7 @@ function testOneOfManyUpdate() {
registry.testing.assertReqMockRsp(
test.testXsrfToken,
'/registrar-settings',
{op: 'read', args: {}},
{op: 'read', id: 'testClientId', args: {}},
{
status: 'SUCCESS',
message: 'OK',
@ -235,7 +225,14 @@ function testOneOfManyUpdate() {
registry.testing.assertReqMockRsp(
test.testXsrfToken,
'/registrar-settings',
{op: 'update', args: {contacts: testContacts, readonly: false}},
{
op: 'update',
id: 'testClientId',
args: {
contacts: testContacts,
readonly: false,
},
},
{
status: 'SUCCESS',
message: 'OK',
@ -251,13 +248,15 @@ function testDomainWhoisAbuseContactOverride() {
registry.registrar.ConsoleTestUtil.visit(test, {
path: 'contact-settings/test@example.com',
xsrfToken: test.testXsrfToken,
testClientId: test.testClientId
clientId: test.testClientId
});
var oldDomainWhoisAbuseContact = createTestContact('old@asdf.com');
const oldDomainWhoisAbuseContact = createTestContact('old@asdf.com');
oldDomainWhoisAbuseContact.visibleInDomainWhoisAsAbuse = true;
var testContacts = [oldDomainWhoisAbuseContact, testContact];
const testContacts = [oldDomainWhoisAbuseContact, testContact];
registry.testing.assertReqMockRsp(
test.testXsrfToken, '/registrar-settings', {op: 'read', args: {}},
test.testXsrfToken,
'/registrar-settings',
{op: 'read', id: 'testClientId', args: {}},
{status: 'SUCCESS', message: 'OK', results: [{contacts: testContacts}]});
// Edit testContact.
registry.testing.click($('reg-app-btn-edit'));
@ -271,8 +270,13 @@ function testDomainWhoisAbuseContactOverride() {
testContact.visibleInDomainWhoisAsAbuse = true;
oldDomainWhoisAbuseContact.visibleInDomainWhoisAsAbuse = false;
registry.testing.assertReqMockRsp(
test.testXsrfToken, '/registrar-settings',
{op: 'update', args: {contacts: testContacts, readonly: false}},
test.testXsrfToken,
'/registrar-settings',
{
op: 'update',
id: 'testClientId',
args: {contacts: testContacts, readonly: false},
},
{status: 'SUCCESS', message: 'OK', results: [{contacts: testContacts}]});
}
@ -281,9 +285,9 @@ function testDelete() {
registry.registrar.ConsoleTestUtil.visit(test, {
path: 'contact-settings/test@example.com',
xsrfToken: test.testXsrfToken,
testClientId: test.testClientId
clientId: test.testClientId
});
var testContacts = [
const testContacts = [
createTestContact('new1@asdf.com'),
testContact,
createTestContact('new2@asdf.com')
@ -291,7 +295,7 @@ function testDelete() {
registry.testing.assertReqMockRsp(
test.testXsrfToken,
'/registrar-settings',
{op: 'read', args: {}},
{op: 'read', id: 'testClientId', args: {}},
{
status: 'SUCCESS',
message: 'OK',
@ -309,7 +313,11 @@ function testDelete() {
registry.testing.assertReqMockRsp(
test.testXsrfToken,
'/registrar-settings',
{op: 'update', args: {contacts: testContacts, readonly: false}},
{
op: 'update',
id: 'testClientId',
args: {contacts: testContacts, readonly: false},
},
{
status: 'SUCCESS',
message: 'OK',
@ -323,10 +331,10 @@ function testDelete() {
/**
* @param {string=} opt_email
* @return {Object}
* @return {!Object}
*/
function createTestContact(opt_email) {
var nameMail = opt_email || 'test@example.com';
const nameMail = opt_email || 'test@example.com';
return {
name: nameMail,
emailAddress: nameMail,
@ -343,14 +351,14 @@ function createTestContact(opt_email) {
/**
* Convert parsed formContact to simulated wire form.
* @param {!Element} contact
* @return {Object}
* @return {!Object}
*/
function simulateJsonForContact(contact) {
contact.visibleInWhoisAsAdmin = contact.visibleInWhoisAsAdmin == 'true';
contact.visibleInWhoisAsTech = contact.visibleInWhoisAsTech == 'true';
contact.visibleInDomainWhoisAsAbuse = contact.visibleInDomainWhoisAsAbuse == 'true';
contact.types = '';
for (var tNdx in contact.type) {
for (const tNdx in contact.type) {
if (contact.type[tNdx]) {
if (contact.types.length > 0) {
contact.types += ',';

View file

@ -16,18 +16,16 @@ goog.setTestOnly();
goog.require('goog.dispose');
goog.require('goog.dom');
goog.require('goog.soy');
goog.require('goog.testing.MockControl');
goog.require('goog.testing.asserts');
goog.require('goog.testing.jsunit');
goog.require('registry.registrar.ConsoleTestUtil');
goog.require('registry.soy.registrar.console');
goog.require('registry.testing');
var $ = goog.dom.getRequiredElement;
const $ = goog.dom.getRequiredElement;
var test = {
const test = {
mockControl: new goog.testing.MockControl()
};
@ -35,20 +33,7 @@ var test = {
function setUp() {
registry.testing.addToDocument('<div id="test"/>');
registry.testing.addToDocument('<div class="kd-butterbar"/>');
goog.soy.renderElement($('test'), registry.soy.registrar.console.main, {
xsrfToken: 'test',
username: 'blah',
logoutUrl: 'omg',
isAdmin: true,
clientId: 'daddy',
logoFilename: 'logo.png',
productName: 'Nomulus',
integrationEmail: 'integration@example.com',
supportEmail: 'support@example.com',
announcementsEmail: 'announcement@example.com',
supportPhoneNumber: '+1 (888) 555 0123',
technicalDocsUrl: 'http://example.com/techdocs'
});
registry.registrar.ConsoleTestUtil.renderConsoleMain($('test'), {});
registry.registrar.ConsoleTestUtil.setup(test);
}
@ -126,7 +111,7 @@ function testEdit() {
/** Contact hash path should nav to contact page. */
function testAddPostalInfo() {
testEdit();
var addPiBtn = $('domain-contact-postalInfo-add-button');
const addPiBtn = $('domain-contact-postalInfo-add-button');
assertNull(addPiBtn.getAttribute('disabled'));
registry.testing.click(addPiBtn);
assertTrue(addPiBtn.hasAttribute('disabled'));

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