Automatically refactor more exception testing to use new JUnit rules

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=178911894
This commit is contained in:
mcilwain 2017-08-14 09:20:03 -04:00 committed by Ben McIlwain
parent 36ad38e5df
commit 7dc224627f
125 changed files with 1970 additions and 1982 deletions

View file

@ -102,7 +102,6 @@ import org.joda.time.Duration;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -111,9 +110,6 @@ import org.junit.runners.JUnit4;
public class DeleteContactsAndHostsActionTest public class DeleteContactsAndHostsActionTest
extends MapreduceTestCase<DeleteContactsAndHostsAction> { extends MapreduceTestCase<DeleteContactsAndHostsAction> {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();

View file

@ -49,9 +49,7 @@ import java.util.Set;
import org.joda.money.Money; import org.joda.money.Money;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -61,9 +59,6 @@ public class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDa
private static final DateTime DELETION_TIME = DateTime.parse("2010-01-01T00:00:00.000Z"); private static final DateTime DELETION_TIME = DateTime.parse("2010-01-01T00:00:00.000Z");
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Before @Before
public void init() { public void init() {
// Entities in these two should not be touched. // Entities in these two should not be touched.

View file

@ -28,6 +28,7 @@ import static google.registry.testing.DatastoreHelper.persistActiveDomain;
import static google.registry.testing.DatastoreHelper.persistDeletedDomain; import static google.registry.testing.DatastoreHelper.persistDeletedDomain;
import static google.registry.testing.DatastoreHelper.persistPremiumList; import static google.registry.testing.DatastoreHelper.persistPremiumList;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.util.DateTimeUtils.END_OF_TIME; import static google.registry.util.DateTimeUtils.END_OF_TIME;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static org.joda.money.CurrencyUnit.USD; import static org.joda.money.CurrencyUnit.USD;
@ -60,7 +61,6 @@ import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -68,10 +68,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class ExpandRecurringBillingEventsActionTest public class ExpandRecurringBillingEventsActionTest
extends MapreduceTestCase<ExpandRecurringBillingEventsAction> { extends MapreduceTestCase<ExpandRecurringBillingEventsAction> {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();
@ -649,18 +645,22 @@ public class ExpandRecurringBillingEventsActionTest
@Test @Test
public void testFailure_cursorAfterExecutionTime() throws Exception { public void testFailure_cursorAfterExecutionTime() throws Exception {
action.cursorTimeParam = Optional.of(clock.nowUtc().plusYears(1)); action.cursorTimeParam = Optional.of(clock.nowUtc().plusYears(1));
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Cursor time must be earlier than execution time."); expectThrows(IllegalArgumentException.class, () -> runMapreduce());
runMapreduce(); assertThat(thrown)
.hasMessageThat()
.contains("Cursor time must be earlier than execution time.");
} }
@Test @Test
public void testFailure_cursorAtExecutionTime() throws Exception { public void testFailure_cursorAtExecutionTime() throws Exception {
// The clock advances one milli on runMapreduce. // The clock advances one milli on runMapreduce.
action.cursorTimeParam = Optional.of(clock.nowUtc().plusMillis(1)); action.cursorTimeParam = Optional.of(clock.nowUtc().plusMillis(1));
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Cursor time must be earlier than execution time."); expectThrows(IllegalArgumentException.class, () -> runMapreduce());
runMapreduce(); assertThat(thrown)
.hasMessageThat()
.contains("Cursor time must be earlier than execution time.");
} }
@Test @Test

View file

@ -52,9 +52,7 @@ import google.registry.testing.mapreduce.MapreduceTestCase;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -62,8 +60,6 @@ import org.junit.runners.JUnit4;
public class MapreduceEntityCleanupActionTest public class MapreduceEntityCleanupActionTest
extends MapreduceTestCase<MapreduceEntityCleanupAction> { extends MapreduceTestCase<MapreduceEntityCleanupAction> {
@Rule public final ExpectedException thrown = ExpectedException.none();
private static final DatastoreService datastore = getDatastoreService(); private static final DatastoreService datastore = getDatastoreService();
private static final FetchOptions FETCH_OPTIONS = FetchOptions.Builder.withChunkSize(200); private static final FetchOptions FETCH_OPTIONS = FetchOptions.Builder.withChunkSize(200);
private static final String QUEUE_NAME = "mapreduce"; private static final String QUEUE_NAME = "mapreduce";

View file

@ -60,7 +60,6 @@ import org.joda.time.Duration;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -69,9 +68,6 @@ import org.junit.runners.JUnit4;
public class RefreshDnsOnHostRenameActionTest public class RefreshDnsOnHostRenameActionTest
extends MapreduceTestCase<RefreshDnsOnHostRenameAction> { extends MapreduceTestCase<RefreshDnsOnHostRenameAction> {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public InjectRule inject = new InjectRule(); public InjectRule inject = new InjectRule();

View file

@ -19,6 +19,7 @@ import static google.registry.bigquery.BigqueryUtils.fromBigqueryTimestampString
import static google.registry.bigquery.BigqueryUtils.toBigqueryTimestamp; import static google.registry.bigquery.BigqueryUtils.toBigqueryTimestamp;
import static google.registry.bigquery.BigqueryUtils.toBigqueryTimestampString; import static google.registry.bigquery.BigqueryUtils.toBigqueryTimestampString;
import static google.registry.bigquery.BigqueryUtils.toJobReferenceString; import static google.registry.bigquery.BigqueryUtils.toJobReferenceString;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.util.DateTimeUtils.END_OF_TIME; import static google.registry.util.DateTimeUtils.END_OF_TIME;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
@ -26,19 +27,13 @@ import com.google.api.services.bigquery.model.JobReference;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.DateTimeZone; import org.joda.time.DateTimeZone;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
/** Unit tests for {@link BigqueryUtils}. */ /** Unit tests for {@link BigqueryUtils}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class BigqueryUtilsTest { public class BigqueryUtilsTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private static final DateTime DATE_0 = DateTime.parse("2014-07-17T20:35:42Z"); private static final DateTime DATE_0 = DateTime.parse("2014-07-17T20:35:42Z");
private static final DateTime DATE_1 = DateTime.parse("2014-07-17T20:35:42.1Z"); private static final DateTime DATE_1 = DateTime.parse("2014-07-17T20:35:42.1Z");
private static final DateTime DATE_2 = DateTime.parse("2014-07-17T20:35:42.12Z"); private static final DateTime DATE_2 = DateTime.parse("2014-07-17T20:35:42.12Z");
@ -84,20 +79,22 @@ public class BigqueryUtilsTest {
@Test @Test
public void testFailure_fromBigqueryTimestampString_nonUtcTimeZone() throws Exception { public void testFailure_fromBigqueryTimestampString_nonUtcTimeZone() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
fromBigqueryTimestampString("2014-01-01 01:01:01 +05:00"); IllegalArgumentException.class,
() -> fromBigqueryTimestampString("2014-01-01 01:01:01 +05:00"));
} }
@Test @Test
public void testFailure_fromBigqueryTimestampString_noTimeZone() throws Exception { public void testFailure_fromBigqueryTimestampString_noTimeZone() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
fromBigqueryTimestampString("2014-01-01 01:01:01"); IllegalArgumentException.class, () -> fromBigqueryTimestampString("2014-01-01 01:01:01"));
} }
@Test @Test
public void testFailure_fromBigqueryTimestampString_tooManyMillisecondDigits() throws Exception { public void testFailure_fromBigqueryTimestampString_tooManyMillisecondDigits() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
fromBigqueryTimestampString("2014-01-01 01:01:01.1234 UTC"); IllegalArgumentException.class,
() -> fromBigqueryTimestampString("2014-01-01 01:01:01.1234 UTC"));
} }
@Test @Test
@ -142,7 +139,6 @@ public class BigqueryUtilsTest {
@Test @Test
public void test_toJobReferenceString_nullThrowsNpe() throws Exception { public void test_toJobReferenceString_nullThrowsNpe() throws Exception {
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class, () -> toJobReferenceString(null));
toJobReferenceString(null);
} }
} }

View file

@ -28,7 +28,6 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -39,9 +38,6 @@ public class CommitLogFanoutActionTest {
private static final String ENDPOINT = "/the/servlet"; private static final String ENDPOINT = "/the/servlet";
private static final String QUEUE = "the-queue"; private static final String QUEUE = "the-queue";
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final AppEngineRule appEngine = AppEngineRule.builder() public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore() .withDatastore()

View file

@ -41,7 +41,6 @@ import java.util.Optional;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -53,9 +52,6 @@ public class TldFanoutActionTest {
private static final String QUEUE = "the-queue"; private static final String QUEUE = "the-queue";
private final FakeResponse response = new FakeResponse(); private final FakeResponse response = new FakeResponse();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final AppEngineRule appEngine = AppEngineRule.builder() public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore() .withDatastore()

View file

@ -14,9 +14,11 @@
package google.registry.dns; package google.registry.dns;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistActiveDomain; import static google.registry.testing.DatastoreHelper.persistActiveDomain;
import static google.registry.testing.DatastoreHelper.persistActiveSubordinateHost; import static google.registry.testing.DatastoreHelper.persistActiveSubordinateHost;
import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.testing.TaskQueueHelper.assertDnsTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertDnsTasksEnqueued;
import static google.registry.testing.TaskQueueHelper.assertNoDnsTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertNoDnsTasksEnqueued;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -36,7 +38,6 @@ import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -50,9 +51,6 @@ public final class DnsInjectionTest {
.withTaskQueue() .withTaskQueue()
.build(); .build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();
@ -97,9 +95,9 @@ public final class DnsInjectionTest {
public void testRefreshDns_missingDomain_throwsNotFound() throws Exception { public void testRefreshDns_missingDomain_throwsNotFound() throws Exception {
when(req.getParameter("type")).thenReturn("domain"); when(req.getParameter("type")).thenReturn("domain");
when(req.getParameter("name")).thenReturn("example.lol"); when(req.getParameter("name")).thenReturn("example.lol");
thrown.expect(NotFoundException.class); NotFoundException thrown =
thrown.expectMessage("domain example.lol not found"); expectThrows(NotFoundException.class, () -> component.refreshDns().run());
component.refreshDns().run(); assertThat(thrown).hasMessageThat().contains("domain example.lol not found");
} }
@Test @Test
@ -115,8 +113,8 @@ public final class DnsInjectionTest {
public void testRefreshDns_missingHost_throwsNotFound() throws Exception { public void testRefreshDns_missingHost_throwsNotFound() throws Exception {
when(req.getParameter("type")).thenReturn("host"); when(req.getParameter("type")).thenReturn("host");
when(req.getParameter("name")).thenReturn("ns1.example.lol"); when(req.getParameter("name")).thenReturn("ns1.example.lol");
thrown.expect(NotFoundException.class); NotFoundException thrown =
thrown.expectMessage("host ns1.example.lol not found"); expectThrows(NotFoundException.class, () -> component.refreshDns().run());
component.refreshDns().run(); assertThat(thrown).hasMessageThat().contains("host ns1.example.lol not found");
} }
} }

View file

@ -14,7 +14,9 @@
package google.registry.dns; package google.registry.dns;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.testing.TaskQueueHelper.assertNoTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertNoTasksEnqueued;
import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
@ -23,7 +25,6 @@ import google.registry.testing.TaskQueueHelper.TaskMatcher;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -36,10 +37,6 @@ public class DnsQueueTest {
.withDatastore() .withDatastore()
.withTaskQueue() .withTaskQueue()
.build(); .build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
private DnsQueue dnsQueue; private DnsQueue dnsQueue;
@Before @Before
@ -62,13 +59,19 @@ public class DnsQueueTest {
@Test @Test
public void test_addHostRefreshTask_failsOnUnknownTld() throws Exception { public void test_addHostRefreshTask_failsOnUnknownTld() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("octopus.notatld is not a subordinate host to a known tld"); expectThrows(
IllegalArgumentException.class,
() -> {
try { try {
dnsQueue.addHostRefreshTask("octopus.notatld"); dnsQueue.addHostRefreshTask("octopus.notatld");
} finally { } finally {
assertNoTasksEnqueued("dns-pull"); assertNoTasksEnqueued("dns-pull");
} }
});
assertThat(thrown)
.hasMessageThat()
.contains("octopus.notatld is not a subordinate host to a known tld");
} }
@Test @Test
@ -85,13 +88,17 @@ public class DnsQueueTest {
@Test @Test
public void test_addDomainRefreshTask_failsOnUnknownTld() throws Exception { public void test_addDomainRefreshTask_failsOnUnknownTld() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("TLD notatld does not exist"); expectThrows(
IllegalArgumentException.class,
() -> {
try { try {
dnsQueue.addDomainRefreshTask("fake.notatld"); dnsQueue.addDomainRefreshTask("fake.notatld");
} finally { } finally {
assertNoTasksEnqueued("dns-pull"); assertNoTasksEnqueued("dns-pull");
} }
});
assertThat(thrown).hasMessageThat().contains("TLD notatld does not exist");
} }
} }

View file

@ -14,10 +14,12 @@
package google.registry.dns; package google.registry.dns;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistActiveDomain; import static google.registry.testing.DatastoreHelper.persistActiveDomain;
import static google.registry.testing.DatastoreHelper.persistActiveSubordinateHost; import static google.registry.testing.DatastoreHelper.persistActiveSubordinateHost;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.expectThrows;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions;
@ -40,7 +42,6 @@ import org.joda.time.Duration;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -56,10 +57,6 @@ public class PublishDnsUpdatesActionTest {
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final FakeClock clock = new FakeClock(DateTime.parse("1971-01-01TZ")); private final FakeClock clock = new FakeClock(DateTime.parse("1971-01-01TZ"));
private final FakeLockHandler lockHandler = new FakeLockHandler(true); private final FakeLockHandler lockHandler = new FakeLockHandler(true);
private final DnsWriter dnsWriter = mock(DnsWriter.class); private final DnsWriter dnsWriter = mock(DnsWriter.class);
@ -187,11 +184,14 @@ public class PublishDnsUpdatesActionTest {
@Test @Test
public void testLockIsntAvailable() throws Exception { public void testLockIsntAvailable() throws Exception {
thrown.expect(ServiceUnavailableException.class); ServiceUnavailableException thrown =
thrown.expectMessage("Lock failure"); expectThrows(
ServiceUnavailableException.class,
() -> {
action = createAction("xn--q9jyb4c"); action = createAction("xn--q9jyb4c");
action.domains = ImmutableSet.of("example.com", "example2.com"); action.domains = ImmutableSet.of("example.com", "example2.com");
action.hosts = ImmutableSet.of("ns1.example.com", "ns2.example.com", "ns1.example2.com"); action.hosts =
ImmutableSet.of("ns1.example.com", "ns2.example.com", "ns1.example2.com");
action.lockHandler = new FakeLockHandler(false); action.lockHandler = new FakeLockHandler(false);
action.run(); action.run();
@ -200,6 +200,8 @@ public class PublishDnsUpdatesActionTest {
verifyNoMoreInteractions(dnsMetrics); verifyNoMoreInteractions(dnsMetrics);
verifyNoMoreInteractions(dnsQueue); verifyNoMoreInteractions(dnsQueue);
});
assertThat(thrown).hasMessageThat().contains("Lock failure");
} }
@Test @Test

View file

@ -14,10 +14,13 @@
package google.registry.dns; package google.registry.dns;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistActiveDomain; import static google.registry.testing.DatastoreHelper.persistActiveDomain;
import static google.registry.testing.DatastoreHelper.persistActiveHost; import static google.registry.testing.DatastoreHelper.persistActiveHost;
import static google.registry.testing.DatastoreHelper.persistActiveSubordinateHost; import static google.registry.testing.DatastoreHelper.persistActiveSubordinateHost;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions;
@ -31,7 +34,6 @@ import google.registry.testing.FakeClock;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -44,10 +46,6 @@ public class RefreshDnsActionTest {
.withDatastore() .withDatastore()
.withTaskQueue() .withTaskQueue()
.build(); .build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final DnsQueue dnsQueue = mock(DnsQueue.class); private final DnsQueue dnsQueue = mock(DnsQueue.class);
private final FakeClock clock = new FakeClock(); private final FakeClock clock = new FakeClock();
@ -78,13 +76,19 @@ public class RefreshDnsActionTest {
public void testSuccess_externalHostNotEnqueued() throws Exception { public void testSuccess_externalHostNotEnqueued() throws Exception {
persistActiveDomain("example.xn--q9jyb4c"); persistActiveDomain("example.xn--q9jyb4c");
persistActiveHost("ns1.example.xn--q9jyb4c"); persistActiveHost("ns1.example.xn--q9jyb4c");
thrown.expect(BadRequestException.class); BadRequestException thrown =
thrown.expectMessage("ns1.example.xn--q9jyb4c isn't a subordinate hostname"); expectThrows(
BadRequestException.class,
() -> {
try { try {
run(TargetType.HOST, "ns1.example.xn--q9jyb4c"); run(TargetType.HOST, "ns1.example.xn--q9jyb4c");
} finally { } finally {
verifyNoMoreInteractions(dnsQueue); verifyNoMoreInteractions(dnsQueue);
} }
});
assertThat(thrown)
.hasMessageThat()
.contains("ns1.example.xn--q9jyb4c isn't a subordinate hostname");
} }
@Test @Test
@ -97,19 +101,16 @@ public class RefreshDnsActionTest {
@Test @Test
public void testFailure_unqualifiedName() throws Exception { public void testFailure_unqualifiedName() throws Exception {
thrown.expect(BadRequestException.class); assertThrows(BadRequestException.class, () -> run(TargetType.DOMAIN, "example"));
run(TargetType.DOMAIN, "example");
} }
@Test @Test
public void testFailure_hostDoesNotExist() throws Exception { public void testFailure_hostDoesNotExist() throws Exception {
thrown.expect(NotFoundException.class); assertThrows(NotFoundException.class, () -> run(TargetType.HOST, "ns1.example.xn--q9jyb4c"));
run(TargetType.HOST, "ns1.example.xn--q9jyb4c");
} }
@Test @Test
public void testFailure_domainDoesNotExist() throws Exception { public void testFailure_domainDoesNotExist() throws Exception {
thrown.expect(NotFoundException.class); assertThrows(NotFoundException.class, () -> run(TargetType.DOMAIN, "example.xn--q9jyb4c"));
run(TargetType.DOMAIN, "example.xn--q9jyb4c");
} }
} }

View file

@ -56,7 +56,6 @@ import org.joda.time.Duration;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Captor; import org.mockito.Captor;
@ -85,8 +84,6 @@ public class CloudDnsWriterTest {
private CloudDnsWriter writer; private CloudDnsWriter writer;
private ImmutableSet<ResourceRecordSet> stubZone; private ImmutableSet<ResourceRecordSet> stubZone;
@Rule public final ExpectedException thrown = ExpectedException.none();
@Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build(); @Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build();
/* /*

View file

@ -17,6 +17,7 @@ package google.registry.dns.writer.dnsupdate;
import static com.google.common.io.BaseEncoding.base16; import static com.google.common.io.BaseEncoding.base16;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.assertThrows; import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -34,9 +35,7 @@ import java.util.Arrays;
import javax.net.SocketFactory; import javax.net.SocketFactory;
import org.joda.time.Duration; import org.joda.time.Duration;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
import org.xbill.DNS.ARecord; import org.xbill.DNS.ARecord;
@ -62,10 +61,6 @@ public class DnsMessageTransportTest {
private Message simpleQuery; private Message simpleQuery;
private Message expectedResponse; private Message expectedResponse;
private DnsMessageTransport resolver; private DnsMessageTransport resolver;
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Before @Before
public void before() throws Exception { public void before() throws Exception {
simpleQuery = simpleQuery =
@ -114,9 +109,7 @@ public class DnsMessageTransportTest {
new ByteArrayInputStream(Arrays.copyOf(messageBytes, messageBytes.length - 1)); new ByteArrayInputStream(Arrays.copyOf(messageBytes, messageBytes.length - 1));
when(mockSocket.getInputStream()).thenReturn(inputStream); when(mockSocket.getInputStream()).thenReturn(inputStream);
when(mockSocket.getOutputStream()).thenReturn(new ByteArrayOutputStream()); when(mockSocket.getOutputStream()).thenReturn(new ByteArrayOutputStream());
thrown.expect(EOFException.class); assertThrows(EOFException.class, () -> resolver.send(new Message()));
resolver.send(new Message());
} }
@Test @Test
@ -145,10 +138,9 @@ public class DnsMessageTransportTest {
} }
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
when(mockSocket.getOutputStream()).thenReturn(outputStream); when(mockSocket.getOutputStream()).thenReturn(outputStream);
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("message larger than maximum"); expectThrows(IllegalArgumentException.class, () -> resolver.send(oversize));
assertThat(thrown).hasMessageThat().contains("message larger than maximum");
resolver.send(oversize);
} }
@Test @Test
@ -157,13 +149,14 @@ public class DnsMessageTransportTest {
when(mockSocket.getInputStream()) when(mockSocket.getInputStream())
.thenReturn(new ByteArrayInputStream(messageToBytesWithLength(expectedResponse))); .thenReturn(new ByteArrayInputStream(messageToBytesWithLength(expectedResponse)));
when(mockSocket.getOutputStream()).thenReturn(new ByteArrayOutputStream()); when(mockSocket.getOutputStream()).thenReturn(new ByteArrayOutputStream());
thrown.expect(VerifyException.class); VerifyException thrown = expectThrows(VerifyException.class, () -> resolver.send(simpleQuery));
thrown.expectMessage("response ID " assertThat(thrown)
.hasMessageThat()
.contains(
"response ID "
+ expectedResponse.getHeader().getID() + expectedResponse.getHeader().getID()
+ " does not match query ID " + " does not match query ID "
+ simpleQuery.getHeader().getID()); + simpleQuery.getHeader().getID());
resolver.send(simpleQuery);
} }
@Test @Test
@ -173,10 +166,10 @@ public class DnsMessageTransportTest {
when(mockSocket.getInputStream()) when(mockSocket.getInputStream())
.thenReturn(new ByteArrayInputStream(messageToBytesWithLength(expectedResponse))); .thenReturn(new ByteArrayInputStream(messageToBytesWithLength(expectedResponse)));
when(mockSocket.getOutputStream()).thenReturn(new ByteArrayOutputStream()); when(mockSocket.getOutputStream()).thenReturn(new ByteArrayOutputStream());
thrown.expect(VerifyException.class); VerifyException thrown = expectThrows(VerifyException.class, () -> resolver.send(simpleQuery));
thrown.expectMessage("response opcode 'STATUS' does not match query opcode 'QUERY'"); assertThat(thrown)
.hasMessageThat()
resolver.send(simpleQuery); .contains("response opcode 'STATUS' does not match query opcode 'QUERY'");
} }
private Message responseMessageWithCode(Message query, int responseCode) { private Message responseMessageWithCode(Message query, int responseCode) {

View file

@ -26,6 +26,7 @@ import static google.registry.testing.DatastoreHelper.persistActiveSubordinateHo
import static google.registry.testing.DatastoreHelper.persistDeletedDomain; import static google.registry.testing.DatastoreHelper.persistDeletedDomain;
import static google.registry.testing.DatastoreHelper.persistDeletedHost; import static google.registry.testing.DatastoreHelper.persistDeletedHost;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.expectThrows;
import static org.mockito.Matchers.any; import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.verifyZeroInteractions;
@ -52,7 +53,6 @@ import org.joda.time.Duration;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Captor; import org.mockito.Captor;
@ -76,9 +76,6 @@ public class DnsUpdateWriterTest {
public final AppEngineRule appEngine = public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastore().withTaskQueue().build(); AppEngineRule.builder().withDatastore().withTaskQueue().build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();
@ -390,11 +387,14 @@ public class DnsUpdateWriterTest {
.build(); .build();
persistResource(domain); persistResource(domain);
when(mockResolver.send(any(Message.class))).thenReturn(messageWithResponseCode(Rcode.SERVFAIL)); when(mockResolver.send(any(Message.class))).thenReturn(messageWithResponseCode(Rcode.SERVFAIL));
thrown.expect(VerifyException.class); VerifyException thrown =
thrown.expectMessage("SERVFAIL"); expectThrows(
VerifyException.class,
() -> {
writer.publishDomain("example.tld"); writer.publishDomain("example.tld");
writer.commit(); writer.commit();
});
assertThat(thrown).hasMessageThat().contains("SERVFAIL");
} }
@Test @Test
@ -406,11 +406,14 @@ public class DnsUpdateWriterTest {
.build(); .build();
persistResource(host); persistResource(host);
when(mockResolver.send(any(Message.class))).thenReturn(messageWithResponseCode(Rcode.SERVFAIL)); when(mockResolver.send(any(Message.class))).thenReturn(messageWithResponseCode(Rcode.SERVFAIL));
thrown.expect(VerifyException.class); VerifyException thrown =
thrown.expectMessage("SERVFAIL"); expectThrows(
VerifyException.class,
() -> {
writer.publishHost("ns1.example.tld"); writer.publishHost("ns1.example.tld");
writer.commit(); writer.commit();
});
assertThat(thrown).hasMessageThat().contains("SERVFAIL");
} }
private void assertThatUpdatedZoneIs(Update update, String zoneName) { private void assertThatUpdatedZoneIs(Update update, String zoneName) {

View file

@ -18,6 +18,8 @@ import static com.google.appengine.api.taskqueue.QueueFactory.getQueue;
import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assert_; import static com.google.common.truth.Truth.assert_;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
@ -55,7 +57,6 @@ import java.util.logging.Logger;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -68,10 +69,6 @@ public class BigqueryPollJobActionTest {
.withDatastore() .withDatastore()
.withTaskQueue() .withTaskQueue()
.build(); .build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
private static final String PROJECT_ID = "project_id"; private static final String PROJECT_ID = "project_id";
private static final String JOB_ID = "job_id"; private static final String JOB_ID = "job_id";
private static final String CHAINED_QUEUE_NAME = UpdateSnapshotViewAction.QUEUE; private static final String CHAINED_QUEUE_NAME = UpdateSnapshotViewAction.QUEUE;
@ -192,15 +189,13 @@ public class BigqueryPollJobActionTest {
public void testJobPending() throws Exception { public void testJobPending() throws Exception {
when(bigqueryJobsGet.execute()).thenReturn( when(bigqueryJobsGet.execute()).thenReturn(
new Job().setStatus(new JobStatus().setState("PENDING"))); new Job().setStatus(new JobStatus().setState("PENDING")));
thrown.expect(NotModifiedException.class); assertThrows(NotModifiedException.class, () -> action.run());
action.run();
} }
@Test @Test
public void testJobStatusUnreadable() throws Exception { public void testJobStatusUnreadable() throws Exception {
when(bigqueryJobsGet.execute()).thenThrow(IOException.class); when(bigqueryJobsGet.execute()).thenThrow(IOException.class);
thrown.expect(NotModifiedException.class); assertThrows(NotModifiedException.class, () -> action.run());
action.run();
} }
@Test @Test
@ -208,8 +203,7 @@ public class BigqueryPollJobActionTest {
when(bigqueryJobsGet.execute()).thenReturn( when(bigqueryJobsGet.execute()).thenReturn(
new Job().setStatus(new JobStatus().setState("DONE"))); new Job().setStatus(new JobStatus().setState("DONE")));
action.payload = "payload".getBytes(UTF_8); action.payload = "payload".getBytes(UTF_8);
thrown.expect(BadRequestException.class); BadRequestException thrown = expectThrows(BadRequestException.class, () -> action.run());
thrown.expectMessage("Cannot deserialize task from payload"); assertThat(thrown).hasMessageThat().contains("Cannot deserialize task from payload");
action.run();
} }
} }

View file

@ -17,6 +17,7 @@ package google.registry.export;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.export.CheckSnapshotAction.CHECK_SNAPSHOT_KINDS_TO_LOAD_PARAM; import static google.registry.export.CheckSnapshotAction.CHECK_SNAPSHOT_KINDS_TO_LOAD_PARAM;
import static google.registry.export.CheckSnapshotAction.CHECK_SNAPSHOT_NAME_PARAM; import static google.registry.export.CheckSnapshotAction.CHECK_SNAPSHOT_NAME_PARAM;
import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.testing.TaskQueueHelper.assertNoTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertNoTasksEnqueued;
import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -40,7 +41,6 @@ import org.joda.time.Duration;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -53,8 +53,6 @@ public class CheckSnapshotActionTest {
@Rule public final InjectRule inject = new InjectRule(); @Rule public final InjectRule inject = new InjectRule();
@Rule public final AppEngineRule appEngine = AppEngineRule.builder().withTaskQueue().build(); @Rule public final AppEngineRule appEngine = AppEngineRule.builder().withTaskQueue().build();
@Rule public final ExpectedException thrown = ExpectedException.none();
private final DatastoreBackupService backupService = mock(DatastoreBackupService.class); private final DatastoreBackupService backupService = mock(DatastoreBackupService.class);
private DatastoreBackupInfo backupInfo; private DatastoreBackupInfo backupInfo;
@ -124,9 +122,8 @@ public class CheckSnapshotActionTest {
public void testPost_forPendingBackup_returnsNotModified() throws Exception { public void testPost_forPendingBackup_returnsNotModified() throws Exception {
setPendingBackup(); setPendingBackup();
thrown.expect(NotModifiedException.class); NotModifiedException thrown = expectThrows(NotModifiedException.class, () -> action.run());
thrown.expectMessage("Datastore backup some_backup still pending"); assertThat(thrown).hasMessageThat().contains("Datastore backup some_backup still pending");
action.run();
} }
@Test @Test
@ -141,11 +138,12 @@ public class CheckSnapshotActionTest {
.plus(Duration.standardMinutes(3)) .plus(Duration.standardMinutes(3))
.plus(Duration.millis(1234))); .plus(Duration.millis(1234)));
thrown.expect(NoContentException.class); NoContentException thrown = expectThrows(NoContentException.class, () -> action.run());
thrown.expectMessage("Datastore backup some_backup abandoned - " assertThat(thrown)
.hasMessageThat()
.contains(
"Datastore backup some_backup abandoned - "
+ "not complete after 20 hours, 3 minutes and 1 second"); + "not complete after 20 hours, 3 minutes and 1 second");
action.run();
} }
@Test @Test
@ -188,10 +186,8 @@ public class CheckSnapshotActionTest {
when(backupService.findByName("some_backup")) when(backupService.findByName("some_backup"))
.thenThrow(new IllegalArgumentException("No backup found")); .thenThrow(new IllegalArgumentException("No backup found"));
thrown.expect(BadRequestException.class); BadRequestException thrown = expectThrows(BadRequestException.class, () -> action.run());
thrown.expectMessage("Bad backup name some_backup: No backup found"); assertThat(thrown).hasMessageThat().contains("Bad backup name some_backup: No backup found");
action.run();
} }
@Test @Test
@ -220,9 +216,7 @@ public class CheckSnapshotActionTest {
when(backupService.findByName("some_backup")) when(backupService.findByName("some_backup"))
.thenThrow(new IllegalArgumentException("No backup found")); .thenThrow(new IllegalArgumentException("No backup found"));
thrown.expect(BadRequestException.class); BadRequestException thrown = expectThrows(BadRequestException.class, () -> action.run());
thrown.expectMessage("Bad backup name some_backup: No backup found"); assertThat(thrown).hasMessageThat().contains("Bad backup name some_backup: No backup found");
action.run();
} }
} }

View file

@ -17,6 +17,7 @@ package google.registry.export;
import static com.google.appengine.api.datastore.DatastoreServiceFactory.getDatastoreService; import static com.google.appengine.api.datastore.DatastoreServiceFactory.getDatastoreService;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat; import static com.google.common.truth.Truth8.assertThat;
import static google.registry.testing.JUnitBackports.assertThrows;
import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.EntityNotFoundException;
@ -32,17 +33,12 @@ import org.joda.time.Duration;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
/** Unit tests for {@link DatastoreBackupInfo}. */ /** Unit tests for {@link DatastoreBackupInfo}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class DatastoreBackupInfoTest { public class DatastoreBackupInfoTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();
@ -107,28 +103,28 @@ public class DatastoreBackupInfoTest {
@Test @Test
public void testFailure_missingName() throws Exception { public void testFailure_missingName() throws Exception {
backupEntity.removeProperty("name"); backupEntity.removeProperty("name");
thrown.expect(NullPointerException.class); assertThrows(
new DatastoreBackupInfo(persistEntity(backupEntity)); NullPointerException.class, () -> new DatastoreBackupInfo(persistEntity(backupEntity)));
} }
@Test @Test
public void testFailure_missingKinds() throws Exception { public void testFailure_missingKinds() throws Exception {
backupEntity.removeProperty("kinds"); backupEntity.removeProperty("kinds");
thrown.expect(NullPointerException.class); assertThrows(
new DatastoreBackupInfo(persistEntity(backupEntity)); NullPointerException.class, () -> new DatastoreBackupInfo(persistEntity(backupEntity)));
} }
@Test @Test
public void testFailure_missingStartTime() throws Exception { public void testFailure_missingStartTime() throws Exception {
backupEntity.removeProperty("start_time"); backupEntity.removeProperty("start_time");
thrown.expect(NullPointerException.class); assertThrows(
new DatastoreBackupInfo(persistEntity(backupEntity)); NullPointerException.class, () -> new DatastoreBackupInfo(persistEntity(backupEntity)));
} }
@Test @Test
public void testFailure_badGcsFilenameFormat() throws Exception { public void testFailure_badGcsFilenameFormat() throws Exception {
backupEntity.setProperty("gs_handle", new Text("foo")); backupEntity.setProperty("gs_handle", new Text("foo"));
thrown.expect(IllegalArgumentException.class); assertThrows(
new DatastoreBackupInfo(persistEntity(backupEntity)); IllegalArgumentException.class, () -> new DatastoreBackupInfo(persistEntity(backupEntity)));
} }
} }

View file

@ -17,6 +17,7 @@ package google.registry.export;
import static com.google.appengine.api.datastore.DatastoreServiceFactory.getDatastoreService; import static com.google.appengine.api.datastore.DatastoreServiceFactory.getDatastoreService;
import static com.google.common.collect.Iterables.transform; import static com.google.common.collect.Iterables.transform;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -33,7 +34,6 @@ import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -41,9 +41,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class DatastoreBackupServiceTest { public class DatastoreBackupServiceTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();
@ -119,13 +116,11 @@ public class DatastoreBackupServiceTest {
@Test @Test
public void testFailure_findByName_multipleMatchingBackups() throws Exception { public void testFailure_findByName_multipleMatchingBackups() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> backupService.findByName("backupA"));
backupService.findByName("backupA");
} }
@Test @Test
public void testFailure_findByName_noMatchingBackups() throws Exception { public void testFailure_findByName_noMatchingBackups() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> backupService.findByName("backupX"));
backupService.findByName("backupX");
} }
} }

View file

@ -22,6 +22,7 @@ import static google.registry.export.LoadSnapshotAction.LOAD_SNAPSHOT_KINDS_PARA
import static google.registry.export.LoadSnapshotAction.PATH; import static google.registry.export.LoadSnapshotAction.PATH;
import static google.registry.export.LoadSnapshotAction.QUEUE; import static google.registry.export.LoadSnapshotAction.QUEUE;
import static google.registry.export.LoadSnapshotAction.enqueueLoadSnapshotTask; import static google.registry.export.LoadSnapshotAction.enqueueLoadSnapshotTask;
import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
import static org.joda.time.DateTimeZone.UTC; import static org.joda.time.DateTimeZone.UTC;
import static org.mockito.Matchers.any; import static org.mockito.Matchers.any;
@ -52,7 +53,6 @@ import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
@ -65,10 +65,6 @@ public class LoadSnapshotActionTest {
public final AppEngineRule appEngine = AppEngineRule.builder() public final AppEngineRule appEngine = AppEngineRule.builder()
.withTaskQueue() .withTaskQueue()
.build(); .build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final BigqueryFactory bigqueryFactory = mock(BigqueryFactory.class); private final BigqueryFactory bigqueryFactory = mock(BigqueryFactory.class);
private final Bigquery bigquery = mock(Bigquery.class); private final Bigquery bigquery = mock(Bigquery.class);
private final Bigquery.Jobs bigqueryJobs = mock(Bigquery.Jobs.class); private final Bigquery.Jobs bigqueryJobs = mock(Bigquery.Jobs.class);
@ -186,16 +182,19 @@ public class LoadSnapshotActionTest {
@Test @Test
public void testFailure_doPost_badGcsFilename() throws Exception { public void testFailure_doPost_badGcsFilename() throws Exception {
action.snapshotFile = "gs://bucket/snapshot"; action.snapshotFile = "gs://bucket/snapshot";
thrown.expect(BadRequestException.class); BadRequestException thrown = expectThrows(BadRequestException.class, () -> action.run());
thrown.expectMessage("Error calling load snapshot: backup info file extension missing"); assertThat(thrown)
action.run(); .hasMessageThat()
.contains("Error calling load snapshot: backup info file extension missing");
} }
@Test @Test
public void testFailure_doPost_bigqueryThrowsException() throws Exception { public void testFailure_doPost_bigqueryThrowsException() throws Exception {
when(bigqueryJobsInsert.execute()).thenThrow(new IOException("The Internet has gone missing")); when(bigqueryJobsInsert.execute()).thenThrow(new IOException("The Internet has gone missing"));
thrown.expect(InternalServerErrorException.class); InternalServerErrorException thrown =
thrown.expectMessage("Error loading snapshot: The Internet has gone missing"); expectThrows(InternalServerErrorException.class, () -> action.run());
action.run(); assertThat(thrown)
.hasMessageThat()
.contains("Error loading snapshot: The Internet has gone missing");
} }
} }

View file

@ -21,6 +21,7 @@ import static google.registry.export.PublishDetailReportAction.GCS_FOLDER_PREFIX
import static google.registry.export.PublishDetailReportAction.REGISTRAR_ID_PARAM; import static google.registry.export.PublishDetailReportAction.REGISTRAR_ID_PARAM;
import static google.registry.testing.DatastoreHelper.loadRegistrar; import static google.registry.testing.DatastoreHelper.loadRegistrar;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.expectThrows;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static org.mockito.Matchers.any; import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.anyString;
@ -45,17 +46,12 @@ import java.util.Map;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
/** Unit tests for {@link PublishDetailReportAction}. */ /** Unit tests for {@link PublishDetailReportAction}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class PublishDetailReportActionTest { public class PublishDetailReportActionTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final AppEngineRule appEngine = AppEngineRule.builder() public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore() .withDatastore()
@ -108,88 +104,120 @@ public class PublishDetailReportActionTest {
@Test @Test
public void testFailure_noRegistrarParameter() throws Exception { public void testFailure_noRegistrarParameter() throws Exception {
thrown.expect(BadRequestException.class); BadRequestException thrown =
thrown.expectMessage(REGISTRAR_ID_PARAM); expectThrows(
action.handleJsonRequest(ImmutableMap.of( BadRequestException.class,
() ->
action.handleJsonRequest(
ImmutableMap.of(
GCS_BUCKET_PARAM, "mah-buckit", GCS_BUCKET_PARAM, "mah-buckit",
GCS_FOLDER_PREFIX_PARAM, "some/folder/", GCS_FOLDER_PREFIX_PARAM, "some/folder/",
DETAIL_REPORT_NAME_PARAM, "detail_report.csv")); DETAIL_REPORT_NAME_PARAM, "detail_report.csv")));
assertThat(thrown).hasMessageThat().contains(REGISTRAR_ID_PARAM);
} }
@Test @Test
public void testFailure_noGcsBucketParameter() throws Exception { public void testFailure_noGcsBucketParameter() throws Exception {
thrown.expect(BadRequestException.class); BadRequestException thrown =
thrown.expectMessage(GCS_BUCKET_PARAM); expectThrows(
action.handleJsonRequest(ImmutableMap.of( BadRequestException.class,
() ->
action.handleJsonRequest(
ImmutableMap.of(
REGISTRAR_ID_PARAM, "TheRegistrar", REGISTRAR_ID_PARAM, "TheRegistrar",
GCS_FOLDER_PREFIX_PARAM, "some/folder/", GCS_FOLDER_PREFIX_PARAM, "some/folder/",
DETAIL_REPORT_NAME_PARAM, "detail_report.csv")); DETAIL_REPORT_NAME_PARAM, "detail_report.csv")));
assertThat(thrown).hasMessageThat().contains(GCS_BUCKET_PARAM);
} }
@Test @Test
public void testFailure_noGcsFolderPrefixParameter() throws Exception { public void testFailure_noGcsFolderPrefixParameter() throws Exception {
thrown.expect(BadRequestException.class); BadRequestException thrown =
thrown.expectMessage(GCS_FOLDER_PREFIX_PARAM); expectThrows(
action.handleJsonRequest(ImmutableMap.of( BadRequestException.class,
() ->
action.handleJsonRequest(
ImmutableMap.of(
REGISTRAR_ID_PARAM, "TheRegistrar", REGISTRAR_ID_PARAM, "TheRegistrar",
GCS_BUCKET_PARAM, "mah-buckit", GCS_BUCKET_PARAM, "mah-buckit",
DETAIL_REPORT_NAME_PARAM, "detail_report.csv")); DETAIL_REPORT_NAME_PARAM, "detail_report.csv")));
assertThat(thrown).hasMessageThat().contains(GCS_FOLDER_PREFIX_PARAM);
} }
@Test @Test
public void testFailure_noReportNameParameter() throws Exception { public void testFailure_noReportNameParameter() throws Exception {
thrown.expect(BadRequestException.class); BadRequestException thrown =
thrown.expectMessage(DETAIL_REPORT_NAME_PARAM); expectThrows(
action.handleJsonRequest(ImmutableMap.of( BadRequestException.class,
() ->
action.handleJsonRequest(
ImmutableMap.of(
REGISTRAR_ID_PARAM, "TheRegistrar", REGISTRAR_ID_PARAM, "TheRegistrar",
GCS_BUCKET_PARAM, "mah-buckit", GCS_BUCKET_PARAM, "mah-buckit",
GCS_FOLDER_PREFIX_PARAM, "some/folder/")); GCS_FOLDER_PREFIX_PARAM, "some/folder/")));
assertThat(thrown).hasMessageThat().contains(DETAIL_REPORT_NAME_PARAM);
} }
@Test @Test
public void testFailure_registrarNotFound() throws Exception { public void testFailure_registrarNotFound() throws Exception {
thrown.expect(BadRequestException.class); BadRequestException thrown =
thrown.expectMessage("FakeRegistrar"); expectThrows(
action.handleJsonRequest(ImmutableMap.of( BadRequestException.class,
() ->
action.handleJsonRequest(
ImmutableMap.of(
REGISTRAR_ID_PARAM, "FakeRegistrar", REGISTRAR_ID_PARAM, "FakeRegistrar",
GCS_BUCKET_PARAM, "mah-buckit", GCS_BUCKET_PARAM, "mah-buckit",
GCS_FOLDER_PREFIX_PARAM, "some/folder/", GCS_FOLDER_PREFIX_PARAM, "some/folder/",
DETAIL_REPORT_NAME_PARAM, "detail_report.csv")); DETAIL_REPORT_NAME_PARAM, "detail_report.csv")));
assertThat(thrown).hasMessageThat().contains("FakeRegistrar");
} }
@Test @Test
public void testFailure_registrarHasNoDriveFolder() throws Exception { public void testFailure_registrarHasNoDriveFolder() throws Exception {
persistResource( persistResource(
loadRegistrar("TheRegistrar").asBuilder().setDriveFolderId(null).build()); loadRegistrar("TheRegistrar").asBuilder().setDriveFolderId(null).build());
thrown.expect(BadRequestException.class); BadRequestException thrown =
thrown.expectMessage("drive folder"); expectThrows(
action.handleJsonRequest(ImmutableMap.of( BadRequestException.class,
() ->
action.handleJsonRequest(
ImmutableMap.of(
REGISTRAR_ID_PARAM, "TheRegistrar", REGISTRAR_ID_PARAM, "TheRegistrar",
GCS_BUCKET_PARAM, "mah-buckit", GCS_BUCKET_PARAM, "mah-buckit",
GCS_FOLDER_PREFIX_PARAM, "some/folder/", GCS_FOLDER_PREFIX_PARAM, "some/folder/",
DETAIL_REPORT_NAME_PARAM, "detail_report.csv")); DETAIL_REPORT_NAME_PARAM, "detail_report.csv")));
assertThat(thrown).hasMessageThat().contains("drive folder");
} }
@Test @Test
public void testFailure_gcsBucketNotFound() throws Exception { public void testFailure_gcsBucketNotFound() throws Exception {
thrown.expect(BadRequestException.class); BadRequestException thrown =
thrown.expectMessage("fake-buckit"); expectThrows(
action.handleJsonRequest(ImmutableMap.of( BadRequestException.class,
() ->
action.handleJsonRequest(
ImmutableMap.of(
REGISTRAR_ID_PARAM, "TheRegistrar", REGISTRAR_ID_PARAM, "TheRegistrar",
GCS_BUCKET_PARAM, "fake-buckit", GCS_BUCKET_PARAM, "fake-buckit",
GCS_FOLDER_PREFIX_PARAM, "some/folder/", GCS_FOLDER_PREFIX_PARAM, "some/folder/",
DETAIL_REPORT_NAME_PARAM, "detail_report.csv")); DETAIL_REPORT_NAME_PARAM, "detail_report.csv")));
assertThat(thrown).hasMessageThat().contains("fake-buckit");
} }
@Test @Test
public void testFailure_gcsFileNotFound() throws Exception { public void testFailure_gcsFileNotFound() throws Exception {
thrown.expect(BadRequestException.class); BadRequestException thrown =
thrown.expectMessage("some/folder/fake_file.csv"); expectThrows(
action.handleJsonRequest(ImmutableMap.of( BadRequestException.class,
() ->
action.handleJsonRequest(
ImmutableMap.of(
REGISTRAR_ID_PARAM, "TheRegistrar", REGISTRAR_ID_PARAM, "TheRegistrar",
GCS_BUCKET_PARAM, "mah-buckit", GCS_BUCKET_PARAM, "mah-buckit",
GCS_FOLDER_PREFIX_PARAM, "some/folder/", GCS_FOLDER_PREFIX_PARAM, "some/folder/",
DETAIL_REPORT_NAME_PARAM, "fake_file.csv")); DETAIL_REPORT_NAME_PARAM, "fake_file.csv")));
assertThat(thrown).hasMessageThat().contains("some/folder/fake_file.csv");
} }
@Test @Test
@ -197,12 +225,16 @@ public class PublishDetailReportActionTest {
when(driveConnection.createFile( when(driveConnection.createFile(
anyString(), any(MediaType.class), anyString(), any(byte[].class))) anyString(), any(MediaType.class), anyString(), any(byte[].class)))
.thenThrow(new IOException("Drive is down")); .thenThrow(new IOException("Drive is down"));
thrown.expect(InternalServerErrorException.class); InternalServerErrorException thrown =
thrown.expectMessage("Drive is down"); expectThrows(
action.handleJsonRequest(ImmutableMap.of( InternalServerErrorException.class,
() ->
action.handleJsonRequest(
ImmutableMap.of(
REGISTRAR_ID_PARAM, "TheRegistrar", REGISTRAR_ID_PARAM, "TheRegistrar",
GCS_BUCKET_PARAM, "mah-buckit", GCS_BUCKET_PARAM, "mah-buckit",
GCS_FOLDER_PREFIX_PARAM, "some/folder/", GCS_FOLDER_PREFIX_PARAM, "some/folder/",
DETAIL_REPORT_NAME_PARAM, "detail_report.csv")); DETAIL_REPORT_NAME_PARAM, "detail_report.csv")));
assertThat(thrown).hasMessageThat().contains("Drive is down");
} }
} }

View file

@ -47,7 +47,6 @@ import google.registry.util.Retrier;
import java.io.IOException; import java.io.IOException;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -65,9 +64,6 @@ public class SyncGroupMembersActionTest {
.withDatastore() .withDatastore()
.build(); .build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();

View file

@ -21,6 +21,7 @@ import static google.registry.export.UpdateSnapshotViewAction.UPDATE_SNAPSHOT_DA
import static google.registry.export.UpdateSnapshotViewAction.UPDATE_SNAPSHOT_KIND_PARAM; import static google.registry.export.UpdateSnapshotViewAction.UPDATE_SNAPSHOT_KIND_PARAM;
import static google.registry.export.UpdateSnapshotViewAction.UPDATE_SNAPSHOT_TABLE_ID_PARAM; import static google.registry.export.UpdateSnapshotViewAction.UPDATE_SNAPSHOT_TABLE_ID_PARAM;
import static google.registry.export.UpdateSnapshotViewAction.createViewUpdateTask; import static google.registry.export.UpdateSnapshotViewAction.createViewUpdateTask;
import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
import static org.mockito.Matchers.any; import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.anyString;
@ -41,7 +42,6 @@ import java.io.IOException;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
@ -55,10 +55,6 @@ public class UpdateSnapshotViewActionTest {
public final AppEngineRule appEngine = AppEngineRule.builder() public final AppEngineRule appEngine = AppEngineRule.builder()
.withTaskQueue() .withTaskQueue()
.build(); .build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final BigqueryFactory bigqueryFactory = mock(BigqueryFactory.class); private final BigqueryFactory bigqueryFactory = mock(BigqueryFactory.class);
private final Bigquery bigquery = mock(Bigquery.class); private final Bigquery bigquery = mock(Bigquery.class);
private final Bigquery.Datasets bigqueryDatasets = mock(Bigquery.Datasets.class); private final Bigquery.Datasets bigqueryDatasets = mock(Bigquery.Datasets.class);
@ -127,8 +123,8 @@ public class UpdateSnapshotViewActionTest {
public void testFailure_bigqueryConnectionThrowsError() throws Exception { public void testFailure_bigqueryConnectionThrowsError() throws Exception {
when(bigqueryTables.update(anyString(), anyString(), anyString(), any(Table.class))) when(bigqueryTables.update(anyString(), anyString(), anyString(), any(Table.class)))
.thenThrow(new IOException("I'm sorry Dave, I can't let you do that")); .thenThrow(new IOException("I'm sorry Dave, I can't let you do that"));
thrown.expect(InternalServerErrorException.class); InternalServerErrorException thrown =
thrown.expectMessage("Error in update snapshot view action"); expectThrows(InternalServerErrorException.class, () -> action.run());
action.run(); assertThat(thrown).hasMessageThat().contains("Error in update snapshot view action");
} }
} }

View file

@ -16,6 +16,8 @@ package google.registry.groups;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.groups.DirectoryGroupsConnection.getDefaultGroupPermissions; import static google.registry.groups.DirectoryGroupsConnection.getDefaultGroupPermissions;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import static javax.servlet.http.HttpServletResponse.SC_CONFLICT; import static javax.servlet.http.HttpServletResponse.SC_CONFLICT;
import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
@ -50,9 +52,7 @@ import google.registry.groups.GroupsConnection.Role;
import java.io.IOException; import java.io.IOException;
import java.util.Set; import java.util.Set;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -61,10 +61,6 @@ import org.junit.runners.JUnit4;
*/ */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class DirectoryGroupsConnectionTest { public class DirectoryGroupsConnectionTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final Directory directory = mock(Directory.class); private final Directory directory = mock(Directory.class);
private final Groupssettings groupsSettings = mock(Groupssettings.class); private final Groupssettings groupsSettings = mock(Groupssettings.class);
private final Directory.Members members = mock(Directory.Members.class); private final Directory.Members members = mock(Directory.Members.class);
@ -118,18 +114,22 @@ public class DirectoryGroupsConnectionTest {
public void test_addMemberToGroup_handlesExceptionThrownByDirectoryService() throws Exception { public void test_addMemberToGroup_handlesExceptionThrownByDirectoryService() throws Exception {
when(membersInsert.execute()).thenThrow( when(membersInsert.execute()).thenThrow(
makeResponseException(SC_INTERNAL_SERVER_ERROR, "Could not contact Directory server.")); makeResponseException(SC_INTERNAL_SERVER_ERROR, "Could not contact Directory server."));
thrown.expect(GoogleJsonResponseException.class); assertThrows(GoogleJsonResponseException.class, () -> runAddMemberTest());
runAddMemberTest();
} }
@Test @Test
public void test_addMemberToGroup_handlesMemberKeyNotFoundException() throws Exception { public void test_addMemberToGroup_handlesMemberKeyNotFoundException() throws Exception {
when(membersInsert.execute()).thenThrow( when(membersInsert.execute()).thenThrow(
makeResponseException(SC_NOT_FOUND, "Resource Not Found: memberKey")); makeResponseException(SC_NOT_FOUND, "Resource Not Found: memberKey"));
thrown.expect(RuntimeException.class); RuntimeException thrown =
thrown.expectMessage("Adding member jim@example.com to group spam@example.com " expectThrows(
RuntimeException.class,
() -> connection.addMemberToGroup("spam@example.com", "jim@example.com", Role.MEMBER));
assertThat(thrown)
.hasMessageThat()
.contains(
"Adding member jim@example.com to group spam@example.com "
+ "failed because the member wasn't found."); + "failed because the member wasn't found.");
connection.addMemberToGroup("spam@example.com", "jim@example.com", Role.MEMBER);
} }
@Test @Test
@ -178,8 +178,7 @@ public class DirectoryGroupsConnectionTest {
public void test_createGroup_handlesExceptionThrownByDirectoryService() throws Exception { public void test_createGroup_handlesExceptionThrownByDirectoryService() throws Exception {
when(groupsInsert.execute()).thenThrow( when(groupsInsert.execute()).thenThrow(
makeResponseException(SC_INTERNAL_SERVER_ERROR, "Could not contact Directory server.")); makeResponseException(SC_INTERNAL_SERVER_ERROR, "Could not contact Directory server."));
thrown.expect(GoogleJsonResponseException.class); assertThrows(GoogleJsonResponseException.class, () -> runCreateGroupTest());
runCreateGroupTest();
} }
@Test @Test

View file

@ -24,6 +24,7 @@ import static google.registry.testing.DatastoreHelper.newDomainResource;
import static google.registry.testing.DatastoreHelper.persistEppResourceInFirstBucket; import static google.registry.testing.DatastoreHelper.persistEppResourceInFirstBucket;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.DatastoreHelper.persistSimpleResource; import static google.registry.testing.DatastoreHelper.persistSimpleResource;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.util.DateTimeUtils.END_OF_TIME; import static google.registry.util.DateTimeUtils.END_OF_TIME;
import static org.joda.money.CurrencyUnit.USD; import static org.joda.money.CurrencyUnit.USD;
@ -51,7 +52,6 @@ import org.joda.time.DateTime;
import org.joda.time.DateTimeZone; import org.joda.time.DateTimeZone;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -63,10 +63,6 @@ public class ChildEntityInputTest {
@Rule @Rule
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build(); public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
DomainResource domainA; DomainResource domainA;
DomainResource domainB; DomainResource domainB;
HistoryEntry domainHistoryEntryA; HistoryEntry domainHistoryEntryA;
@ -173,10 +169,13 @@ public class ChildEntityInputTest {
reader = serializeAndDeserialize(reader); reader = serializeAndDeserialize(reader);
reader.beginSlice(); reader.beginSlice();
if (i == 7) { if (i == 7) {
thrown.expect(NoSuchElementException.class); // This final readerCopy is needed for the assertThrows lambda.
} final InputReader<ImmutableObject> readerCopy = reader;
assertThrows(NoSuchElementException.class, () -> seen.add(readerCopy.next()));
} else {
seen.add(reader.next()); seen.add(reader.next());
} }
}
assertThat(seen).containsExactly( assertThat(seen).containsExactly(
domainHistoryEntryA, domainHistoryEntryA,
domainHistoryEntryB, domainHistoryEntryB,
@ -300,7 +299,6 @@ public class ChildEntityInputTest {
assertThat(seen).containsExactlyElementsIn(historyEntries); assertThat(seen).containsExactlyElementsIn(historyEntries);
} }
@Test @Test
public void testSuccess_childEntityReader_survivesAcrossSerialization() throws Exception { public void testSuccess_childEntityReader_survivesAcrossSerialization() throws Exception {
setupResources(); setupResources();
@ -315,13 +313,12 @@ public class ChildEntityInputTest {
seen.add(reader.next()); seen.add(reader.next());
seen.add(reader.next()); seen.add(reader.next());
reader.endSlice(); reader.endSlice();
reader = serializeAndDeserialize(reader); InputReader<ImmutableObject> deserializedReader = serializeAndDeserialize(reader);
reader.beginSlice(); deserializedReader.beginSlice();
seen.add(reader.next()); seen.add(deserializedReader.next());
seen.add(reader.next()); seen.add(deserializedReader.next());
assertThat(seen).containsExactly( assertThat(seen)
domainHistoryEntryA, contactHistoryEntry, oneTimeA, recurringA); .containsExactly(domainHistoryEntryA, contactHistoryEntry, oneTimeA, recurringA);
thrown.expect(NoSuchElementException.class); assertThrows(NoSuchElementException.class, deserializedReader::next);
reader.next();
} }
} }

View file

@ -28,6 +28,8 @@ import static google.registry.testing.DatastoreHelper.persistActiveContact;
import static google.registry.testing.DatastoreHelper.persistEppResourceInFirstBucket; import static google.registry.testing.DatastoreHelper.persistEppResourceInFirstBucket;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.DatastoreHelper.persistSimpleResource; import static google.registry.testing.DatastoreHelper.persistSimpleResource;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import com.google.appengine.tools.mapreduce.InputReader; import com.google.appengine.tools.mapreduce.InputReader;
import com.googlecode.objectify.Key; import com.googlecode.objectify.Key;
@ -48,7 +50,6 @@ import java.util.NoSuchElementException;
import java.util.Set; import java.util.Set;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -60,10 +61,6 @@ public class EppResourceInputsTest {
@Rule @Rule
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build(); public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private <T> T serializeAndDeserialize(T obj) throws Exception { private <T> T serializeAndDeserialize(T obj) throws Exception {
try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
@ -83,16 +80,18 @@ public class EppResourceInputsTest {
@Test @Test
public void testFailure_keyInputType_polymorphicSubclass() throws Exception { public void testFailure_keyInputType_polymorphicSubclass() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("non-polymorphic"); expectThrows(IllegalArgumentException.class, () -> createKeyInput(DomainResource.class));
createKeyInput(DomainResource.class); assertThat(thrown).hasMessageThat().contains("non-polymorphic");
} }
@Test @Test
public void testFailure_keyInputType_noInheritanceBetweenTypes_eppResource() throws Exception { public void testFailure_keyInputType_noInheritanceBetweenTypes_eppResource() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("inheritance"); expectThrows(
createKeyInput(EppResource.class, DomainBase.class); IllegalArgumentException.class,
() -> createKeyInput(EppResource.class, DomainBase.class));
assertThat(thrown).hasMessageThat().contains("inheritance");
} }
@Test @Test
@ -104,16 +103,20 @@ public class EppResourceInputsTest {
@Test @Test
public void testFailure_entityInputType_noInheritanceBetweenTypes_eppResource() throws Exception { public void testFailure_entityInputType_noInheritanceBetweenTypes_eppResource() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("inheritance"); expectThrows(
createEntityInput(EppResource.class, DomainResource.class); IllegalArgumentException.class,
() -> createEntityInput(EppResource.class, DomainResource.class));
assertThat(thrown).hasMessageThat().contains("inheritance");
} }
@Test @Test
public void testFailure_entityInputType_noInheritanceBetweenTypes_subclasses() throws Exception { public void testFailure_entityInputType_noInheritanceBetweenTypes_subclasses() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("inheritance"); expectThrows(
createEntityInput(DomainBase.class, DomainResource.class); IllegalArgumentException.class,
() -> createEntityInput(DomainBase.class, DomainResource.class));
assertThat(thrown).hasMessageThat().contains("inheritance");
} }
@Test @Test
@ -191,8 +194,7 @@ public class EppResourceInputsTest {
seen.add(reader.next()); seen.add(reader.next());
assertThat(reader.getProgress()).isWithin(EPSILON).of(1); assertThat(reader.getProgress()).isWithin(EPSILON).of(1);
assertThat(seen).containsExactly(Key.create(domainA), Key.create(domainB)); assertThat(seen).containsExactly(Key.create(domainA), Key.create(domainB));
thrown.expect(NoSuchElementException.class); assertThrows(NoSuchElementException.class, reader::next);
reader.next();
} }
@Test @Test
@ -211,16 +213,15 @@ public class EppResourceInputsTest {
seen.add(reader.next()); seen.add(reader.next());
assertThat(reader.getProgress()).isWithin(EPSILON).of(0.5); assertThat(reader.getProgress()).isWithin(EPSILON).of(0.5);
reader.endSlice(); reader.endSlice();
reader = serializeAndDeserialize(reader); InputReader<DomainResource> deserializedReader = serializeAndDeserialize(reader);
reader.beginSlice(); deserializedReader.beginSlice();
assertThat(reader.getProgress()).isWithin(EPSILON).of(0.5); assertThat(deserializedReader.getProgress()).isWithin(EPSILON).of(0.5);
seen.add(reader.next()); seen.add(deserializedReader.next());
assertThat(reader.getProgress()).isWithin(EPSILON).of(1); assertThat(deserializedReader.getProgress()).isWithin(EPSILON).of(1);
reader.endSlice(); deserializedReader.endSlice();
reader.endShard(); deserializedReader.endShard();
assertThat(seen).containsExactly(domainA, domainB); assertThat(seen).containsExactly(domainA, domainB);
thrown.expect(NoSuchElementException.class); assertThrows(NoSuchElementException.class, deserializedReader::next);
reader.next();
} }
@Test @Test
@ -238,8 +239,7 @@ public class EppResourceInputsTest {
seen.add(reader.next()); seen.add(reader.next());
assertThat(reader.getProgress()).isWithin(EPSILON).of(1.0); assertThat(reader.getProgress()).isWithin(EPSILON).of(1.0);
assertThat(seen).containsExactly(domain, application); assertThat(seen).containsExactly(domain, application);
thrown.expect(NoSuchElementException.class); assertThrows(NoSuchElementException.class, reader::next);
reader.next();
} }
@Test @Test
@ -256,8 +256,7 @@ public class EppResourceInputsTest {
// We can't reliably assert getProgress() here, since it counts before the postfilter that weeds // We can't reliably assert getProgress() here, since it counts before the postfilter that weeds
// out polymorphic mismatches, and so depending on whether the domain or the application was // out polymorphic mismatches, and so depending on whether the domain or the application was
// seen first it will be 0.5 or 1.0. However, there should be nothing left when we call next(). // seen first it will be 0.5 or 1.0. However, there should be nothing left when we call next().
thrown.expect(NoSuchElementException.class); assertThrows(NoSuchElementException.class, reader::next);
reader.next();
} }
@Test @Test
@ -278,8 +277,7 @@ public class EppResourceInputsTest {
seen.add(reader.next()); seen.add(reader.next());
assertThat(reader.getProgress()).isWithin(EPSILON).of(1.0); assertThat(reader.getProgress()).isWithin(EPSILON).of(1.0);
assertThat(seen).containsExactly(domain, host); assertThat(seen).containsExactly(domain, host);
thrown.expect(NoSuchElementException.class); assertThrows(NoSuchElementException.class, reader::next);
reader.next();
} }
@Test @Test
@ -305,7 +303,6 @@ public class EppResourceInputsTest {
seen.add(reader.next()); seen.add(reader.next());
assertThat(reader.getProgress()).isWithin(EPSILON).of(1.0); assertThat(reader.getProgress()).isWithin(EPSILON).of(1.0);
assertThat(seen).containsExactly(domain, host, application, contact); assertThat(seen).containsExactly(domain, host, application, contact);
thrown.expect(NoSuchElementException.class); assertThrows(NoSuchElementException.class, reader::next);
reader.next();
} }
} }

View file

@ -33,7 +33,6 @@ import org.joda.time.Duration;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -47,9 +46,6 @@ public class EppResourceUtilsTest {
.withTaskQueue() .withTaskQueue()
.build(); .build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();

View file

@ -24,7 +24,6 @@ import java.util.Map;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -32,9 +31,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class ModelUtilsTest { public class ModelUtilsTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public AppEngineRule appEngineRule = new AppEngineRule.Builder().build(); public AppEngineRule appEngineRule = new AppEngineRule.Builder().build();

View file

@ -19,6 +19,7 @@ import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistActiveDomain; import static google.registry.testing.DatastoreHelper.persistActiveDomain;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.util.DateTimeUtils.END_OF_TIME; import static google.registry.util.DateTimeUtils.END_OF_TIME;
import static org.joda.money.CurrencyUnit.USD; import static org.joda.money.CurrencyUnit.USD;
import static org.joda.time.DateTimeZone.UTC; import static org.joda.time.DateTimeZone.UTC;
@ -35,16 +36,10 @@ import google.registry.model.reporting.HistoryEntry;
import org.joda.money.Money; import org.joda.money.Money;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
/** Unit tests for {@link BillingEvent}. */ /** Unit tests for {@link BillingEvent}. */
public class BillingEventTest extends EntityTestCase { public class BillingEventTest extends EntityTestCase {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final DateTime now = DateTime.now(UTC); private final DateTime now = DateTime.now(UTC);
HistoryEntry historyEntry; HistoryEntry historyEntry;
@ -182,44 +177,64 @@ public class BillingEventTest extends EntityTestCase {
@Test @Test
public void testFailure_syntheticFlagWithoutCreationTime() { public void testFailure_syntheticFlagWithoutCreationTime() {
thrown.expect(IllegalStateException.class); IllegalStateException thrown =
thrown.expectMessage( expectThrows(
"Synthetic creation time must be set if and only if the SYNTHETIC flag is set."); IllegalStateException.class,
oneTime.asBuilder() () ->
oneTime
.asBuilder()
.setFlags(ImmutableSet.of(BillingEvent.Flag.SYNTHETIC)) .setFlags(ImmutableSet.of(BillingEvent.Flag.SYNTHETIC))
.setCancellationMatchingBillingEvent(Key.create(recurring)) .setCancellationMatchingBillingEvent(Key.create(recurring))
.build(); .build());
assertThat(thrown)
.hasMessageThat()
.contains("Synthetic creation time must be set if and only if the SYNTHETIC flag is set.");
} }
@Test @Test
public void testFailure_syntheticCreationTimeWithoutFlag() { public void testFailure_syntheticCreationTimeWithoutFlag() {
thrown.expect(IllegalStateException.class); IllegalStateException thrown =
thrown.expectMessage( expectThrows(
"Synthetic creation time must be set if and only if the SYNTHETIC flag is set"); IllegalStateException.class,
oneTime.asBuilder() () -> oneTime.asBuilder().setSyntheticCreationTime(now.plusDays(10)).build());
.setSyntheticCreationTime(now.plusDays(10)) assertThat(thrown)
.build(); .hasMessageThat()
.contains("Synthetic creation time must be set if and only if the SYNTHETIC flag is set");
} }
@Test @Test
public void testFailure_syntheticFlagWithoutCancellationMatchingKey() { public void testFailure_syntheticFlagWithoutCancellationMatchingKey() {
thrown.expect(IllegalStateException.class); IllegalStateException thrown =
thrown.expectMessage( expectThrows(
"Cancellation matching billing event must be set if and only if the SYNTHETIC flag is set"); IllegalStateException.class,
oneTime.asBuilder() () ->
oneTime
.asBuilder()
.setFlags(ImmutableSet.of(BillingEvent.Flag.SYNTHETIC)) .setFlags(ImmutableSet.of(BillingEvent.Flag.SYNTHETIC))
.setSyntheticCreationTime(END_OF_TIME) .setSyntheticCreationTime(END_OF_TIME)
.build(); .build());
assertThat(thrown)
.hasMessageThat()
.contains(
"Cancellation matching billing event must be set "
+ "if and only if the SYNTHETIC flag is set");
} }
@Test @Test
public void testFailure_cancellationMatchingKeyWithoutFlag() { public void testFailure_cancellationMatchingKeyWithoutFlag() {
thrown.expect(IllegalStateException.class); IllegalStateException thrown =
thrown.expectMessage( expectThrows(
"Cancellation matching billing event must be set if and only if the SYNTHETIC flag is set"); IllegalStateException.class,
oneTime.asBuilder() () ->
oneTime
.asBuilder()
.setCancellationMatchingBillingEvent(Key.create(recurring)) .setCancellationMatchingBillingEvent(Key.create(recurring))
.build(); .build());
assertThat(thrown)
.hasMessageThat()
.contains(
"Cancellation matching billing event must be set "
+ "if and only if the SYNTHETIC flag is set");
} }
@Test @Test
@ -250,32 +265,44 @@ public class BillingEventTest extends EntityTestCase {
@Test @Test
public void testFailure_cancellation_forGracePeriodWithoutBillingEvent() { public void testFailure_cancellation_forGracePeriodWithoutBillingEvent() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("grace period without billing event"); expectThrows(
IllegalArgumentException.class,
() ->
BillingEvent.Cancellation.forGracePeriod( BillingEvent.Cancellation.forGracePeriod(
GracePeriod.createWithoutBillingEvent( GracePeriod.createWithoutBillingEvent(
GracePeriodStatus.REDEMPTION, GracePeriodStatus.REDEMPTION, now.plusDays(1), "a registrar"),
now.plusDays(1),
"a registrar"),
historyEntry, historyEntry,
"foo.tld"); "foo.tld"));
assertThat(thrown).hasMessageThat().contains("grace period without billing event");
} }
@Test @Test
public void testFailure_cancellationWithNoBillingEvent() { public void testFailure_cancellationWithNoBillingEvent() {
thrown.expect(IllegalStateException.class); IllegalStateException thrown =
thrown.expectMessage("exactly one billing event"); expectThrows(
cancellationOneTime.asBuilder().setOneTimeEventKey(null).setRecurringEventKey(null).build(); IllegalStateException.class,
() ->
cancellationOneTime
.asBuilder()
.setOneTimeEventKey(null)
.setRecurringEventKey(null)
.build());
assertThat(thrown).hasMessageThat().contains("exactly one billing event");
} }
@Test @Test
public void testFailure_cancellationWithBothBillingEvents() { public void testFailure_cancellationWithBothBillingEvents() {
thrown.expect(IllegalStateException.class); IllegalStateException thrown =
thrown.expectMessage("exactly one billing event"); expectThrows(
cancellationOneTime.asBuilder() IllegalStateException.class,
() ->
cancellationOneTime
.asBuilder()
.setOneTimeEventKey(Key.create(oneTime)) .setOneTimeEventKey(Key.create(oneTime))
.setRecurringEventKey(Key.create(recurring)) .setRecurringEventKey(Key.create(recurring))
.build(); .build());
assertThat(thrown).hasMessageThat().contains("exactly one billing event");
} }
@Test @Test

View file

@ -17,6 +17,8 @@ package google.registry.model.billing;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.DatastoreHelper.loadRegistrar; import static google.registry.testing.DatastoreHelper.loadRegistrar;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import static org.joda.money.CurrencyUnit.USD; import static org.joda.money.CurrencyUnit.USD;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -25,9 +27,7 @@ import google.registry.model.EntityTestCase;
import org.joda.money.CurrencyMismatchException; import org.joda.money.CurrencyMismatchException;
import org.joda.money.Money; import org.joda.money.Money;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -35,9 +35,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public final class RegistrarBillingEntryTest extends EntityTestCase { public final class RegistrarBillingEntryTest extends EntityTestCase {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void testIndexing() throws Exception { public void testIndexing() throws Exception {
verifyIndexing( verifyIndexing(
@ -100,8 +97,10 @@ public final class RegistrarBillingEntryTest extends EntityTestCase {
@Test @Test
public void testBadTimeOrdering_causesError() throws Exception { public void testBadTimeOrdering_causesError() throws Exception {
thrown.expect(IllegalStateException.class); IllegalStateException thrown =
thrown.expectMessage("Created timestamp not after previous"); expectThrows(
IllegalStateException.class,
() ->
new RegistrarBillingEntry.Builder() new RegistrarBillingEntry.Builder()
.setPrevious( .setPrevious(
new RegistrarBillingEntry.Builder() new RegistrarBillingEntry.Builder()
@ -116,13 +115,16 @@ public final class RegistrarBillingEntryTest extends EntityTestCase {
.setTransactionId("goblin") .setTransactionId("goblin")
.setDescription("USD Invoice for August") .setDescription("USD Invoice for August")
.setAmount(Money.parse("USD 3.50")) .setAmount(Money.parse("USD 3.50"))
.build(); .build());
assertThat(thrown).hasMessageThat().contains("Created timestamp not after previous");
} }
@Test @Test
public void testRegistrarMismatch_causesError() throws Exception { public void testRegistrarMismatch_causesError() throws Exception {
thrown.expect(IllegalStateException.class); IllegalStateException thrown =
thrown.expectMessage("Parent not same as previous"); expectThrows(
IllegalStateException.class,
() ->
new RegistrarBillingEntry.Builder() new RegistrarBillingEntry.Builder()
.setPrevious( .setPrevious(
new RegistrarBillingEntry.Builder() new RegistrarBillingEntry.Builder()
@ -137,12 +139,15 @@ public final class RegistrarBillingEntryTest extends EntityTestCase {
.setTransactionId("goblin") .setTransactionId("goblin")
.setDescription("USD Invoice for August") .setDescription("USD Invoice for August")
.setAmount(Money.parse("USD 3.50")) .setAmount(Money.parse("USD 3.50"))
.build(); .build());
assertThat(thrown).hasMessageThat().contains("Parent not same as previous");
} }
@Test @Test
public void testCurrencyMismatch_causesError() throws Exception { public void testCurrencyMismatch_causesError() throws Exception {
thrown.expect(CurrencyMismatchException.class); assertThrows(
CurrencyMismatchException.class,
() ->
new RegistrarBillingEntry.Builder() new RegistrarBillingEntry.Builder()
.setPrevious( .setPrevious(
new RegistrarBillingEntry.Builder() new RegistrarBillingEntry.Builder()
@ -157,20 +162,23 @@ public final class RegistrarBillingEntryTest extends EntityTestCase {
.setTransactionId("goblin") .setTransactionId("goblin")
.setDescription("JPY Invoice for August") .setDescription("JPY Invoice for August")
.setAmount(Money.parse("JPY 350")) .setAmount(Money.parse("JPY 350"))
.build(); .build());
} }
@Test @Test
public void testZeroAmount_causesError() throws Exception { public void testZeroAmount_causesError() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Amount can't be zero"); expectThrows(
IllegalArgumentException.class,
() ->
new RegistrarBillingEntry.Builder() new RegistrarBillingEntry.Builder()
.setPrevious(null) .setPrevious(null)
.setParent(loadRegistrar("NewRegistrar")) .setParent(loadRegistrar("NewRegistrar"))
.setCreated(DateTime.parse("1984-12-18TZ")) .setCreated(DateTime.parse("1984-12-18TZ"))
.setDescription("USD Invoice for December") .setDescription("USD Invoice for December")
.setAmount(Money.zero(USD)) .setAmount(Money.zero(USD))
.build(); .build());
assertThat(thrown).hasMessageThat().contains("Amount can't be zero");
} }
@Test @Test

View file

@ -20,6 +20,7 @@ import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.loadRegistrar; import static google.registry.testing.DatastoreHelper.loadRegistrar;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.util.DateTimeUtils.END_OF_TIME; import static google.registry.util.DateTimeUtils.END_OF_TIME;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
@ -33,16 +34,10 @@ import org.joda.money.CurrencyUnit;
import org.joda.money.Money; import org.joda.money.Money;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
/** Unit tests for {@link RegistrarCreditBalance}. */ /** Unit tests for {@link RegistrarCreditBalance}. */
public class RegistrarCreditBalanceTest extends EntityTestCase { public class RegistrarCreditBalanceTest extends EntityTestCase {
@Rule
public ExpectedException thrown = ExpectedException.none();
private DateTime then = clock.nowUtc().plusDays(1); private DateTime then = clock.nowUtc().plusDays(1);
private Registrar theRegistrar; private Registrar theRegistrar;
@ -100,19 +95,21 @@ public class RegistrarCreditBalanceTest extends EntityTestCase {
@Test @Test
public void testFailure_balanceNotInCreditCurrency() throws Exception { public void testFailure_balanceNotInCreditCurrency() throws Exception {
thrown.expect(IllegalStateException.class); assertThrows(
balance.asBuilder() IllegalStateException.class,
.setAmount(Money.parse("JPY 1")) () -> balance.asBuilder().setAmount(Money.parse("JPY 1")).build());
.build();
} }
@Test @Test
public void testFailure_balanceNotInCreditCurrencyWithUnpersistedCredit() throws Exception { public void testFailure_balanceNotInCreditCurrencyWithUnpersistedCredit() throws Exception {
thrown.expect(IllegalStateException.class); assertThrows(
balance.asBuilder() IllegalStateException.class,
() ->
balance
.asBuilder()
.setParent(unpersistedCredit) .setParent(unpersistedCredit)
.setAmount(Money.parse("JPY 1")) .setAmount(Money.parse("JPY 1"))
.build(); .build());
} }
@Test @Test

View file

@ -19,6 +19,7 @@ import static google.registry.model.common.EntityGroupRoot.getCrossTldKey;
import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.expectThrows;
import static org.joda.money.CurrencyUnit.JPY; import static org.joda.money.CurrencyUnit.JPY;
import static org.joda.money.CurrencyUnit.USD; import static org.joda.money.CurrencyUnit.USD;
@ -28,16 +29,10 @@ import google.registry.model.registrar.Registrar;
import google.registry.model.registry.Registry; import google.registry.model.registry.Registry;
import org.joda.money.CurrencyUnit; import org.joda.money.CurrencyUnit;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
/** Unit tests for {@link RegistrarCredit}. */ /** Unit tests for {@link RegistrarCredit}. */
public class RegistrarCreditTest extends EntityTestCase { public class RegistrarCreditTest extends EntityTestCase {
@Rule
public ExpectedException thrown = ExpectedException.none();
private RegistrarCredit auctionCredit; private RegistrarCredit auctionCredit;
private RegistrarCredit promoCredit; private RegistrarCredit promoCredit;
@ -81,23 +76,28 @@ public class RegistrarCreditTest extends EntityTestCase {
@Test @Test
public void testFailure_missingTld() throws Exception { public void testFailure_missingTld() throws Exception {
thrown.expect(NullPointerException.class); NullPointerException thrown =
thrown.expectMessage("tld"); expectThrows(
promoCredit.asBuilder().setTld(null).build(); NullPointerException.class, () -> promoCredit.asBuilder().setTld(null).build());
assertThat(thrown).hasMessageThat().contains("tld");
} }
@Test @Test
public void testFailure_NonexistentTld() throws Exception { public void testFailure_NonexistentTld() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("example"); expectThrows(
promoCredit.asBuilder().setTld("example").build(); IllegalArgumentException.class,
() -> promoCredit.asBuilder().setTld("example").build());
assertThat(thrown).hasMessageThat().contains("example");
} }
@Test @Test
public void testFailure_CurrencyDoesNotMatchTldCurrency() throws Exception { public void testFailure_CurrencyDoesNotMatchTldCurrency() throws Exception {
assertThat(Registry.get("tld").getCurrency()).isEqualTo(USD); assertThat(Registry.get("tld").getCurrency()).isEqualTo(USD);
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("currency"); expectThrows(
promoCredit.asBuilder().setTld("tld").setCurrency(JPY).build(); IllegalArgumentException.class,
() -> promoCredit.asBuilder().setTld("tld").setCurrency(JPY).build());
assertThat(thrown).hasMessageThat().contains("currency");
} }
} }

View file

@ -21,21 +21,17 @@ import static google.registry.model.common.Cursor.CursorType.RECURRING_BILLING;
import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistActiveDomain; import static google.registry.testing.DatastoreHelper.persistActiveDomain;
import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
import google.registry.model.EntityTestCase; import google.registry.model.EntityTestCase;
import google.registry.model.domain.DomainResource; import google.registry.model.domain.DomainResource;
import google.registry.model.registry.Registry; import google.registry.model.registry.Registry;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
/** Unit tests for {@link Cursor}. */ /** Unit tests for {@link Cursor}. */
public class CursorTest extends EntityTestCase { public class CursorTest extends EntityTestCase {
@Rule public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void testSuccess_persistScopedCursor() { public void testSuccess_persistScopedCursor() {
createTld("tld"); createTld("tld");
@ -74,54 +70,72 @@ public class CursorTest extends EntityTestCase {
clock.advanceOneMilli(); clock.advanceOneMilli();
final DateTime time = DateTime.parse("2012-07-12T03:30:00.000Z"); final DateTime time = DateTime.parse("2012-07-12T03:30:00.000Z");
final DomainResource domain = persistActiveDomain("notaregistry.tld"); final DomainResource domain = persistActiveDomain("notaregistry.tld");
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Class required for cursor does not match scope class"); expectThrows(
ofy().transact(() -> ofy().save().entity(Cursor.create(RDE_UPLOAD, time, domain))); IllegalArgumentException.class,
() ->
ofy().transact(() -> ofy().save().entity(Cursor.create(RDE_UPLOAD, time, domain))));
assertThat(thrown)
.hasMessageThat()
.contains("Class required for cursor does not match scope class");
} }
@Test @Test
public void testFailure_invalidScopeOnKeyCreate() throws Exception { public void testFailure_invalidScopeOnKeyCreate() throws Exception {
createTld("tld"); createTld("tld");
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Class required for cursor does not match scope class"); expectThrows(
Cursor.createKey(RDE_UPLOAD, persistActiveDomain("notaregistry.tld")); IllegalArgumentException.class,
() -> Cursor.createKey(RDE_UPLOAD, persistActiveDomain("notaregistry.tld")));
assertThat(thrown)
.hasMessageThat()
.contains("Class required for cursor does not match scope class");
} }
@Test @Test
public void testFailure_createGlobalKeyForScopedCursorType() throws Exception { public void testFailure_createGlobalKeyForScopedCursorType() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Cursor type is not a global cursor"); expectThrows(IllegalArgumentException.class, () -> Cursor.createGlobalKey(RDE_UPLOAD));
Cursor.createGlobalKey(RDE_UPLOAD); assertThat(thrown).hasMessageThat().contains("Cursor type is not a global cursor");
} }
@Test @Test
public void testFailure_invalidScopeOnGlobalKeyCreate() throws Exception { public void testFailure_invalidScopeOnGlobalKeyCreate() throws Exception {
createTld("tld"); createTld("tld");
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Class required for cursor does not match scope class"); expectThrows(
Cursor.createKey(RECURRING_BILLING, persistActiveDomain("notaregistry.tld")); IllegalArgumentException.class,
() -> Cursor.createKey(RECURRING_BILLING, persistActiveDomain("notaregistry.tld")));
assertThat(thrown)
.hasMessageThat()
.contains("Class required for cursor does not match scope class");
} }
@Test @Test
public void testFailure_nullScope() throws Exception { public void testFailure_nullScope() throws Exception {
thrown.expect(NullPointerException.class); NullPointerException thrown =
thrown.expectMessage("Cursor scope cannot be null"); expectThrows(
Cursor.create(RECURRING_BILLING, START_OF_TIME, null); NullPointerException.class,
() -> Cursor.create(RECURRING_BILLING, START_OF_TIME, null));
assertThat(thrown).hasMessageThat().contains("Cursor scope cannot be null");
} }
@Test @Test
public void testFailure_nullCursorType() throws Exception { public void testFailure_nullCursorType() throws Exception {
createTld("tld"); createTld("tld");
thrown.expect(NullPointerException.class); NullPointerException thrown =
thrown.expectMessage("Cursor type cannot be null"); expectThrows(
Cursor.create(null, START_OF_TIME, Registry.get("tld")); NullPointerException.class,
() -> Cursor.create(null, START_OF_TIME, Registry.get("tld")));
assertThat(thrown).hasMessageThat().contains("Cursor type cannot be null");
} }
@Test @Test
public void testFailure_nullTime() throws Exception { public void testFailure_nullTime() throws Exception {
createTld("tld"); createTld("tld");
thrown.expect(NullPointerException.class); NullPointerException thrown =
thrown.expectMessage("Cursor time cannot be null"); expectThrows(
Cursor.create(RDE_UPLOAD, null, Registry.get("tld")); NullPointerException.class, () -> Cursor.create(RDE_UPLOAD, null, Registry.get("tld")));
assertThat(thrown).hasMessageThat().contains("Cursor time cannot be null");
} }
} }

View file

@ -21,9 +21,7 @@ import static google.registry.util.DateTimeUtils.START_OF_TIME;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Range; import com.google.common.collect.Range;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -35,9 +33,6 @@ public class TimeOfYearTest {
private static final DateTime february29 = DateTime.parse("2012-02-29T01:02:03.0Z"); private static final DateTime february29 = DateTime.parse("2012-02-29T01:02:03.0Z");
private static final DateTime march1 = DateTime.parse("2012-03-01T01:02:03.0Z"); private static final DateTime march1 = DateTime.parse("2012-03-01T01:02:03.0Z");
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void testSuccess_fromDateTime() throws Exception { public void testSuccess_fromDateTime() throws Exception {
// We intentionally don't allow leap years in TimeOfYear, so February 29 should be February 28. // We intentionally don't allow leap years in TimeOfYear, so February 29 should be February 28.

View file

@ -16,6 +16,7 @@ package google.registry.model.common;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.common.TimedTransitionProperty.forMapify; import static google.registry.model.common.TimedTransitionProperty.forMapify;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.util.DateTimeUtils.END_OF_TIME; import static google.registry.util.DateTimeUtils.END_OF_TIME;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static org.joda.time.DateTimeZone.UTC; import static org.joda.time.DateTimeZone.UTC;
@ -26,19 +27,13 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
/** Unit tests for {@link TimedTransitionProperty}. */ /** Unit tests for {@link TimedTransitionProperty}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class TimedTransitionPropertyTest { public class TimedTransitionPropertyTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private static final DateTime A_LONG_TIME_AGO = new DateTime(Long.MIN_VALUE, UTC); private static final DateTime A_LONG_TIME_AGO = new DateTime(Long.MIN_VALUE, UTC);
private static final DateTime DATE_1 = DateTime.parse("2001-01-01T00:00:00.0Z"); private static final DateTime DATE_1 = DateTime.parse("2001-01-01T00:00:00.0Z");
@ -130,31 +125,39 @@ public class TimedTransitionPropertyTest {
@Test @Test
public void testFailure_valueMapNotChronologicallyOrdered() throws Exception { public void testFailure_valueMapNotChronologicallyOrdered() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
IllegalArgumentException.class,
() ->
TimedTransitionProperty.fromValueMap( TimedTransitionProperty.fromValueMap(
ImmutableSortedMap.<DateTime, String>reverseOrder().put(START_OF_TIME, "0").build(), ImmutableSortedMap.<DateTime, String>reverseOrder().put(START_OF_TIME, "0").build(),
StringTimedTransition.class); StringTimedTransition.class));
} }
@Test @Test
public void testFailure_transitionTimeBeforeStartOfTime() throws Exception { public void testFailure_transitionTimeBeforeStartOfTime() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
IllegalArgumentException.class,
() ->
TimedTransitionProperty.fromValueMap( TimedTransitionProperty.fromValueMap(
ImmutableSortedMap.of(A_LONG_TIME_AGO, "?"), StringTimedTransition.class); ImmutableSortedMap.of(A_LONG_TIME_AGO, "?"), StringTimedTransition.class));
} }
@Test @Test
public void testFailure_noValues() throws Exception { public void testFailure_noValues() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
IllegalArgumentException.class,
() ->
TimedTransitionProperty.fromValueMap( TimedTransitionProperty.fromValueMap(
ImmutableSortedMap.<DateTime, String>of(), StringTimedTransition.class); ImmutableSortedMap.<DateTime, String>of(), StringTimedTransition.class));
} }
@Test @Test
public void testFailure_noValueAtStartOfTime() throws Exception { public void testFailure_noValueAtStartOfTime() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
IllegalArgumentException.class,
() ->
TimedTransitionProperty.fromValueMap( TimedTransitionProperty.fromValueMap(
ImmutableSortedMap.of(DATE_1, "1"), StringTimedTransition.class); ImmutableSortedMap.of(DATE_1, "1"), StringTimedTransition.class));
} }
@Test @Test
@ -162,8 +165,7 @@ public class TimedTransitionPropertyTest {
timedString = forMapify("0", StringTimedTransition.class); timedString = forMapify("0", StringTimedTransition.class);
// Simulate a load from Datastore by clearing, but don't insert any transitions. // Simulate a load from Datastore by clearing, but don't insert any transitions.
timedString.clear(); timedString.clear();
thrown.expect(IllegalStateException.class); assertThrows(IllegalStateException.class, () -> timedString.checkValidity());
timedString.checkValidity();
} }
@Test @Test
@ -175,7 +177,6 @@ public class TimedTransitionPropertyTest {
// omit a transition corresponding to START_OF_TIME. // omit a transition corresponding to START_OF_TIME.
timedString.clear(); timedString.clear();
timedString.put(DATE_1, transition1); timedString.put(DATE_1, transition1);
thrown.expect(IllegalStateException.class); assertThrows(IllegalStateException.class, () -> timedString.checkValidity());
timedString.checkValidity();
} }
} }

View file

@ -20,6 +20,7 @@ import static google.registry.testing.ContactResourceSubject.assertAboutContacts
import static google.registry.testing.DatastoreHelper.cloneAndSetAutoTimestamps; import static google.registry.testing.DatastoreHelper.cloneAndSetAutoTimestamps;
import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.util.DateTimeUtils.END_OF_TIME; import static google.registry.util.DateTimeUtils.END_OF_TIME;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
@ -37,16 +38,10 @@ import google.registry.model.transfer.TransferData;
import google.registry.model.transfer.TransferData.TransferServerApproveEntity; import google.registry.model.transfer.TransferData.TransferServerApproveEntity;
import google.registry.model.transfer.TransferStatus; import google.registry.model.transfer.TransferStatus;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
/** Unit tests for {@link ContactResource}. */ /** Unit tests for {@link ContactResource}. */
public class ContactResourceTest extends EntityTestCase { public class ContactResourceTest extends EntityTestCase {
@Rule
public final ExpectedException thrown = ExpectedException.none();
ContactResource contactResource; ContactResource contactResource;
@Before @Before
@ -206,9 +201,11 @@ public class ContactResourceTest extends EntityTestCase {
@Test @Test
public void testSetCreationTime_cantBeCalledTwice() { public void testSetCreationTime_cantBeCalledTwice() {
thrown.expect(IllegalStateException.class); IllegalStateException thrown =
thrown.expectMessage("creationTime can only be set once"); expectThrows(
contactResource.asBuilder().setCreationTime(END_OF_TIME); IllegalStateException.class,
() -> contactResource.asBuilder().setCreationTime(END_OF_TIME));
assertThat(thrown).hasMessageThat().contains("creationTime can only be set once");
} }
@Test @Test

View file

@ -41,16 +41,11 @@ import google.registry.model.host.HostResource;
import google.registry.model.smd.EncodedSignedMark; import google.registry.model.smd.EncodedSignedMark;
import org.joda.money.Money; import org.joda.money.Money;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
/** Unit tests for {@link DomainApplication}. */ /** Unit tests for {@link DomainApplication}. */
public class DomainApplicationTest extends EntityTestCase { public class DomainApplicationTest extends EntityTestCase {
@Rule
public final ExpectedException thrown = ExpectedException.none();
DomainApplication domainApplication; DomainApplication domainApplication;
@Before @Before

View file

@ -24,6 +24,7 @@ import static google.registry.testing.DatastoreHelper.newDomainResource;
import static google.registry.testing.DatastoreHelper.newHostResource; import static google.registry.testing.DatastoreHelper.newHostResource;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.DomainResourceSubject.assertAboutDomains; import static google.registry.testing.DomainResourceSubject.assertAboutDomains;
import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static org.joda.money.CurrencyUnit.USD; import static org.joda.money.CurrencyUnit.USD;
@ -55,16 +56,10 @@ import java.util.stream.Stream;
import org.joda.money.Money; import org.joda.money.Money;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
/** Unit tests for {@link DomainResource}. */ /** Unit tests for {@link DomainResource}. */
public class DomainResourceTest extends EntityTestCase { public class DomainResourceTest extends EntityTestCase {
@Rule
public final ExpectedException thrown = ExpectedException.none();
DomainResource domain; DomainResource domain;
@Before @Before
@ -445,15 +440,23 @@ public class DomainResourceTest extends EntityTestCase {
@Test @Test
public void testFailure_uppercaseDomainName() { public void testFailure_uppercaseDomainName() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Domain name must be in puny-coded, lower-case form"); expectThrows(
domain.asBuilder().setFullyQualifiedDomainName("AAA.BBB"); IllegalArgumentException.class,
() -> domain.asBuilder().setFullyQualifiedDomainName("AAA.BBB"));
assertThat(thrown)
.hasMessageThat()
.contains("Domain name must be in puny-coded, lower-case form");
} }
@Test @Test
public void testFailure_utf8DomainName() { public void testFailure_utf8DomainName() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Domain name must be in puny-coded, lower-case form"); expectThrows(
domain.asBuilder().setFullyQualifiedDomainName("みんな.みんな"); IllegalArgumentException.class,
() -> domain.asBuilder().setFullyQualifiedDomainName("みんな.みんな"));
assertThat(thrown)
.hasMessageThat()
.contains("Domain name must be in puny-coded, lower-case form");
} }
} }

View file

@ -15,6 +15,7 @@
package google.registry.model.domain; package google.registry.model.domain;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.expectThrows;
import static org.joda.time.DateTimeZone.UTC; import static org.joda.time.DateTimeZone.UTC;
import com.googlecode.objectify.Key; import com.googlecode.objectify.Key;
@ -30,7 +31,6 @@ import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -42,10 +42,6 @@ public class GracePeriodTest {
public final AppEngineRule appEngine = AppEngineRule.builder() public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore() // Needed to be able to construct Keys. .withDatastore() // Needed to be able to construct Keys.
.build(); .build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final DateTime now = DateTime.now(UTC); private final DateTime now = DateTime.now(UTC);
private BillingEvent.OneTime onetime; private BillingEvent.OneTime onetime;
@ -96,19 +92,24 @@ public class GracePeriodTest {
@Test @Test
public void testFailure_forBillingEvent_autoRenew() { public void testFailure_forBillingEvent_autoRenew() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("autorenew"); expectThrows(
GracePeriod.forBillingEvent(GracePeriodStatus.AUTO_RENEW, onetime); IllegalArgumentException.class,
() -> GracePeriod.forBillingEvent(GracePeriodStatus.AUTO_RENEW, onetime));
assertThat(thrown).hasMessageThat().contains("autorenew");
} }
@Test @Test
public void testFailure_createForRecurring_notAutoRenew() { public void testFailure_createForRecurring_notAutoRenew() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("autorenew"); expectThrows(
IllegalArgumentException.class,
() ->
GracePeriod.createForRecurring( GracePeriod.createForRecurring(
GracePeriodStatus.RENEW, GracePeriodStatus.RENEW,
now.plusDays(1), now.plusDays(1),
"TheRegistrar", "TheRegistrar",
Key.create(Recurring.class, 12345)); Key.create(Recurring.class, 12345)));
assertThat(thrown).hasMessageThat().contains("autorenew");
} }
} }

View file

@ -26,9 +26,7 @@ import com.googlecode.objectify.Key;
import google.registry.model.EntityTestCase; import google.registry.model.EntityTestCase;
import google.registry.model.reporting.HistoryEntry; import google.registry.model.reporting.HistoryEntry;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
/** Unit tests for {@link LrpTokenEntity}. */ /** Unit tests for {@link LrpTokenEntity}. */
public class LrpTokenEntityTest extends EntityTestCase { public class LrpTokenEntityTest extends EntityTestCase {
@ -36,9 +34,6 @@ public class LrpTokenEntityTest extends EntityTestCase {
LrpTokenEntity unredeemedToken; LrpTokenEntity unredeemedToken;
LrpTokenEntity redeemedToken; LrpTokenEntity redeemedToken;
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
createTld("tld"); createTld("tld");

View file

@ -21,6 +21,7 @@ import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.newDomainResource; import static google.registry.testing.DatastoreHelper.newDomainResource;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.HostResourceSubject.assertAboutHosts; import static google.registry.testing.HostResourceSubject.assertAboutHosts;
import static google.registry.testing.JUnitBackports.expectThrows;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.net.InetAddresses; import com.google.common.net.InetAddresses;
@ -36,16 +37,10 @@ import google.registry.model.transfer.TransferStatus;
import java.net.InetAddress; import java.net.InetAddress;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
/** Unit tests for {@link HostResource}. */ /** Unit tests for {@link HostResource}. */
public class HostResourceTest extends EntityTestCase { public class HostResourceTest extends EntityTestCase {
@Rule
public final ExpectedException thrown = ExpectedException.none();
final DateTime day3 = clock.nowUtc(); final DateTime day3 = clock.nowUtc();
final DateTime day2 = day3.minusDays(1); final DateTime day2 = day3.minusDays(1);
final DateTime day1 = day2.minusDays(1); final DateTime day1 = day2.minusDays(1);
@ -163,16 +158,24 @@ public class HostResourceTest extends EntityTestCase {
@Test @Test
public void testFailure_uppercaseHostName() { public void testFailure_uppercaseHostName() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Host name must be in puny-coded, lower-case form"); expectThrows(
host.asBuilder().setFullyQualifiedHostName("AAA.BBB.CCC"); IllegalArgumentException.class,
() -> host.asBuilder().setFullyQualifiedHostName("AAA.BBB.CCC"));
assertThat(thrown)
.hasMessageThat()
.contains("Host name must be in puny-coded, lower-case form");
} }
@Test @Test
public void testFailure_utf8HostName() { public void testFailure_utf8HostName() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Host name must be in puny-coded, lower-case form"); expectThrows(
host.asBuilder().setFullyQualifiedHostName("みんな.みんな.みんな"); IllegalArgumentException.class,
() -> host.asBuilder().setFullyQualifiedHostName("みんな.みんな.みんな"));
assertThat(thrown)
.hasMessageThat()
.contains("Host name must be in puny-coded, lower-case form");
} }
@Test @Test

View file

@ -23,6 +23,7 @@ import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.newDomainApplication; import static google.registry.testing.DatastoreHelper.newDomainApplication;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.DatastoreHelper.persistSimpleResource; import static google.registry.testing.DatastoreHelper.persistSimpleResource;
import static google.registry.testing.JUnitBackports.expectThrows;
import static org.joda.time.DateTimeZone.UTC; import static org.joda.time.DateTimeZone.UTC;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
@ -32,16 +33,10 @@ import google.registry.model.EntityTestCase;
import google.registry.model.domain.DomainApplication; import google.registry.model.domain.DomainApplication;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
/** Unit tests for {@link DomainApplicationIndex}. */ /** Unit tests for {@link DomainApplicationIndex}. */
public class DomainApplicationIndexTest extends EntityTestCase { public class DomainApplicationIndexTest extends EntityTestCase {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Before @Before
public void init() throws Exception { public void init() throws Exception {
createTld("com"); createTld("com");
@ -49,16 +44,20 @@ public class DomainApplicationIndexTest extends EntityTestCase {
@Test @Test
public void testFailure_create_nullReferences() { public void testFailure_create_nullReferences() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Keys must not be null or empty."); expectThrows(
DomainApplicationIndex.createWithSpecifiedKeys("blah.com", null); IllegalArgumentException.class,
() -> DomainApplicationIndex.createWithSpecifiedKeys("blah.com", null));
assertThat(thrown).hasMessageThat().contains("Keys must not be null or empty.");
} }
@Test @Test
public void testFailure_create_emptyReferences() { public void testFailure_create_emptyReferences() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Keys must not be null or empty."); expectThrows(
createWithSpecifiedKeys("blah.com", ImmutableSet.<Key<DomainApplication>>of()); IllegalArgumentException.class,
() -> createWithSpecifiedKeys("blah.com", ImmutableSet.<Key<DomainApplication>>of()));
assertThat(thrown).hasMessageThat().contains("Keys must not be null or empty.");
} }
@Test @Test

View file

@ -27,16 +27,11 @@ import google.registry.model.EntityTestCase;
import google.registry.model.host.HostResource; import google.registry.model.host.HostResource;
import google.registry.model.index.ForeignKeyIndex.ForeignKeyHostIndex; import google.registry.model.index.ForeignKeyIndex.ForeignKeyHostIndex;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
/** Unit tests for {@link ForeignKeyIndex}. */ /** Unit tests for {@link ForeignKeyIndex}. */
public class ForeignKeyIndexTest extends EntityTestCase { public class ForeignKeyIndexTest extends EntityTestCase {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
createTld("com"); createTld("com");

View file

@ -19,6 +19,7 @@ import static google.registry.model.ofy.CommitLogBucket.getBucketKey;
import static google.registry.model.ofy.CommitLogBucket.loadAllBuckets; import static google.registry.model.ofy.CommitLogBucket.loadAllBuckets;
import static google.registry.model.ofy.CommitLogBucket.loadBucket; import static google.registry.model.ofy.CommitLogBucket.loadBucket;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.util.DateTimeUtils.END_OF_TIME; import static google.registry.util.DateTimeUtils.END_OF_TIME;
import com.google.common.base.Suppliers; import com.google.common.base.Suppliers;
@ -29,7 +30,6 @@ import google.registry.testing.InjectRule;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -44,10 +44,6 @@ public class CommitLogBucketTest {
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();
@Rule
public final ExpectedException thrown = ExpectedException.none();
CommitLogBucket bucket; CommitLogBucket bucket;
@Before @Before
@ -69,16 +65,16 @@ public class CommitLogBucketTest {
@Test @Test
public void test_getBucketKey_bucketNumberTooLow_throws() { public void test_getBucketKey_bucketNumberTooLow_throws() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("0 not in ["); expectThrows(IllegalArgumentException.class, () -> getBucketKey(0));
getBucketKey(0); assertThat(thrown).hasMessageThat().contains("0 not in [");
} }
@Test @Test
public void test_getBucketKey_bucketNumberTooHigh_throws() { public void test_getBucketKey_bucketNumberTooHigh_throws() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("11 not in ["); expectThrows(IllegalArgumentException.class, () -> getBucketKey(11));
getBucketKey(11); assertThat(thrown).hasMessageThat().contains("11 not in [");
} }
@Test @Test

View file

@ -15,6 +15,7 @@
package google.registry.model.ofy; package google.registry.model.ofy;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static org.joda.time.DateTimeZone.UTC; import static org.joda.time.DateTimeZone.UTC;
@ -23,7 +24,6 @@ import google.registry.testing.AppEngineRule;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -36,9 +36,6 @@ public class CommitLogCheckpointTest {
.withDatastore() .withDatastore()
.build(); .build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
private static final DateTime T1 = START_OF_TIME; private static final DateTime T1 = START_OF_TIME;
private static final DateTime T2 = START_OF_TIME.plusMillis(1); private static final DateTime T2 = START_OF_TIME.plusMillis(1);
private static final DateTime T3 = START_OF_TIME.plusMillis(2); private static final DateTime T3 = START_OF_TIME.plusMillis(2);
@ -60,29 +57,43 @@ public class CommitLogCheckpointTest {
@Test @Test
public void test_create_notEnoughBucketTimestamps_throws() { public void test_create_notEnoughBucketTimestamps_throws() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Bucket ids are incorrect"); expectThrows(
CommitLogCheckpoint.create(DateTime.now(UTC), ImmutableMap.of(1, T1, 2, T2)); IllegalArgumentException.class,
() -> CommitLogCheckpoint.create(DateTime.now(UTC), ImmutableMap.of(1, T1, 2, T2)));
assertThat(thrown).hasMessageThat().contains("Bucket ids are incorrect");
} }
@Test @Test
public void test_create_tooManyBucketTimestamps_throws() { public void test_create_tooManyBucketTimestamps_throws() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Bucket ids are incorrect"); expectThrows(
CommitLogCheckpoint.create(DateTime.now(UTC), ImmutableMap.of(1, T1, 2, T2, 3, T3, 4, T1)); IllegalArgumentException.class,
() ->
CommitLogCheckpoint.create(
DateTime.now(UTC), ImmutableMap.of(1, T1, 2, T2, 3, T3, 4, T1)));
assertThat(thrown).hasMessageThat().contains("Bucket ids are incorrect");
} }
@Test @Test
public void test_create_wrongBucketIds_throws() { public void test_create_wrongBucketIds_throws() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Bucket ids are incorrect"); expectThrows(
CommitLogCheckpoint.create(DateTime.now(UTC), ImmutableMap.of(0, T1, 1, T2, 2, T3)); IllegalArgumentException.class,
() ->
CommitLogCheckpoint.create(
DateTime.now(UTC), ImmutableMap.of(0, T1, 1, T2, 2, T3)));
assertThat(thrown).hasMessageThat().contains("Bucket ids are incorrect");
} }
@Test @Test
public void test_create_wrongBucketIdOrder_throws() { public void test_create_wrongBucketIdOrder_throws() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Bucket ids are incorrect"); expectThrows(
CommitLogCheckpoint.create(DateTime.now(UTC), ImmutableMap.of(2, T2, 1, T1, 3, T3)); IllegalArgumentException.class,
() ->
CommitLogCheckpoint.create(
DateTime.now(UTC), ImmutableMap.of(2, T2, 1, T1, 3, T3)));
assertThat(thrown).hasMessageThat().contains("Bucket ids are incorrect");
} }
} }

View file

@ -20,6 +20,7 @@ import static com.googlecode.objectify.ObjectifyService.register;
import static google.registry.model.common.EntityGroupRoot.getCrossTldKey; import static google.registry.model.common.EntityGroupRoot.getCrossTldKey;
import static google.registry.model.ofy.CommitLogBucket.getBucketKey; import static google.registry.model.ofy.CommitLogBucket.getBucketKey;
import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.testing.JUnitBackports.expectThrows;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.googlecode.objectify.Key; import com.googlecode.objectify.Key;
@ -37,7 +38,6 @@ import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -50,9 +50,6 @@ public class OfyCommitLogTest {
.withDatastore() .withDatastore()
.build(); .build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();
@ -163,74 +160,91 @@ public class OfyCommitLogTest {
public void testTransactNew_deleteNotBackedUpKind_throws() throws Exception { public void testTransactNew_deleteNotBackedUpKind_throws() throws Exception {
final CommitLogManifest backupsArentAllowedOnMe = final CommitLogManifest backupsArentAllowedOnMe =
CommitLogManifest.create(getBucketKey(1), clock.nowUtc(), ImmutableSet.<Key<?>>of()); CommitLogManifest.create(getBucketKey(1), clock.nowUtc(), ImmutableSet.<Key<?>>of());
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Can't save/delete a @NotBackedUp"); expectThrows(
ofy().transactNew(() -> ofy().delete().entity(backupsArentAllowedOnMe)); IllegalArgumentException.class,
() -> ofy().transactNew(() -> ofy().delete().entity(backupsArentAllowedOnMe)));
assertThat(thrown).hasMessageThat().contains("Can't save/delete a @NotBackedUp");
} }
@Test @Test
public void testTransactNew_saveNotBackedUpKind_throws() throws Exception { public void testTransactNew_saveNotBackedUpKind_throws() throws Exception {
final CommitLogManifest backupsArentAllowedOnMe = final CommitLogManifest backupsArentAllowedOnMe =
CommitLogManifest.create(getBucketKey(1), clock.nowUtc(), ImmutableSet.<Key<?>>of()); CommitLogManifest.create(getBucketKey(1), clock.nowUtc(), ImmutableSet.<Key<?>>of());
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Can't save/delete a @NotBackedUp"); expectThrows(
ofy().transactNew(() -> ofy().save().entity(backupsArentAllowedOnMe)); IllegalArgumentException.class,
() -> ofy().transactNew(() -> ofy().save().entity(backupsArentAllowedOnMe)));
assertThat(thrown).hasMessageThat().contains("Can't save/delete a @NotBackedUp");
} }
@Test @Test
public void testTransactNew_deleteVirtualEntityKey_throws() throws Exception { public void testTransactNew_deleteVirtualEntityKey_throws() throws Exception {
final Key<TestVirtualObject> virtualEntityKey = TestVirtualObject.createKey("virtual"); final Key<TestVirtualObject> virtualEntityKey = TestVirtualObject.createKey("virtual");
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Can't save/delete a @VirtualEntity"); expectThrows(
ofy().transactNew(() -> ofy().delete().key(virtualEntityKey)); IllegalArgumentException.class,
() -> ofy().transactNew(() -> ofy().delete().key(virtualEntityKey)));
assertThat(thrown).hasMessageThat().contains("Can't save/delete a @VirtualEntity");
} }
@Test @Test
public void testTransactNew_saveVirtualEntity_throws() throws Exception { public void testTransactNew_saveVirtualEntity_throws() throws Exception {
final TestVirtualObject virtualEntity = TestVirtualObject.create("virtual"); final TestVirtualObject virtualEntity = TestVirtualObject.create("virtual");
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Can't save/delete a @VirtualEntity"); expectThrows(
ofy().transactNew(() -> ofy().save().entity(virtualEntity)); IllegalArgumentException.class,
() -> ofy().transactNew(() -> ofy().save().entity(virtualEntity)));
assertThat(thrown).hasMessageThat().contains("Can't save/delete a @VirtualEntity");
} }
@Test @Test
public void test_deleteWithoutBackup_withVirtualEntityKey_throws() throws Exception { public void test_deleteWithoutBackup_withVirtualEntityKey_throws() throws Exception {
final Key<TestVirtualObject> virtualEntityKey = TestVirtualObject.createKey("virtual"); final Key<TestVirtualObject> virtualEntityKey = TestVirtualObject.createKey("virtual");
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Can't save/delete a @VirtualEntity"); expectThrows(
ofy().deleteWithoutBackup().key(virtualEntityKey); IllegalArgumentException.class,
() -> ofy().deleteWithoutBackup().key(virtualEntityKey));
assertThat(thrown).hasMessageThat().contains("Can't save/delete a @VirtualEntity");
} }
@Test @Test
public void test_saveWithoutBackup_withVirtualEntity_throws() throws Exception { public void test_saveWithoutBackup_withVirtualEntity_throws() throws Exception {
final TestVirtualObject virtualEntity = TestVirtualObject.create("virtual"); final TestVirtualObject virtualEntity = TestVirtualObject.create("virtual");
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Can't save/delete a @VirtualEntity"); expectThrows(
ofy().saveWithoutBackup().entity(virtualEntity); IllegalArgumentException.class, () -> ofy().saveWithoutBackup().entity(virtualEntity));
assertThat(thrown).hasMessageThat().contains("Can't save/delete a @VirtualEntity");
} }
@Test @Test
public void testTransact_twoSavesOnSameKey_throws() throws Exception { public void testTransact_twoSavesOnSameKey_throws() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Multiple entries with same key"); expectThrows(
IllegalArgumentException.class,
() ->
ofy() ofy()
.transact( .transact(
() -> { () -> {
ofy().save().entity(Root.create(1, getCrossTldKey())); ofy().save().entity(Root.create(1, getCrossTldKey()));
ofy().save().entity(Root.create(1, getCrossTldKey())); ofy().save().entity(Root.create(1, getCrossTldKey()));
}); }));
assertThat(thrown).hasMessageThat().contains("Multiple entries with same key");
} }
@Test @Test
public void testTransact_saveAndDeleteSameKey_throws() throws Exception { public void testTransact_saveAndDeleteSameKey_throws() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Multiple entries with same key"); expectThrows(
IllegalArgumentException.class,
() ->
ofy() ofy()
.transact( .transact(
() -> { () -> {
ofy().save().entity(Root.create(1, getCrossTldKey())); ofy().save().entity(Root.create(1, getCrossTldKey()));
ofy().delete().entity(Root.create(1, getCrossTldKey())); ofy().delete().entity(Root.create(1, getCrossTldKey()));
}); }));
assertThat(thrown).hasMessageThat().contains("Multiple entries with same key");
} }
@Test @Test

View file

@ -30,9 +30,7 @@ import com.googlecode.objectify.annotation.Id;
import google.registry.model.contact.ContactResource; import google.registry.model.contact.ContactResource;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -63,9 +61,6 @@ public class OfyFilterTest {
helper.tearDown(); helper.tearDown();
} }
@Rule
public final ExpectedException thrown = ExpectedException.none();
/** /**
* Key.create looks up kind metadata for the class of the object it is given. If this happens * Key.create looks up kind metadata for the class of the object it is given. If this happens
* before the first reference to ObjectifyService, which statically triggers type registrations, * before the first reference to ObjectifyService, which statically triggers type registrations,

View file

@ -23,6 +23,8 @@ import static google.registry.model.ofy.Ofy.getBaseEntityClassFromEntityOrKey;
import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.newContactResource; import static google.registry.testing.DatastoreHelper.newContactResource;
import static google.registry.testing.DatastoreHelper.persistActiveContact; import static google.registry.testing.DatastoreHelper.persistActiveContact;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.util.DateTimeUtils.END_OF_TIME; import static google.registry.util.DateTimeUtils.END_OF_TIME;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
@ -55,7 +57,6 @@ import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -67,10 +68,6 @@ public class OfyTest {
public final AppEngineRule appEngine = AppEngineRule.builder() public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore() .withDatastore()
.build(); .build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
/** An entity to use in save and delete tests. */ /** An entity to use in save and delete tests. */
private HistoryEntry someObject; private HistoryEntry someObject;
@ -92,13 +89,15 @@ public class OfyTest {
.getUpdateAutoTimestamp().getTimestamp(); .getUpdateAutoTimestamp().getTimestamp();
// Set the clock in Ofy to the same time as the backup group root's save time. // Set the clock in Ofy to the same time as the backup group root's save time.
Ofy ofy = new Ofy(new FakeClock(groupTimestamp)); Ofy ofy = new Ofy(new FakeClock(groupTimestamp));
thrown.expect(TimestampInversionException.class); TimestampInversionException thrown =
thrown.expectMessage(String.format( expectThrows(TimestampInversionException.class, () -> ofy.transact(work));
assertThat(thrown)
.hasMessageThat()
.contains(
String.format(
"Timestamp inversion between transaction time (%s) and entities rooted under:\n" "Timestamp inversion between transaction time (%s) and entities rooted under:\n"
+ "{Key<?>(ContactResource(\"2-ROID\"))=%s}", + "{Key<?>(ContactResource(\"2-ROID\"))=%s}",
groupTimestamp, groupTimestamp, groupTimestamp));
groupTimestamp));
ofy.transact(work);
} }
@Test @Test
@ -121,60 +120,89 @@ public class OfyTest {
@Test @Test
public void testSavingKeyTwice() { public void testSavingKeyTwice() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Multiple entries with same key"); expectThrows(
ofy().transact(new VoidWork() { IllegalArgumentException.class,
() ->
ofy()
.transact(
new VoidWork() {
@Override @Override
public void vrun() { public void vrun() {
ofy().save().entity(someObject); ofy().save().entity(someObject);
ofy().save().entity(someObject); ofy().save().entity(someObject);
}}); }
}));
assertThat(thrown).hasMessageThat().contains("Multiple entries with same key");
} }
@Test @Test
public void testDeletingKeyTwice() { public void testDeletingKeyTwice() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Multiple entries with same key"); expectThrows(
ofy().transact(new VoidWork() { IllegalArgumentException.class,
() ->
ofy()
.transact(
new VoidWork() {
@Override @Override
public void vrun() { public void vrun() {
ofy().delete().entity(someObject); ofy().delete().entity(someObject);
ofy().delete().entity(someObject); ofy().delete().entity(someObject);
}}); }
}));
assertThat(thrown).hasMessageThat().contains("Multiple entries with same key");
} }
@Test @Test
public void testSaveDeleteKey() { public void testSaveDeleteKey() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Multiple entries with same key"); expectThrows(
ofy().transact(new VoidWork() { IllegalArgumentException.class,
() ->
ofy()
.transact(
new VoidWork() {
@Override @Override
public void vrun() { public void vrun() {
ofy().save().entity(someObject); ofy().save().entity(someObject);
ofy().delete().entity(someObject); ofy().delete().entity(someObject);
}}); }
}));
assertThat(thrown).hasMessageThat().contains("Multiple entries with same key");
} }
@Test @Test
public void testDeleteSaveKey() { public void testDeleteSaveKey() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Multiple entries with same key"); expectThrows(
ofy().transact(new VoidWork() { IllegalArgumentException.class,
() ->
ofy()
.transact(
new VoidWork() {
@Override @Override
public void vrun() { public void vrun() {
ofy().delete().entity(someObject); ofy().delete().entity(someObject);
ofy().save().entity(someObject); ofy().save().entity(someObject);
}}); }
}));
assertThat(thrown).hasMessageThat().contains("Multiple entries with same key");
} }
@Test @Test
public void testSavingKeyTwiceInOneCall() { public void testSavingKeyTwiceInOneCall() {
thrown.expect(IllegalArgumentException.class); assertThrows(
ofy().transact(new VoidWork() { IllegalArgumentException.class,
() ->
ofy()
.transact(
new VoidWork() {
@Override @Override
public void vrun() { public void vrun() {
ofy().save().entities(someObject, someObject); ofy().save().entities(someObject, someObject);
}}); }
}));
} }
/** Simple entity class with lifecycle callbacks. */ /** Simple entity class with lifecycle callbacks. */
@ -375,17 +403,24 @@ public class OfyTest {
@Test @Test
public void test_getBaseEntityClassFromEntityOrKey_unregisteredEntity() { public void test_getBaseEntityClassFromEntityOrKey_unregisteredEntity() {
thrown.expect(IllegalStateException.class); IllegalStateException thrown =
thrown.expectMessage("SystemClock"); expectThrows(
getBaseEntityClassFromEntityOrKey(new SystemClock()); IllegalStateException.class,
() -> getBaseEntityClassFromEntityOrKey(new SystemClock()));
assertThat(thrown).hasMessageThat().contains("SystemClock");
} }
@Test @Test
public void test_getBaseEntityClassFromEntityOrKey_unregisteredEntityKey() { public void test_getBaseEntityClassFromEntityOrKey_unregisteredEntityKey() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("UnknownKind"); expectThrows(
getBaseEntityClassFromEntityOrKey(Key.create( IllegalArgumentException.class,
com.google.appengine.api.datastore.KeyFactory.createKey("UnknownKind", 1))); () ->
getBaseEntityClassFromEntityOrKey(
Key.create(
com.google.appengine.api.datastore.KeyFactory.createKey(
"UnknownKind", 1))));
assertThat(thrown).hasMessageThat().contains("UnknownKind");
} }
@Test @Test

View file

@ -38,7 +38,6 @@ import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -54,9 +53,6 @@ public class PollMessageExternalKeyConverterTest {
@Rule @Rule
public InjectRule inject = new InjectRule(); public InjectRule inject = new InjectRule();
@Rule
public final ExpectedException thrown = ExpectedException.none();
HistoryEntry historyEntry; HistoryEntry historyEntry;
FakeClock clock = new FakeClock(DateTime.parse("2007-07-07T01:01:01Z")); FakeClock clock = new FakeClock(DateTime.parse("2007-07-07T01:01:01Z"));

View file

@ -19,21 +19,16 @@ import static google.registry.model.rde.RdeMode.FULL;
import static google.registry.model.rde.RdeMode.THIN; import static google.registry.model.rde.RdeMode.THIN;
import static google.registry.model.rde.RdeNamingUtils.makePartialName; import static google.registry.model.rde.RdeNamingUtils.makePartialName;
import static google.registry.model.rde.RdeNamingUtils.makeRydeFilename; import static google.registry.model.rde.RdeNamingUtils.makeRydeFilename;
import static google.registry.testing.JUnitBackports.assertThrows;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
/** Unit tests for {@link RdeNamingUtils}. */ /** Unit tests for {@link RdeNamingUtils}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class RdeNamingUtilsTest { public class RdeNamingUtilsTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void testMakeRydeFilename_rdeDeposit() throws Exception { public void testMakeRydeFilename_rdeDeposit() throws Exception {
assertThat(makeRydeFilename("numbness", DateTime.parse("1984-12-18TZ"), FULL, 1, 0)) assertThat(makeRydeFilename("numbness", DateTime.parse("1984-12-18TZ"), FULL, 1, 0))
@ -54,8 +49,9 @@ public class RdeNamingUtilsTest {
@Test @Test
public void testMakeRydeFilename_timestampNotAtTheWitchingHour_throwsIae() throws Exception { public void testMakeRydeFilename_timestampNotAtTheWitchingHour_throwsIae() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
makeRydeFilename("wretched", DateTime.parse("2000-12-18T04:20Z"), THIN, 1, 0); IllegalArgumentException.class,
() -> makeRydeFilename("wretched", DateTime.parse("2000-12-18T04:20Z"), THIN, 1, 0));
} }
@Test @Test

View file

@ -19,6 +19,7 @@ import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.model.rde.RdeMode.FULL; import static google.registry.model.rde.RdeMode.FULL;
import static google.registry.model.rde.RdeRevision.getNextRevision; import static google.registry.model.rde.RdeRevision.getNextRevision;
import static google.registry.model.rde.RdeRevision.saveRevision; import static google.registry.model.rde.RdeRevision.saveRevision;
import static google.registry.testing.JUnitBackports.expectThrows;
import com.google.common.base.VerifyException; import com.google.common.base.VerifyException;
import com.googlecode.objectify.VoidWork; import com.googlecode.objectify.VoidWork;
@ -26,7 +27,6 @@ import google.registry.testing.AppEngineRule;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -36,10 +36,6 @@ public class RdeRevisionTest {
@Rule @Rule
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build(); public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void testGetNextRevision_objectDoesntExist_returnsZero() throws Exception { public void testGetNextRevision_objectDoesntExist_returnsZero() throws Exception {
assertThat(getNextRevision("torment", DateTime.parse("1984-12-18TZ"), FULL)) assertThat(getNextRevision("torment", DateTime.parse("1984-12-18TZ"), FULL))
@ -70,25 +66,37 @@ public class RdeRevisionTest {
@Test @Test
public void testSaveRevision_objectDoesntExist_newRevisionIsOne_throwsVe() throws Exception { public void testSaveRevision_objectDoesntExist_newRevisionIsOne_throwsVe() throws Exception {
thrown.expect(VerifyException.class); VerifyException thrown =
thrown.expectMessage("object missing"); expectThrows(
ofy().transact(new VoidWork() { VerifyException.class,
() ->
ofy()
.transact(
new VoidWork() {
@Override @Override
public void vrun() { public void vrun() {
saveRevision("despondency", DateTime.parse("1984-12-18TZ"), FULL, 1); saveRevision("despondency", DateTime.parse("1984-12-18TZ"), FULL, 1);
}}); }
}));
assertThat(thrown).hasMessageThat().contains("object missing");
} }
@Test @Test
public void testSaveRevision_objectExistsAtZero_newRevisionIsZero_throwsVe() throws Exception { public void testSaveRevision_objectExistsAtZero_newRevisionIsZero_throwsVe() throws Exception {
save("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0); save("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0);
thrown.expect(VerifyException.class); VerifyException thrown =
thrown.expectMessage("object already created"); expectThrows(
ofy().transact(new VoidWork() { VerifyException.class,
() ->
ofy()
.transact(
new VoidWork() {
@Override @Override
public void vrun() { public void vrun() {
saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0); saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0);
}}); }
}));
assertThat(thrown).hasMessageThat().contains("object already created");
} }
@Test @Test
@ -110,31 +118,45 @@ public class RdeRevisionTest {
@Test @Test
public void testSaveRevision_objectExistsAtZero_newRevisionIsTwo_throwsVe() throws Exception { public void testSaveRevision_objectExistsAtZero_newRevisionIsTwo_throwsVe() throws Exception {
save("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0); save("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0);
thrown.expect(VerifyException.class); VerifyException thrown =
thrown.expectMessage("should be at 1 "); expectThrows(
ofy().transact(new VoidWork() { VerifyException.class,
() ->
ofy()
.transact(
new VoidWork() {
@Override @Override
public void vrun() { public void vrun() {
saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 2); saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 2);
}}); }
}));
assertThat(thrown).hasMessageThat().contains("should be at 1 ");
} }
@Test @Test
public void testSaveRevision_negativeRevision_throwsIae() throws Exception { public void testSaveRevision_negativeRevision_throwsIae() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Negative revision"); expectThrows(
ofy().transact(new VoidWork() { IllegalArgumentException.class,
() ->
ofy()
.transact(
new VoidWork() {
@Override @Override
public void vrun() { public void vrun() {
saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, -1); saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, -1);
}}); }
}));
assertThat(thrown).hasMessageThat().contains("Negative revision");
} }
@Test @Test
public void testSaveRevision_callerNotInTransaction_throwsIse() throws Exception { public void testSaveRevision_callerNotInTransaction_throwsIse() throws Exception {
thrown.expect(IllegalStateException.class); IllegalStateException thrown =
thrown.expectMessage("transaction"); expectThrows(
saveRevision("frenzy", DateTime.parse("1984-12-18TZ"), FULL, 1); IllegalStateException.class,
() -> saveRevision("frenzy", DateTime.parse("1984-12-18TZ"), FULL, 1));
assertThat(thrown).hasMessageThat().contains("transaction");
} }
public static void save(String tld, DateTime date, RdeMode mode, int revision) { public static void save(String tld, DateTime date, RdeMode mode, int revision) {

View file

@ -26,6 +26,8 @@ import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.DatastoreHelper.persistSimpleResource; import static google.registry.testing.DatastoreHelper.persistSimpleResource;
import static google.registry.testing.DatastoreHelper.persistSimpleResources; import static google.registry.testing.DatastoreHelper.persistSimpleResources;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -40,16 +42,10 @@ import google.registry.model.registrar.Registrar.Type;
import google.registry.util.CidrAddressBlock; import google.registry.util.CidrAddressBlock;
import org.joda.money.CurrencyUnit; import org.joda.money.CurrencyUnit;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
/** Unit tests for {@link Registrar}. */ /** Unit tests for {@link Registrar}. */
public class RegistrarTest extends EntityTestCase { public class RegistrarTest extends EntityTestCase {
@Rule
public ExpectedException thrown = ExpectedException.none();
private Registrar registrar; private Registrar registrar;
private RegistrarContact abuseAdminContact; private RegistrarContact abuseAdminContact;
@ -143,23 +139,27 @@ public class RegistrarTest extends EntityTestCase {
@Test @Test
public void testFailure_passwordNull() throws Exception { public void testFailure_passwordNull() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Password must be 6-16 characters long."); expectThrows(
new Registrar.Builder().setPassword(null); IllegalArgumentException.class, () -> new Registrar.Builder().setPassword(null));
assertThat(thrown).hasMessageThat().contains("Password must be 6-16 characters long.");
} }
@Test @Test
public void testFailure_passwordTooShort() throws Exception { public void testFailure_passwordTooShort() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Password must be 6-16 characters long."); expectThrows(
new Registrar.Builder().setPassword("abcde"); IllegalArgumentException.class, () -> new Registrar.Builder().setPassword("abcde"));
assertThat(thrown).hasMessageThat().contains("Password must be 6-16 characters long.");
} }
@Test @Test
public void testFailure_passwordTooLong() throws Exception { public void testFailure_passwordTooLong() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Password must be 6-16 characters long."); expectThrows(
new Registrar.Builder().setPassword("abcdefghijklmnopq"); IllegalArgumentException.class,
() -> new Registrar.Builder().setPassword("abcdefghijklmnopq"));
assertThat(thrown).hasMessageThat().contains("Password must be 6-16 characters long.");
} }
@Test @Test
@ -172,14 +172,14 @@ public class RegistrarTest extends EntityTestCase {
@Test @Test
public void testFailure_clientId_tooShort() throws Exception { public void testFailure_clientId_tooShort() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> new Registrar.Builder().setClientId("ab"));
new Registrar.Builder().setClientId("ab");
} }
@Test @Test
public void testFailure_clientId_tooLong() throws Exception { public void testFailure_clientId_tooLong() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
new Registrar.Builder().setClientId("abcdefghijklmnopq"); IllegalArgumentException.class,
() -> new Registrar.Builder().setClientId("abcdefghijklmnopq"));
} }
@Test @Test
@ -318,87 +318,103 @@ public class RegistrarTest extends EntityTestCase {
@Test @Test
public void testFailure_missingRegistrarType() throws Exception { public void testFailure_missingRegistrarType() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Registrar type cannot be null"); expectThrows(
new Registrar.Builder().setRegistrarName("blah").build(); IllegalArgumentException.class,
() -> new Registrar.Builder().setRegistrarName("blah").build());
assertThat(thrown).hasMessageThat().contains("Registrar type cannot be null");
} }
@Test @Test
public void testFailure_missingRegistrarName() throws Exception { public void testFailure_missingRegistrarName() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Registrar name cannot be null"); expectThrows(
new Registrar.Builder().setClientId("blahid").setType(Registrar.Type.TEST).build(); IllegalArgumentException.class,
() ->
new Registrar.Builder().setClientId("blahid").setType(Registrar.Type.TEST).build());
assertThat(thrown).hasMessageThat().contains("Registrar name cannot be null");
} }
@Test @Test
public void testFailure_missingAddress() throws Exception { public void testFailure_missingAddress() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Must specify at least one of localized or internationalized address"); expectThrows(
IllegalArgumentException.class,
() ->
new Registrar.Builder() new Registrar.Builder()
.setClientId("blahid") .setClientId("blahid")
.setType(Registrar.Type.TEST) .setType(Registrar.Type.TEST)
.setRegistrarName("Blah Co") .setRegistrarName("Blah Co")
.build(); .build());
assertThat(thrown)
.hasMessageThat()
.contains("Must specify at least one of localized or internationalized address");
} }
@Test @Test
public void testFailure_badIanaIdForInternal() throws Exception { public void testFailure_badIanaIdForInternal() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
new Registrar.Builder().setType(Type.INTERNAL).setIanaIdentifier(8L).build(); IllegalArgumentException.class,
() -> new Registrar.Builder().setType(Type.INTERNAL).setIanaIdentifier(8L).build());
} }
@Test @Test
public void testFailure_badIanaIdForPdt() throws Exception { public void testFailure_badIanaIdForPdt() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
new Registrar.Builder().setType(Type.PDT).setIanaIdentifier(8L).build(); IllegalArgumentException.class,
() -> new Registrar.Builder().setType(Type.PDT).setIanaIdentifier(8L).build());
} }
@Test @Test
public void testFailure_badIanaIdForExternalMonitoring() throws Exception { public void testFailure_badIanaIdForExternalMonitoring() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
registrar.asBuilder().setType(Type.EXTERNAL_MONITORING).setIanaIdentifier(8L).build(); IllegalArgumentException.class,
() ->
registrar.asBuilder().setType(Type.EXTERNAL_MONITORING).setIanaIdentifier(8L).build());
} }
@Test @Test
public void testFailure_missingIanaIdForReal() throws Exception { public void testFailure_missingIanaIdForReal() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
new Registrar.Builder().setType(Type.REAL).build(); IllegalArgumentException.class, () -> new Registrar.Builder().setType(Type.REAL).build());
} }
@Test @Test
public void testFailure_missingIanaIdForInternal() throws Exception { public void testFailure_missingIanaIdForInternal() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
new Registrar.Builder().setType(Type.INTERNAL).build(); IllegalArgumentException.class,
() -> new Registrar.Builder().setType(Type.INTERNAL).build());
} }
@Test @Test
public void testFailure_missingIanaIdForPdt() throws Exception { public void testFailure_missingIanaIdForPdt() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
new Registrar.Builder().setType(Type.PDT).build(); IllegalArgumentException.class, () -> new Registrar.Builder().setType(Type.PDT).build());
} }
@Test @Test
public void testFailure_missingIanaIdForExternalMonitoring() throws Exception { public void testFailure_missingIanaIdForExternalMonitoring() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
new Registrar.Builder().setType(Type.EXTERNAL_MONITORING).build(); IllegalArgumentException.class,
() -> new Registrar.Builder().setType(Type.EXTERNAL_MONITORING).build());
} }
@Test @Test
public void testFailure_phonePasscodeTooShort() throws Exception { public void testFailure_phonePasscodeTooShort() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
new Registrar.Builder().setPhonePasscode("0123"); IllegalArgumentException.class, () -> new Registrar.Builder().setPhonePasscode("0123"));
} }
@Test @Test
public void testFailure_phonePasscodeTooLong() throws Exception { public void testFailure_phonePasscodeTooLong() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
new Registrar.Builder().setPhonePasscode("012345"); IllegalArgumentException.class, () -> new Registrar.Builder().setPhonePasscode("012345"));
} }
@Test @Test
public void testFailure_phonePasscodeInvalidCharacters() throws Exception { public void testFailure_phonePasscodeInvalidCharacters() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
new Registrar.Builder().setPhonePasscode("code1"); IllegalArgumentException.class, () -> new Registrar.Builder().setPhonePasscode("code1"));
} }
@Test @Test
@ -420,29 +436,29 @@ public class RegistrarTest extends EntityTestCase {
@Test @Test
public void testFailure_loadByClientId_clientIdIsNull() throws Exception { public void testFailure_loadByClientId_clientIdIsNull() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("clientId must be specified"); expectThrows(IllegalArgumentException.class, () -> Registrar.loadByClientId(null));
Registrar.loadByClientId(null); assertThat(thrown).hasMessageThat().contains("clientId must be specified");
} }
@Test @Test
public void testFailure_loadByClientId_clientIdIsEmpty() throws Exception { public void testFailure_loadByClientId_clientIdIsEmpty() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("clientId must be specified"); expectThrows(IllegalArgumentException.class, () -> Registrar.loadByClientId(""));
Registrar.loadByClientId(""); assertThat(thrown).hasMessageThat().contains("clientId must be specified");
} }
@Test @Test
public void testFailure_loadByClientIdCached_clientIdIsNull() throws Exception { public void testFailure_loadByClientIdCached_clientIdIsNull() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("clientId must be specified"); expectThrows(IllegalArgumentException.class, () -> Registrar.loadByClientIdCached(null));
Registrar.loadByClientIdCached(null); assertThat(thrown).hasMessageThat().contains("clientId must be specified");
} }
@Test @Test
public void testFailure_loadByClientIdCached_clientIdIsEmpty() throws Exception { public void testFailure_loadByClientIdCached_clientIdIsEmpty() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("clientId must be specified"); expectThrows(IllegalArgumentException.class, () -> Registrar.loadByClientIdCached(""));
Registrar.loadByClientIdCached(""); assertThat(thrown).hasMessageThat().contains("clientId must be specified");
} }
} }

View file

@ -17,12 +17,12 @@ package google.registry.model.registry;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat; import static com.google.common.truth.Truth8.assertThat;
import static google.registry.testing.DatastoreHelper.createTlds; import static google.registry.testing.DatastoreHelper.createTlds;
import static google.registry.testing.JUnitBackports.assertThrows;
import com.google.common.net.InternetDomainName; import com.google.common.net.InternetDomainName;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -32,10 +32,6 @@ public class RegistriesTest {
@Rule @Rule
public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build(); public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build();
@Rule
public ExpectedException thrown = ExpectedException.none();
private void initTestTlds() { private void initTestTlds() {
createTlds("foo", "a.b.c"); // Test a multipart tld. createTlds("foo", "a.b.c"); // Test a multipart tld.
} }
@ -61,8 +57,7 @@ public class RegistriesTest {
@Test @Test
public void testAssertTldExists_doesntExist() { public void testAssertTldExists_doesntExist() {
initTestTlds(); initTestTlds();
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> Registries.assertTldExists("baz"));
Registries.assertTldExists("baz");
} }
@Test @Test

View file

@ -44,15 +44,10 @@ import java.math.BigDecimal;
import org.joda.money.Money; import org.joda.money.Money;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
/** Unit tests for {@link Registry}. */ /** Unit tests for {@link Registry}. */
public class RegistryTest extends EntityTestCase { public class RegistryTest extends EntityTestCase {
@Rule public final ExpectedException thrown = ExpectedException.none();
Registry registry; Registry registry;
@Before @Before
@ -71,8 +66,7 @@ public class RegistryTest extends EntityTestCase {
@Test @Test
public void testFailure_registryNotFound() throws Exception { public void testFailure_registryNotFound() throws Exception {
createTld("foo"); createTld("foo");
thrown.expect(RegistryNotFoundException.class); assertThrows(RegistryNotFoundException.class, () -> Registry.get("baz"));
Registry.get("baz");
} }
@Test @Test
@ -202,11 +196,17 @@ public class RegistryTest extends EntityTestCase {
ReservedList rl3 = persistReservedList( ReservedList rl3 = persistReservedList(
"tld-reserved057", "tld-reserved057",
"lol,RESERVED_FOR_ANCHOR_TENANT,another_conflict"); "lol,RESERVED_FOR_ANCHOR_TENANT,another_conflict");
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage( expectThrows(
"auth code conflicts for labels: [lol=[conflict1, conflict2, another_conflict]]"); IllegalArgumentException.class,
() -> {
@SuppressWarnings("unused") @SuppressWarnings("unused")
Registry unused = Registry.get("tld").asBuilder().setReservedLists(rl1, rl2, rl3).build(); Registry unused =
Registry.get("tld").asBuilder().setReservedLists(rl1, rl2, rl3).build();
});
assertThat(thrown)
.hasMessageThat()
.contains("auth code conflicts for labels: [lol=[conflict1, conflict2, another_conflict]]");
} }
@Test @Test
@ -354,116 +354,167 @@ public class RegistryTest extends EntityTestCase {
@Test @Test
public void testFailure_tldNeverSet() { public void testFailure_tldNeverSet() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("No registry TLD specified"); expectThrows(IllegalArgumentException.class, () -> new Registry.Builder().build());
new Registry.Builder().build(); assertThat(thrown).hasMessageThat().contains("No registry TLD specified");
} }
@Test @Test
public void testFailure_setTldStr_null() { public void testFailure_setTldStr_null() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("TLD must not be null"); expectThrows(IllegalArgumentException.class, () -> new Registry.Builder().setTldStr(null));
new Registry.Builder().setTldStr(null); assertThat(thrown).hasMessageThat().contains("TLD must not be null");
} }
@Test @Test
public void testFailure_setTldStr_invalidTld() { public void testFailure_setTldStr_invalidTld() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown expectThrows(
.expectMessage("Cannot create registry for TLD that is not a valid, canonical domain name"); IllegalArgumentException.class, () -> new Registry.Builder().setTldStr(".tld").build());
new Registry.Builder().setTldStr(".tld").build(); assertThat(thrown)
.hasMessageThat()
.contains("Cannot create registry for TLD that is not a valid, canonical domain name");
} }
@Test @Test
public void testFailure_setTldStr_nonCanonicalTld() { public void testFailure_setTldStr_nonCanonicalTld() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown expectThrows(
.expectMessage("Cannot create registry for TLD that is not a valid, canonical domain name"); IllegalArgumentException.class, () -> new Registry.Builder().setTldStr("TLD").build());
new Registry.Builder().setTldStr("TLD").build(); assertThat(thrown)
.hasMessageThat()
.contains("Cannot create registry for TLD that is not a valid, canonical domain name");
} }
@Test @Test
public void testFailure_tldStatesOutOfOrder() { public void testFailure_tldStatesOutOfOrder() {
thrown.expect(IllegalArgumentException.class); assertThrows(
Registry.get("tld").asBuilder() IllegalArgumentException.class,
.setTldStateTransitions(ImmutableSortedMap.of( () ->
clock.nowUtc(), TldState.SUNRUSH, clock.nowUtc().plusMonths(1), TldState.SUNRISE)) Registry.get("tld")
.build(); .asBuilder()
.setTldStateTransitions(
ImmutableSortedMap.of(
clock.nowUtc(),
TldState.SUNRUSH,
clock.nowUtc().plusMonths(1),
TldState.SUNRISE))
.build());
} }
@Test @Test
public void testFailure_duplicateTldState() { public void testFailure_duplicateTldState() {
thrown.expect(IllegalArgumentException.class); assertThrows(
Registry.get("tld").asBuilder() IllegalArgumentException.class,
.setTldStateTransitions(ImmutableSortedMap.of( () ->
clock.nowUtc(), TldState.SUNRUSH, clock.nowUtc().plusMonths(1), TldState.SUNRUSH)) Registry.get("tld")
.build(); .asBuilder()
.setTldStateTransitions(
ImmutableSortedMap.of(
clock.nowUtc(),
TldState.SUNRUSH,
clock.nowUtc().plusMonths(1),
TldState.SUNRUSH))
.build());
} }
@Test @Test
public void testFailure_pricingEngineIsRequired() { public void testFailure_pricingEngineIsRequired() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("All registries must have a configured pricing engine"); expectThrows(
new Registry.Builder().setTldStr("invalid").build(); IllegalArgumentException.class,
() -> new Registry.Builder().setTldStr("invalid").build());
assertThat(thrown)
.hasMessageThat()
.contains("All registries must have a configured pricing engine");
} }
@Test @Test
public void testFailure_negativeRenewBillingCostTransitionValue() { public void testFailure_negativeRenewBillingCostTransitionValue() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("billing cost cannot be negative"); expectThrows(
Registry.get("tld").asBuilder() IllegalArgumentException.class,
.setRenewBillingCostTransitions(ImmutableSortedMap.of(START_OF_TIME, Money.of(USD, -42))); () ->
Registry.get("tld")
.asBuilder()
.setRenewBillingCostTransitions(
ImmutableSortedMap.of(START_OF_TIME, Money.of(USD, -42))));
assertThat(thrown).hasMessageThat().contains("billing cost cannot be negative");
} }
@Test @Test
public void testFailure_negativeCreateBillingCost() { public void testFailure_negativeCreateBillingCost() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("createBillingCost cannot be negative"); expectThrows(
Registry.get("tld").asBuilder().setCreateBillingCost(Money.of(USD, -42)); IllegalArgumentException.class,
() -> Registry.get("tld").asBuilder().setCreateBillingCost(Money.of(USD, -42)));
assertThat(thrown).hasMessageThat().contains("createBillingCost cannot be negative");
} }
@Test @Test
public void testFailure_negativeRestoreBillingCost() { public void testFailure_negativeRestoreBillingCost() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("restoreBillingCost cannot be negative"); expectThrows(
Registry.get("tld").asBuilder().setRestoreBillingCost(Money.of(USD, -42)); IllegalArgumentException.class,
() -> Registry.get("tld").asBuilder().setRestoreBillingCost(Money.of(USD, -42)));
assertThat(thrown).hasMessageThat().contains("restoreBillingCost cannot be negative");
} }
@Test @Test
public void testFailure_negativeServerStatusChangeBillingCost() { public void testFailure_negativeServerStatusChangeBillingCost() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("billing cost cannot be negative"); expectThrows(
Registry.get("tld").asBuilder().setServerStatusChangeBillingCost(Money.of(USD, -42)); IllegalArgumentException.class,
() ->
Registry.get("tld")
.asBuilder()
.setServerStatusChangeBillingCost(Money.of(USD, -42)));
assertThat(thrown).hasMessageThat().contains("billing cost cannot be negative");
} }
@Test @Test
public void testFailure_renewBillingCostTransitionValue_wrongCurrency() { public void testFailure_renewBillingCostTransitionValue_wrongCurrency() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("cost must be in the registry's currency"); expectThrows(
Registry.get("tld").asBuilder() IllegalArgumentException.class,
.setRenewBillingCostTransitions(ImmutableSortedMap.of(START_OF_TIME, Money.of(EUR, 42))) () ->
.build(); Registry.get("tld")
.asBuilder()
.setRenewBillingCostTransitions(
ImmutableSortedMap.of(START_OF_TIME, Money.of(EUR, 42)))
.build());
assertThat(thrown).hasMessageThat().contains("cost must be in the registry's currency");
} }
@Test @Test
public void testFailure_createBillingCost_wrongCurrency() { public void testFailure_createBillingCost_wrongCurrency() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("cost must be in the registry's currency"); expectThrows(
Registry.get("tld").asBuilder().setCreateBillingCost(Money.of(EUR, 42)).build(); IllegalArgumentException.class,
() -> Registry.get("tld").asBuilder().setCreateBillingCost(Money.of(EUR, 42)).build());
assertThat(thrown).hasMessageThat().contains("cost must be in the registry's currency");
} }
@Test @Test
public void testFailure_restoreBillingCost_wrongCurrency() { public void testFailure_restoreBillingCost_wrongCurrency() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("cost must be in the registry's currency"); expectThrows(
Registry.get("tld").asBuilder().setRestoreBillingCost(Money.of(EUR, 42)).build(); IllegalArgumentException.class,
() -> Registry.get("tld").asBuilder().setRestoreBillingCost(Money.of(EUR, 42)).build());
assertThat(thrown).hasMessageThat().contains("cost must be in the registry's currency");
} }
@Test @Test
public void testFailure_serverStatusChangeBillingCost_wrongCurrency() { public void testFailure_serverStatusChangeBillingCost_wrongCurrency() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("cost must be in the registry's currency"); expectThrows(
Registry.get("tld").asBuilder().setServerStatusChangeBillingCost(Money.of(EUR, 42)).build(); IllegalArgumentException.class,
() ->
Registry.get("tld")
.asBuilder()
.setServerStatusChangeBillingCost(Money.of(EUR, 42))
.build());
assertThat(thrown).hasMessageThat().contains("cost must be in the registry's currency");
} }
@Test @Test
@ -493,11 +544,15 @@ public class RegistryTest extends EntityTestCase {
@Test @Test
public void testFailure_eapFee_wrongCurrency() { public void testFailure_eapFee_wrongCurrency() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("All EAP fees must be in the registry's currency"); expectThrows(
Registry.get("tld").asBuilder() IllegalArgumentException.class,
() ->
Registry.get("tld")
.asBuilder()
.setEapFeeSchedule(ImmutableSortedMap.of(START_OF_TIME, Money.zero(EUR))) .setEapFeeSchedule(ImmutableSortedMap.of(START_OF_TIME, Money.zero(EUR)))
.build(); .build());
assertThat(thrown).hasMessageThat().contains("All EAP fees must be in the registry's currency");
} }
@Test @Test

View file

@ -21,6 +21,8 @@ import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistPremiumList; import static google.registry.testing.DatastoreHelper.persistPremiumList;
import static google.registry.testing.DatastoreHelper.persistReservedList; import static google.registry.testing.DatastoreHelper.persistReservedList;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import google.registry.model.registry.Registry; import google.registry.model.registry.Registry;
@ -29,7 +31,6 @@ import google.registry.testing.AppEngineRule;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -37,7 +38,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class PremiumListTest { public class PremiumListTest {
@Rule public final ExpectedException thrown = ExpectedException.none();
@Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build(); @Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build();
@Before @Before
@ -56,14 +56,15 @@ public class PremiumListTest {
@Test @Test
public void testSave_badSyntax() throws Exception { public void testSave_badSyntax() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
persistPremiumList("gtld1", "lol,nonsense USD,e,e # yup"); IllegalArgumentException.class,
() -> persistPremiumList("gtld1", "lol,nonsense USD,e,e # yup"));
} }
@Test @Test
public void testSave_invalidCurrencySymbol() throws Exception { public void testSave_invalidCurrencySymbol() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
persistReservedList("gtld1", "lol,XBTC 200"); IllegalArgumentException.class, () -> persistReservedList("gtld1", "lol,XBTC 200"));
} }
@Test @Test
@ -80,13 +81,22 @@ public class PremiumListTest {
@Test @Test
public void testParse_cannotIncludeDuplicateLabels() { public void testParse_cannotIncludeDuplicateLabels() {
thrown.expect(IllegalStateException.class); IllegalStateException thrown =
thrown.expectMessage( expectThrows(
"List 'tld' cannot contain duplicate labels. Dupes (with counts) were: [lol x 2]"); IllegalStateException.class,
() ->
PremiumList.get("tld") PremiumList.get("tld")
.get() .get()
.parse( .parse(
ImmutableList.of( ImmutableList.of(
"lol,USD 100", "rofl,USD 90", "paper,USD 80", "wood,USD 70", "lol,USD 200")); "lol,USD 100",
"rofl,USD 90",
"paper,USD 80",
"wood,USD 70",
"lol,USD 200")));
assertThat(thrown)
.hasMessageThat()
.contains(
"List 'tld' cannot contain duplicate labels. Dupes (with counts) were: [lol x 2]");
} }
} }

View file

@ -34,6 +34,7 @@ import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.loadPremiumListEntries; import static google.registry.testing.DatastoreHelper.loadPremiumListEntries;
import static google.registry.testing.DatastoreHelper.persistPremiumList; import static google.registry.testing.DatastoreHelper.persistPremiumList;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.expectThrows;
import static org.joda.time.Duration.standardMinutes; import static org.joda.time.Duration.standardMinutes;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
@ -52,7 +53,6 @@ import org.joda.money.Money;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -60,7 +60,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class PremiumListUtilsTest { public class PremiumListUtilsTest {
@Rule public final ExpectedException thrown = ExpectedException.none();
@Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build(); @Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build();
@Before @Before
@ -112,9 +111,10 @@ public class PremiumListUtilsTest {
public void testGetPremiumPrice_throwsExceptionWhenNonExistentPremiumListConfigured() public void testGetPremiumPrice_throwsExceptionWhenNonExistentPremiumListConfigured()
throws Exception { throws Exception {
deletePremiumList(PremiumList.get("tld").get()); deletePremiumList(PremiumList.get("tld").get());
thrown.expect(IllegalStateException.class); IllegalStateException thrown =
thrown.expectMessage("Could not load premium list 'tld'"); expectThrows(
getPremiumPrice("blah", Registry.get("tld")); IllegalStateException.class, () -> getPremiumPrice("blah", Registry.get("tld")));
assertThat(thrown).hasMessageThat().contains("Could not load premium list 'tld'");
} }
@Test @Test

View file

@ -33,6 +33,8 @@ import static google.registry.monitoring.metrics.contrib.LongMetricSubject.asser
import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistReservedList; import static google.registry.testing.DatastoreHelper.persistReservedList;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
@ -49,7 +51,6 @@ import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -60,9 +61,6 @@ public class ReservedListTest {
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final AppEngineRule appEngine = AppEngineRule.builder() public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore() .withDatastore()
@ -269,9 +267,13 @@ public class ReservedListTest {
assertThat(matchesAnchorTenantReservation(InternetDomainName.from("lol.tld"), "foo")).isTrue(); assertThat(matchesAnchorTenantReservation(InternetDomainName.from("lol.tld"), "foo")).isTrue();
assertThat(matchesAnchorTenantReservation(InternetDomainName.from("lol.tld"), "bar")).isFalse(); assertThat(matchesAnchorTenantReservation(InternetDomainName.from("lol.tld"), "bar")).isFalse();
persistReservedList("reserved2", "lol,RESERVED_FOR_ANCHOR_TENANT,bar"); persistReservedList("reserved2", "lol,RESERVED_FOR_ANCHOR_TENANT,bar");
thrown.expect(IllegalStateException.class); IllegalStateException thrown =
thrown.expectMessage("There are conflicting auth codes for domain: lol.tld"); expectThrows(
matchesAnchorTenantReservation(InternetDomainName.from("lol.tld"), "bar"); IllegalStateException.class,
() -> matchesAnchorTenantReservation(InternetDomainName.from("lol.tld"), "bar"));
assertThat(thrown)
.hasMessageThat()
.contains("There are conflicting auth codes for domain: lol.tld");
} }
@Test @Test
@ -468,88 +470,120 @@ public class ReservedListTest {
@Test @Test
public void testSave_badSyntax() throws Exception { public void testSave_badSyntax() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Could not parse line in reserved list"); expectThrows(
persistReservedList("tld", "lol,FULLY_BLOCKED,e,e # yup"); IllegalArgumentException.class,
() -> persistReservedList("tld", "lol,FULLY_BLOCKED,e,e # yup"));
assertThat(thrown).hasMessageThat().contains("Could not parse line in reserved list");
} }
@Test @Test
public void testSave_badReservationType() throws Exception { public void testSave_badReservationType() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
persistReservedList("tld", "lol,FULLY_BLOCKZ # yup"); IllegalArgumentException.class, () -> persistReservedList("tld", "lol,FULLY_BLOCKZ # yup"));
} }
@Test @Test
public void testSave_additionalRestrictionWithIncompatibleReservationType() throws Exception { public void testSave_additionalRestrictionWithIncompatibleReservationType() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Only anchor tenant and nameserver restricted reservations " expectThrows(
+ "should have restrictions imposed"); IllegalArgumentException.class,
() ->
persistResource( persistResource(
Registry.get("tld") Registry.get("tld")
.asBuilder() .asBuilder()
.setReservedLists( .setReservedLists(
ImmutableSet.of(persistReservedList("reserved1", "lol,FULLY_BLOCKED,foobar1"))) ImmutableSet.of(
.build()); persistReservedList("reserved1", "lol,FULLY_BLOCKED,foobar1")))
.build()));
assertThat(thrown)
.hasMessageThat()
.contains(
"Only anchor tenant and nameserver restricted reservations "
+ "should have restrictions imposed");
} }
@Test @Test
public void testSave_badNameservers_invalidSyntax() throws Exception { public void testSave_badNameservers_invalidSyntax() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Not a valid domain name: 'ns@.domain.tld'"); expectThrows(
IllegalArgumentException.class,
() ->
persistReservedList( persistReservedList(
"reserved1", "reserved1",
"lol,NAMESERVER_RESTRICTED,ns1.domain.tld:ns2.domain.tld", "lol,NAMESERVER_RESTRICTED,ns1.domain.tld:ns2.domain.tld",
"lol1,NAMESERVER_RESTRICTED,ns1.domain.tld:ns@.domain.tld"); "lol1,NAMESERVER_RESTRICTED,ns1.domain.tld:ns@.domain.tld"));
assertThat(thrown).hasMessageThat().contains("Not a valid domain name: 'ns@.domain.tld'");
} }
@Test @Test
public void testSave_badNameservers_tooFewPartsForHostname() throws Exception { public void testSave_badNameservers_tooFewPartsForHostname() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("domain.tld is not a valid nameserver hostname"); expectThrows(
IllegalArgumentException.class,
() ->
persistReservedList( persistReservedList(
"reserved1", "reserved1",
"lol,NAMESERVER_RESTRICTED,ns1.domain.tld:ns2.domain.tld", "lol,NAMESERVER_RESTRICTED,ns1.domain.tld:ns2.domain.tld",
"lol1,NAMESERVER_RESTRICTED,ns1.domain.tld:domain.tld"); "lol1,NAMESERVER_RESTRICTED,ns1.domain.tld:domain.tld"));
assertThat(thrown).hasMessageThat().contains("domain.tld is not a valid nameserver hostname");
} }
@Test @Test
public void testSave_noPasswordWithAnchorTenantReservation() throws Exception { public void testSave_noPasswordWithAnchorTenantReservation() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Anchor tenant reservations must have an auth code configured"); expectThrows(
IllegalArgumentException.class,
() ->
persistResource( persistResource(
Registry.get("tld") Registry.get("tld")
.asBuilder() .asBuilder()
.setReservedLists( .setReservedLists(
ImmutableSet.of(persistReservedList("reserved1", "lol,RESERVED_FOR_ANCHOR_TENANT"))) ImmutableSet.of(
.build()); persistReservedList("reserved1", "lol,RESERVED_FOR_ANCHOR_TENANT")))
.build()));
assertThat(thrown)
.hasMessageThat()
.contains("Anchor tenant reservations must have an auth code configured");
} }
@Test @Test
public void testSave_noNameserversWithNameserverRestrictedReservation() throws Exception { public void testSave_noNameserversWithNameserverRestrictedReservation() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage( expectThrows(
"Nameserver restricted reservations must have at least one nameserver configured"); IllegalArgumentException.class,
() ->
persistResource( persistResource(
Registry.get("tld") Registry.get("tld")
.asBuilder() .asBuilder()
.setReservedLists( .setReservedLists(
ImmutableSet.of(persistReservedList("reserved1", "lol,NAMESERVER_RESTRICTED"))) ImmutableSet.of(
.build()); persistReservedList("reserved1", "lol,NAMESERVER_RESTRICTED")))
.build()));
assertThat(thrown)
.hasMessageThat()
.contains(
"Nameserver restricted reservations must have at least one nameserver configured");
} }
@Test @Test
public void testParse_cannotIncludeDuplicateLabels() { public void testParse_cannotIncludeDuplicateLabels() {
ReservedList rl = new ReservedList.Builder().setName("blah").build(); ReservedList rl = new ReservedList.Builder().setName("blah").build();
thrown.expect(IllegalStateException.class); IllegalStateException thrown =
thrown.expectMessage( expectThrows(
"List 'blah' cannot contain duplicate labels. Dupes (with counts) were: [lol x 2]"); IllegalStateException.class,
() ->
rl.parse( rl.parse(
ImmutableList.of( ImmutableList.of(
"lol,FULLY_BLOCKED", "lol,FULLY_BLOCKED",
"rofl,FULLY_BLOCKED", "rofl,FULLY_BLOCKED",
"paper,FULLY_BLOCKED", "paper,FULLY_BLOCKED",
"wood,FULLY_BLOCKED", "wood,FULLY_BLOCKED",
"lol,FULLY_BLOCKED")); "lol,FULLY_BLOCKED")));
assertThat(thrown)
.hasMessageThat()
.contains(
"List 'blah' cannot contain duplicate labels. Dupes (with counts) were: [lol x 2]");
} }
/** Gets the name of a reserved list. */ /** Gets the name of a reserved list. */

View file

@ -17,13 +17,13 @@ package google.registry.model.server;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.expectThrows;
import com.google.common.base.Strings; import com.google.common.base.Strings;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -31,9 +31,6 @@ import org.junit.runners.JUnit4;
public class KmsSecretRevisionTest { public class KmsSecretRevisionTest {
@Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build(); @Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build();
@Rule public final ExpectedException thrown = ExpectedException.none();
private KmsSecretRevision secretRevision; private KmsSecretRevision secretRevision;
@Before @Before
@ -49,15 +46,18 @@ public class KmsSecretRevisionTest {
@Test @Test
public void test_setEncryptedValue_tooLong_throwsException() { public void test_setEncryptedValue_tooLong_throwsException() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Secret is greater than 67108864 bytes"); expectThrows(
IllegalArgumentException.class,
() ->
secretRevision = secretRevision =
persistResource( persistResource(
new KmsSecretRevision.Builder() new KmsSecretRevision.Builder()
.setKmsCryptoKeyVersionName("foo") .setKmsCryptoKeyVersionName("foo")
.setParent("bar") .setParent("bar")
.setEncryptedValue(Strings.repeat("a", 64 * 1024 * 1024 + 1)) .setEncryptedValue(Strings.repeat("a", 64 * 1024 * 1024 + 1))
.build()); .build()));
assertThat(thrown).hasMessageThat().contains("Secret is greater than 67108864 bytes");
} }
@Test @Test

View file

@ -14,11 +14,13 @@
package google.registry.model.server; package google.registry.model.server;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat; import static com.google.common.truth.Truth8.assertThat;
import static google.registry.model.server.Lock.LockState.FREE; import static google.registry.model.server.Lock.LockState.FREE;
import static google.registry.model.server.Lock.LockState.IN_USE; import static google.registry.model.server.Lock.LockState.IN_USE;
import static google.registry.model.server.Lock.LockState.OWNER_DIED; import static google.registry.model.server.Lock.LockState.OWNER_DIED;
import static google.registry.model.server.Lock.LockState.TIMED_OUT; import static google.registry.model.server.Lock.LockState.TIMED_OUT;
import static google.registry.testing.JUnitBackports.expectThrows;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions;
@ -35,7 +37,6 @@ import org.joda.time.Duration;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -56,10 +57,6 @@ public class LockTest {
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();
@Rule
public final ExpectedException thrown = ExpectedException.none();
private Optional<Lock> acquire(String tld, Duration leaseLength, LockState expectedLockState) { private Optional<Lock> acquire(String tld, Duration leaseLength, LockState expectedLockState) {
Lock.lockMetrics = mock(LockMetrics.class); Lock.lockMetrics = mock(LockMetrics.class);
Optional<Lock> lock = Lock.acquire(RESOURCE_NAME, tld, leaseLength, requestStatusChecker); Optional<Lock> lock = Lock.acquire(RESOURCE_NAME, tld, leaseLength, requestStatusChecker);
@ -138,8 +135,10 @@ public class LockTest {
@Test @Test
public void testFailure_emptyResourceName() throws Exception { public void testFailure_emptyResourceName() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("resourceName cannot be null or empty"); expectThrows(
Lock.acquire("", "", TWO_MILLIS, requestStatusChecker); IllegalArgumentException.class,
() -> Lock.acquire("", "", TWO_MILLIS, requestStatusChecker));
assertThat(thrown).hasMessageThat().contains("resourceName cannot be null or empty");
} }
} }

View file

@ -17,6 +17,7 @@ package google.registry.model.smd;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.model.smd.SignedMarkRevocationList.SHARD_SIZE; import static google.registry.model.smd.SignedMarkRevocationList.SHARD_SIZE;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static org.joda.time.Duration.standardDays; import static org.joda.time.Duration.standardDays;
@ -26,7 +27,6 @@ import google.registry.testing.FakeClock;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -38,25 +38,24 @@ public class SignedMarkRevocationListTest {
public final AppEngineRule appEngine = AppEngineRule.builder() public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore() .withDatastore()
.build(); .build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final FakeClock clock = new FakeClock(DateTime.parse("2013-01-01T00:00:00Z")); private final FakeClock clock = new FakeClock(DateTime.parse("2013-01-01T00:00:00Z"));
@Test @Test
public void testUnshardedSaveFails() throws Exception { public void testUnshardedSaveFails() throws Exception {
thrown.expect(SignedMarkRevocationList.UnshardedSaveException.class);
// Our @Entity's @OnSave method will notice that this shouldn't be saved. // Our @Entity's @OnSave method will notice that this shouldn't be saved.
assertThrows(
SignedMarkRevocationList.UnshardedSaveException.class,
() ->
ofy() ofy()
.transact( .transact(
() -> { () -> {
SignedMarkRevocationList smdrl = SignedMarkRevocationList smdrl =
SignedMarkRevocationList.create( SignedMarkRevocationList.create(
ofy().getTransactionTime(), ImmutableMap.of("a", ofy().getTransactionTime())); ofy().getTransactionTime(),
ImmutableMap.of("a", ofy().getTransactionTime()));
smdrl.id = 1; // Without an id this won't save anyways. smdrl.id = 1; // Without an id this won't save anyways.
ofy().saveWithoutBackup().entity(smdrl).now(); ofy().saveWithoutBackup().entity(smdrl).now();
}); }));
} }
@Test @Test
@ -112,9 +111,11 @@ public class SignedMarkRevocationListTest {
@Test @Test
public void test_isSmdRevoked_null() throws Exception { public void test_isSmdRevoked_null() throws Exception {
thrown.expect(NullPointerException.class); assertThrows(
NullPointerException.class,
() ->
SignedMarkRevocationList.create(START_OF_TIME, ImmutableMap.<String, DateTime>of()) SignedMarkRevocationList.create(START_OF_TIME, ImmutableMap.<String, DateTime>of())
.isSmdRevoked(null, clock.nowUtc()); .isSmdRevoked(null, clock.nowUtc()));
} }
@Test @Test

View file

@ -16,6 +16,7 @@ package google.registry.model.tmch;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static org.joda.time.DateTimeZone.UTC; import static org.joda.time.DateTimeZone.UTC;
@ -32,7 +33,6 @@ import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -45,9 +45,6 @@ public class ClaimsListShardTest {
.withDatastore() .withDatastore()
.build(); .build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();
@ -58,16 +55,19 @@ public class ClaimsListShardTest {
@Test @Test
public void test_unshardedSaveFails() throws Exception { public void test_unshardedSaveFails() throws Exception {
thrown.expect(UnshardedSaveException.class); assertThrows(
UnshardedSaveException.class,
() ->
ofy() ofy()
.transact( .transact(
() -> { () -> {
ClaimsListShard claimsList = ClaimsListShard claimsList =
ClaimsListShard.create(ofy().getTransactionTime(), ImmutableMap.of("a", "b")); ClaimsListShard.create(
ofy().getTransactionTime(), ImmutableMap.of("a", "b"));
claimsList.id = 1; // Without an id this won't save anyways. claimsList.id = 1; // Without an id this won't save anyways.
claimsList.parent = ClaimsListRevision.createKey(); claimsList.parent = ClaimsListRevision.createKey();
ofy().saveWithoutBackup().entity(claimsList).now(); ofy().saveWithoutBackup().entity(claimsList).now();
}); }));
} }
@Test @Test

View file

@ -35,7 +35,6 @@ import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -58,9 +57,6 @@ public class CommitLogRevisionsTranslatorFactoryTest {
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final FakeClock clock = new FakeClock(START_TIME); private final FakeClock clock = new FakeClock(START_TIME);
@Before @Before

View file

@ -21,6 +21,7 @@ import static google.registry.pricing.PricingEngineProxy.isDomainPremium;
import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistPremiumList; import static google.registry.testing.DatastoreHelper.persistPremiumList;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static org.joda.money.CurrencyUnit.USD; import static org.joda.money.CurrencyUnit.USD;
@ -35,17 +36,12 @@ import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
/** Tests for {@link PricingEngineProxy}. */ /** Tests for {@link PricingEngineProxy}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class PricingEngineProxyTest { public class PricingEngineProxyTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final AppEngineRule appEngine = AppEngineRule.builder() public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore() .withDatastore()
@ -148,8 +144,12 @@ public class PricingEngineProxyTest {
.asBuilder() .asBuilder()
.setPremiumPricingEngine("fake") .setPremiumPricingEngine("fake")
.build()); .build());
thrown.expect(IllegalStateException.class); IllegalStateException thrown =
thrown.expectMessage("Could not load pricing engine fake for TLD example"); expectThrows(
getDomainCreateCost("bad.example", clock.nowUtc(), 1); IllegalStateException.class,
() -> getDomainCreateCost("bad.example", clock.nowUtc(), 1));
assertThat(thrown)
.hasMessageThat()
.contains("Could not load pricing engine fake for TLD example");
} }
} }

View file

@ -15,11 +15,10 @@
package google.registry.rdap; package google.registry.rdap;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.assertThrows;
import google.registry.request.HttpException.UnprocessableEntityException; import google.registry.request.HttpException.UnprocessableEntityException;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -27,9 +26,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class RdapSearchPatternTest { public class RdapSearchPatternTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void testNoWildcards_ok() throws Exception { public void testNoWildcards_ok() throws Exception {
RdapSearchPattern rdapSearchPattern = RdapSearchPattern.create("example.lol", true); RdapSearchPattern rdapSearchPattern = RdapSearchPattern.create("example.lol", true);
@ -56,20 +52,19 @@ public class RdapSearchPatternTest {
@Test @Test
public void testMultipleWildcards_unprocessable() throws Exception { public void testMultipleWildcards_unprocessable() throws Exception {
thrown.expect(UnprocessableEntityException.class); assertThrows(
RdapSearchPattern.create("ex*am*.lol", true); UnprocessableEntityException.class, () -> RdapSearchPattern.create("ex*am*.lol", true));
} }
@Test @Test
public void testWildcardNotAtEnd_unprocessable() throws Exception { public void testWildcardNotAtEnd_unprocessable() throws Exception {
thrown.expect(UnprocessableEntityException.class); assertThrows(UnprocessableEntityException.class, () -> RdapSearchPattern.create("ex*am", true));
RdapSearchPattern.create("ex*am", true);
} }
@Test @Test
public void testWildcardNotAtEndWithTld_unprocessable() throws Exception { public void testWildcardNotAtEndWithTld_unprocessable() throws Exception {
thrown.expect(UnprocessableEntityException.class); assertThrows(
RdapSearchPattern.create("ex*am.lol", true); UnprocessableEntityException.class, () -> RdapSearchPattern.create("ex*am.lol", true));
} }
@Test @Test
@ -82,14 +77,14 @@ public class RdapSearchPatternTest {
@Test @Test
public void testZeroLengthSuffix_unprocessable() throws Exception { public void testZeroLengthSuffix_unprocessable() throws Exception {
thrown.expect(UnprocessableEntityException.class); assertThrows(
RdapSearchPattern.create("exam*.", true); UnprocessableEntityException.class, () -> RdapSearchPattern.create("exam*.", true));
} }
@Test @Test
public void testDisallowedSuffix_unprocessable() throws Exception { public void testDisallowedSuffix_unprocessable() throws Exception {
thrown.expect(UnprocessableEntityException.class); assertThrows(
RdapSearchPattern.create("exam*.lol", false); UnprocessableEntityException.class, () -> RdapSearchPattern.create("exam*.lol", false));
} }
@Test @Test

View file

@ -18,6 +18,7 @@ import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.expectThrows;
import static org.joda.time.Duration.standardDays; import static org.joda.time.Duration.standardDays;
import static org.joda.time.Duration.standardSeconds; import static org.joda.time.Duration.standardSeconds;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -37,7 +38,6 @@ import org.joda.time.DateTimeZone;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -45,9 +45,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class EscrowTaskRunnerTest { public class EscrowTaskRunnerTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final AppEngineRule appEngine = AppEngineRule.builder() public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore() .withDatastore()
@ -99,10 +96,13 @@ public class EscrowTaskRunnerTest {
clock.setTo(DateTime.parse("2006-06-06T00:30:00Z")); clock.setTo(DateTime.parse("2006-06-06T00:30:00Z"));
persistResource( persistResource(
Cursor.create(CursorType.RDE_STAGING, DateTime.parse("2006-06-07TZ"), registry)); Cursor.create(CursorType.RDE_STAGING, DateTime.parse("2006-06-07TZ"), registry));
thrown.expect(NoContentException.class); NoContentException thrown =
thrown.expectMessage("Already completed"); expectThrows(
NoContentException.class,
() ->
runner.lockRunAndRollForward( runner.lockRunAndRollForward(
task, registry, standardSeconds(30), CursorType.RDE_STAGING, standardDays(1)); task, registry, standardSeconds(30), CursorType.RDE_STAGING, standardDays(1)));
assertThat(thrown).hasMessageThat().contains("Already completed");
} }
@Test @Test
@ -111,10 +111,14 @@ public class EscrowTaskRunnerTest {
clock.setTo(DateTime.parse("2006-06-06T00:30:00Z")); clock.setTo(DateTime.parse("2006-06-06T00:30:00Z"));
persistResource( persistResource(
Cursor.create(CursorType.RDE_STAGING, DateTime.parse("2006-06-06TZ"), registry)); Cursor.create(CursorType.RDE_STAGING, DateTime.parse("2006-06-06TZ"), registry));
thrown.expect(ServiceUnavailableException.class); ServiceUnavailableException thrown =
thrown.expectMessage("Lock in use: " + lockName + " for TLD: lol"); expectThrows(
ServiceUnavailableException.class,
() -> {
runner.lockHandler = new FakeLockHandler(false); runner.lockHandler = new FakeLockHandler(false);
runner.lockRunAndRollForward( runner.lockRunAndRollForward(
task, registry, standardSeconds(30), CursorType.RDE_STAGING, standardDays(1)); task, registry, standardSeconds(30), CursorType.RDE_STAGING, standardDays(1));
});
assertThat(thrown).hasMessageThat().contains("Lock in use: " + lockName + " for TLD: lol");
} }
} }

View file

@ -17,6 +17,8 @@ package google.registry.rde;
import static com.google.common.base.Strings.repeat; import static com.google.common.base.Strings.repeat;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.keyring.api.PgpHelper.KeyRequirement.ENCRYPT; import static google.registry.keyring.api.PgpHelper.KeyRequirement.ENCRYPT;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;
@ -42,7 +44,6 @@ import org.junit.Test;
import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory; import org.junit.experimental.theories.Theory;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
/** Unit tests for {@link Ghostryde}. */ /** Unit tests for {@link Ghostryde}. */
@ -50,9 +51,6 @@ import org.junit.runner.RunWith;
@SuppressWarnings("resource") @SuppressWarnings("resource")
public class GhostrydeTest { public class GhostrydeTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule(); public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule();
@ -194,11 +192,15 @@ public class GhostrydeTest {
korruption(ciphertext, ciphertext.length / 2); korruption(ciphertext, ciphertext.length / 2);
ByteArrayInputStream bsIn = new ByteArrayInputStream(ciphertext); ByteArrayInputStream bsIn = new ByteArrayInputStream(ciphertext);
thrown.expect(IllegalStateException.class); IllegalStateException thrown =
thrown.expectMessage("tampering"); expectThrows(
IllegalStateException.class,
() -> {
try (Ghostryde.Decryptor decryptor = ghost.openDecryptor(bsIn, privateKey)) { try (Ghostryde.Decryptor decryptor = ghost.openDecryptor(bsIn, privateKey)) {
ByteStreams.copy(decryptor, ByteStreams.nullOutputStream()); ByteStreams.copy(decryptor, ByteStreams.nullOutputStream());
} }
});
assertThat(thrown).hasMessageThat().contains("tampering");
} }
@Theory @Theory
@ -223,10 +225,13 @@ public class GhostrydeTest {
korruption(ciphertext, ciphertext.length / 2); korruption(ciphertext, ciphertext.length / 2);
ByteArrayInputStream bsIn = new ByteArrayInputStream(ciphertext); ByteArrayInputStream bsIn = new ByteArrayInputStream(ciphertext);
thrown.expect(PGPException.class); assertThrows(
PGPException.class,
() -> {
try (Ghostryde.Decryptor decryptor = ghost.openDecryptor(bsIn, privateKey)) { try (Ghostryde.Decryptor decryptor = ghost.openDecryptor(bsIn, privateKey)) {
ByteStreams.copy(decryptor, ByteStreams.nullOutputStream()); ByteStreams.copy(decryptor, ByteStreams.nullOutputStream());
} }
});
} }
@Test @Test
@ -248,12 +253,17 @@ public class GhostrydeTest {
} }
ByteArrayInputStream bsIn = new ByteArrayInputStream(bsOut.toByteArray()); ByteArrayInputStream bsIn = new ByteArrayInputStream(bsOut.toByteArray());
thrown.expect(PGPException.class); PGPException thrown =
thrown.expectMessage( expectThrows(
"Message was encrypted for keyid a59c132f3589a1d5 but ours is c9598c84ec70b9fd"); PGPException.class,
() -> {
try (Ghostryde.Decryptor decryptor = ghost.openDecryptor(bsIn, privateKey)) { try (Ghostryde.Decryptor decryptor = ghost.openDecryptor(bsIn, privateKey)) {
ByteStreams.copy(decryptor, ByteStreams.nullOutputStream()); ByteStreams.copy(decryptor, ByteStreams.nullOutputStream());
} }
});
assertThat(thrown)
.hasMessageThat()
.contains("Message was encrypted for keyid a59c132f3589a1d5 but ours is c9598c84ec70b9fd");
} }
@Test @Test

View file

@ -17,6 +17,7 @@ package google.registry.rde;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.newDomainResource; import static google.registry.testing.DatastoreHelper.newDomainResource;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.xjc.XjcXmlTransformer.marshalStrict; import static google.registry.xjc.XjcXmlTransformer.marshalStrict;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
@ -36,7 +37,6 @@ import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -54,9 +54,6 @@ public class HostResourceToXjcConverterTest {
.withDatastore() .withDatastore()
.build(); .build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Before @Before
public void init() { public void init() {
createTld("foobar"); createTld("foobar");
@ -192,7 +189,9 @@ public class HostResourceToXjcConverterTest {
@Test @Test
public void testHostStatusValueIsInvalid() throws Exception { public void testHostStatusValueIsInvalid() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
IllegalArgumentException.class,
() ->
HostResourceToXjcConverter.convertExternalHost( HostResourceToXjcConverter.convertExternalHost(
new HostResource.Builder() new HostResource.Builder()
.setCreationClientId("LawyerCat") .setCreationClientId("LawyerCat")
@ -205,7 +204,7 @@ public class HostResourceToXjcConverterTest {
.setLastEppUpdateTime(DateTime.parse("1920-01-01T00:00:00Z")) .setLastEppUpdateTime(DateTime.parse("1920-01-01T00:00:00Z"))
.setRepoId("2-LOL") .setRepoId("2-LOL")
.setStatusValues(ImmutableSet.of(StatusValue.SERVER_HOLD)) // <-- OOPS .setStatusValues(ImmutableSet.of(StatusValue.SERVER_HOLD)) // <-- OOPS
.build()); .build()));
} }
@Test @Test

View file

@ -21,6 +21,8 @@ import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.GcsTestingUtils.writeGcsFile; import static google.registry.testing.GcsTestingUtils.writeGcsFile;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_OK; import static javax.servlet.http.HttpServletResponse.SC_OK;
import static org.joda.time.DateTimeZone.UTC; import static org.joda.time.DateTimeZone.UTC;
@ -65,7 +67,6 @@ import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
@ -77,10 +78,6 @@ public class RdeReportActionTest {
private static final ByteSource REPORT_XML = RdeTestData.loadBytes("report.xml"); private static final ByteSource REPORT_XML = RdeTestData.loadBytes("report.xml");
private static final ByteSource IIRDEA_BAD_XML = RdeTestData.loadBytes("iirdea_bad.xml"); private static final ByteSource IIRDEA_BAD_XML = RdeTestData.loadBytes("iirdea_bad.xml");
private static final ByteSource IIRDEA_GOOD_XML = RdeTestData.loadBytes("iirdea_good.xml"); private static final ByteSource IIRDEA_GOOD_XML = RdeTestData.loadBytes("iirdea_good.xml");
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule(); public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule();
@ -175,17 +172,19 @@ public class RdeReportActionTest {
when(httpResponse.getResponseCode()).thenReturn(SC_BAD_REQUEST); when(httpResponse.getResponseCode()).thenReturn(SC_BAD_REQUEST);
when(httpResponse.getContent()).thenReturn(IIRDEA_BAD_XML.read()); when(httpResponse.getContent()).thenReturn(IIRDEA_BAD_XML.read());
when(urlFetchService.fetch(request.capture())).thenReturn(httpResponse); when(urlFetchService.fetch(request.capture())).thenReturn(httpResponse);
thrown.expect(InternalServerErrorException.class); InternalServerErrorException thrown =
thrown.expectMessage("The structure of the report is invalid."); expectThrows(
createAction().runWithLock(loadRdeReportCursor()); InternalServerErrorException.class,
() -> createAction().runWithLock(loadRdeReportCursor()));
assertThat(thrown).hasMessageThat().contains("The structure of the report is invalid.");
} }
@Test @Test
public void testRunWithLock_fetchFailed_throwsRuntimeException() throws Exception { public void testRunWithLock_fetchFailed_throwsRuntimeException() throws Exception {
class ExpectedThrownException extends RuntimeException {} class ExpectedThrownException extends RuntimeException {}
when(urlFetchService.fetch(any(HTTPRequest.class))).thenThrow(new ExpectedThrownException()); when(urlFetchService.fetch(any(HTTPRequest.class))).thenThrow(new ExpectedThrownException());
thrown.expect(ExpectedThrownException.class); assertThrows(
createAction().runWithLock(loadRdeReportCursor()); ExpectedThrownException.class, () -> createAction().runWithLock(loadRdeReportCursor()));
} }
@Test @Test

View file

@ -26,6 +26,7 @@ import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.DatastoreHelper.persistResourceWithCommitLog; import static google.registry.testing.DatastoreHelper.persistResourceWithCommitLog;
import static google.registry.testing.GcsTestingUtils.readGcsFile; import static google.registry.testing.GcsTestingUtils.readGcsFile;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.TaskQueueHelper.assertAtLeastOneTaskIsEnqueued; import static google.registry.testing.TaskQueueHelper.assertAtLeastOneTaskIsEnqueued;
import static google.registry.testing.TaskQueueHelper.assertNoTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertNoTasksEnqueued;
import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
@ -92,7 +93,6 @@ import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -108,9 +108,6 @@ public class RdeStagingActionTest extends MapreduceTestCase<RdeStagingAction> {
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final FakeClock clock = new FakeClock(); private final FakeClock clock = new FakeClock();
private final FakeResponse response = new FakeResponse(); private final FakeResponse response = new FakeResponse();
private final GcsService gcsService = GcsServiceFactory.createGcsService(); private final GcsService gcsService = GcsServiceFactory.createGcsService();
@ -162,8 +159,7 @@ public class RdeStagingActionTest extends MapreduceTestCase<RdeStagingAction> {
createTldWithEscrowEnabled("lol"); createTldWithEscrowEnabled("lol");
clock.setTo(DateTime.parse("2000-01-01TZ")); clock.setTo(DateTime.parse("2000-01-01TZ"));
action.modeStrings = ImmutableSet.of("full"); action.modeStrings = ImmutableSet.of("full");
thrown.expect(BadRequestException.class); assertThrows(BadRequestException.class, () -> action.run());
action.run();
} }
@Test @Test
@ -171,8 +167,7 @@ public class RdeStagingActionTest extends MapreduceTestCase<RdeStagingAction> {
createTldWithEscrowEnabled("lol"); createTldWithEscrowEnabled("lol");
clock.setTo(DateTime.parse("2000-01-01TZ")); clock.setTo(DateTime.parse("2000-01-01TZ"));
action.tlds = ImmutableSet.of("tld"); action.tlds = ImmutableSet.of("tld");
thrown.expect(BadRequestException.class); assertThrows(BadRequestException.class, () -> action.run());
action.run();
} }
@Test @Test
@ -180,8 +175,7 @@ public class RdeStagingActionTest extends MapreduceTestCase<RdeStagingAction> {
createTldWithEscrowEnabled("lol"); createTldWithEscrowEnabled("lol");
clock.setTo(DateTime.parse("2000-01-01TZ")); clock.setTo(DateTime.parse("2000-01-01TZ"));
action.watermarks = ImmutableSet.of(clock.nowUtc()); action.watermarks = ImmutableSet.of(clock.nowUtc());
thrown.expect(BadRequestException.class); assertThrows(BadRequestException.class, () -> action.run());
action.run();
} }
@Test @Test
@ -189,8 +183,7 @@ public class RdeStagingActionTest extends MapreduceTestCase<RdeStagingAction> {
createTldWithEscrowEnabled("lol"); createTldWithEscrowEnabled("lol");
clock.setTo(DateTime.parse("2000-01-01TZ")); clock.setTo(DateTime.parse("2000-01-01TZ"));
action.revision = Optional.of(42); action.revision = Optional.of(42);
thrown.expect(BadRequestException.class); assertThrows(BadRequestException.class, () -> action.run());
action.run();
} }
@Test @Test
@ -248,8 +241,7 @@ public class RdeStagingActionTest extends MapreduceTestCase<RdeStagingAction> {
action.modeStrings = ImmutableSet.of(); action.modeStrings = ImmutableSet.of();
action.tlds = ImmutableSet.of("lol"); action.tlds = ImmutableSet.of("lol");
action.watermarks = ImmutableSet.of(clock.nowUtc()); action.watermarks = ImmutableSet.of(clock.nowUtc());
thrown.expect(BadRequestException.class); assertThrows(BadRequestException.class, () -> action.run());
action.run();
} }
@Test @Test
@ -261,8 +253,7 @@ public class RdeStagingActionTest extends MapreduceTestCase<RdeStagingAction> {
action.modeStrings = ImmutableSet.of("full", "thing"); action.modeStrings = ImmutableSet.of("full", "thing");
action.tlds = ImmutableSet.of("lol"); action.tlds = ImmutableSet.of("lol");
action.watermarks = ImmutableSet.of(clock.nowUtc()); action.watermarks = ImmutableSet.of(clock.nowUtc());
thrown.expect(BadRequestException.class); assertThrows(BadRequestException.class, () -> action.run());
action.run();
} }
@Test @Test
@ -274,8 +265,7 @@ public class RdeStagingActionTest extends MapreduceTestCase<RdeStagingAction> {
action.modeStrings = ImmutableSet.of("full"); action.modeStrings = ImmutableSet.of("full");
action.tlds = ImmutableSet.of(); action.tlds = ImmutableSet.of();
action.watermarks = ImmutableSet.of(clock.nowUtc()); action.watermarks = ImmutableSet.of(clock.nowUtc());
thrown.expect(BadRequestException.class); assertThrows(BadRequestException.class, () -> action.run());
action.run();
} }
@Test @Test
@ -287,8 +277,7 @@ public class RdeStagingActionTest extends MapreduceTestCase<RdeStagingAction> {
action.modeStrings = ImmutableSet.of("full"); action.modeStrings = ImmutableSet.of("full");
action.tlds = ImmutableSet.of("lol"); action.tlds = ImmutableSet.of("lol");
action.watermarks = ImmutableSet.of(); action.watermarks = ImmutableSet.of();
thrown.expect(BadRequestException.class); assertThrows(BadRequestException.class, () -> action.run());
action.run();
} }
@Test @Test
@ -300,8 +289,7 @@ public class RdeStagingActionTest extends MapreduceTestCase<RdeStagingAction> {
action.modeStrings = ImmutableSet.of("full"); action.modeStrings = ImmutableSet.of("full");
action.tlds = ImmutableSet.of("lol"); action.tlds = ImmutableSet.of("lol");
action.watermarks = ImmutableSet.of(DateTime.parse("2001-01-01T01:36:45Z")); action.watermarks = ImmutableSet.of(DateTime.parse("2001-01-01T01:36:45Z"));
thrown.expect(BadRequestException.class); assertThrows(BadRequestException.class, () -> action.run());
action.run();
} }
@Test @Test
@ -314,8 +302,7 @@ public class RdeStagingActionTest extends MapreduceTestCase<RdeStagingAction> {
action.tlds = ImmutableSet.of("lol"); action.tlds = ImmutableSet.of("lol");
action.watermarks = ImmutableSet.of(DateTime.parse("2001-01-01T00:00:00Z")); action.watermarks = ImmutableSet.of(DateTime.parse("2001-01-01T00:00:00Z"));
action.revision = Optional.of(-1); action.revision = Optional.of(-1);
thrown.expect(BadRequestException.class); assertThrows(BadRequestException.class, () -> action.run());
action.run();
} }
@Test @Test

View file

@ -24,6 +24,7 @@ import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.DatastoreHelper.persistSimpleResource; import static google.registry.testing.DatastoreHelper.persistSimpleResource;
import static google.registry.testing.GcsTestingUtils.readGcsFile; import static google.registry.testing.GcsTestingUtils.readGcsFile;
import static google.registry.testing.GcsTestingUtils.writeGcsFile; import static google.registry.testing.GcsTestingUtils.writeGcsFile;
import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.testing.SystemInfo.hasCommand; import static google.registry.testing.SystemInfo.hasCommand;
import static google.registry.testing.TaskQueueHelper.assertNoTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertNoTasksEnqueued;
import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
@ -86,7 +87,6 @@ import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder; import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -113,10 +113,6 @@ public class RdeUploadActionTest {
new GcsFilename("bucket", "tld_2010-10-17_full_S1_R1.xml.length"); new GcsFilename("bucket", "tld_2010-10-17_full_S1_R1.xml.length");
private static final GcsFilename REPORT_R1_FILE = private static final GcsFilename REPORT_R1_FILE =
new GcsFilename("bucket", "tld_2010-10-17_full_S1_R1-report.xml.ghostryde"); new GcsFilename("bucket", "tld_2010-10-17_full_S1_R1-report.xml.ghostryde");
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final SftpServerRule sftpd = new SftpServerRule(); public final SftpServerRule sftpd = new SftpServerRule();
@ -312,9 +308,9 @@ public class RdeUploadActionTest {
Cursor.create(CursorType.RDE_STAGING, stagingCursor, Registry.get("tld"))); Cursor.create(CursorType.RDE_STAGING, stagingCursor, Registry.get("tld")));
RdeUploadAction action = createAction(uploadUrl); RdeUploadAction action = createAction(uploadUrl);
action.lazyJsch = Lazies.of(createThrowingJSchSpy(action.lazyJsch.get(), 3)); action.lazyJsch = Lazies.of(createThrowingJSchSpy(action.lazyJsch.get(), 3));
thrown.expect(RuntimeException.class); RuntimeException thrown =
thrown.expectMessage("The crow flies in square circles."); expectThrows(RuntimeException.class, () -> action.runWithLock(uploadCursor));
action.runWithLock(uploadCursor); assertThat(thrown).hasMessageThat().contains("The crow flies in square circles.");
} }
@Test @Test
@ -387,9 +383,10 @@ public class RdeUploadActionTest {
DateTime uploadCursor = DateTime.parse("2010-10-17TZ"); DateTime uploadCursor = DateTime.parse("2010-10-17TZ");
persistResource( persistResource(
Cursor.create(CursorType.RDE_STAGING, stagingCursor, Registry.get("tld"))); Cursor.create(CursorType.RDE_STAGING, stagingCursor, Registry.get("tld")));
thrown.expect(ServiceUnavailableException.class); ServiceUnavailableException thrown =
thrown.expectMessage("Waiting for RdeStagingAction to complete"); expectThrows(
createAction(null).runWithLock(uploadCursor); ServiceUnavailableException.class, () -> createAction(null).runWithLock(uploadCursor));
assertThat(thrown).hasMessageThat().contains("Waiting for RdeStagingAction to complete");
} }
private String slurp(InputStream is) throws FileNotFoundException, IOException { private String slurp(InputStream is) throws FileNotFoundException, IOException {

View file

@ -18,6 +18,7 @@ import static com.google.common.net.MediaType.CSV_UTF_8;
import static com.google.common.net.MediaType.PLAIN_TEXT_UTF_8; import static com.google.common.net.MediaType.PLAIN_TEXT_UTF_8;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.JUnitBackports.expectThrows;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.api.client.http.LowLevelHttpRequest; import com.google.api.client.http.LowLevelHttpRequest;
@ -35,7 +36,6 @@ import java.util.Map;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -50,9 +50,6 @@ public class IcannHttpReporterTest {
private static final byte[] FAKE_PAYLOAD = "test,csv\n1,2".getBytes(UTF_8); private static final byte[] FAKE_PAYLOAD = "test,csv\n1,2".getBytes(UTF_8);
private MockLowLevelHttpRequest mockRequest; private MockLowLevelHttpRequest mockRequest;
@Rule public final ExpectedException thrown = ExpectedException.none();
@Rule public AppEngineRule appEngineRule = new AppEngineRule.Builder().withDatastore().build(); @Rule public AppEngineRule appEngineRule = new AppEngineRule.Builder().withDatastore().build();
private MockHttpTransport createMockTransport (final ByteSource iirdeaResponse) { private MockHttpTransport createMockTransport (final ByteSource iirdeaResponse) {
@ -127,36 +124,60 @@ public class IcannHttpReporterTest {
@Test @Test
public void testFail_invalidFilename_nonSixDigitYearMonth() throws Exception { public void testFail_invalidFilename_nonSixDigitYearMonth() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage( expectThrows(
"Expected file format: tld-reportType-yyyyMM.csv, got test-transactions-20176.csv instead"); IllegalArgumentException.class,
() -> {
IcannHttpReporter reporter = createReporter(); IcannHttpReporter reporter = createReporter();
reporter.send(FAKE_PAYLOAD, "test-transactions-20176.csv"); reporter.send(FAKE_PAYLOAD, "test-transactions-20176.csv");
});
assertThat(thrown)
.hasMessageThat()
.contains(
"Expected file format: tld-reportType-yyyyMM.csv, "
+ "got test-transactions-20176.csv instead");
} }
@Test @Test
public void testFail_invalidFilename_notActivityOrTransactions() throws Exception { public void testFail_invalidFilename_notActivityOrTransactions() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage( expectThrows(
"Expected file format: tld-reportType-yyyyMM.csv, got test-invalid-201706.csv instead"); IllegalArgumentException.class,
() -> {
IcannHttpReporter reporter = createReporter(); IcannHttpReporter reporter = createReporter();
reporter.send(FAKE_PAYLOAD, "test-invalid-201706.csv"); reporter.send(FAKE_PAYLOAD, "test-invalid-201706.csv");
});
assertThat(thrown)
.hasMessageThat()
.contains(
"Expected file format: tld-reportType-yyyyMM.csv, got test-invalid-201706.csv instead");
} }
@Test @Test
public void testFail_invalidFilename_invalidTldName() throws Exception { public void testFail_invalidFilename_invalidTldName() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage( expectThrows(
"Expected file format: tld-reportType-yyyyMM.csv, got n!-n-activity-201706.csv instead"); IllegalArgumentException.class,
() -> {
IcannHttpReporter reporter = createReporter(); IcannHttpReporter reporter = createReporter();
reporter.send(FAKE_PAYLOAD, "n!-n-activity-201706.csv"); reporter.send(FAKE_PAYLOAD, "n!-n-activity-201706.csv");
});
assertThat(thrown)
.hasMessageThat()
.contains(
"Expected file format: tld-reportType-yyyyMM.csv, "
+ "got n!-n-activity-201706.csv instead");
} }
@Test @Test
public void testFail_invalidFilename_tldDoesntExist() throws Exception { public void testFail_invalidFilename_tldDoesntExist() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("TLD hello does not exist"); expectThrows(
IllegalArgumentException.class,
() -> {
IcannHttpReporter reporter = createReporter(); IcannHttpReporter reporter = createReporter();
reporter.send(FAKE_PAYLOAD, "hello-activity-201706.csv"); reporter.send(FAKE_PAYLOAD, "hello-activity-201706.csv");
});
assertThat(thrown).hasMessageThat().contains("TLD hello does not exist");
} }
} }

View file

@ -15,6 +15,7 @@
package google.registry.reporting; package google.registry.reporting;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.expectThrows;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -27,9 +28,7 @@ import javax.servlet.http.HttpServletRequest;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.YearMonth; import org.joda.time.YearMonth;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -39,9 +38,6 @@ public class IcannReportingModuleTest {
HttpServletRequest req = mock(HttpServletRequest.class); HttpServletRequest req = mock(HttpServletRequest.class);
Clock clock; Clock clock;
@Rule public final ExpectedException thrown = ExpectedException.none();
@Before @Before
public void setUp() { public void setUp() {
clock = new FakeClock(DateTime.parse("2017-07-01TZ")); clock = new FakeClock(DateTime.parse("2017-07-01TZ"));
@ -56,9 +52,12 @@ public class IcannReportingModuleTest {
@Test @Test
public void testInvalidYearMonthParameter_throwsException() { public void testInvalidYearMonthParameter_throwsException() {
when(req.getParameter("yearMonth")).thenReturn("201705"); when(req.getParameter("yearMonth")).thenReturn("201705");
thrown.expect(BadRequestException.class); BadRequestException thrown =
thrown.expectMessage("yearMonth must be in yyyy-MM format, got 201705 instead"); expectThrows(
IcannReportingModule.provideYearMonthOptional(req); BadRequestException.class, () -> IcannReportingModule.provideYearMonthOptional(req));
assertThat(thrown)
.hasMessageThat()
.contains("yearMonth must be in yyyy-MM format, got 201705 instead");
} }
@Test @Test
@ -88,9 +87,14 @@ public class IcannReportingModuleTest {
@Test @Test
public void testInvalidSubdir_throwsException() { public void testInvalidSubdir_throwsException() {
thrown.expect(BadRequestException.class); BadRequestException thrown =
thrown.expectMessage("subdir must not start or end with a \"/\", got /whoops instead."); expectThrows(
IcannReportingModule.provideSubdir(Optional.of("/whoops"), new YearMonth(2017, 6)); BadRequestException.class,
() ->
IcannReportingModule.provideSubdir(Optional.of("/whoops"), new YearMonth(2017, 6)));
assertThat(thrown)
.hasMessageThat()
.contains("subdir must not start or end with a \"/\", got /whoops instead.");
} }
@Test @Test

View file

@ -21,9 +21,7 @@ import com.google.common.collect.ImmutableMap;
import google.registry.testing.FakeResponse; import google.registry.testing.FakeResponse;
import java.util.Map; import java.util.Map;
import org.json.simple.JSONValue; import org.json.simple.JSONValue;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -31,9 +29,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class JsonResponseTest { public class JsonResponseTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
FakeResponse fakeResponse = new FakeResponse(); FakeResponse fakeResponse = new FakeResponse();
JsonResponse jsonResponse = new JsonResponse(fakeResponse); JsonResponse jsonResponse = new JsonResponse(fakeResponse);

View file

@ -16,23 +16,19 @@ package google.registry.request;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.request.RequestModule.provideJsonPayload; import static google.registry.request.RequestModule.provideJsonPayload;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import com.google.common.net.MediaType; import com.google.common.net.MediaType;
import google.registry.request.HttpException.BadRequestException; import google.registry.request.HttpException.BadRequestException;
import google.registry.request.HttpException.UnsupportedMediaTypeException; import google.registry.request.HttpException.UnsupportedMediaTypeException;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
/** Unit tests for {@link RequestModule}. */ /** Unit tests for {@link RequestModule}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public final class RequestModuleTest { public final class RequestModuleTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void testProvideJsonPayload() throws Exception { public void testProvideJsonPayload() throws Exception {
assertThat(provideJsonPayload(MediaType.JSON_UTF_8, "{\"k\":\"v\"}")) assertThat(provideJsonPayload(MediaType.JSON_UTF_8, "{\"k\":\"v\"}"))
@ -47,27 +43,30 @@ public final class RequestModuleTest {
@Test @Test
public void testProvideJsonPayload_malformedInput_throws500() throws Exception { public void testProvideJsonPayload_malformedInput_throws500() throws Exception {
thrown.expect(BadRequestException.class); BadRequestException thrown =
thrown.expectMessage("Malformed JSON"); expectThrows(
provideJsonPayload(MediaType.JSON_UTF_8, "{\"k\":"); BadRequestException.class, () -> provideJsonPayload(MediaType.JSON_UTF_8, "{\"k\":"));
assertThat(thrown).hasMessageThat().contains("Malformed JSON");
} }
@Test @Test
public void testProvideJsonPayload_emptyInput_throws500() throws Exception { public void testProvideJsonPayload_emptyInput_throws500() throws Exception {
thrown.expect(BadRequestException.class); BadRequestException thrown =
thrown.expectMessage("Malformed JSON"); expectThrows(BadRequestException.class, () -> provideJsonPayload(MediaType.JSON_UTF_8, ""));
provideJsonPayload(MediaType.JSON_UTF_8, ""); assertThat(thrown).hasMessageThat().contains("Malformed JSON");
} }
@Test @Test
public void testProvideJsonPayload_nonJsonContentType_throws415() throws Exception { public void testProvideJsonPayload_nonJsonContentType_throws415() throws Exception {
thrown.expect(UnsupportedMediaTypeException.class); assertThrows(
provideJsonPayload(MediaType.PLAIN_TEXT_UTF_8, "{}"); UnsupportedMediaTypeException.class,
() -> provideJsonPayload(MediaType.PLAIN_TEXT_UTF_8, "{}"));
} }
@Test @Test
public void testProvideJsonPayload_contentTypeWithWeirdParam_throws415() throws Exception { public void testProvideJsonPayload_contentTypeWithWeirdParam_throws415() throws Exception {
thrown.expect(UnsupportedMediaTypeException.class); assertThrows(
provideJsonPayload(MediaType.JSON_UTF_8.withParameter("omg", "handel"), "{}"); UnsupportedMediaTypeException.class,
() -> provideJsonPayload(MediaType.JSON_UTF_8.withParameter("omg", "handel"), "{}"));
} }
} }

View file

@ -23,6 +23,7 @@ import static google.registry.request.RequestParameters.extractOptionalEnumParam
import static google.registry.request.RequestParameters.extractOptionalParameter; import static google.registry.request.RequestParameters.extractOptionalParameter;
import static google.registry.request.RequestParameters.extractRequiredDatetimeParameter; import static google.registry.request.RequestParameters.extractRequiredDatetimeParameter;
import static google.registry.request.RequestParameters.extractRequiredParameter; import static google.registry.request.RequestParameters.extractRequiredParameter;
import static google.registry.testing.JUnitBackports.expectThrows;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -30,19 +31,13 @@ import com.google.common.collect.ImmutableMap;
import google.registry.request.HttpException.BadRequestException; import google.registry.request.HttpException.BadRequestException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
/** Unit tests for {@link RequestParameters}. */ /** Unit tests for {@link RequestParameters}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class RequestParametersTest { public class RequestParametersTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final HttpServletRequest req = mock(HttpServletRequest.class); private final HttpServletRequest req = mock(HttpServletRequest.class);
@Test @Test
@ -53,17 +48,17 @@ public class RequestParametersTest {
@Test @Test
public void testExtractRequiredParameter_notPresent_throwsBadRequest() throws Exception { public void testExtractRequiredParameter_notPresent_throwsBadRequest() throws Exception {
thrown.expect(BadRequestException.class); BadRequestException thrown =
thrown.expectMessage("spin"); expectThrows(BadRequestException.class, () -> extractRequiredParameter(req, "spin"));
extractRequiredParameter(req, "spin"); assertThat(thrown).hasMessageThat().contains("spin");
} }
@Test @Test
public void testExtractRequiredParameter_empty_throwsBadRequest() throws Exception { public void testExtractRequiredParameter_empty_throwsBadRequest() throws Exception {
when(req.getParameter("spin")).thenReturn(""); when(req.getParameter("spin")).thenReturn("");
thrown.expect(BadRequestException.class); BadRequestException thrown =
thrown.expectMessage("spin"); expectThrows(BadRequestException.class, () -> extractRequiredParameter(req, "spin"));
extractRequiredParameter(req, "spin"); assertThat(thrown).hasMessageThat().contains("spin");
} }
@Test @Test
@ -146,9 +141,10 @@ public class RequestParametersTest {
@Test @Test
public void testExtractEnumValue_nonExistentValue_throwsBadRequest() throws Exception { public void testExtractEnumValue_nonExistentValue_throwsBadRequest() throws Exception {
when(req.getParameter("spin")).thenReturn("sing"); when(req.getParameter("spin")).thenReturn("sing");
thrown.expect(BadRequestException.class); BadRequestException thrown =
thrown.expectMessage("spin"); expectThrows(
extractEnumParameter(req, Club.class, "spin"); BadRequestException.class, () -> extractEnumParameter(req, Club.class, "spin"));
assertThat(thrown).hasMessageThat().contains("spin");
} }
@Test @Test
@ -166,9 +162,10 @@ public class RequestParametersTest {
@Test @Test
public void testOptionalExtractEnumValue_nonExistentValue_throwsBadRequest() throws Exception { public void testOptionalExtractEnumValue_nonExistentValue_throwsBadRequest() throws Exception {
when(req.getParameter("spin")).thenReturn("sing"); when(req.getParameter("spin")).thenReturn("sing");
thrown.expect(BadRequestException.class); BadRequestException thrown =
thrown.expectMessage("spin"); expectThrows(
extractOptionalEnumParameter(req, Club.class, "spin"); BadRequestException.class, () -> extractOptionalEnumParameter(req, Club.class, "spin"));
assertThat(thrown).hasMessageThat().contains("spin");
} }
@Test @Test
@ -181,9 +178,10 @@ public class RequestParametersTest {
@Test @Test
public void testExtractRequiredDatetimeParameter_badValue_throwsBadRequest() throws Exception { public void testExtractRequiredDatetimeParameter_badValue_throwsBadRequest() throws Exception {
when(req.getParameter("timeParam")).thenReturn("Tuesday at three o'clock"); when(req.getParameter("timeParam")).thenReturn("Tuesday at three o'clock");
thrown.expect(BadRequestException.class); BadRequestException thrown =
thrown.expectMessage("timeParam"); expectThrows(
extractRequiredDatetimeParameter(req, "timeParam"); BadRequestException.class, () -> extractRequiredDatetimeParameter(req, "timeParam"));
assertThat(thrown).hasMessageThat().contains("timeParam");
} }
@Test @Test
@ -196,9 +194,10 @@ public class RequestParametersTest {
@Test @Test
public void testExtractOptionalDatetimeParameter_badValue_throwsBadRequest() throws Exception { public void testExtractOptionalDatetimeParameter_badValue_throwsBadRequest() throws Exception {
when(req.getParameter("timeParam")).thenReturn("Tuesday at three o'clock"); when(req.getParameter("timeParam")).thenReturn("Tuesday at three o'clock");
thrown.expect(BadRequestException.class); BadRequestException thrown =
thrown.expectMessage("timeParam"); expectThrows(
extractOptionalDatetimeParameter(req, "timeParam"); BadRequestException.class, () -> extractOptionalDatetimeParameter(req, "timeParam"));
assertThat(thrown).hasMessageThat().contains("timeParam");
} }
@Test @Test
@ -209,8 +208,9 @@ public class RequestParametersTest {
@Test @Test
public void testExtractRequiredDatetimeParameter_noValue_throwsBadRequest() throws Exception { public void testExtractRequiredDatetimeParameter_noValue_throwsBadRequest() throws Exception {
thrown.expect(BadRequestException.class); BadRequestException thrown =
thrown.expectMessage("timeParam"); expectThrows(
extractRequiredDatetimeParameter(req, "timeParam"); BadRequestException.class, () -> extractRequiredDatetimeParameter(req, "timeParam"));
assertThat(thrown).hasMessageThat().contains("timeParam");
} }
} }

View file

@ -24,9 +24,7 @@ import static org.mockito.Mockito.when;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -34,9 +32,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class ResponseImplTest { public class ResponseImplTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final HttpServletResponse rsp = mock(HttpServletResponse.class); private final HttpServletResponse rsp = mock(HttpServletResponse.class);
@Test @Test

View file

@ -17,13 +17,12 @@ package google.registry.request;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat; import static com.google.common.truth.Truth8.assertThat;
import static google.registry.request.auth.Auth.AUTH_INTERNAL_ONLY; import static google.registry.request.auth.Auth.AUTH_INTERNAL_ONLY;
import static google.registry.testing.JUnitBackports.expectThrows;
import com.google.common.base.Function; import com.google.common.base.Function;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -31,18 +30,17 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public final class RouterTest { public final class RouterTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
//////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////
public interface Empty {} public interface Empty {}
@Test @Test
public void testRoute_noRoutes_throws() throws Exception { public void testRoute_noRoutes_throws() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("No routes found for class: google.registry.request.RouterTest.Empty"); expectThrows(IllegalArgumentException.class, () -> Router.create(Empty.class));
Router.create(Empty.class); assertThat(thrown)
.hasMessageThat()
.contains("No routes found for class: google.registry.request.RouterTest.Empty");
} }
//////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////
@ -144,10 +142,13 @@ public final class RouterTest {
@Test @Test
public void testRoute_methodsInComponentAreIgnored_throws() throws Exception { public void testRoute_methodsInComponentAreIgnored_throws() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage( expectThrows(
IllegalArgumentException.class, () -> Router.create(WeirdMethodsComponent.class));
assertThat(thrown)
.hasMessageThat()
.contains(
"No routes found for class: google.registry.request.RouterTest.WeirdMethodsComponent"); "No routes found for class: google.registry.request.RouterTest.WeirdMethodsComponent");
Router.create(WeirdMethodsComponent.class);
} }
//////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////
@ -171,8 +172,8 @@ public final class RouterTest {
@Test @Test
public void testCreate_twoTasksWithSameMethodAndPath_resultsInError() throws Exception { public void testCreate_twoTasksWithSameMethodAndPath_resultsInError() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Multiple entries with same key"); expectThrows(IllegalArgumentException.class, () -> Router.create(DuplicateComponent.class));
Router.create(DuplicateComponent.class); assertThat(thrown).hasMessageThat().contains("Multiple entries with same key");
} }
} }

View file

@ -17,6 +17,7 @@ package google.registry.request.auth;
import static com.google.common.net.HttpHeaders.AUTHORIZATION; import static com.google.common.net.HttpHeaders.AUTHORIZATION;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat; import static com.google.common.truth.Truth8.assertThat;
import static google.registry.testing.JUnitBackports.expectThrows;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -38,7 +39,6 @@ import javax.servlet.http.HttpServletRequest;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -48,10 +48,6 @@ public class RequestAuthenticatorTest {
@Rule @Rule
public final AppEngineRule appEngine = AppEngineRule.builder().build(); public final AppEngineRule appEngine = AppEngineRule.builder().build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
private static final AuthSettings AUTH_NONE = AuthSettings.create( private static final AuthSettings AUTH_NONE = AuthSettings.create(
ImmutableList.of(AuthMethod.INTERNAL), ImmutableList.of(AuthMethod.INTERNAL),
AuthLevel.NONE, AuthLevel.NONE,
@ -391,44 +387,55 @@ public class RequestAuthenticatorTest {
@Test @Test
public void testCheckAuthConfig_NoMethods_failure() throws Exception { public void testCheckAuthConfig_NoMethods_failure() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Must specify at least one auth method"); expectThrows(
IllegalArgumentException.class,
RequestAuthenticator.checkAuthConfig(AUTH_NO_METHODS); () -> RequestAuthenticator.checkAuthConfig(AUTH_NO_METHODS));
assertThat(thrown).hasMessageThat().contains("Must specify at least one auth method");
} }
@Test @Test
public void testCheckAuthConfig_WrongMethodOrdering_failure() throws Exception { public void testCheckAuthConfig_WrongMethodOrdering_failure() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown expectThrows(
.expectMessage("Auth methods must be unique and strictly in order - INTERNAL, API, LEGACY"); IllegalArgumentException.class,
() -> RequestAuthenticator.checkAuthConfig(AUTH_WRONG_METHOD_ORDERING));
RequestAuthenticator.checkAuthConfig(AUTH_WRONG_METHOD_ORDERING); assertThat(thrown)
.hasMessageThat()
.contains("Auth methods must be unique and strictly in order - INTERNAL, API, LEGACY");
} }
@Test @Test
public void testCheckAuthConfig_DuplicateMethods_failure() throws Exception { public void testCheckAuthConfig_DuplicateMethods_failure() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown expectThrows(
.expectMessage("Auth methods must be unique and strictly in order - INTERNAL, API, LEGACY"); IllegalArgumentException.class,
() -> RequestAuthenticator.checkAuthConfig(AUTH_DUPLICATE_METHODS));
RequestAuthenticator.checkAuthConfig(AUTH_DUPLICATE_METHODS); assertThat(thrown)
.hasMessageThat()
.contains("Auth methods must be unique and strictly in order - INTERNAL, API, LEGACY");
} }
@Test @Test
public void testCheckAuthConfig_InternalWithUser_failure() throws Exception { public void testCheckAuthConfig_InternalWithUser_failure() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Actions with INTERNAL auth method may not require USER auth level"); expectThrows(
IllegalArgumentException.class,
RequestAuthenticator.checkAuthConfig(AUTH_INTERNAL_WITH_USER); () -> RequestAuthenticator.checkAuthConfig(AUTH_INTERNAL_WITH_USER));
assertThat(thrown)
.hasMessageThat()
.contains("Actions with INTERNAL auth method may not require USER auth level");
} }
@Test @Test
public void testCheckAuthConfig_WronglyIgnoringUser_failure() throws Exception { public void testCheckAuthConfig_WronglyIgnoringUser_failure() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage( expectThrows(
IllegalArgumentException.class,
() -> RequestAuthenticator.checkAuthConfig(AUTH_WRONGLY_IGNORING_USER));
assertThat(thrown)
.hasMessageThat()
.contains(
"Actions with auth methods beyond INTERNAL must not specify the IGNORED user policy"); "Actions with auth methods beyond INTERNAL must not specify the IGNORED user policy");
RequestAuthenticator.checkAuthConfig(AUTH_WRONGLY_IGNORING_USER);
} }
} }

View file

@ -29,7 +29,6 @@ import org.joda.time.Duration;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -43,9 +42,6 @@ public final class LockHandlerImplTest {
public final AppEngineRule appEngine = AppEngineRule.builder() public final AppEngineRule appEngine = AppEngineRule.builder()
.build(); .build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
private static class CountingCallable implements Callable<Void> { private static class CountingCallable implements Callable<Void> {
int numCalled = 0; int numCalled = 0;

View file

@ -16,6 +16,7 @@ package google.registry.storage.drive;
import static com.google.common.io.ByteStreams.toByteArray; import static com.google.common.io.ByteStreams.toByteArray;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.expectThrows;
import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.argThat; import static org.mockito.Matchers.argThat;
import static org.mockito.Matchers.eq; import static org.mockito.Matchers.eq;
@ -37,9 +38,7 @@ import com.google.common.net.MediaType;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
import org.mockito.ArgumentMatcher; import org.mockito.ArgumentMatcher;
@ -47,10 +46,6 @@ import org.mockito.ArgumentMatcher;
/** Tests for {@link DriveConnection}.*/ /** Tests for {@link DriveConnection}.*/
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class DriveConnectionTest { public class DriveConnectionTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final Drive drive = mock(Drive.class); private final Drive drive = mock(Drive.class);
private final Files files = mock(Files.class); private final Files files = mock(Files.class);
private final Children children = mock(Children.class); private final Children children = mock(Children.class);
@ -215,10 +210,17 @@ public class DriveConnectionTest {
new ChildReference().setId("id2"))) new ChildReference().setId("id2")))
.setNextPageToken(null); .setNextPageToken(null);
when(childrenList.execute()).thenReturn(childList); when(childrenList.execute()).thenReturn(childList);
thrown.expect(IllegalStateException.class); IllegalStateException thrown =
thrown.expectMessage("Could not update file 'title' in Drive folder id 'driveFolderId' " expectThrows(
IllegalStateException.class,
() ->
driveConnection.createOrUpdateFile(
"title", MediaType.WEBM_VIDEO, "driveFolderId", DATA));
assertThat(thrown)
.hasMessageThat()
.contains(
"Could not update file 'title' in Drive folder id 'driveFolderId' "
+ "because multiple files with that name already exist."); + "because multiple files with that name already exist.");
driveConnection.createOrUpdateFile("title", MediaType.WEBM_VIDEO, "driveFolderId", DATA);
} }
@Test @Test

View file

@ -15,23 +15,18 @@
package google.registry.tldconfig.idn; package google.registry.tldconfig.idn;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.expectThrows;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import java.net.URI; import java.net.URI;
import java.util.Optional; import java.util.Optional;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
/** Unit tests for {@link IdnTable}. */ /** Unit tests for {@link IdnTable}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class IdnTableTest { public class IdnTableTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void testDigits() { public void testDigits() {
ImmutableList<String> of = ImmutableList.<String>of( ImmutableList<String> of = ImmutableList.<String>of(
@ -108,17 +103,21 @@ public class IdnTableTest {
public void testMissingUrl_throwsNpe() { public void testMissingUrl_throwsNpe() {
ImmutableList<String> of = ImmutableList.<String>of( ImmutableList<String> of = ImmutableList.<String>of(
"# Policy: https://love.example/policy.html"); "# Policy: https://love.example/policy.html");
thrown.expect(NullPointerException.class); NullPointerException thrown =
thrown.expectMessage("sloth missing '# URL:"); expectThrows(
IdnTable.createFrom("sloth", of, Optional.<LanguageValidator>empty()); NullPointerException.class,
() -> IdnTable.createFrom("sloth", of, Optional.<LanguageValidator>empty()));
assertThat(thrown).hasMessageThat().contains("sloth missing '# URL:");
} }
@Test @Test
public void testMissingPolicy_throwsNpe() { public void testMissingPolicy_throwsNpe() {
ImmutableList<String> of = ImmutableList.<String>of( ImmutableList<String> of = ImmutableList.<String>of(
"# URL: https://love.example/sloth.txt"); "# URL: https://love.example/sloth.txt");
thrown.expect(NullPointerException.class); NullPointerException thrown =
thrown.expectMessage("sloth missing '# Policy:"); expectThrows(
IdnTable.createFrom("sloth", of, Optional.<LanguageValidator>empty()); NullPointerException.class,
() -> IdnTable.createFrom("sloth", of, Optional.<LanguageValidator>empty()));
assertThat(thrown).hasMessageThat().contains("sloth missing '# Policy:");
} }
} }

View file

@ -15,14 +15,13 @@
package google.registry.tmch; package google.registry.tmch;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.assertThrows;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import google.registry.tmch.LordnLog.Result; import google.registry.tmch.LordnLog.Result;
import java.util.Map.Entry; import java.util.Map.Entry;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -30,9 +29,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class LordnLogTest { public class LordnLogTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
public static final ImmutableList<String> EXAMPLE_FROM_RFC = public static final ImmutableList<String> EXAMPLE_FROM_RFC =
ImmutableList.of( ImmutableList.of(
"1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z," "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,"
@ -89,29 +85,33 @@ public class LordnLogTest {
@Test @Test
public void testFailure_noDnLineMismatch() throws Exception { public void testFailure_noDnLineMismatch() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
LordnLog.parse(ImmutableList.of( IllegalArgumentException.class,
() ->
LordnLog.parse(
ImmutableList.of(
"1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,lolcat,accepted,no-warnings,1", "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,lolcat,accepted,no-warnings,1",
"roid,result-code")); "roid,result-code")));
} }
@Test @Test
public void testFailure_parseNull() throws Exception { public void testFailure_parseNull() throws Exception {
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class, () -> LordnLog.parse(null));
LordnLog.parse(null);
} }
@Test @Test
public void testFailure_parseEmpty() throws Exception { public void testFailure_parseEmpty() throws Exception {
thrown.expect(Exception.class); assertThrows(Exception.class, () -> LordnLog.parse(ImmutableList.of()));
LordnLog.parse(ImmutableList.of());
} }
@Test @Test
public void testFailure_parseMissingHeaderLine() throws Exception { public void testFailure_parseMissingHeaderLine() throws Exception {
thrown.expect(Exception.class); assertThrows(
LordnLog.parse(ImmutableList.of( Exception.class,
"1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,lolcat,accepted,no-warnings,0")); () ->
LordnLog.parse(
ImmutableList.of(
"1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,lolcat,accepted,no-warnings,0")));
} }
@Test @Test

View file

@ -20,6 +20,8 @@ import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.loadRegistrar; import static google.registry.testing.DatastoreHelper.loadRegistrar;
import static google.registry.testing.DatastoreHelper.persistActiveContact; import static google.registry.testing.DatastoreHelper.persistActiveContact;
import static google.registry.testing.DatastoreHelper.persistDomainAndEnqueueLordn; import static google.registry.testing.DatastoreHelper.persistDomainAndEnqueueLordn;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
import static org.mockito.Matchers.any; import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -49,7 +51,6 @@ import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -64,10 +65,6 @@ public class LordnTaskTest {
.withDatastore() .withDatastore()
.withTaskQueue() .withTaskQueue()
.build(); .build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();
@ -97,8 +94,9 @@ public class LordnTaskTest {
@Test @Test
public void test_convertTasksToCsv_throwsNpeOnNullTasks() throws Exception { public void test_convertTasksToCsv_throwsNpeOnNullTasks() throws Exception {
thrown.expect(NullPointerException.class); assertThrows(
LordnTask.convertTasksToCsv(null, clock.nowUtc(), "header"); NullPointerException.class,
() -> LordnTask.convertTasksToCsv(null, clock.nowUtc(), "header"));
} }
private DomainResource.Builder newDomainBuilder(DateTime applicationTime) { private DomainResource.Builder newDomainBuilder(DateTime applicationTime) {
@ -166,19 +164,26 @@ public class LordnTaskTest {
.setRepoId("9000-EXAMPLE") .setRepoId("9000-EXAMPLE")
.setCreationClientId("nonexistentRegistrar") .setCreationClientId("nonexistentRegistrar")
.build(); .build();
thrown.expect(IllegalStateException.class); IllegalStateException thrown =
thrown.expectMessage("No registrar found for client id: nonexistentRegistrar"); expectThrows(IllegalStateException.class, () -> persistDomainAndEnqueueLordn(domain));
persistDomainAndEnqueueLordn(domain); assertThat(thrown)
.hasMessageThat()
.contains("No registrar found for client id: nonexistentRegistrar");
} }
@Test @Test
public void test_enqueueDomainResourceTask_throwsNpeOnNullDomain() throws Exception { public void test_enqueueDomainResourceTask_throwsNpeOnNullDomain() throws Exception {
thrown.expect(NullPointerException.class); assertThrows(
ofy().transactNew(new VoidWork() { NullPointerException.class,
() ->
ofy()
.transactNew(
new VoidWork() {
@Override @Override
public void vrun() { public void vrun() {
LordnTask.enqueueDomainResourceTask(null); LordnTask.enqueueDomainResourceTask(null);
}}); }
}));
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -198,9 +203,9 @@ public class LordnTaskTest {
public void test_loadAllTasks_retryLogic_allFailures() throws Exception { public void test_loadAllTasks_retryLogic_allFailures() throws Exception {
Queue queue = mock(Queue.class); Queue queue = mock(Queue.class);
when(queue.leaseTasks(any(LeaseOptions.class))).thenThrow(TransientFailureException.class); when(queue.leaseTasks(any(LeaseOptions.class))).thenThrow(TransientFailureException.class);
thrown.expect(RuntimeException.class); RuntimeException thrown =
thrown.expectMessage("Error leasing tasks"); expectThrows(RuntimeException.class, () -> LordnTask.loadAllTasks(queue, "tld"));
LordnTask.loadAllTasks(queue, "tld"); assertThat(thrown).hasMessageThat().contains("Error leasing tasks");
} }
private static TaskHandle makeTaskHandle( private static TaskHandle makeTaskHandle(

View file

@ -25,6 +25,8 @@ import static google.registry.testing.DatastoreHelper.loadRegistrar;
import static google.registry.testing.DatastoreHelper.newDomainResource; import static google.registry.testing.DatastoreHelper.newDomainResource;
import static google.registry.testing.DatastoreHelper.persistDomainAndEnqueueLordn; import static google.registry.testing.DatastoreHelper.persistDomainAndEnqueueLordn;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
import static google.registry.util.UrlFetchUtils.getHeaderFirst; import static google.registry.util.UrlFetchUtils.getHeaderFirst;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
@ -55,7 +57,6 @@ import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Captor; import org.mockito.Captor;
@ -86,10 +87,6 @@ public class NordnUploadActionTest {
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Mock @Mock
private URLFetchService fetchService; private URLFetchService fetchService;
@ -202,17 +199,15 @@ public class NordnUploadActionTest {
public void testFailure_nullRegistryUser() throws Exception { public void testFailure_nullRegistryUser() throws Exception {
persistClaimsModeDomain(); persistClaimsModeDomain();
persistResource(Registry.get("tld").asBuilder().setLordnUsername(null).build()); persistResource(Registry.get("tld").asBuilder().setLordnUsername(null).build());
thrown.expect(VerifyException.class); VerifyException thrown = expectThrows(VerifyException.class, () -> action.run());
thrown.expectMessage("lordnUsername is not set for tld."); assertThat(thrown).hasMessageThat().contains("lordnUsername is not set for tld.");
action.run();
} }
@Test @Test
public void testFetchFailure() throws Exception { public void testFetchFailure() throws Exception {
persistClaimsModeDomain(); persistClaimsModeDomain();
when(httpResponse.getResponseCode()).thenReturn(SC_INTERNAL_SERVER_ERROR); when(httpResponse.getResponseCode()).thenReturn(SC_INTERNAL_SERVER_ERROR);
thrown.expect(UrlFetchException.class); assertThrows(UrlFetchException.class, () -> action.run());
action.run();
} }
private HTTPRequest getCapturedHttpRequest() throws Exception { private HTTPRequest getCapturedHttpRequest() throws Exception {

View file

@ -19,6 +19,8 @@ import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat; import static com.google.common.truth.Truth8.assertThat;
import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.util.UrlFetchUtils.getHeaderFirst; import static google.registry.util.UrlFetchUtils.getHeaderFirst;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT; import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT;
@ -40,7 +42,6 @@ import java.util.Optional;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Captor; import org.mockito.Captor;
@ -86,10 +87,6 @@ public class NordnVerifyActionTest {
.withDatastore() .withDatastore()
.withTaskQueue() .withTaskQueue()
.build(); .build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Mock @Mock
private URLFetchService fetchService; private URLFetchService fetchService;
@ -168,15 +165,13 @@ public class NordnVerifyActionTest {
@Test @Test
public void failureVerifyUnauthorized() throws Exception { public void failureVerifyUnauthorized() throws Exception {
when(httpResponse.getResponseCode()).thenReturn(SC_UNAUTHORIZED); when(httpResponse.getResponseCode()).thenReturn(SC_UNAUTHORIZED);
thrown.expect(Exception.class); assertThrows(Exception.class, () -> action.run());
action.run();
} }
@Test @Test
public void failureVerifyNotReady() throws Exception { public void failureVerifyNotReady() throws Exception {
when(httpResponse.getResponseCode()).thenReturn(SC_NO_CONTENT); when(httpResponse.getResponseCode()).thenReturn(SC_NO_CONTENT);
thrown.expect(ConflictException.class); ConflictException thrown = expectThrows(ConflictException.class, () -> action.run());
thrown.expectMessage("Not ready"); assertThat(thrown).hasMessageThat().contains("Not ready");
action.run();
} }
} }

View file

@ -15,6 +15,7 @@
package google.registry.tmch; package google.registry.tmch;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.expectThrows;
import static java.nio.charset.StandardCharsets.US_ASCII; import static java.nio.charset.StandardCharsets.US_ASCII;
import static org.joda.time.Duration.millis; import static org.joda.time.Duration.millis;
import static org.joda.time.Duration.standardDays; import static org.joda.time.Duration.standardDays;
@ -27,7 +28,6 @@ import google.registry.testing.FakeClock;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -38,10 +38,6 @@ public class SmdrlCsvParserTest {
@Rule @Rule
public final AppEngineRule appEngine = AppEngineRule.builder() public final AppEngineRule appEngine = AppEngineRule.builder()
.build(); .build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final FakeClock clock = new FakeClock(); private final FakeClock clock = new FakeClock();
private static final CharSource SMDRL_LATEST_CSV = private static final CharSource SMDRL_LATEST_CSV =
@ -110,31 +106,43 @@ public class SmdrlCsvParserTest {
@Test @Test
public void testFail_badVersion() throws Exception { public void testFail_badVersion() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("version"); expectThrows(
SmdrlCsvParser.parse(ImmutableList.of( IllegalArgumentException.class,
() ->
SmdrlCsvParser.parse(
ImmutableList.of(
"666,2013-11-24T23:30:04.3Z", "666,2013-11-24T23:30:04.3Z",
"smd-id,insertion-datetime", "smd-id,insertion-datetime",
"0000001681375789102250-65535,2013-08-09T12:00:00.0Z")); "0000001681375789102250-65535,2013-08-09T12:00:00.0Z")));
assertThat(thrown).hasMessageThat().contains("version");
} }
@Test @Test
public void testFail_badHeader() throws Exception { public void testFail_badHeader() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("header"); expectThrows(
SmdrlCsvParser.parse(ImmutableList.of( IllegalArgumentException.class,
() ->
SmdrlCsvParser.parse(
ImmutableList.of(
"1,2013-11-24T23:30:04.3Z", "1,2013-11-24T23:30:04.3Z",
"lol,cat", "lol,cat",
"0000001681375789102250-65535,2013-08-09T12:00:00.0Z")); "0000001681375789102250-65535,2013-08-09T12:00:00.0Z")));
assertThat(thrown).hasMessageThat().contains("header");
} }
@Test @Test
public void testFail_tooManyColumns() throws Exception { public void testFail_tooManyColumns() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("elements"); expectThrows(
SmdrlCsvParser.parse(ImmutableList.of( IllegalArgumentException.class,
() ->
SmdrlCsvParser.parse(
ImmutableList.of(
"1,2013-11-24T23:30:04.3Z", "1,2013-11-24T23:30:04.3Z",
"smd-id,insertion-datetime", "smd-id,insertion-datetime",
"0000001681375789102250-65535,haha,2013-08-09T12:00:00.0Z")); "0000001681375789102250-65535,haha,2013-08-09T12:00:00.0Z")));
assertThat(thrown).hasMessageThat().contains("elements");
} }
} }

View file

@ -27,7 +27,6 @@ import google.registry.testing.FakeClock;
import google.registry.testing.InjectRule; import google.registry.testing.InjectRule;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Captor; import org.mockito.Captor;
@ -50,9 +49,6 @@ public class TmchActionTestCase {
@Rule @Rule
public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule(); public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();

View file

@ -34,7 +34,6 @@ import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -49,10 +48,6 @@ public class TmchCertificateAuthorityTest {
public final AppEngineRule appEngine = AppEngineRule.builder() public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore() .withDatastore()
.build(); .build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();
@ -113,8 +108,10 @@ public class TmchCertificateAuthorityTest {
@Test @Test
public void testFailure_verifyRevoked() throws Exception { public void testFailure_verifyRevoked() throws Exception {
TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PILOT); TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PILOT);
thrown.expect(CertificateRevokedException.class); CertificateRevokedException thrown =
thrown.expectMessage("revoked, reason: KEY_COMPROMISE"); expectThrows(
tmchCertificateAuthority.verify(loadCertificate(REVOKED_TEST_CERTIFICATE)); CertificateRevokedException.class,
() -> tmchCertificateAuthority.verify(loadCertificate(REVOKED_TEST_CERTIFICATE)));
assertThat(thrown).hasMessageThat().contains("revoked, reason: KEY_COMPROMISE");
} }
} }

View file

@ -32,7 +32,6 @@ import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -49,9 +48,6 @@ public class TmchXmlSignatureTest {
.withDatastore() .withDatastore()
.build(); .build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();
@ -291,36 +287,31 @@ public class TmchXmlSignatureTest {
@Test @Test
public void testInvalidInvalidsignatureCourtAgentFrenchActive() throws Exception { public void testInvalidInvalidsignatureCourtAgentFrenchActive() throws Exception {
smdData = loadSmd("invalid/InvalidSignature-Court-Agent-French-Active.smd"); smdData = loadSmd("invalid/InvalidSignature-Court-Agent-French-Active.smd");
thrown.expect(XMLSignatureException.class); assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData));
tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testInvalidInvalidsignatureTrademarkAgentEnglishActive() throws Exception { public void testInvalidInvalidsignatureTrademarkAgentEnglishActive() throws Exception {
smdData = loadSmd("invalid/InvalidSignature-Trademark-Agent-English-Active.smd"); smdData = loadSmd("invalid/InvalidSignature-Trademark-Agent-English-Active.smd");
thrown.expect(XMLSignatureException.class); assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData));
tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testInvalidInvalidsignatureTrademarkAgentRussianActive() throws Exception { public void testInvalidInvalidsignatureTrademarkAgentRussianActive() throws Exception {
smdData = loadSmd("invalid/InvalidSignature-Trademark-Agent-Russian-Active.smd"); smdData = loadSmd("invalid/InvalidSignature-Trademark-Agent-Russian-Active.smd");
thrown.expect(XMLSignatureException.class); assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData));
tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testInvalidInvalidsignatureTreatystatuteAgentChineseActive() throws Exception { public void testInvalidInvalidsignatureTreatystatuteAgentChineseActive() throws Exception {
smdData = loadSmd("invalid/InvalidSignature-TreatyStatute-Agent-Chinese-Active.smd"); smdData = loadSmd("invalid/InvalidSignature-TreatyStatute-Agent-Chinese-Active.smd");
thrown.expect(XMLSignatureException.class); assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData));
tmchXmlSignature.verify(smdData);
} }
@Test @Test
public void testInvalidInvalidsignatureTreatystatuteAgentEnglishActive() throws Exception { public void testInvalidInvalidsignatureTreatystatuteAgentEnglishActive() throws Exception {
smdData = loadSmd("invalid/InvalidSignature-TreatyStatute-Agent-English-Active.smd"); smdData = loadSmd("invalid/InvalidSignature-TreatyStatute-Agent-English-Active.smd");
thrown.expect(XMLSignatureException.class); assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData));
tmchXmlSignature.verify(smdData);
} }
@Test @Test

View file

@ -15,11 +15,10 @@
package google.registry.tools.params; package google.registry.tools.params;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.assertThrows;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -27,9 +26,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class DateParameterTest { public class DateParameterTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final DateParameter instance = new DateParameter(); private final DateParameter instance = new DateParameter();
@Test @Test
@ -40,61 +36,52 @@ public class DateParameterTest {
@Test @Test
public void testConvert_numeric_throwsException() throws Exception { public void testConvert_numeric_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("1234"));
instance.convert("1234");
} }
@Test @Test
public void testConvert_validDateAndTime_throwsException() throws Exception { public void testConvert_validDateAndTime_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
instance.convert("2014-01-01T01:02:03.004Z"); IllegalArgumentException.class, () -> instance.convert("2014-01-01T01:02:03.004Z"));
} }
@Test @Test
public void testConvert_invalidDate_throwsException() throws Exception { public void testConvert_invalidDate_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("2014-13-33"));
instance.convert("2014-13-33");
} }
@Test @Test
public void testConvert_null_throwsException() throws Exception { public void testConvert_null_throwsException() throws Exception {
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class, () -> instance.convert(null));
instance.convert(null);
} }
@Test @Test
public void testConvert_empty_throwsException() throws Exception { public void testConvert_empty_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert(""));
instance.convert("");
} }
@Test @Test
public void testConvert_sillyString_throwsException() throws Exception { public void testConvert_sillyString_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("foo"));
instance.convert("foo");
} }
@Test @Test
public void testConvert_partialDate_throwsException() throws Exception { public void testConvert_partialDate_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("2014-01"));
instance.convert("2014-01");
} }
@Test @Test
public void testConvert_onlyTime_throwsException() throws Exception { public void testConvert_onlyTime_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("T01:02:03"));
instance.convert("T01:02:03");
} }
@Test @Test
public void testConvert_partialDateAndPartialTime_throwsException() throws Exception { public void testConvert_partialDateAndPartialTime_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("9T9"));
instance.convert("9T9");
} }
@Test @Test
public void testConvert_dateAndPartialTime_throwsException() throws Exception { public void testConvert_dateAndPartialTime_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("2014-01-01T01:02"));
instance.convert("2014-01-01T01:02");
} }
} }

View file

@ -15,23 +15,19 @@
package google.registry.tools.params; package google.registry.tools.params;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import static org.joda.time.DateTimeZone.UTC; import static org.joda.time.DateTimeZone.UTC;
import com.beust.jcommander.ParameterException; import com.beust.jcommander.ParameterException;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
/** Unit tests for {@link DateTimeParameter}. */ /** Unit tests for {@link DateTimeParameter}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class DateTimeParameterTest { public class DateTimeParameterTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final DateTimeParameter instance = new DateTimeParameter(); private final DateTimeParameter instance = new DateTimeParameter();
@Test @Test
@ -60,69 +56,59 @@ public class DateTimeParameterTest {
@Test @Test
public void testConvert_null_throwsException() throws Exception { public void testConvert_null_throwsException() throws Exception {
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class, () -> instance.convert(null));
instance.convert(null);
} }
@Test @Test
public void testConvert_empty_throwsException() throws Exception { public void testConvert_empty_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert(""));
instance.convert("");
} }
@Test @Test
public void testConvert_sillyString_throwsException() throws Exception { public void testConvert_sillyString_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("foo"));
instance.convert("foo");
} }
@Test @Test
public void testConvert_partialDate_throwsException() throws Exception { public void testConvert_partialDate_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("2014-01"));
instance.convert("2014-01");
} }
@Test @Test
public void testConvert_onlyDate_throwsException() throws Exception { public void testConvert_onlyDate_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("2014-01-01"));
instance.convert("2014-01-01");
} }
@Test @Test
public void testConvert_partialTime_throwsException() throws Exception { public void testConvert_partialTime_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("T01:02"));
instance.convert("T01:02");
} }
@Test @Test
public void testConvert_onlyTime_throwsException() throws Exception { public void testConvert_onlyTime_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("T01:02:03"));
instance.convert("T01:02:03");
} }
@Test @Test
public void testConvert_partialDateAndPartialTime_throwsException() throws Exception { public void testConvert_partialDateAndPartialTime_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("9T9"));
instance.convert("9T9");
} }
@Test @Test
public void testConvert_dateAndPartialTime_throwsException() throws Exception { public void testConvert_dateAndPartialTime_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("2014-01-01T01:02"));
instance.convert("2014-01-01T01:02");
} }
@Test @Test
public void testConvert_noTimeZone_throwsException() throws Exception { public void testConvert_noTimeZone_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("2014-01-01T01:02:03"));
instance.convert("2014-01-01T01:02:03");
} }
@Test @Test
public void testValidate_sillyString_throwsParameterException() throws Exception { public void testValidate_sillyString_throwsParameterException() throws Exception {
thrown.expect(ParameterException.class); ParameterException thrown =
thrown.expectMessage("--time=foo not an ISO"); expectThrows(ParameterException.class, () -> instance.validate("--time", "foo"));
instance.validate("--time", "foo"); assertThat(thrown).hasMessageThat().contains("--time=foo not an ISO");
} }
@Test @Test

View file

@ -15,23 +15,19 @@
package google.registry.tools.params; package google.registry.tools.params;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import com.beust.jcommander.ParameterException; import com.beust.jcommander.ParameterException;
import org.joda.time.Duration; import org.joda.time.Duration;
import org.joda.time.Period; import org.joda.time.Period;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
/** Unit tests for {@link DurationParameter}. */ /** Unit tests for {@link DurationParameter}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class DurationParameterTest { public class DurationParameterTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final DurationParameter instance = new DurationParameter(); private final DurationParameter instance = new DurationParameter();
@Test @Test
@ -51,50 +47,43 @@ public class DurationParameterTest {
@Test @Test
public void testIsoMissingP_notAllowed() throws Exception { public void testIsoMissingP_notAllowed() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> Period.parse("T36H"));
Period.parse("T36H");
} }
@Test @Test
public void testIsoMissingPT_notAllowed() throws Exception { public void testIsoMissingPT_notAllowed() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> Period.parse("36H"));
Period.parse("36H");
} }
@Test @Test
public void testConvert_isoMissingP_notAllowed() throws Exception { public void testConvert_isoMissingP_notAllowed() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("T36H"));
instance.convert("T36H");
} }
@Test @Test
public void testConvert_null_throws() throws Exception { public void testConvert_null_throws() throws Exception {
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class, () -> instance.convert(null));
instance.convert(null);
} }
@Test @Test
public void testConvert_empty_throws() throws Exception { public void testConvert_empty_throws() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert(""));
instance.convert("");
} }
@Test @Test
public void testConvert_numeric_throws() throws Exception { public void testConvert_numeric_throws() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("1234"));
instance.convert("1234");
} }
@Test @Test
public void testConvert_sillyString_throws() throws Exception { public void testConvert_sillyString_throws() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("foo"));
instance.convert("foo");
} }
@Test @Test
public void testValidate_sillyString_throws() throws Exception { public void testValidate_sillyString_throws() throws Exception {
thrown.expect(ParameterException.class); ParameterException thrown =
thrown.expectMessage("--time=foo not an"); expectThrows(ParameterException.class, () -> instance.validate("--time", "foo"));
instance.validate("--time", "foo"); assertThat(thrown).hasMessageThat().contains("--time=foo not an");
} }
} }

View file

@ -15,11 +15,10 @@
package google.registry.tools.params; package google.registry.tools.params;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.expectThrows;
import google.registry.model.registry.Registry.TldState; import google.registry.model.registry.Registry.TldState;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -27,9 +26,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class EnumParameterTest { public class EnumParameterTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
// There's no additional functionality exposed by this (or any other) EnumParameter, but using // There's no additional functionality exposed by this (or any other) EnumParameter, but using
// this in the test as EnumParameter is abstract. // this in the test as EnumParameter is abstract.
private final TldStateParameter instance = new TldStateParameter(); private final TldStateParameter instance = new TldStateParameter();
@ -41,9 +37,11 @@ public class EnumParameterTest {
@Test @Test
public void testFailure_badValue() throws Exception { public void testFailure_badValue() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage( expectThrows(IllegalArgumentException.class, () -> instance.convert("GENERAL_SUNRUSH"));
assertThat(thrown)
.hasMessageThat()
.contains(
"No enum constant google.registry.model.registry.Registry.TldState.GENERAL_SUNRUSH"); "No enum constant google.registry.model.registry.Registry.TldState.GENERAL_SUNRUSH");
instance.convert("GENERAL_SUNRUSH");
} }
} }

View file

@ -15,23 +15,19 @@
package google.registry.tools.params; package google.registry.tools.params;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import com.beust.jcommander.ParameterException; import com.beust.jcommander.ParameterException;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.Interval; import org.joda.time.Interval;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
/** Unit tests for {@link IntervalParameter}. */ /** Unit tests for {@link IntervalParameter}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class IntervalParameterTest { public class IntervalParameterTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final IntervalParameter instance = new IntervalParameter(); private final IntervalParameter instance = new IntervalParameter();
@Test @Test
@ -44,38 +40,35 @@ public class IntervalParameterTest {
@Test @Test
public void testConvert_singleDate() throws Exception { public void testConvert_singleDate() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("2004-06-09T12:30:00Z"));
instance.convert("2004-06-09T12:30:00Z");
} }
@Test @Test
public void testConvert_backwardsInterval() throws Exception { public void testConvert_backwardsInterval() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
instance.convert("2004-07-10T13:30:00Z/2004-06-09T12:30:00Z"); IllegalArgumentException.class,
() -> instance.convert("2004-07-10T13:30:00Z/2004-06-09T12:30:00Z"));
} }
@Test @Test
public void testConvert_empty_throws() throws Exception { public void testConvert_empty_throws() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert(""));
instance.convert("");
} }
@Test @Test
public void testConvert_null_throws() throws Exception { public void testConvert_null_throws() throws Exception {
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class, () -> instance.convert(null));
instance.convert(null);
} }
@Test @Test
public void testConvert_sillyString_throws() throws Exception { public void testConvert_sillyString_throws() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("foo"));
instance.convert("foo");
} }
@Test @Test
public void testValidate_sillyString_throws() throws Exception { public void testValidate_sillyString_throws() throws Exception {
thrown.expect(ParameterException.class); ParameterException thrown =
thrown.expectMessage("--time=foo not an"); expectThrows(ParameterException.class, () -> instance.validate("--time", "foo"));
instance.validate("--time", "foo"); assertThat(thrown).hasMessageThat().contains("--time=foo not an");
} }
} }

View file

@ -15,6 +15,8 @@
package google.registry.tools.params; package google.registry.tools.params;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import google.registry.tools.params.KeyValueMapParameter.CurrencyUnitToStringMap; import google.registry.tools.params.KeyValueMapParameter.CurrencyUnitToStringMap;
@ -22,19 +24,13 @@ import google.registry.tools.params.KeyValueMapParameter.StringToIntegerMap;
import google.registry.tools.params.KeyValueMapParameter.StringToStringMap; import google.registry.tools.params.KeyValueMapParameter.StringToStringMap;
import org.joda.money.CurrencyUnit; import org.joda.money.CurrencyUnit;
import org.joda.money.IllegalCurrencyException; import org.joda.money.IllegalCurrencyException;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
/** Unit tests for {@link KeyValueMapParameter}. */ /** Unit tests for {@link KeyValueMapParameter}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class KeyValueMapParameterTest { public class KeyValueMapParameterTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final StringToStringMap stringToStringInstance = new StringToStringMap(); private final StringToStringMap stringToStringInstance = new StringToStringMap();
private final StringToIntegerMap stringToIntegerInstance = new StringToIntegerMap(); private final StringToIntegerMap stringToIntegerInstance = new StringToIntegerMap();
private final CurrencyUnitToStringMap currencyUnitToStringMap = new CurrencyUnitToStringMap(); private final CurrencyUnitToStringMap currencyUnitToStringMap = new CurrencyUnitToStringMap();
@ -92,51 +88,51 @@ public class KeyValueMapParameterTest {
@Test @Test
public void testFailure_convertStringToInteger_badType() throws Exception { public void testFailure_convertStringToInteger_badType() throws Exception {
thrown.expect(NumberFormatException.class); assertThrows(
stringToIntegerInstance.convert("key=1,key2=foo"); NumberFormatException.class, () -> stringToIntegerInstance.convert("key=1,key2=foo"));
} }
@Test @Test
public void testFailure_convertCurrencyUnitToString_badType() throws Exception { public void testFailure_convertCurrencyUnitToString_badType() throws Exception {
thrown.expect(IllegalCurrencyException.class); IllegalCurrencyException thrown =
thrown.expectMessage("XYZ"); expectThrows(
currencyUnitToStringMap.convert("USD=123abc,XYZ=xyz789"); IllegalCurrencyException.class,
() -> currencyUnitToStringMap.convert("USD=123abc,XYZ=xyz789"));
assertThat(thrown).hasMessageThat().contains("XYZ");
} }
@Test @Test
public void testFailure_convertStringToString_badSeparator() throws Exception { public void testFailure_convertStringToString_badSeparator() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
stringToStringInstance.convert("key=foo&key2=bar"); IllegalArgumentException.class, () -> stringToStringInstance.convert("key=foo&key2=bar"));
} }
@Test @Test
public void testFailure_convertStringToInteger_badSeparator() throws Exception { public void testFailure_convertStringToInteger_badSeparator() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
stringToIntegerInstance.convert("key=1&key2=2"); IllegalArgumentException.class, () -> stringToIntegerInstance.convert("key=1&key2=2"));
} }
@Test @Test
public void testFailure_convertCurrencyUnitToString_badSeparator() throws Exception { public void testFailure_convertCurrencyUnitToString_badSeparator() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(
currencyUnitToStringMap.convert("USD=123abc&JPY=xyz789"); IllegalArgumentException.class,
() -> currencyUnitToStringMap.convert("USD=123abc&JPY=xyz789"));
} }
@Test @Test
public void testFailure_convertStringToString_badFormat() throws Exception { public void testFailure_convertStringToString_badFormat() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> stringToStringInstance.convert("foo"));
stringToStringInstance.convert("foo");
} }
@Test @Test
public void testFailure_convertStringToInteger_badFormat() throws Exception { public void testFailure_convertStringToInteger_badFormat() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> stringToIntegerInstance.convert("foo"));
stringToIntegerInstance.convert("foo");
} }
@Test @Test
public void testFailure_convertCurrencyUnitToString_badFormat() throws Exception { public void testFailure_convertCurrencyUnitToString_badFormat() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> currencyUnitToStringMap.convert("foo"));
currencyUnitToStringMap.convert("foo");
} }
} }

View file

@ -15,22 +15,18 @@
package google.registry.tools.params; package google.registry.tools.params;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import com.beust.jcommander.ParameterException; import com.beust.jcommander.ParameterException;
import org.joda.money.Money; import org.joda.money.Money;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
/** Unit tests for {@link MoneyParameter}. */ /** Unit tests for {@link MoneyParameter}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class MoneyParameterTest { public class MoneyParameterTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final MoneyParameter instance = new MoneyParameter(); private final MoneyParameter instance = new MoneyParameter();
@Test @Test
@ -55,33 +51,29 @@ public class MoneyParameterTest {
@Test @Test
public void testConvert_badCurrency_throws() throws Exception { public void testConvert_badCurrency_throws() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("FOO 1337"));
instance.convert("FOO 1337");
} }
@Test @Test
public void testConvert_null_throws() throws Exception { public void testConvert_null_throws() throws Exception {
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class, () -> instance.convert(null));
instance.convert(null);
} }
@Test @Test
public void testConvert_empty_throws() throws Exception { public void testConvert_empty_throws() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert(""));
instance.convert("");
} }
@Test @Test
public void testConvert_sillyString_throws() throws Exception { public void testConvert_sillyString_throws() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("foo"));
instance.convert("foo");
} }
@Test @Test
public void testValidate_sillyString_throws() throws Exception { public void testValidate_sillyString_throws() throws Exception {
thrown.expect(ParameterException.class); ParameterException thrown =
thrown.expectMessage("--money=foo not valid"); expectThrows(ParameterException.class, () -> instance.validate("--money", "foo"));
instance.validate("--money", "foo"); assertThat(thrown).hasMessageThat().contains("--money=foo not valid");
} }
@Test @Test

View file

@ -15,6 +15,8 @@
package google.registry.tools.params; package google.registry.tools.params;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.not;
@ -31,7 +33,6 @@ import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermissions; import java.nio.file.attribute.PosixFilePermissions;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder; import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -39,10 +40,6 @@ import org.junit.runners.JUnit4;
/** Unit tests for {@link PathParameter}. */ /** Unit tests for {@link PathParameter}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class PathParameterTest { public class PathParameterTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final TemporaryFolder folder = new TemporaryFolder(); public final TemporaryFolder folder = new TemporaryFolder();
@ -57,14 +54,12 @@ public class PathParameterTest {
@Test @Test
public void testConvert_null_throws() throws Exception { public void testConvert_null_throws() throws Exception {
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class, () -> vanilla.convert(null));
vanilla.convert(null);
} }
@Test @Test
public void testConvert_empty_throws() throws Exception { public void testConvert_empty_throws() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> vanilla.convert(""));
vanilla.convert("");
} }
@Test @Test
@ -86,8 +81,7 @@ public class PathParameterTest {
@Test @Test
public void testConvert_uriNotProvided() throws Exception { public void testConvert_uriNotProvided() throws Exception {
thrown.expect(FileSystemNotFoundException.class); assertThrows(FileSystemNotFoundException.class, () -> vanilla.convert("bog://bucket/lolcat"));
vanilla.convert("bog://bucket/lolcat");
} }
// =========================== Test InputFile Validate ======================================== // =========================== Test InputFile Validate ========================================
@ -101,25 +95,29 @@ public class PathParameterTest {
@Test @Test
public void testInputFileValidate_missingFile_throws() throws Exception { public void testInputFileValidate_missingFile_throws() throws Exception {
thrown.expect(ParameterException.class); ParameterException thrown =
thrown.expectMessage("not found"); expectThrows(
inputFile.validate("input", new File(folder.getRoot(), "foo").toString()); ParameterException.class,
() -> inputFile.validate("input", new File(folder.getRoot(), "foo").toString()));
assertThat(thrown).hasMessageThat().contains("not found");
} }
@Test @Test
public void testInputFileValidate_directory_throws() throws Exception { public void testInputFileValidate_directory_throws() throws Exception {
thrown.expect(ParameterException.class); ParameterException thrown =
thrown.expectMessage("is a directory"); expectThrows(
inputFile.validate("input", folder.getRoot().toString()); ParameterException.class,
() -> inputFile.validate("input", folder.getRoot().toString()));
assertThat(thrown).hasMessageThat().contains("is a directory");
} }
@Test @Test
public void testInputFileValidate_unreadableFile_throws() throws Exception { public void testInputFileValidate_unreadableFile_throws() throws Exception {
Path file = Paths.get(folder.newFile().toString()); Path file = Paths.get(folder.newFile().toString());
Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("-w-------")); Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("-w-------"));
thrown.expect(ParameterException.class); ParameterException thrown =
thrown.expectMessage("not readable"); expectThrows(ParameterException.class, () -> inputFile.validate("input", file.toString()));
inputFile.validate("input", file.toString()); assertThat(thrown).hasMessageThat().contains("not readable");
} }
// =========================== Test OutputFile Validate ======================================== // =========================== Test OutputFile Validate ========================================
@ -144,33 +142,35 @@ public class PathParameterTest {
@Test @Test
public void testOutputFileValidate_directory_throws() throws Exception { public void testOutputFileValidate_directory_throws() throws Exception {
thrown.expect(ParameterException.class); ParameterException thrown =
thrown.expectMessage("is a directory"); expectThrows(
outputFile.validate("input", folder.getRoot().toString()); ParameterException.class,
() -> outputFile.validate("input", folder.getRoot().toString()));
assertThat(thrown).hasMessageThat().contains("is a directory");
} }
@Test @Test
public void testOutputFileValidate_notWritable_throws() throws Exception { public void testOutputFileValidate_notWritable_throws() throws Exception {
Path file = Paths.get(folder.newFile().toString()); Path file = Paths.get(folder.newFile().toString());
Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("r--------")); Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("r--------"));
thrown.expect(ParameterException.class); ParameterException thrown =
thrown.expectMessage("not writable"); expectThrows(ParameterException.class, () -> outputFile.validate("input", file.toString()));
outputFile.validate("input", file.toString()); assertThat(thrown).hasMessageThat().contains("not writable");
} }
@Test @Test
public void testOutputFileValidate_parentDirMissing_throws() throws Exception { public void testOutputFileValidate_parentDirMissing_throws() throws Exception {
Path file = Paths.get(folder.getRoot().toString(), "MISSINGNO", "foo.txt"); Path file = Paths.get(folder.getRoot().toString(), "MISSINGNO", "foo.txt");
thrown.expect(ParameterException.class); ParameterException thrown =
thrown.expectMessage("parent dir doesn't exist"); expectThrows(ParameterException.class, () -> outputFile.validate("input", file.toString()));
outputFile.validate("input", file.toString()); assertThat(thrown).hasMessageThat().contains("parent dir doesn't exist");
} }
@Test @Test
public void testOutputFileValidate_parentDirIsFile_throws() throws Exception { public void testOutputFileValidate_parentDirIsFile_throws() throws Exception {
Path file = Paths.get(folder.newFile().toString(), "foo.txt"); Path file = Paths.get(folder.newFile().toString(), "foo.txt");
thrown.expect(ParameterException.class); ParameterException thrown =
thrown.expectMessage("parent is non-directory"); expectThrows(ParameterException.class, () -> outputFile.validate("input", file.toString()));
outputFile.validate("input", file.toString()); assertThat(thrown).hasMessageThat().contains("parent is non-directory");
} }
} }

View file

@ -15,20 +15,15 @@
package google.registry.tools.params; package google.registry.tools.params;
import static com.google.common.truth.Truth8.assertThat; import static com.google.common.truth.Truth8.assertThat;
import static google.registry.testing.JUnitBackports.assertThrows;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
/** Unit tests for {@link PhoneNumberParameter}. */ /** Unit tests for {@link PhoneNumberParameter}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class PhoneNumberParameterTest { public class PhoneNumberParameterTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final OptionalPhoneNumberParameter instance = new OptionalPhoneNumberParameter(); private final OptionalPhoneNumberParameter instance = new OptionalPhoneNumberParameter();
@Test @Test
@ -38,8 +33,7 @@ public class PhoneNumberParameterTest {
@Test @Test
public void testConvert_sillyString_throws() throws Exception { public void testConvert_sillyString_throws() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("foo"));
instance.convert("foo");
} }
@Test @Test

View file

@ -15,22 +15,18 @@
package google.registry.tools.params; package google.registry.tools.params;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows;
import com.beust.jcommander.ParameterException; import com.beust.jcommander.ParameterException;
import org.joda.time.YearMonth; import org.joda.time.YearMonth;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
/** Unit tests for {@link YearMonthParameter}. */ /** Unit tests for {@link YearMonthParameter}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class YearMonthParameterTest { public class YearMonthParameterTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final YearMonthParameter instance = new YearMonthParameter(); private final YearMonthParameter instance = new YearMonthParameter();
@Test @Test
@ -40,39 +36,34 @@ public class YearMonthParameterTest {
@Test @Test
public void testConvert_null_throwsException() throws Exception { public void testConvert_null_throwsException() throws Exception {
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class, () -> instance.convert(null));
instance.convert(null);
} }
@Test @Test
public void testConvert_empty_throwsException() throws Exception { public void testConvert_empty_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert(""));
instance.convert("");
} }
@Test @Test
public void testConvert_sillyString_throwsException() throws Exception { public void testConvert_sillyString_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("foo"));
instance.convert("foo");
} }
@Test @Test
public void testConvert_wrongOrder() throws Exception { public void testConvert_wrongOrder() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("12-1984"));
instance.convert("12-1984");
} }
@Test @Test
public void testConvert_noHyphen() throws Exception { public void testConvert_noHyphen() throws Exception {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> instance.convert("198412"));
instance.convert("198412");
} }
@Test @Test
public void testValidate_sillyString_throwsParameterException() throws Exception { public void testValidate_sillyString_throwsParameterException() throws Exception {
thrown.expect(ParameterException.class); ParameterException thrown =
thrown.expectMessage("--time=foo not a valid"); expectThrows(ParameterException.class, () -> instance.validate("--time", "foo"));
instance.validate("--time", "foo"); assertThat(thrown).hasMessageThat().contains("--time=foo not a valid");
} }
@Test @Test

View file

@ -32,7 +32,6 @@ import google.registry.testing.InjectRule;
import java.util.Optional; import java.util.Optional;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -46,10 +45,6 @@ public class CreateGroupsActionTest {
public final AppEngineRule appEngine = AppEngineRule.builder() public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore() .withDatastore()
.build(); .build();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();
@ -67,17 +62,21 @@ public class CreateGroupsActionTest {
@Test @Test
public void test_invalidRequest_missingClientId() throws Exception { public void test_invalidRequest_missingClientId() throws Exception {
thrown.expect(BadRequestException.class); BadRequestException thrown = expectThrows(BadRequestException.class, () -> runAction(null));
thrown.expectMessage("Error creating Google Groups, missing parameter: clientId"); assertThat(thrown)
runAction(null); .hasMessageThat()
.contains("Error creating Google Groups, missing parameter: clientId");
} }
@Test @Test
public void test_invalidRequest_invalidClientId() throws Exception { public void test_invalidRequest_invalidClientId() throws Exception {
thrown.expect(BadRequestException.class); BadRequestException thrown =
thrown.expectMessage( expectThrows(BadRequestException.class, () -> runAction("completelyMadeUpClientId"));
"Error creating Google Groups; could not find registrar with id completelyMadeUpClientId"); assertThat(thrown)
runAction("completelyMadeUpClientId"); .hasMessageThat()
.contains(
"Error creating Google Groups; "
+ "could not find registrar with id completelyMadeUpClientId");
} }
@Test @Test

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