Migrate final try/catch test assertions to use assert/expectThrows

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=182091814
This commit is contained in:
mcilwain 2018-01-16 12:08:08 -08:00 committed by Ben McIlwain
parent fe7cc4f782
commit c416b3892d
17 changed files with 124 additions and 172 deletions

View file

@ -15,7 +15,6 @@
package google.registry.batch;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assert_;
import static google.registry.model.EppResourceUtils.loadByForeignKey;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.testing.DatastoreHelper.createTld;
@ -26,6 +25,7 @@ import static google.registry.testing.DatastoreHelper.persistDeletedDomain;
import static google.registry.testing.DatastoreHelper.persistDomainAsDeleted;
import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.DatastoreHelper.persistSimpleResource;
import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.testing.TaskQueueHelper.assertDnsTasksEnqueued;
import static google.registry.util.DateTimeUtils.END_OF_TIME;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
@ -207,13 +207,8 @@ public class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDa
.setCreationTimeForTest(DateTime.now(UTC).minusYears(1))
.build());
action.registryAdminClientId = null;
try {
runMapreduce();
} catch (IllegalStateException e) {
assertThat(e).hasMessageThat().contains("Registry admin client ID must be configured");
return;
}
assert_().fail("Expected IllegalStateException");
IllegalStateException thrown = expectThrows(IllegalStateException.class, this::runMapreduce);
assertThat(thrown).hasMessageThat().contains("Registry admin client ID must be configured");
}
/**

View file

@ -15,10 +15,10 @@
package google.registry.billing;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static google.registry.testing.DatastoreHelper.loadRegistrar;
import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.GcsTestingUtils.writeGcsFile;
import static google.registry.testing.JUnitBackports.expectThrows;
import static java.nio.charset.StandardCharsets.UTF_8;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import static org.mockito.Matchers.any;
@ -169,12 +169,8 @@ public class CopyDetailReportsActionTest {
when(driveConnection.createFile(any(), any(), any(), any()))
.thenThrow(new IOException("expected"));
try {
action.run();
assertWithMessage("Expected a runtime exception to be thrown!").fail();
} catch (RuntimeException e) {
assertThat(e).hasMessageThat().isEqualTo("java.io.IOException: expected");
}
RuntimeException thrown = expectThrows(RuntimeException.class, action::run);
assertThat(thrown).hasMessageThat().isEqualTo("java.io.IOException: expected");
verify(driveConnection, times(3))
.createFile(
"invoice_details_2017-10_TheRegistrar_hello.csv",

View file

@ -16,13 +16,13 @@ package google.registry.export;
import static com.google.appengine.tools.cloudstorage.GcsServiceFactory.createGcsService;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistActiveDomain;
import static google.registry.testing.DatastoreHelper.persistActiveDomainApplication;
import static google.registry.testing.DatastoreHelper.persistDeletedDomain;
import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.GcsTestingUtils.readGcsFile;
import static google.registry.testing.JUnitBackports.assertThrows;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.appengine.tools.cloudstorage.GcsFilename;
@ -90,16 +90,12 @@ public class ExportDomainListsActionTest extends MapreduceTestCase<ExportDomainL
assertThat(Splitter.on('\n').splitToList(tlds)).containsExactly("onetwo.tld", "rudnitzky.tld");
// Make sure that the test TLD file wasn't written out.
GcsFilename nonexistentFile = new GcsFilename("outputbucket", "testtld.txt");
try {
readGcsFile(gcsService, nonexistentFile);
assertWithMessage("Expected FileNotFoundException to be thrown").fail();
} catch (FileNotFoundException e) {
assertThrows(FileNotFoundException.class, () -> readGcsFile(gcsService, nonexistentFile));
ListResult ls = gcsService.list("outputbucket", ListOptions.DEFAULT);
assertThat(ls.next().getName()).isEqualTo("tld.txt");
// Make sure that no other files were written out.
assertThat(ls.hasNext()).isFalse();
}
}
@Test
public void test_outputsDomainsFromDifferentTldsToMultipleFiles() throws Exception {

View file

@ -15,12 +15,12 @@
package google.registry.export;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static google.registry.export.ExportReservedTermsAction.EXPORT_MIME_TYPE;
import static google.registry.export.ExportReservedTermsAction.RESERVED_TERMS_FILENAME;
import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistReservedList;
import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.expectThrows;
import static java.nio.charset.StandardCharsets.UTF_8;
import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
import static javax.servlet.http.HttpServletResponse.SC_OK;
@ -123,26 +123,18 @@ public class ExportReservedTermsActionTest {
any(MediaType.class),
anyString(),
any(byte[].class))).thenThrow(new IOException("errorMessage"));
try {
runAction("tld");
assertWithMessage("Expected RuntimeException to be thrown").fail();
} catch (RuntimeException e) {
RuntimeException thrown = expectThrows(RuntimeException.class, () -> runAction("tld"));
verify(response).setStatus(SC_INTERNAL_SERVER_ERROR);
assertThat(e).hasCauseThat().hasMessageThat().isEqualTo("errorMessage");
}
assertThat(thrown).hasCauseThat().hasMessageThat().isEqualTo("errorMessage");
}
@Test
public void test_uploadFileToDrive_failsWhenTldDoesntExist() throws Exception {
try {
runAction("fakeTld");
assertWithMessage("Expected RuntimeException to be thrown").fail();
} catch (RuntimeException e) {
RuntimeException thrown = expectThrows(RuntimeException.class, () -> runAction("fakeTld"));
verify(response).setStatus(SC_INTERNAL_SERVER_ERROR);
assertThat(e)
assertThat(thrown)
.hasCauseThat()
.hasMessageThat()
.isEqualTo("No registry object found for fakeTld");
}
}
}

View file

@ -17,7 +17,6 @@ package google.registry.flows.domain;
import static com.google.common.collect.Iterables.getLast;
import static com.google.common.io.BaseEncoding.base16;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assert_;
import static google.registry.model.index.DomainApplicationIndex.loadActiveApplicationsByDomainName;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.testing.DatastoreHelper.assertNoBillingEvents;
@ -1603,22 +1602,15 @@ public class DomainApplicationCreateFlowTest
persistContactsAndHosts();
clock.advanceOneMilli();
persistActiveDomain(getUniqueIdFromCommand());
try {
runFlow();
assert_()
.fail(
"Expected to throw ResourceAlreadyExistsException with message "
+ "Object with given ID (%s) already exists",
getUniqueIdFromCommand());
} catch (ResourceAlreadyExistsException e) {
ResourceAlreadyExistsException thrown =
expectThrows(ResourceAlreadyExistsException.class, this::runFlow);
assertAboutEppExceptions()
.that(e)
.that(thrown)
.marshalsToXml()
.and()
.hasMessage(
String.format("Object with given ID (%s) already exists", getUniqueIdFromCommand()));
}
}
@Test
public void testFailure_registrantNotWhitelisted() throws Exception {
@ -1631,7 +1623,7 @@ public class DomainApplicationCreateFlowTest
.build());
RegistrantNotAllowedException thrown =
expectThrows(RegistrantNotAllowedException.class, this::runFlow);
assertThat(thrown).hasMessageThat().contains("jd1234");
assertAboutEppExceptions().that(thrown).marshalsToXml().and().hasMessageThatContains("jd1234");
}
@Test
@ -1644,7 +1636,11 @@ public class DomainApplicationCreateFlowTest
.build());
NameserversNotAllowedForTldException thrown =
expectThrows(NameserversNotAllowedForTldException.class, this::runFlow);
assertThat(thrown).hasMessageThat().contains("ns1.example.net");
assertAboutEppExceptions()
.that(thrown)
.marshalsToXml()
.and()
.hasMessageThatContains("ns1.example.net");
}
@Test

View file

@ -16,7 +16,6 @@ package google.registry.flows.domain;
import static com.google.common.io.BaseEncoding.base16;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assert_;
import static com.google.common.truth.Truth8.assertThat;
import static google.registry.model.domain.fee.Fee.FEE_EXTENSION_URIS;
import static google.registry.model.eppcommon.StatusValue.OK;
@ -998,22 +997,15 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
public void testFailure_alreadyExists() throws Exception {
persistContactsAndHosts();
persistActiveDomain(getUniqueIdFromCommand());
try {
runFlow();
assert_()
.fail(
"Expected to throw ResourceAlreadyExistsException with message "
+ "Object with given ID (%s) already exists",
getUniqueIdFromCommand());
} catch (ResourceAlreadyExistsException e) {
ResourceAlreadyExistsException thrown =
expectThrows(ResourceAlreadyExistsException.class, this::runFlow);
assertAboutEppExceptions()
.that(e)
.that(thrown)
.marshalsToXml()
.and()
.hasMessage(
String.format("Object with given ID (%s) already exists", getUniqueIdFromCommand()));
}
}
@Test
public void testFailure_reserved() throws Exception {

View file

@ -64,8 +64,8 @@ public final class CommitLogManifestInputTest {
reader.beginSlice();
seen.add(reader.next());
try {
reader.next();
assert_().fail("Unexpected element");
Key<CommitLogManifest> key = reader.next();
assert_().fail("Unexpected element: " + key);
} catch (NoSuchElementException expected) {
}
}
@ -88,10 +88,12 @@ public final class CommitLogManifestInputTest {
reader.beginShard();
reader.beginSlice();
try {
Key<CommitLogManifest> key = null;
for (int i = 0; i < 10; i++) {
seen.add(reader.next());
key = reader.next();
seen.add(key);
}
assert_().fail("Unexpected element");
assert_().fail("Unexpected element: " + key);
} catch (NoSuchElementException expected) {
}
}
@ -114,10 +116,12 @@ public final class CommitLogManifestInputTest {
reader.beginShard();
reader.beginSlice();
try {
Key<CommitLogManifest> key = null;
for (int i = 0; i < 10; i++) {
seen.add(reader.next());
key = reader.next();
seen.add(key);
}
assert_().fail("Unexpected element");
assert_().fail("Unexpected element: " + key);
} catch (NoSuchElementException expected) {
}
}

View file

@ -140,8 +140,8 @@ public class EppResourceInputsTest {
reader.beginSlice();
seen.add(reader.next());
try {
reader.next();
assert_().fail("Unexpected element");
Key<DomainBase> key = reader.next();
assert_().fail("Unexpected element: " + key);
} catch (NoSuchElementException expected) {
}
}
@ -165,8 +165,8 @@ public class EppResourceInputsTest {
reader.beginSlice();
seen.add(reader.next());
try {
reader.next();
assert_().fail("Unexpected element");
DomainResource domain = reader.next();
assert_().fail("Unexpected element: " + domain);
} catch (NoSuchElementException expected) {
}
}

View file

@ -15,7 +15,7 @@
package google.registry.reporting;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.testing.TaskQueueHelper.assertNoTasksEnqueued;
import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
import static org.mockito.Mockito.mock;
@ -135,13 +135,9 @@ public class IcannReportingStagingActionTest {
createAction(ImmutableList.of(ReportType.ACTIVITY));
when(stager.stageReports(ReportType.ACTIVITY))
.thenThrow(new BigqueryJobFailureException("Expected failure", null, null, null));
try {
action.run();
assertWithMessage("Expected to encounter a BigqueryJobFailureException").fail();
} catch (BigqueryJobFailureException expected) {
// Expect the exception.
assertThat(expected).hasMessageThat().isEqualTo("Expected failure");
}
BigqueryJobFailureException thrown =
expectThrows(BigqueryJobFailureException.class, action::run);
assertThat(thrown).hasMessageThat().isEqualTo("Expected failure");
verify(stager, times(3)).stageReports(ReportType.ACTIVITY);
verify(emailUtils)
.emailResults(

View file

@ -15,8 +15,8 @@
package google.registry.reporting;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static google.registry.testing.GcsTestingUtils.writeGcsFile;
import static google.registry.testing.JUnitBackports.expectThrows;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@ -144,14 +144,10 @@ public class IcannReportingUploadActionTest {
public void testFail_FileNotFound() throws Exception {
IcannReportingUploadAction action = createAction();
action.subdir = "somewhere/else";
try {
action.run();
assertWithMessage("Expected IllegalStateException to be thrown").fail();
} catch (IllegalArgumentException expected) {
assertThat(expected)
IllegalArgumentException thrown = expectThrows(IllegalArgumentException.class, action::run);
assertThat(thrown)
.hasMessageThat()
.isEqualTo("Object MANIFEST.txt in bucket basin/somewhere/else not found");
}
}
}

View file

@ -41,6 +41,11 @@ public class EppExceptionSubject extends Subject<EppExceptionSubject, EppExcepti
return new And<>(this);
}
public And<EppExceptionSubject> hasMessageThatContains(String expected) {
assertThat(actual()).hasMessageThat().contains(expected);
return new And<>(this);
}
public And<EppExceptionSubject> marshalsToXml() {
// Attempt to marshal the exception to EPP. If it doesn't work, this will throw.
try {

View file

@ -15,7 +15,6 @@
package google.registry.tools;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.common.truth.Truth8.assertThat;
import static google.registry.model.registry.label.ReservationType.FULLY_BLOCKED;
import static google.registry.testing.DatastoreHelper.createTlds;
@ -175,13 +174,12 @@ public class CreateReservedListCommandTest extends
}
private void runNameTestExpectedFailure(String name, String expectedErrorMsg) throws Exception {
try {
runCommandForced("--name=" + name, "--input=" + reservedTermsPath);
assertWithMessage("Expected IllegalArgumentException to be thrown").fail();
} catch (IllegalArgumentException e) {
IllegalArgumentException thrown =
expectThrows(
IllegalArgumentException.class,
() -> runCommandForced("--name=" + name, "--input=" + reservedTermsPath));
assertThat(ReservedList.get(name)).isEmpty();
assertThat(e).hasMessageThat().isEqualTo(expectedErrorMsg);
}
assertThat(thrown).hasMessageThat().isEqualTo(expectedErrorMsg);
}
private void runNameTestWithOverride(String name) throws Exception {

View file

@ -15,7 +15,6 @@
package google.registry.tools;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.common.truth.Truth8.assertThat;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.testing.DatastoreHelper.createTld;
@ -61,14 +60,13 @@ public class DeletePremiumListCommandTest extends CommandTestCase<DeletePremiumL
PremiumList premiumList = persistPremiumList("xn--q9jyb4c", "blah,USD 100");
createTld("xn--q9jyb4c");
persistResource(Registry.get("xn--q9jyb4c").asBuilder().setPremiumList(premiumList).build());
try {
runCommandForced("--name=" + premiumList.getName());
assertWithMessage("Expected IllegalArgumentException to be thrown").fail();
} catch (IllegalArgumentException e) {
IllegalArgumentException thrown =
expectThrows(
IllegalArgumentException.class,
() -> runCommandForced("--name=" + premiumList.getName()));
assertThat(PremiumList.get(premiumList.getName())).isPresent();
assertThat(e)
assertThat(thrown)
.hasMessageThat()
.isEqualTo("Cannot delete premium list because it is used on these tld(s): xn--q9jyb4c");
}
}
}

View file

@ -15,7 +15,6 @@
package google.registry.tools;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.common.truth.Truth8.assertThat;
import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistReservedList;
@ -59,14 +58,13 @@ public class DeleteReservedListCommandTest extends CommandTestCase<DeleteReserve
public void testFailure_whenReservedListIsInUse() throws Exception {
createTld("xn--q9jyb4c");
persistResource(Registry.get("xn--q9jyb4c").asBuilder().setReservedLists(reservedList).build());
try {
runCommandForced("--name=" + reservedList.getName());
assertWithMessage("Expected IllegalArgumentException to be thrown").fail();
} catch (IllegalArgumentException e) {
IllegalArgumentException thrown =
expectThrows(
IllegalArgumentException.class,
() -> runCommandForced("--name=" + reservedList.getName()));
assertThat(ReservedList.get(reservedList.getName())).isPresent();
assertThat(e)
assertThat(thrown)
.hasMessageThat()
.isEqualTo("Cannot delete reserved list because it is used on these tld(s): xn--q9jyb4c");
}
}
}

View file

@ -15,7 +15,6 @@
package google.registry.tools;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.deleteResource;
@ -273,19 +272,15 @@ public class MutatingCommandTest {
+ "\n"
+ "Update Registrar@Registrar2\n"
+ "blockPremiumNames: false -> true\n");
try {
command.execute();
assertWithMessage("Expected transaction to fail with IllegalStateException").fail();
} catch (IllegalStateException e) {
assertThat(e.getMessage()).contains("Entity changed since init() was called.");
IllegalStateException thrown = expectThrows(IllegalStateException.class, command::execute);
assertThat(thrown).hasMessageThat().contains("Entity changed since init() was called.");
assertThat(ofy().load().entity(host1).now()).isNull();
assertThat(ofy().load().entity(host2).now()).isEqualTo(newHost2);
// These two shouldn't've changed.
assertThat(ofy().load().entity(registrar1).now()).isEqualTo(registrar1);
assertThat(ofy().load().entity(registrar2).now()).isEqualTo(registrar2);
}
}
@Test
public void testFailure_nullEntityChange() throws Exception {

View file

@ -23,6 +23,7 @@ import static google.registry.testing.DatastoreHelper.loadRegistrar;
import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.DatastoreHelper.persistSimpleResource;
import static google.registry.testing.DatastoreHelper.persistSimpleResources;
import static google.registry.testing.JUnitBackports.expectThrows;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.collect.ImmutableList;
@ -191,17 +192,18 @@ public class RegistrarContactCommandTest extends CommandTestCase<RegistrarContac
.setGaeUserId("11111")
.setVisibleInDomainWhoisAsAbuse(true)
.build());
try {
IllegalArgumentException thrown =
expectThrows(
IllegalArgumentException.class,
() ->
runCommandForced(
"--mode=UPDATE",
"--email=john.doe@example.com",
"--visible_in_domain_whois_as_abuse=false",
"NewRegistrar");
throw new Exception(
"Expected IllegalArgumentException: Cannot clear visible_in_domain_whois_as_abuse flag");
} catch (IllegalArgumentException e) {
assertThat(e).hasMessageThat().contains("Cannot clear visible_in_domain_whois_as_abuse flag");
}
"NewRegistrar"));
assertThat(thrown)
.hasMessageThat()
.contains("Cannot clear visible_in_domain_whois_as_abuse flag");
RegistrarContact registrarContact = loadRegistrar("NewRegistrar").getContacts().asList().get(1);
assertThat(registrarContact.getVisibleInDomainWhoisAsAbuse()).isTrue();
}
@ -323,16 +325,13 @@ public class RegistrarContactCommandTest extends CommandTestCase<RegistrarContac
RegistrarContact registrarContact = loadRegistrar("NewRegistrar").getContacts().asList().get(0);
persistSimpleResource(
registrarContact.asBuilder().setVisibleInDomainWhoisAsAbuse(true).build());
try {
IllegalArgumentException thrown =
expectThrows(
IllegalArgumentException.class,
() ->
runCommandForced(
"--mode=DELETE",
"--email=janedoe@theregistrar.com",
"NewRegistrar");
throw new Exception(
"Expected IllegalArgumentException: Cannot delete the domain WHOIS abuse contact");
} catch (IllegalArgumentException e) {
assertThat(e).hasMessageThat().contains("Cannot delete the domain WHOIS abuse contact");
}
"--mode=DELETE", "--email=janedoe@theregistrar.com", "NewRegistrar"));
assertThat(thrown).hasMessageThat().contains("Cannot delete the domain WHOIS abuse contact");
assertThat(loadRegistrar("NewRegistrar").getContacts()).isNotEmpty();
}

View file

@ -16,7 +16,6 @@ package google.registry.whois;
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.assert_;
import static google.registry.testing.DatastoreHelper.createTlds;
import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.DatastoreHelper.persistSimpleResources;
@ -25,6 +24,7 @@ import static google.registry.testing.FullFieldsTestEntityHelper.makeDomainResou
import static google.registry.testing.FullFieldsTestEntityHelper.makeHostResource;
import static google.registry.testing.FullFieldsTestEntityHelper.makeRegistrar;
import static google.registry.testing.FullFieldsTestEntityHelper.makeRegistrarContacts;
import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.whois.WhoisTestData.loadFile;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
@ -379,12 +379,8 @@ public class WhoisHttpServerTest {
.thenThrow(new IOException("missing cat interface"));
server.whoisMetrics = mock(WhoisMetrics.class);
try {
server.run();
assert_().fail("Should have thrown RuntimeException");
} catch (RuntimeException e) {
assertThat(e.getCause().getMessage()).isEqualTo("missing cat interface");
}
RuntimeException thrown = expectThrows(RuntimeException.class, server::run);
assertThat(thrown).hasCauseThat().hasMessageThat().isEqualTo("missing cat interface");
WhoisMetric expected =
WhoisMetric.builderForRequest(clock)
.setNumResults(0)