mv com/google/domain/registry google/registry

This change renames directories in preparation for the great package
rename. The repository is now in a broken state because the code
itself hasn't been updated. However this should ensure that git
correctly preserves history for each file.
This commit is contained in:
Justine Tunney 2016-05-13 18:55:08 -04:00
parent a41677aea1
commit 5012893c1d
2396 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,41 @@
package(
default_visibility = ["//java/com/google/domain/registry:registry_project"],
)
load("//java/com/google/testing/builddefs:GenTestRules.bzl", "GenTestRules")
java_library(
name = "server",
srcs = glob(["*.java"]),
resources = glob(["testdata/*"]),
deps = [
"//java/com/google/common/base",
"//java/com/google/common/collect",
"//java/com/google/domain/registry/groups",
"//java/com/google/domain/registry/mapreduce",
"//java/com/google/domain/registry/model",
"//java/com/google/domain/registry/request",
"//java/com/google/domain/registry/tools/server",
"//java/com/google/domain/registry/util",
"//javatests/com/google/domain/registry/model",
"//javatests/com/google/domain/registry/testing",
"//javatests/com/google/domain/registry/testing/mapreduce",
"//third_party/java/appengine:appengine-api-testonly",
"//third_party/java/appengine_gcs_client",
"//third_party/java/appengine_mapreduce2:appengine_mapreduce",
"//third_party/java/joda_money",
"//third_party/java/joda_time",
"//third_party/java/junit",
"//third_party/java/mockito",
"//third_party/java/objectify:objectify-v4_1",
"//third_party/java/servlet/servlet_api",
"//third_party/java/truth",
],
)
GenTestRules(
name = "GeneratedTestRules",
test_files = glob(["*Test.java"]),
deps = [":server"],
)

View file

@ -0,0 +1,155 @@
// Copyright 2016 The Domain Registry 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 com.google.domain.registry.tools.server;
import static com.google.common.truth.Truth.assertThat;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.common.base.Optional;
import com.google.domain.registry.groups.DirectoryGroupsConnection;
import com.google.domain.registry.groups.GroupsConnection.Role;
import com.google.domain.registry.request.HttpException.BadRequestException;
import com.google.domain.registry.request.HttpException.InternalServerErrorException;
import com.google.domain.registry.request.Response;
import com.google.domain.registry.testing.AppEngineRule;
import com.google.domain.registry.testing.ExceptionRule;
import com.google.domain.registry.testing.InjectRule;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
/**
* Unit tests for {@link CreateGroupsAction}.
*/
@RunWith(MockitoJUnitRunner.class)
public class CreateGroupsActionTest {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore()
.build();
@Rule
public final ExceptionRule thrown = new ExceptionRule();
@Rule
public final InjectRule inject = new InjectRule();
@Mock
private DirectoryGroupsConnection connection;
@Mock
private Response response;
private void runAction(String clientId) {
CreateGroupsAction action = new CreateGroupsAction();
action.response = response;
action.groupsConnection = connection;
action.publicDomainName = "domain-registry.example";
action.clientId = Optional.fromNullable(clientId);
action.run();
}
@Test
public void test_invalidRequest_missingClientId() throws Exception {
thrown.expect(BadRequestException.class,
"Error creating Google Groups, missing parameter: clientId");
runAction(null);
}
@Test
public void test_invalidRequest_invalidClientId() throws Exception {
thrown.expect(BadRequestException.class,
"Error creating Google Groups; could not find registrar with id completelyMadeUpClientId");
runAction("completelyMadeUpClientId");
}
@Test
public void test_createsAllGroupsSuccessfully() throws Exception {
runAction("NewRegistrar");
verify(response).setStatus(SC_OK);
verify(response).setPayload("Success!");
verifyGroupCreationCallsForNewRegistrar();
verify(connection).addMemberToGroup("registrar-primary-contacts@domain-registry.example",
"newregistrar-primary-contacts@domain-registry.example",
Role.MEMBER);
}
@Test
public void test_createsSomeGroupsSuccessfully_whenOthersFail() throws Exception {
when(connection.createGroup("newregistrar-primary-contacts@domain-registry.example"))
.thenThrow(new RuntimeException("Could not contact server."));
doThrow(new RuntimeException("Invalid access.")).when(connection).addMemberToGroup(
"registrar-technical-contacts@domain-registry.example",
"newregistrar-technical-contacts@domain-registry.example",
Role.MEMBER);
try {
runAction("NewRegistrar");
} catch (InternalServerErrorException e) {
String responseString = e.toString();
assertThat(responseString).contains("abuse => Success");
assertThat(responseString).contains("billing => Success");
assertThat(responseString).contains("legal => Success");
assertThat(responseString).contains("marketing => Success");
assertThat(responseString).contains("whois-inquiry => Success");
assertThat(responseString).contains(
"primary => java.lang.RuntimeException: Could not contact server.");
assertThat(responseString).contains(
"technical => java.lang.RuntimeException: Invalid access.");
verifyGroupCreationCallsForNewRegistrar();
return;
}
Assert.fail("Should have thrown InternalServerErrorException.");
}
private void verifyGroupCreationCallsForNewRegistrar() throws Exception {
verify(connection).createGroup("newregistrar-abuse-contacts@domain-registry.example");
verify(connection).createGroup("newregistrar-primary-contacts@domain-registry.example");
verify(connection).createGroup("newregistrar-billing-contacts@domain-registry.example");
verify(connection).createGroup("newregistrar-legal-contacts@domain-registry.example");
verify(connection).createGroup("newregistrar-marketing-contacts@domain-registry.example");
verify(connection).createGroup("newregistrar-technical-contacts@domain-registry.example");
verify(connection).createGroup("newregistrar-whois-inquiry-contacts@domain-registry.example");
verify(connection).addMemberToGroup("registrar-abuse-contacts@domain-registry.example",
"newregistrar-abuse-contacts@domain-registry.example",
Role.MEMBER);
// Note that addMemberToGroup for primary is verified separately for the success test because
// the exception thrown on group creation in the failure test causes the servlet not to get to
// this line.
verify(connection).addMemberToGroup("registrar-billing-contacts@domain-registry.example",
"newregistrar-billing-contacts@domain-registry.example",
Role.MEMBER);
verify(connection).addMemberToGroup("registrar-legal-contacts@domain-registry.example",
"newregistrar-legal-contacts@domain-registry.example",
Role.MEMBER);
verify(connection).addMemberToGroup("registrar-marketing-contacts@domain-registry.example",
"newregistrar-marketing-contacts@domain-registry.example",
Role.MEMBER);
verify(connection).addMemberToGroup("registrar-technical-contacts@domain-registry.example",
"newregistrar-technical-contacts@domain-registry.example",
Role.MEMBER);
verify(connection).addMemberToGroup(
"registrar-whois-inquiry-contacts@domain-registry.example",
"newregistrar-whois-inquiry-contacts@domain-registry.example",
Role.MEMBER);
}
}

View file

@ -0,0 +1,102 @@
// Copyright 2016 The Domain Registry 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 com.google.domain.registry.tools.server;
import static com.google.common.truth.Truth.assertThat;
import static com.google.domain.registry.testing.DatastoreHelper.createTlds;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import com.google.domain.registry.model.registry.label.PremiumList;
import com.google.domain.registry.testing.AppEngineRule;
import com.google.domain.registry.testing.ExceptionRule;
import com.google.domain.registry.testing.FakeJsonResponse;
import org.joda.money.Money;
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 CreatePremiumListAction}.
*/
@RunWith(JUnit4.class)
public class CreatePremiumListActionTest {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore()
.build();
@Rule
public final ExceptionRule thrown = new ExceptionRule();
CreatePremiumListAction action;
FakeJsonResponse response;
@Before
public void init() throws Exception {
createTlds("foo", "xn--q9jyb4c", "how");
PremiumList.get("foo").get().delete();
action = new CreatePremiumListAction();
response = new FakeJsonResponse();
action.response = response;
}
@Test
public void test_invalidRequest_missingInput_returnsErrorStatus() throws Exception {
action.name = "foo";
action.run();
assertThat(response.getResponseMap().get("status")).isEqualTo("error");
}
@Test
public void test_invalidRequest_listAlreadyExists_returnsErrorStatus() throws Exception {
action.name = "how";
action.inputData = "richer,JPY 5000";
action.run();
assertThat(response.getResponseMap().get("status")).isEqualTo("error");
Object obj = response.getResponseMap().get("error");
assertThat(obj).isInstanceOf(String.class);
String error = obj.toString();
assertThat(error).contains("A premium list of this name already exists");
}
@Test
public void test_nonExistentTld_successWithOverride() throws Exception {
action.name = "zanzibar";
action.inputData = "zanzibar,USD 100";
action.override = true;
action.run();
assertThat(response.getStatus()).isEqualTo(SC_OK);
PremiumList premiumList = PremiumList.get("zanzibar").get();
assertThat(premiumList.getPremiumListEntries()).hasSize(1);
assertThat(premiumList.getPremiumPrice("zanzibar")).hasValue(Money.parse("USD 100"));
assertThat(premiumList.getPremiumPrice("diamond")).isAbsent();
}
@Test
public void test_success() throws Exception {
action.name = "foo";
action.inputData = "rich,USD 25\nricher,USD 1000\n";
action.run();
assertThat(response.getStatus()).isEqualTo(SC_OK);
PremiumList premiumList = PremiumList.get("foo").get();
assertThat(premiumList.getPremiumListEntries()).hasSize(2);
assertThat(premiumList.getPremiumPrice("rich")).hasValue(Money.parse("USD 25"));
assertThat(premiumList.getPremiumPrice("diamond")).isAbsent();
}
}

View file

@ -0,0 +1,108 @@
// Copyright 2016 The Domain Registry 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 com.google.domain.registry.tools.server;
import static com.google.appengine.api.datastore.DatastoreServiceFactory.getDatastoreService;
import static com.google.common.truth.Truth.assertThat;
import static com.google.domain.registry.model.ofy.ObjectifyService.ofy;
import static com.googlecode.objectify.Key.create;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.domain.registry.model.registry.label.ReservedList;
import com.google.domain.registry.request.HttpException.BadRequestException;
import com.google.domain.registry.testing.AppEngineRule;
import com.google.domain.registry.testing.ExceptionRule;
import com.google.domain.registry.testing.FakeResponse;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
/** Unit tests for {@link DeleteEntityAction}. */
@RunWith(MockitoJUnitRunner.class)
public class DeleteEntityActionTest {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build();
@Rule
public final ExceptionRule thrown = new ExceptionRule();
FakeResponse response = new FakeResponse();
DeleteEntityAction action = new DeleteEntityAction();
@Before
public void init() throws Exception {
action.response = response;
}
@Test
public void test_deleteSingleRawEntitySuccessfully() throws Exception {
Entity entity = new Entity("single", "raw");
getDatastoreService().put(entity);
action.rawKeys = KeyFactory.keyToString(entity.getKey());
action.run();
assertThat(response.getPayload())
.isEqualTo("Deleted 1 raw entities and 0 registered entities");
}
@Test
public void test_deleteSingleRegisteredEntitySuccessfully() throws Exception {
ReservedList ofyEntity = new ReservedList.Builder().setName("foo").build();
ofy().saveWithoutBackup().entity(ofyEntity).now();
action.rawKeys = KeyFactory.keyToString(create(ofyEntity).getRaw());
action.run();
assertThat(response.getPayload())
.isEqualTo("Deleted 0 raw entities and 1 registered entities");
}
@Test
public void test_deleteOneRawEntityAndOneRegisteredEntitySuccessfully() throws Exception {
Entity entity = new Entity("first", "raw");
getDatastoreService().put(entity);
String rawKey = KeyFactory.keyToString(entity.getKey());
ReservedList ofyEntity = new ReservedList.Builder().setName("registered").build();
ofy().saveWithoutBackup().entity(ofyEntity).now();
String ofyKey = KeyFactory.keyToString(create(ofyEntity).getRaw());
action.rawKeys = String.format("%s,%s", rawKey, ofyKey);
action.run();
assertThat(response.getPayload())
.isEqualTo("Deleted 1 raw entities and 1 registered entities");
}
@Test
public void test_deleteNonExistentEntityRepliesWithError() throws Exception {
Entity entity = new Entity("not", "here");
String rawKey = KeyFactory.keyToString(entity.getKey());
action.rawKeys = rawKey;
thrown.expect(BadRequestException.class, "Could not find entity with key " + rawKey);
action.run();
}
@Test
public void test_deleteOneEntityAndNonExistentEntityRepliesWithError() throws Exception {
ReservedList ofyEntity = new ReservedList.Builder().setName("first_registered").build();
ofy().saveWithoutBackup().entity(ofyEntity).now();
String ofyKey = KeyFactory.keyToString(create(ofyEntity).getRaw());
Entity entity = new Entity("non", "existent");
String rawKey = KeyFactory.keyToString(entity.getKey());
action.rawKeys = String.format("%s,%s", ofyKey, rawKey);
thrown.expect(BadRequestException.class, "Could not find entity with key " + rawKey);
action.run();
}
}

View file

@ -0,0 +1,179 @@
// Copyright 2016 The Domain Registry 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 com.google.domain.registry.tools.server;
import static com.google.common.truth.Truth.assertThat;
import static com.google.domain.registry.model.ofy.ObjectifyService.ofy;
import static com.google.domain.registry.testing.DatastoreHelper.createTld;
import static com.google.domain.registry.testing.DatastoreHelper.persistActiveDomain;
import static com.google.domain.registry.testing.DatastoreHelper.persistDeletedDomain;
import static com.google.domain.registry.testing.DatastoreHelper.persistResource;
import static com.google.domain.registry.testing.DatastoreHelper.persistSimpleResource;
import static com.google.domain.registry.util.DateTimeUtils.START_OF_TIME;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
import com.google.domain.registry.mapreduce.MapreduceRunner;
import com.google.domain.registry.model.ImmutableObject;
import com.google.domain.registry.model.billing.BillingEvent;
import com.google.domain.registry.model.billing.BillingEvent.Reason;
import com.google.domain.registry.model.domain.DomainResource;
import com.google.domain.registry.model.index.EppResourceIndex;
import com.google.domain.registry.model.index.ForeignKeyIndex;
import com.google.domain.registry.model.poll.PollMessage;
import com.google.domain.registry.model.registry.Registry;
import com.google.domain.registry.model.registry.Registry.TldType;
import com.google.domain.registry.model.reporting.HistoryEntry;
import com.google.domain.registry.testing.ExceptionRule;
import com.google.domain.registry.testing.FakeResponse;
import com.google.domain.registry.testing.mapreduce.MapreduceTestCase;
import com.googlecode.objectify.Key;
import org.joda.money.Money;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.util.Set;
/** Unit tests for {@link DeleteProberDataAction}. */
@RunWith(JUnit4.class)
public class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDataAction> {
private static final DateTime DELETION_TIME = DateTime.parse("2010-01-01T00:00:00.000Z");
@Rule
public final ExceptionRule thrown = new ExceptionRule();
@Before
public void init() {
// Entities in these two should not be touched.
createTld("tld", "TLD");
// Since "example" doesn't end with .test, its entities won't be deleted even though it is of
// TEST type.
createTld("example", "EXAMPLE");
persistResource(Registry.get("example").asBuilder().setTldType(TldType.TEST).build());
// Entities in these two should be deleted.
createTld("ib-any.test", "IBANYT");
persistResource(Registry.get("ib-any.test").asBuilder().setTldType(TldType.TEST).build());
createTld("oa-canary.test", "OACANT");
persistResource(Registry.get("oa-canary.test").asBuilder().setTldType(TldType.TEST).build());
action = new DeleteProberDataAction();
action.mrRunner = new MapreduceRunner(Optional.<Integer>absent(), Optional.<Integer>absent());
action.response = new FakeResponse();
action.isDryRun = false;
}
private void runMapreduce() throws Exception {
action.run();
executeTasksUntilEmpty("mapreduce");
}
@Test
public void test_deletesAllAndOnlyProberData() throws Exception {
Set<ImmutableObject> tldEntities = persistLotsOfDomains("tld");
Set<ImmutableObject> exampleEntities = persistLotsOfDomains("example");
Set<ImmutableObject> ibEntities = persistLotsOfDomains("ib-any.test");
Set<ImmutableObject> oaEntities = persistLotsOfDomains("oa-canary.test");
runMapreduce();
assertNotDeleted(tldEntities);
assertNotDeleted(exampleEntities);
assertDeleted(ibEntities);
assertDeleted(oaEntities);
}
@Test
public void testSuccess_doesntDeleteNicDomainForProbers() throws Exception {
DomainResource nic = persistActiveDomain("nic.ib-any.test");
ForeignKeyIndex<DomainResource> fkiNic =
ForeignKeyIndex.load(DomainResource.class, "nic.ib-any.test", START_OF_TIME);
Set<ImmutableObject> ibEntities = persistLotsOfDomains("ib-any.test");
runMapreduce();
assertDeleted(ibEntities);
assertNotDeleted(ImmutableSet.<ImmutableObject>of(nic, fkiNic));
}
@Test
public void testSuccess_dryRunDoesntDeleteData() throws Exception {
Set<ImmutableObject> tldEntities = persistLotsOfDomains("tld");
Set<ImmutableObject> oaEntities = persistLotsOfDomains("oa-canary.test");
action.isDryRun = true;
assertNotDeleted(tldEntities);
assertNotDeleted(oaEntities);
}
/**
* Persists and returns a domain and a descendant history entry, billing event, and poll message,
* along with the ForeignKeyIndex and EppResourceIndex.
*/
private static Set<ImmutableObject> persistDomainAndDescendants(String fqdn) {
DomainResource domain = persistDeletedDomain(fqdn, DELETION_TIME);
HistoryEntry historyEntry = persistSimpleResource(
new HistoryEntry.Builder()
.setParent(domain)
.setType(HistoryEntry.Type.DOMAIN_CREATE)
.build());
BillingEvent.OneTime billingEvent = persistSimpleResource(
new BillingEvent.OneTime.Builder()
.setParent(historyEntry)
.setBillingTime(DELETION_TIME.plusYears(1))
.setCost(Money.parse("USD 10"))
.setPeriodYears(1)
.setReason(Reason.CREATE)
.setClientId("TheRegistrar")
.setEventTime(DELETION_TIME)
.setTargetId(fqdn)
.build());
PollMessage.OneTime pollMessage = persistSimpleResource(
new PollMessage.OneTime.Builder()
.setParent(historyEntry)
.setEventTime(DELETION_TIME)
.setClientId("TheRegistrar")
.setMsg("Domain registered")
.build());
ForeignKeyIndex<DomainResource> fki =
ForeignKeyIndex.load(DomainResource.class, fqdn, START_OF_TIME);
EppResourceIndex eppIndex =
ofy().load().entity(EppResourceIndex.create(Key.create(domain))).now();
return ImmutableSet.<ImmutableObject>of(
domain, historyEntry, billingEvent, pollMessage, fki, eppIndex);
}
private static Set<ImmutableObject> persistLotsOfDomains(String tld) {
ImmutableSet.Builder<ImmutableObject> persistedObjects = new ImmutableSet.Builder<>();
for (int i = 0; i < 20; i++) {
persistedObjects.addAll(persistDomainAndDescendants(String.format("domain%d.%s", i, tld)));
}
return persistedObjects.build();
}
private static void assertNotDeleted(Iterable<ImmutableObject> entities) {
for (ImmutableObject entity : entities) {
assertThat(ofy().load().entity(entity).now()).isNotNull();
}
}
private static void assertDeleted(Iterable<ImmutableObject> entities) {
for (ImmutableObject entity : entities) {
assertThat(ofy().load().entity(entity).now()).isNull();
}
}
}

View file

@ -0,0 +1,133 @@
// Copyright 2016 The Domain Registry 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 com.google.domain.registry.tools.server;
import static com.google.appengine.tools.cloudstorage.GcsServiceFactory.createGcsService;
import static com.google.common.truth.Truth.assertThat;
import static com.google.domain.registry.testing.DatastoreHelper.createTld;
import static com.google.domain.registry.testing.DatastoreHelper.newDomainResource;
import static com.google.domain.registry.testing.DatastoreHelper.newHostResource;
import static com.google.domain.registry.testing.DatastoreHelper.persistActiveContact;
import static com.google.domain.registry.testing.DatastoreHelper.persistActiveDomain;
import static com.google.domain.registry.testing.DatastoreHelper.persistActiveDomainApplication;
import static com.google.domain.registry.testing.DatastoreHelper.persistActiveHost;
import static com.google.domain.registry.testing.DatastoreHelper.persistResource;
import static com.google.domain.registry.testing.GcsTestingUtils.readGcsFile;
import static com.google.domain.registry.util.ResourceUtils.readResourceUtf8;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.joda.time.Duration.standardDays;
import com.google.appengine.tools.cloudstorage.GcsFilename;
import com.google.appengine.tools.cloudstorage.GcsService;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.domain.registry.mapreduce.MapreduceRunner;
import com.google.domain.registry.model.domain.ReferenceUnion;
import com.google.domain.registry.model.domain.secdns.DelegationSignerData;
import com.google.domain.registry.model.host.HostResource;
import com.google.domain.registry.testing.FakeClock;
import com.google.domain.registry.testing.mapreduce.MapreduceTestCase;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.net.InetAddress;
import java.util.Map;
/** Tests for {@link GenerateZoneFilesAction}.*/
@RunWith(JUnit4.class)
public class GenerateZoneFilesActionTest extends MapreduceTestCase<GenerateZoneFilesAction> {
private final GcsService gcsService = createGcsService();
@Test
public void testGenerate() throws Exception {
DateTime now = DateTime.now(DateTimeZone.UTC).withTimeAtStartOfDay();
createTld("tld");
createTld("com");
ImmutableSet<InetAddress> ips =
ImmutableSet.of(InetAddress.getByName("127.0.0.1"), InetAddress.getByName("::1"));
HostResource host1 =
persistResource(newHostResource("ns.foo.tld").asBuilder().addInetAddresses(ips).build());
HostResource host2 =
persistResource(newHostResource("ns.bar.tld").asBuilder().addInetAddresses(ips).build());
ImmutableSet<ReferenceUnion<HostResource>> nameservers =
ImmutableSet.of(
ReferenceUnion.<HostResource>create(host1),
ReferenceUnion.<HostResource>create(host2));
persistResource(newDomainResource("ns-and-ds.tld").asBuilder()
.addNameservers(nameservers)
.setDsData(ImmutableSet.of(DelegationSignerData.create(1, 2, 3, new byte[] {0, 1, 2})))
.build());
persistResource(newDomainResource("ns-only.tld").asBuilder()
.addNameservers(nameservers)
.build());
persistResource(newDomainResource("ds-only.tld").asBuilder()
.setDsData(ImmutableSet.of(DelegationSignerData.create(1, 2, 3, new byte[] {0, 1, 2})))
.build());
// These should be ignored; contact and applications aren't in DNS, hosts need to be from the
// same tld and have ip addresses, and domains need to be from the same tld and have hosts.
persistActiveContact("ignored_contact");
persistActiveDomainApplication("ignored_application.tld");
persistActiveHost("ignored.host.tld"); // No ips.
persistActiveDomain("ignored_domain.tld"); // No hosts or DS data.
persistResource(newHostResource("ignored.foo.com").asBuilder().addInetAddresses(ips).build());
persistResource(newDomainResource("ignored.com")
.asBuilder()
.addNameservers(nameservers)
.setDsData(ImmutableSet.of(DelegationSignerData.create(1, 2, 3, new byte[] {0, 1, 2})))
.build());
GenerateZoneFilesAction action = new GenerateZoneFilesAction();
action.mrRunner = new MapreduceRunner(Optional.<Integer>absent(), Optional.<Integer>absent());
action.bucket = "zonefiles-bucket";
action.gcsBufferSize = 123;
action.datastoreRetention = standardDays(29);
action.clock = new FakeClock(now.plusMinutes(2)); // Move past the actions' 2 minute check.
Map<String, Object> response = action.handleJsonRequest(ImmutableMap.<String, Object>of(
"tlds", ImmutableList.of("tld"),
"exportTime", now));
assertThat(response).containsEntry(
"filenames",
ImmutableList.of("gs://zonefiles-bucket/tld-" + now + ".zone"));
executeTasksUntilEmpty("mapreduce");
GcsFilename gcsFilename =
new GcsFilename("zonefiles-bucket", String.format("tld-%s.zone", now));
String generatedFile = new String(readGcsFile(gcsService, gcsFilename), UTF_8);
// The generated file contains spaces and tabs, but the golden file contains only spaces, as
// files with literal tabs irritate our build tools.
Splitter splitter = Splitter.on('\n').omitEmptyStrings();
Iterable<String> generatedFileLines = splitter.split(generatedFile.replaceAll("\t", " "));
Iterable<String> goldenFileLines =
splitter.split(readResourceUtf8(getClass(), "testdata/tld.zone"));
// The first line needs to be the same as the golden file.
assertThat(generatedFileLines.iterator().next()).isEqualTo(goldenFileLines.iterator().next());
// The remaining lines can be in any order.
assertThat(generatedFileLines).containsExactlyElementsIn(goldenFileLines);
}
}

View file

@ -0,0 +1,240 @@
// Copyright 2016 The Domain Registry 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 com.google.domain.registry.tools.server;
import static com.google.appengine.api.datastore.DatastoreServiceFactory.getDatastoreService;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.instanceOf;
import static com.google.common.base.Predicates.not;
import static com.google.common.collect.Multimaps.filterKeys;
import static com.google.common.truth.Truth.assertThat;
import static com.google.domain.registry.model.ofy.ObjectifyService.ofy;
import static com.google.domain.registry.model.server.ServerSecret.getServerSecret;
import static com.google.domain.registry.testing.DatastoreHelper.createTld;
import static com.google.domain.registry.testing.DatastoreHelper.newContactResource;
import static com.google.domain.registry.testing.DatastoreHelper.newDomainApplication;
import static com.google.domain.registry.testing.DatastoreHelper.newDomainResource;
import static com.google.domain.registry.testing.DatastoreHelper.newHostResource;
import static com.google.domain.registry.testing.DatastoreHelper.persistPremiumList;
import static com.google.domain.registry.testing.DatastoreHelper.persistReservedList;
import static com.google.domain.registry.testing.DatastoreHelper.persistResource;
import static com.google.domain.registry.testing.DatastoreHelper.persistResourceWithCommitLog;
import static com.google.domain.registry.util.DateTimeUtils.END_OF_TIME;
import static com.google.domain.registry.util.DateTimeUtils.START_OF_TIME;
import static java.util.Arrays.asList;
import static org.joda.money.CurrencyUnit.USD;
import com.google.appengine.api.datastore.Entity;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.domain.registry.mapreduce.MapreduceAction;
import com.google.domain.registry.model.EntityClasses;
import com.google.domain.registry.model.EppResource;
import com.google.domain.registry.model.ImmutableObject;
import com.google.domain.registry.model.annotations.VirtualEntity;
import com.google.domain.registry.model.billing.BillingEvent;
import com.google.domain.registry.model.billing.BillingEvent.Reason;
import com.google.domain.registry.model.billing.RegistrarBillingEntry;
import com.google.domain.registry.model.billing.RegistrarCredit;
import com.google.domain.registry.model.billing.RegistrarCredit.CreditType;
import com.google.domain.registry.model.billing.RegistrarCreditBalance;
import com.google.domain.registry.model.common.EntityGroupRoot;
import com.google.domain.registry.model.common.GaeUserIdConverter;
import com.google.domain.registry.model.export.LogsExportCursor;
import com.google.domain.registry.model.ofy.CommitLogCheckpoint;
import com.google.domain.registry.model.ofy.CommitLogCheckpointRoot;
import com.google.domain.registry.model.poll.PollMessage;
import com.google.domain.registry.model.rde.RdeMode;
import com.google.domain.registry.model.rde.RdeRevision;
import com.google.domain.registry.model.registrar.Registrar;
import com.google.domain.registry.model.registry.Registry;
import com.google.domain.registry.model.registry.RegistryCursor;
import com.google.domain.registry.model.registry.RegistryCursor.CursorType;
import com.google.domain.registry.model.reporting.HistoryEntry;
import com.google.domain.registry.model.server.Lock;
import com.google.domain.registry.model.smd.SignedMarkRevocationList;
import com.google.domain.registry.model.tmch.ClaimsListShard;
import com.google.domain.registry.model.tmch.TmchCrl;
import com.google.domain.registry.testing.mapreduce.MapreduceTestCase;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.VoidWork;
import org.joda.money.Money;
import org.junit.Test;
public abstract class KillAllActionTestCase<T> extends MapreduceTestCase<T>{
private final ImmutableSet<String> affectedKinds;
private static final ImmutableSet<String> ALL_PERSISTED_KINDS = FluentIterable
.from(EntityClasses.ALL_CLASSES)
.filter(
new Predicate<Class<?>>() {
@Override
public boolean apply(Class<?> clazz) {
return !clazz.isAnnotationPresent(VirtualEntity.class);
}})
.transform(EntityClasses.CLASS_TO_KIND_FUNCTION)
.toSet();
public KillAllActionTestCase(ImmutableSet<String> affectedKinds) {
this.affectedKinds = affectedKinds;
}
/** Create at least one of each type of entity in the schema. */
void createData() {
createTld("tld1");
createTld("tld2");
persistResource(CommitLogCheckpointRoot.create(START_OF_TIME.plusDays(1)));
persistResource(
CommitLogCheckpoint.create(
START_OF_TIME.plusDays(1),
ImmutableMap.of(1, START_OF_TIME.plusDays(2))));
for (EppResource resource : asList(
newDomainResource("foo.tld1"),
newDomainResource("foo.tld2"),
newDomainApplication("foo.tld1"),
newDomainApplication("foo.tld2"),
newContactResource("foo1"),
newContactResource("foo2"),
newHostResource("ns.foo.tld1"),
newHostResource("ns.foo.tld2"))) {
persistResourceWithCommitLog(resource);
HistoryEntry history =
persistResource(new HistoryEntry.Builder().setParent(resource).build());
BillingEvent.OneTime oneTime = persistResource(new BillingEvent.OneTime.Builder()
.setParent(history)
.setBillingTime(START_OF_TIME)
.setEventTime(START_OF_TIME)
.setClientId("")
.setTargetId("")
.setReason(Reason.ERROR)
.setCost(Money.of(USD, 1))
.build());
for (ImmutableObject descendant : asList(
new PollMessage.OneTime.Builder()
.setParent(history)
.setClientId("")
.setEventTime(START_OF_TIME)
.build(),
new PollMessage.Autorenew.Builder()
.setParent(history)
.setClientId("")
.setEventTime(START_OF_TIME)
.build(),
new BillingEvent.Cancellation.Builder()
.setOneTimeEventRef(Ref.create(oneTime))
.setParent(history)
.setBillingTime(START_OF_TIME)
.setEventTime(START_OF_TIME)
.setClientId("")
.setTargetId("")
.setReason(Reason.ERROR)
.build(),
new BillingEvent.Modification.Builder()
.setEventRef(Ref.create(oneTime))
.setParent(history)
.setEventTime(START_OF_TIME)
.setClientId("")
.setTargetId("")
.setReason(Reason.ERROR)
.setCost(Money.of(USD, 1))
.build(),
new BillingEvent.Recurring.Builder()
.setParent(history)
.setEventTime(START_OF_TIME)
.setClientId("")
.setTargetId("")
.setReason(Reason.ERROR)
.build())) {
persistResource(descendant);
}
}
persistResource(new RegistrarBillingEntry.Builder()
.setParent(Registrar.loadByClientId("TheRegistrar"))
.setCreated(START_OF_TIME)
.setDescription("description")
.setAmount(Money.of(USD, 1))
.build());
RegistrarCredit credit = persistResource(new RegistrarCredit.Builder()
.setParent(Registrar.loadByClientId("TheRegistrar"))
.setCreationTime(START_OF_TIME)
.setCurrency(USD)
.setDescription("description")
.setTld("tld1")
.setType(CreditType.AUCTION)
.build());
persistResource(new RegistrarCreditBalance.Builder()
.setParent(credit)
.setAmount(Money.of(USD, 1))
.setEffectiveTime(START_OF_TIME)
.setWrittenTime(START_OF_TIME)
.build());
persistPremiumList("premium", "a,USD 100", "b,USD 200");
persistReservedList("reserved", "lol,RESERVED_FOR_ANCHOR_TENANT,foobar1");
getServerSecret(); // Forces persist.
TmchCrl.set("crl content");
persistResource(new LogsExportCursor.Builder().build());
persistPremiumList("premium", "a,USD 100", "b,USD 200");
SignedMarkRevocationList.create(
START_OF_TIME, ImmutableMap.of("a", START_OF_TIME, "b", END_OF_TIME)).save();
ClaimsListShard.create(START_OF_TIME, ImmutableMap.of("a", "1", "b", "2")).save();
// These entities must be saved within a transaction.
ofy().transact(new VoidWork() {
@Override
public void vrun() {
RegistryCursor.save(Registry.get("tld1"), CursorType.BRDA, START_OF_TIME);
RdeRevision.saveRevision("tld1", START_OF_TIME, RdeMode.FULL, 0);
}});
// These entities intentionally don't expose constructors or factory methods.
getDatastoreService().put(new Entity(EntityGroupRoot.getCrossTldKey().getRaw()));
getDatastoreService().put(new Entity(Key.getKind(GaeUserIdConverter.class), 1));
getDatastoreService().put(new Entity(Key.getKind(Lock.class), 1));
}
abstract MapreduceAction createAction();
@Test
public void testKill() throws Exception {
createData();
ImmutableMultimap<String, Object> beforeContents = getDatastoreContents();
assertThat(beforeContents.keySet()).named("persisted test data")
.containsAllIn(ALL_PERSISTED_KINDS);
MapreduceAction action = createAction();
action.run();
executeTasksUntilEmpty("mapreduce");
ImmutableMultimap<String, Object> afterContents = getDatastoreContents();
assertThat(afterContents.keySet()).containsNoneIn(affectedKinds);
assertThat(afterContents)
.containsExactlyEntriesIn(filterKeys(beforeContents, not(in(affectedKinds))));
}
private ImmutableMultimap<String, Object> getDatastoreContents() {
ofy().clearSessionCache();
ImmutableMultimap.Builder<String, Object> contentsBuilder = new ImmutableMultimap.Builder<>();
// Filter out raw Entity objects created by the mapreduce.
for (Object obj : Iterables.filter(ofy().load(), not(instanceOf(Entity.class)))) {
contentsBuilder.put(Key.getKind(obj.getClass()), obj);
}
return contentsBuilder.build();
}
}

View file

@ -0,0 +1,57 @@
// Copyright 2016 The Domain Registry 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 com.google.domain.registry.tools.server;
import static com.google.domain.registry.model.EntityClasses.CLASS_TO_KIND_FUNCTION;
import static java.util.Arrays.asList;
import com.google.common.base.Optional;
import com.google.common.collect.FluentIterable;
import com.google.domain.registry.mapreduce.MapreduceAction;
import com.google.domain.registry.mapreduce.MapreduceRunner;
import com.google.domain.registry.model.ofy.CommitLogBucket;
import com.google.domain.registry.model.ofy.CommitLogCheckpoint;
import com.google.domain.registry.model.ofy.CommitLogCheckpointRoot;
import com.google.domain.registry.model.ofy.CommitLogManifest;
import com.google.domain.registry.model.ofy.CommitLogMutation;
import com.google.domain.registry.testing.FakeResponse;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link KillAllCommitLogsAction}.*/
@RunWith(JUnit4.class)
public class KillAllCommitLogsActionTest extends KillAllActionTestCase<KillAllCommitLogsAction> {
public KillAllCommitLogsActionTest() {
super(FluentIterable
.from(asList(
CommitLogBucket.class,
CommitLogCheckpoint.class,
CommitLogCheckpointRoot.class,
CommitLogMutation.class,
CommitLogManifest.class))
.transform(CLASS_TO_KIND_FUNCTION)
.toSet());
}
@Override
MapreduceAction createAction() {
action = new KillAllCommitLogsAction();
action.mrRunner = new MapreduceRunner(Optional.<Integer>absent(), Optional.<Integer>absent());
action.response = new FakeResponse();
return action;
}
}

View file

@ -0,0 +1,82 @@
// Copyright 2016 The Domain Registry 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 com.google.domain.registry.tools.server;
import static com.google.domain.registry.model.EntityClasses.CLASS_TO_KIND_FUNCTION;
import static java.util.Arrays.asList;
import com.google.common.base.Optional;
import com.google.common.collect.FluentIterable;
import com.google.domain.registry.mapreduce.MapreduceAction;
import com.google.domain.registry.mapreduce.MapreduceRunner;
import com.google.domain.registry.model.billing.RegistrarBillingEntry;
import com.google.domain.registry.model.billing.RegistrarCredit;
import com.google.domain.registry.model.billing.RegistrarCreditBalance;
import com.google.domain.registry.model.common.EntityGroupRoot;
import com.google.domain.registry.model.export.LogsExportCursor;
import com.google.domain.registry.model.registrar.Registrar;
import com.google.domain.registry.model.registrar.RegistrarContact;
import com.google.domain.registry.model.registry.Registry;
import com.google.domain.registry.model.registry.RegistryCursor;
import com.google.domain.registry.model.registry.label.PremiumList;
import com.google.domain.registry.model.registry.label.PremiumList.PremiumListEntry;
import com.google.domain.registry.model.registry.label.ReservedList;
import com.google.domain.registry.model.server.ServerSecret;
import com.google.domain.registry.model.smd.SignedMarkRevocationList;
import com.google.domain.registry.model.tmch.ClaimsListShard;
import com.google.domain.registry.model.tmch.ClaimsListShard.ClaimsListSingleton;
import com.google.domain.registry.model.tmch.TmchCrl;
import com.google.domain.registry.testing.FakeResponse;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link KillAllCommitLogsAction}.*/
@RunWith(JUnit4.class)
public class KillAllCrossTldEntitiesActionTest
extends KillAllActionTestCase<KillAllCrossTldEntitiesAction> {
public KillAllCrossTldEntitiesActionTest() {
super(FluentIterable
.from(asList(
ClaimsListShard.class,
ClaimsListSingleton.class,
EntityGroupRoot.class,
LogsExportCursor.class,
PremiumList.class,
PremiumListEntry.class,
Registrar.class,
RegistrarBillingEntry.class,
RegistrarContact.class,
RegistrarCredit.class,
RegistrarCreditBalance.class,
Registry.class,
RegistryCursor.class,
ReservedList.class,
ServerSecret.class,
SignedMarkRevocationList.class,
TmchCrl.class))
.transform(CLASS_TO_KIND_FUNCTION)
.toSet());
}
@Override
MapreduceAction createAction() {
action = new KillAllCrossTldEntitiesAction();
action.mrRunner = new MapreduceRunner(Optional.<Integer>absent(), Optional.<Integer>absent());
action.response = new FakeResponse();
return action;
}
}

View file

@ -0,0 +1,73 @@
// Copyright 2016 The Domain Registry 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 com.google.domain.registry.tools.server;
import static com.google.domain.registry.model.EntityClasses.CLASS_TO_KIND_FUNCTION;
import static java.util.Arrays.asList;
import com.google.common.base.Optional;
import com.google.common.collect.FluentIterable;
import com.google.domain.registry.mapreduce.MapreduceAction;
import com.google.domain.registry.mapreduce.MapreduceRunner;
import com.google.domain.registry.model.billing.BillingEvent;
import com.google.domain.registry.model.contact.ContactResource;
import com.google.domain.registry.model.domain.DomainBase;
import com.google.domain.registry.model.host.HostResource;
import com.google.domain.registry.model.index.DomainApplicationIndex;
import com.google.domain.registry.model.index.EppResourceIndex;
import com.google.domain.registry.model.index.ForeignKeyIndex.ForeignKeyContactIndex;
import com.google.domain.registry.model.index.ForeignKeyIndex.ForeignKeyDomainIndex;
import com.google.domain.registry.model.index.ForeignKeyIndex.ForeignKeyHostIndex;
import com.google.domain.registry.model.poll.PollMessage;
import com.google.domain.registry.model.reporting.HistoryEntry;
import com.google.domain.registry.testing.FakeResponse;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link KillAllEppResourcesAction}.*/
@RunWith(JUnit4.class)
public class KillAllEppResourcesActionTest
extends KillAllActionTestCase<KillAllEppResourcesAction> {
public KillAllEppResourcesActionTest() {
super(FluentIterable
.from(asList(
EppResourceIndex.class,
ForeignKeyContactIndex.class,
ForeignKeyDomainIndex.class,
ForeignKeyHostIndex.class,
DomainApplicationIndex.class,
DomainBase.class,
ContactResource.class,
HostResource.class,
HistoryEntry.class,
PollMessage.class,
BillingEvent.OneTime.class,
BillingEvent.Recurring.class,
BillingEvent.Cancellation.class,
BillingEvent.Modification.class))
.transform(CLASS_TO_KIND_FUNCTION)
.toSet());
}
@Override
MapreduceAction createAction() {
action = new KillAllEppResourcesAction();
action.mrRunner = new MapreduceRunner(Optional.<Integer>absent(), Optional.<Integer>absent());
action.response = new FakeResponse();
return action;
}
}

View file

@ -0,0 +1,92 @@
// Copyright 2016 The Domain Registry 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 com.google.domain.registry.tools.server;
import static com.google.common.truth.Truth.assertThat;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import com.google.common.base.Optional;
import com.google.domain.registry.testing.AppEngineRule;
import com.google.domain.registry.testing.ExceptionRule;
import com.google.domain.registry.testing.FakeJsonResponse;
import org.junit.Rule;
import java.util.List;
import java.util.regex.Pattern;
/**
* Base class for tests of list actions.
*/
public class ListActionTestCase {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore()
.build();
@Rule
public final ExceptionRule thrown = new ExceptionRule();
private FakeJsonResponse response;
void runAction(
ListObjectsAction<?> action,
Optional<String> fields,
Optional<Boolean> printHeaderRow,
Optional<Boolean> fullFieldNames) {
response = new FakeJsonResponse();
action.response = response;
action.fields = fields;
action.printHeaderRow = printHeaderRow;
action.fullFieldNames = fullFieldNames;
action.run();
assertThat(response.getStatus()).isEqualTo(SC_OK);
}
void testRunSuccess(
ListObjectsAction<?> action,
Optional<String> fields,
Optional<Boolean> printHeaderRow,
Optional<Boolean> fullFieldNames,
String ... expectedLinePatterns) {
assertThat(expectedLinePatterns).isNotNull();
runAction(action, fields, printHeaderRow, fullFieldNames);
assertThat(response.getResponseMap().get("status")).isEqualTo("success");
Object obj = response.getResponseMap().get("lines");
assertThat(obj).isInstanceOf(List.class);
@SuppressWarnings("unchecked")
List<String> lines = (List<String>) obj;
assertThat(lines).hasSize(expectedLinePatterns.length);
for (int i = 0; i < lines.size(); i++) {
assertThat(lines.get(i)).containsMatch(Pattern.compile(expectedLinePatterns[i]));
}
}
void testRunError(
ListObjectsAction<?> action,
Optional<String> fields,
Optional<Boolean> printHeaderRow,
Optional<Boolean> fullFieldNames,
String expectedErrorPattern) {
assertThat(expectedErrorPattern).isNotNull();
runAction(action, fields, printHeaderRow, fullFieldNames);
assertThat(response.getResponseMap().get("status")).isEqualTo("error");
Object obj = response.getResponseMap().get("error");
assertThat(obj).isInstanceOf(String.class);
String error = obj.toString();
assertThat(error).containsMatch(Pattern.compile(expectedErrorPattern));
}
}

View file

@ -0,0 +1,215 @@
// Copyright 2016 The Domain Registry 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 com.google.domain.registry.tools.server;
import static com.google.domain.registry.testing.DatastoreHelper.createTld;
import static com.google.domain.registry.testing.DatastoreHelper.createTlds;
import static com.google.domain.registry.testing.DatastoreHelper.persistActiveDomain;
import com.google.common.base.Optional;
import com.google.domain.registry.testing.FakeClock;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for {@link ListDomainsAction}.
*/
@RunWith(JUnit4.class)
public class ListDomainsActionTest extends ListActionTestCase {
ListDomainsAction action;
@Before
public void init() throws Exception {
createTld("foo");
action = new ListDomainsAction();
action.clock = new FakeClock(DateTime.parse("2000-01-01TZ"));
}
@Test
public void testRun_invalidRequest_missingTld() throws Exception {
action.tld = null;
testRunError(
action,
null,
null,
null,
"^Null or empty TLD specified$");
}
@Test
public void testRun_invalidRequest_invalidTld() throws Exception {
action.tld = "%%%badtld%%%";
testRunError(
action,
null,
null,
null,
"^TLD %%%badtld%%% does not exist$");
}
@Test
public void testRun_noParameters() throws Exception {
action.tld = "foo";
testRunSuccess(
action,
null,
null,
null);
}
@Test
public void testRun_twoLinesWithIdOnly() throws Exception {
action.tld = "foo";
createTlds("bar", "sim");
persistActiveDomain("dontlist.bar");
persistActiveDomain("example1.foo");
persistActiveDomain("example2.foo");
persistActiveDomain("notlistedaswell.sim");
// Only list the two domains in .foo, not the .bar or .sim ones.
testRunSuccess(
action,
null,
null,
null,
"^example1.foo$",
"^example2.foo$");
}
@Test
public void testRun_twoLinesWithIdOnlyNoHeader() throws Exception {
action.tld = "foo";
persistActiveDomain("example1.foo");
persistActiveDomain("example2.foo");
testRunSuccess(
action,
null,
Optional.of(false),
null,
"^example1.foo$",
"^example2.foo$");
}
@Test
public void testRun_twoLinesWithIdOnlyExplicitHeader() throws Exception {
action.tld = "foo";
persistActiveDomain("example1.foo");
persistActiveDomain("example2.foo");
testRunSuccess(
action,
null,
Optional.of(true),
null,
"^fullyQualifiedDomainName$",
"^-+\\s*$",
"^example1.foo\\s*$",
"^example2.foo\\s*$");
}
@Test
public void testRun_twoLinesWithRepoId() throws Exception {
action.tld = "foo";
persistActiveDomain("example1.foo");
persistActiveDomain("example3.foo");
testRunSuccess(
action,
Optional.of("repoId"),
null,
null,
"^fullyQualifiedDomainName\\s+repoId\\s*$",
"^-+\\s+-+\\s*$",
"^example1.foo\\s+2-FOO\\s*$",
"^example3.foo\\s+4-FOO\\s*$");
}
@Test
public void testRun_twoLinesWithRepoIdNoHeader() throws Exception {
action.tld = "foo";
persistActiveDomain("example1.foo");
persistActiveDomain("example3.foo");
testRunSuccess(
action,
Optional.of("repoId"),
Optional.of(false),
null,
"^example1.foo 2-FOO$",
"^example3.foo 4-FOO$");
}
@Test
public void testRun_twoLinesWithRepoIdExplicitHeader() throws Exception {
action.tld = "foo";
persistActiveDomain("example1.foo");
persistActiveDomain("example3.foo");
testRunSuccess(
action,
Optional.of("repoId"),
Optional.of(true),
null,
"^fullyQualifiedDomainName\\s+repoId\\s*$",
"^-+\\s+-+\\s*$",
"^example1.foo\\s+2-FOO\\s*$",
"^example3.foo\\s+4-FOO\\s*$");
}
@Test
public void testRun_twoLinesWithWildcard() throws Exception {
action.tld = "foo";
persistActiveDomain("example1.foo");
persistActiveDomain("example3.foo");
testRunSuccess(
action,
Optional.of("*"),
null,
null,
"^fullyQualifiedDomainName\\s+.*repoId",
"^-+\\s+-+",
"^example1.foo\\s+.*2-FOO",
"^example3.foo\\s+.*4-FOO");
}
@Test
public void testRun_twoLinesWithWildcardAndAnotherField() throws Exception {
action.tld = "foo";
persistActiveDomain("example1.foo");
persistActiveDomain("example3.foo");
testRunSuccess(
action,
Optional.of("*,repoId"),
null,
null,
"^fullyQualifiedDomainName\\s+.*repoId",
"^-+\\s+-+",
"^example1.foo\\s+.*2-FOO",
"^example3.foo\\s+.*4-FOO");
}
@Test
public void testRun_withBadField_returnsError() throws Exception {
action.tld = "foo";
persistActiveDomain("example2.foo");
persistActiveDomain("example1.foo");
testRunError(
action,
Optional.of("badfield"),
null,
null,
"^Field 'badfield' not found - recognized fields are:");
}
}

View file

@ -0,0 +1,109 @@
// Copyright 2016 The Domain Registry 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 com.google.domain.registry.tools.server;
import static com.google.domain.registry.testing.DatastoreHelper.createTld;
import static com.google.domain.registry.testing.DatastoreHelper.persistActiveHost;
import com.google.common.base.Optional;
import com.google.domain.registry.testing.FakeClock;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for {@link ListHostsAction}.
*/
@RunWith(JUnit4.class)
public class ListHostsActionTest extends ListActionTestCase {
ListHostsAction action;
@Before
public void init() throws Exception {
createTld("foo");
action = new ListHostsAction();
action.clock = new FakeClock(DateTime.parse("2000-01-01TZ"));
}
@Test
public void testRun_noParameters() throws Exception {
testRunSuccess(
action,
null,
null,
null);
}
@Test
public void testRun_twoLinesWithRepoId() throws Exception {
persistActiveHost("example2.foo");
persistActiveHost("example1.foo");
testRunSuccess(
action,
Optional.of("repoId"),
null,
null,
"^fullyQualifiedHostName\\s+repoId\\s*$",
"^-+\\s+-+\\s*$",
"^example1.foo\\s+3-ROID\\s*$",
"^example2.foo\\s+2-ROID\\s*$");
}
@Test
public void testRun_twoLinesWithWildcard() throws Exception {
persistActiveHost("example2.foo");
persistActiveHost("example1.foo");
testRunSuccess(
action,
Optional.of("*"),
null,
null,
"^fullyQualifiedHostName\\s+.*repoId",
"^-+\\s+-+",
"^example1.foo\\s+.*2",
"^example2.foo\\s+.*1");
}
@Test
public void testRun_twoLinesWithWildcardAndAnotherField() throws Exception {
persistActiveHost("example2.foo");
persistActiveHost("example1.foo");
testRunSuccess(
action,
Optional.of("*,repoId"),
null,
null,
"^fullyQualifiedHostName\\s+.*repoId",
"^-+\\s+-+",
"^example1.foo\\s+.*2",
"^example2.foo\\s+.*1");
}
@Test
public void testRun_withBadField_returnsError() throws Exception {
persistActiveHost("example2.foo");
persistActiveHost("example1.foo");
testRunError(
action,
Optional.of("badfield"),
null,
null,
"^Field 'badfield' not found - recognized fields are:");
}
}

View file

@ -0,0 +1,92 @@
// Copyright 2016 The Domain Registry 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 com.google.domain.registry.tools.server;
import static com.google.domain.registry.testing.DatastoreHelper.persistPremiumList;
import com.google.common.base.Optional;
import com.google.domain.registry.model.registry.label.PremiumList;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for {@link ListPremiumListsAction}.
*/
@RunWith(JUnit4.class)
public class ListPremiumListsActionTest extends ListActionTestCase {
ListPremiumListsAction action;
@Before
public void init() throws Exception {
persistPremiumList("xn--q9jyb4c", "rich,USD 100");
persistPremiumList("how", "richer,JPY 5000");
PremiumList.get("how").get().asBuilder()
.setDescription("foobar")
.build()
.saveAndUpdateEntries();
action = new ListPremiumListsAction();
}
@Test
public void testRun_noParameters() throws Exception {
testRunSuccess(
action,
null,
null,
null,
"^how $",
"^xn--q9jyb4c$");
}
@Test
public void testRun_withParameters() throws Exception {
testRunSuccess(
action,
Optional.of("revisionKey,description"),
null,
null,
"^name\\s+revisionKey\\s+description\\s*$",
"^-+\\s+-+\\s+-+\\s*$",
"^how\\s+.*PremiumList.*$",
"^xn--q9jyb4c\\s+.*PremiumList.*$");
}
@Test
public void testRun_withWildcard() throws Exception {
testRunSuccess(
action,
Optional.of("*"),
null,
null,
"^name\\s+.*revisionKey",
"^-+\\s+-+.*",
"^how\\s+.*PremiumList",
"^xn--q9jyb4c\\s+.*PremiumList");
}
@Test
public void testRun_withBadField_returnsError() throws Exception {
testRunError(
action,
Optional.of("badfield"),
null,
null,
"^Field 'badfield' not found - recognized fields are:");
}
}

View file

@ -0,0 +1,101 @@
// Copyright 2016 The Domain Registry 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 com.google.domain.registry.tools.server;
import static com.google.domain.registry.testing.DatastoreHelper.createTlds;
import static com.google.domain.registry.testing.DatastoreHelper.persistResource;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
import com.google.domain.registry.model.registrar.Registrar;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for {@link ListRegistrarsAction}.
*/
@RunWith(JUnit4.class)
public class ListRegistrarsActionTest extends ListActionTestCase {
ListRegistrarsAction action;
@Before
public void init() throws Exception {
action = new ListRegistrarsAction();
createTlds("xn--q9jyb4c", "example");
// Ensure that NewRegistrar only has access to xn--q9jyb4c and that TheRegistrar only has access
// to example.
persistResource(
Registrar.loadByClientId("NewRegistrar")
.asBuilder()
.setAllowedTlds(ImmutableSet.of("xn--q9jyb4c"))
.build());
persistResource(
Registrar.loadByClientId("TheRegistrar")
.asBuilder()
.setAllowedTlds(ImmutableSet.of("example"))
.build());
}
@Test
public void testRun_noParameters() throws Exception {
testRunSuccess(
action,
null,
null,
null,
"^NewRegistrar$",
"^TheRegistrar$");
}
@Test
public void testRun_withParameters() throws Exception {
testRunSuccess(
action,
Optional.of("allowedTlds"),
null,
null,
"^clientId\\s+allowedTlds\\s*$",
"-+\\s+-+\\s*$",
"^NewRegistrar\\s+\\[xn--q9jyb4c\\]\\s*$",
"^TheRegistrar\\s+\\[example\\]\\s*$");
}
@Test
public void testRun_withWildcard() throws Exception {
testRunSuccess(
action,
Optional.of("*"),
null,
null,
"^clientId\\s+.*allowedTlds",
"^-+\\s+-+",
"^NewRegistrar\\s+.*\\[xn--q9jyb4c\\]",
"^TheRegistrar\\s+.*\\[example\\]");
}
@Test
public void testRun_withBadField_returnsError() throws Exception {
testRunError(
action,
Optional.of("badfield"),
null,
null,
"^Field 'badfield' not found - recognized fields are:");
}
}

View file

@ -0,0 +1,93 @@
// Copyright 2016 The Domain Registry 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 com.google.domain.registry.tools.server;
import static com.google.domain.registry.testing.DatastoreHelper.createTld;
import static com.google.domain.registry.testing.DatastoreHelper.persistReservedList;
import static com.google.domain.registry.testing.DatastoreHelper.persistResource;
import com.google.common.base.Optional;
import com.google.domain.registry.model.registry.Registry;
import com.google.domain.registry.model.registry.label.ReservedList;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for {@link ListReservedListsAction}.
*/
@RunWith(JUnit4.class)
public class ListReservedListsActionTest extends ListActionTestCase {
ListReservedListsAction action;
@Before
public void init() throws Exception {
ReservedList rl1 = persistReservedList("xn--q9jyb4c-published", true, "blah,FULLY_BLOCKED");
ReservedList rl2 = persistReservedList("xn--q9jyb4c-private", false, "dugong,FULLY_BLOCKED");
createTld("xn--q9jyb4c");
persistResource(Registry.get("xn--q9jyb4c").asBuilder().setReservedLists(rl1, rl2).build());
action = new ListReservedListsAction();
}
@Test
public void testRun_noParameters() throws Exception {
testRunSuccess(
action,
null,
null,
null,
"^xn--q9jyb4c-private\\s*$",
"^xn--q9jyb4c-published\\s*$");
}
@Test
public void testRun_withParameters() throws Exception {
testRunSuccess(
action,
Optional.of("shouldPublish"),
null,
null,
"^name\\s+shouldPublish\\s*$",
"^-+\\s+-+\\s*$",
"^xn--q9jyb4c-private\\s+false\\s*$",
"^xn--q9jyb4c-published\\s+true\\s*$");
}
@Test
public void testRun_withWildcard() throws Exception {
testRunSuccess(
action,
Optional.of("*"),
null,
null,
"^name\\s+.*shouldPublish.*",
"^-+\\s+-+",
"^xn--q9jyb4c-private\\s+.*false",
"^xn--q9jyb4c-published\\s+.*true");
}
@Test
public void testRun_withBadField_returnsError() throws Exception {
testRunError(
action,
Optional.of("badfield"),
null,
null,
"^Field 'badfield' not found - recognized fields are:");
}
}

View file

@ -0,0 +1,81 @@
// Copyright 2016 The Domain Registry 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 com.google.domain.registry.tools.server;
import static com.google.domain.registry.testing.DatastoreHelper.createTld;
import com.google.common.base.Optional;
import com.google.domain.registry.testing.FakeClock;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for {@link ListTldsAction}.
*/
@RunWith(JUnit4.class)
public class ListTldsActionTest extends ListActionTestCase {
ListTldsAction action;
@Before
public void init() throws Exception {
createTld("xn--q9jyb4c");
action = new ListTldsAction();
action.clock = new FakeClock(DateTime.parse("2000-01-01TZ"));
}
@Test
public void testRun_noParameters() throws Exception {
testRunSuccess(action, null, null, null, "xn--q9jyb4c");
}
@Test
public void testRun_withParameters() throws Exception {
testRunSuccess(
action,
Optional.of("tldType"),
null,
null,
"TLD tldType",
"----------- -------",
"xn--q9jyb4c REAL ");
}
@Test
public void testRun_withWildcard() throws Exception {
testRunSuccess(
action,
Optional.of("*"),
null,
null,
"^TLD .*tldType",
"^----------- .*-------",
"^xn--q9jyb4c .*REAL ");
}
@Test
public void testRun_withBadField_returnsError() throws Exception {
testRunError(
action,
Optional.of("badfield"),
null,
null,
"^Field 'badfield' not found - recognized fields are:");
}
}

View file

@ -0,0 +1,61 @@
// Copyright 2016 The Domain Registry 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 com.google.domain.registry.tools.server;
import static com.google.common.truth.Truth.assertThat;
import static com.google.domain.registry.model.ofy.ObjectifyService.ofy;
import static com.google.domain.registry.testing.DatastoreHelper.persistActiveContact;
import com.google.common.base.Optional;
import com.google.domain.registry.mapreduce.MapreduceRunner;
import com.google.domain.registry.model.contact.ContactResource;
import com.google.domain.registry.testing.FakeResponse;
import com.google.domain.registry.testing.mapreduce.MapreduceTestCase;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link ResaveAllEppResourcesAction}. */
@RunWith(JUnit4.class)
public class ResaveAllEppResourcesActionTest
extends MapreduceTestCase<ResaveAllEppResourcesAction> {
@Before
public void init() {
action = new ResaveAllEppResourcesAction();
action.mrRunner = new MapreduceRunner(Optional.<Integer>absent(), Optional.<Integer>absent());
action.response = new FakeResponse();
}
private void runMapreduce() throws Exception {
action.run();
executeTasksUntilEmpty("mapreduce");
}
@Test
public void test_mapreduceSuccessfullyResavesEntity() throws Exception {
ContactResource contact = persistActiveContact("test123");
DateTime creationTime = contact.getUpdateAutoTimestamp().getTimestamp();
assertThat(ofy().load().entity(contact).now().getUpdateAutoTimestamp().getTimestamp())
.isEqualTo(creationTime);
ofy().clearSessionCache();
runMapreduce();
assertThat(ofy().load().entity(contact).now().getUpdateAutoTimestamp().getTimestamp())
.isGreaterThan(creationTime);
}
}

View file

@ -0,0 +1,90 @@
// Copyright 2016 The Domain Registry 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 com.google.domain.registry.tools.server;
import static com.google.common.truth.Truth.assertThat;
import static com.google.domain.registry.testing.DatastoreHelper.createTlds;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import com.google.domain.registry.model.registry.label.PremiumList;
import com.google.domain.registry.testing.AppEngineRule;
import com.google.domain.registry.testing.ExceptionRule;
import com.google.domain.registry.testing.FakeJsonResponse;
import org.joda.money.Money;
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 UpdatePremiumListAction}.
*/
@RunWith(JUnit4.class)
public class UpdatePremiumListActionTest {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore()
.build();
@Rule
public final ExceptionRule thrown = new ExceptionRule();
UpdatePremiumListAction action;
FakeJsonResponse response;
@Before
public void init() throws Exception {
createTlds("foo", "xn--q9jyb4c", "how");
action = new UpdatePremiumListAction();
response = new FakeJsonResponse();
action.response = response;
}
@Test
public void test_invalidRequest_missingInput_returnsErrorStatus() throws Exception {
action.name = "foo";
action.run();
assertThat(response.getResponseMap().get("status")).isEqualTo("error");
}
@Test
public void test_invalidRequest_listDoesNotExist_returnsErrorStatus() throws Exception {
action.name = "bamboozle";
action.inputData = "richer,JPY 5000";
action.run();
assertThat(response.getResponseMap().get("status")).isEqualTo("error");
Object obj = response.getResponseMap().get("error");
assertThat(obj).isInstanceOf(String.class);
String error = obj.toString();
assertThat(error).contains("Could not update premium list");
}
@Test
public void test_success() throws Exception {
action.name = "foo";
action.inputData = "rich,USD 75\nricher,USD 5000\npoor, USD 0.99";
action.run();
assertThat(response.getStatus()).isEqualTo(SC_OK);
PremiumList premiumList = PremiumList.get("foo").get();
assertThat(premiumList.getPremiumListEntries()).hasSize(3);
assertThat(premiumList.getPremiumPrice("rich")).hasValue(Money.parse("USD 75"));
assertThat(premiumList.getPremiumPrice("richer")).hasValue(Money.parse("USD 5000"));
assertThat(premiumList.getPremiumPrice("poor")).hasValue(Money.parse("USD 0.99"));
assertThat(premiumList.getPremiumPrice("diamond")).isAbsent();
}
}

View file

@ -0,0 +1,16 @@
$ORIGIN tld.
ns.bar.tld 3600 IN A 127.0.0.1
ns.bar.tld 3600 IN AAAA 0:0:0:0:0:0:0:1
ns-only.tld 180 IN NS ns.foo.tld.
ns-only.tld 180 IN NS ns.bar.tld.
ds-only.tld 86400 IN DS 1 2 3 000102
ns-and-ds.tld 180 IN NS ns.foo.tld.
ns-and-ds.tld 180 IN NS ns.bar.tld.
ns-and-ds.tld 86400 IN DS 1 2 3 000102
ns.foo.tld 3600 IN A 127.0.0.1
ns.foo.tld 3600 IN AAAA 0:0:0:0:0:0:0:1