From 0e110f9c4f02a06decd2dfc3bd1e064601ffd91f Mon Sep 17 00:00:00 2001 From: nickreid Date: Tue, 5 Mar 2019 19:53:14 -0800 Subject: [PATCH] Make some assertions more Truth-y. This should make the code and assertion output more readable. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=236969746 --- .../jscomp/testing/JSCompCorrespondences.java | 53 ++++++++++++++ .../javascript/jscomp/CompilerTest.java | 19 ++--- .../jscomp/CompilerTypeTestCase.java | 16 +---- .../jscomp/JsMessageVisitorTest.java | 68 +++++++++--------- .../javascript/jscomp/TypeCheckTestCase.java | 1 + .../jscomp/deps/DepsGeneratorTest.java | 71 +++++++------------ .../jscomp/deps/JsFileParserTest.java | 12 ++-- 7 files changed, 132 insertions(+), 108 deletions(-) create mode 100644 src/com/google/javascript/jscomp/testing/JSCompCorrespondences.java diff --git a/src/com/google/javascript/jscomp/testing/JSCompCorrespondences.java b/src/com/google/javascript/jscomp/testing/JSCompCorrespondences.java new file mode 100644 index 00000000000..e69dcceaafb --- /dev/null +++ b/src/com/google/javascript/jscomp/testing/JSCompCorrespondences.java @@ -0,0 +1,53 @@ +/* + * Copyright 2010 The Closure Compiler Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.javascript.jscomp.testing; + +import com.google.common.truth.Correspondence; +import com.google.javascript.jscomp.CompilerInput; +import com.google.javascript.jscomp.DiagnosticType; +import com.google.javascript.jscomp.JSError; +import java.util.function.Function; + +/** Well known {@link Correspondence} instances for use in tests. */ +public final class JSCompCorrespondences { + + public static final Correspondence DIAGNOSTIC_EQUALITY = + transforming(JSError::getType, "has diagnostic type equal to"); + + public static final Correspondence DESCRIPTION_EQUALITY = + transforming((e) -> e.description, "has description equal to"); + + public static final Correspondence INPUT_NAME_EQUALITY = + transforming(CompilerInput::getName, "has name equal to"); + + private static final Correspondence transforming( + Function transformation, String description) { + return new Correspondence() { + @Override + public boolean compare(A actual, E expected) { + return transformation.apply(actual).equals(expected); + } + + @Override + public String toString() { + return description; + } + }; + } + + // Not instantiable. + private JSCompCorrespondences() {} +} diff --git a/test/com/google/javascript/jscomp/CompilerTest.java b/test/com/google/javascript/jscomp/CompilerTest.java index 945c1537464..64ab86b17b1 100644 --- a/test/com/google/javascript/jscomp/CompilerTest.java +++ b/test/com/google/javascript/jscomp/CompilerTest.java @@ -18,6 +18,7 @@ import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import static com.google.javascript.jscomp.CompilerTestCase.lines; +import static com.google.javascript.jscomp.testing.JSCompCorrespondences.DIAGNOSTIC_EQUALITY; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.fail; @@ -453,8 +454,8 @@ public void testBug2176967Default() { // Default is warning. compiler.compile(SourceFile.fromCode("extern.js", ""), SourceFile.fromCode("test.js", badJsDoc), options); - assertThat(compiler.getWarningCount()).isEqualTo(1); - assertThat(compiler.getErrorCount()).isEqualTo(0); + assertThat(compiler.getWarnings()).hasSize(1); + assertThat(compiler.getErrors()).isEmpty(); } /** @@ -471,8 +472,8 @@ public void testBug2176967Off() { DiagnosticGroups.NON_STANDARD_JSDOC, CheckLevel.OFF); compiler.compile(SourceFile.fromCode("extern.js", ""), SourceFile.fromCode("test.js", badJsDoc), options); - assertThat(compiler.getWarningCount()).isEqualTo(0); - assertThat(compiler.getErrorCount()).isEqualTo(0); + assertThat(compiler.getWarnings()).isEmpty(); + assertThat(compiler.getErrors()).isEmpty(); } /** @@ -490,8 +491,8 @@ public void testBug2176967Error() { DiagnosticGroups.NON_STANDARD_JSDOC, CheckLevel.ERROR); compiler.compile(SourceFile.fromCode("extern.js", ""), SourceFile.fromCode("test.js", badJsDoc), options); - assertThat(compiler.getWarningCount()).isEqualTo(0); - assertThat(compiler.getErrorCount()).isEqualTo(1); + assertThat(compiler.getWarnings()).isEmpty(); + assertThat(compiler.getErrors()).hasSize(1); } @Test @@ -2035,9 +2036,9 @@ public void testCodeReferenceToTypeImport() throws Exception { compiler.check(); assertThat(compiler.getWarnings()).isEmpty(); - assertThat(compiler.getErrors()).hasSize(1); - assertThat(compiler.getErrors().get(0).getType()) - .isEqualTo(CheckTypeImportCodeReferences.TYPE_IMPORT_CODE_REFERENCE); + assertThat(compiler.getErrors()) + .comparingElementsUsing(DIAGNOSTIC_EQUALITY) + .containsExactly(CheckTypeImportCodeReferences.TYPE_IMPORT_CODE_REFERENCE); } @Test diff --git a/test/com/google/javascript/jscomp/CompilerTypeTestCase.java b/test/com/google/javascript/jscomp/CompilerTypeTestCase.java index 1d851e8f1e9..eda58dd0738 100644 --- a/test/com/google/javascript/jscomp/CompilerTypeTestCase.java +++ b/test/com/google/javascript/jscomp/CompilerTypeTestCase.java @@ -18,12 +18,12 @@ package com.google.javascript.jscomp; import static com.google.common.truth.Truth.assertWithMessage; +import static com.google.javascript.jscomp.testing.JSCompCorrespondences.DESCRIPTION_EQUALITY; import static com.google.javascript.rhino.testing.TypeSubject.assertType; import static com.google.javascript.rhino.testing.TypeSubject.types; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; -import com.google.common.truth.Correspondence; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import com.google.javascript.jscomp.parsing.parser.FeatureSet.Feature; import com.google.javascript.rhino.JSTypeExpression; @@ -36,7 +36,6 @@ import com.google.javascript.rhino.jstype.RecordTypeBuilder; import com.google.javascript.rhino.jstype.TemplatizedType; import com.google.javascript.rhino.testing.TestErrorReporter; -import java.util.Objects; import org.junit.Before; /** @@ -314,17 +313,4 @@ JSType getNativeAllType() { JSType getNativeType(JSTypeNative jsTypeNative) { return registry.getNativeType(jsTypeNative); } - - static final Correspondence DESCRIPTION_EQUALITY = - new Correspondence() { - @Override - public boolean compare(JSError error, String description) { - return Objects.equals(error.description, description); - } - - @Override - public String toString() { - return "has description equal to"; - } - }; } diff --git a/test/com/google/javascript/jscomp/JsMessageVisitorTest.java b/test/com/google/javascript/jscomp/JsMessageVisitorTest.java index ca7df9ce482..955059f26b9 100644 --- a/test/com/google/javascript/jscomp/JsMessageVisitorTest.java +++ b/test/com/google/javascript/jscomp/JsMessageVisitorTest.java @@ -23,6 +23,8 @@ import static com.google.javascript.jscomp.JsMessageVisitor.MESSAGE_TREE_MALFORMED; import static com.google.javascript.jscomp.JsMessageVisitor.isLowerCamelCaseWithNumericSuffixes; import static com.google.javascript.jscomp.JsMessageVisitor.toLowerCamelCaseWithNumericSuffixes; +import static com.google.javascript.jscomp.testing.JSCompCorrespondences.DESCRIPTION_EQUALITY; +import static com.google.javascript.jscomp.testing.JSCompCorrespondences.DIAGNOSTIC_EQUALITY; import static com.google.javascript.jscomp.testing.JSErrorSubject.assertError; import com.google.common.base.Joiner; @@ -274,23 +276,24 @@ public void testJsMessageOnRHSOfVar() { @Test public void testOrphanedJsMessage() { extractMessagesSafely("goog.getMsg('a')"); - assertThat(compiler.getWarnings()).hasSize(1); assertThat(messages).isEmpty(); - JSError warn = compiler.getWarnings().get(0); - assertError(warn).hasType(JsMessageVisitor.MESSAGE_NODE_IS_ORPHANED); + assertThat(compiler.getWarnings()) + .comparingElementsUsing(DIAGNOSTIC_EQUALITY) + .containsExactly(JsMessageVisitor.MESSAGE_NODE_IS_ORPHANED); } @Test public void testMessageWithoutDescription() { extractMessagesSafely("var MSG_HELLO = goog.getMsg('a')"); - assertThat(compiler.getWarnings()).hasSize(1); - assertThat(messages).hasSize(1); + assertThat(messages).hasSize(1); JsMessage msg = messages.get(0); assertThat(msg.getKey()).isEqualTo("MSG_HELLO"); - assertError(compiler.getWarnings().get(0)).hasType(JsMessageVisitor.MESSAGE_HAS_NO_DESCRIPTION); + assertThat(compiler.getWarnings()) + .comparingElementsUsing(DIAGNOSTIC_EQUALITY) + .containsExactly(JsMessageVisitor.MESSAGE_HAS_NO_DESCRIPTION); } @Test @@ -505,10 +508,10 @@ public void testEmptyTextMessage() { extractMessagesSafely("/** @desc text */ var MSG_FOO = goog.getMsg('');"); assertThat(messages).hasSize(1); - assertThat(compiler.getWarnings()).hasSize(1); - assertThat(compiler.getWarnings().get(0).description) - .isEqualTo( - "Message value of MSG_FOO is just an empty string. " + "Empty messages are forbidden."); + assertThat(compiler.getWarnings()) + .comparingElementsUsing(DESCRIPTION_EQUALITY) + .containsExactly( + "Message value of MSG_FOO is just an empty string. Empty messages are forbidden."); } @Test @@ -517,9 +520,9 @@ public void testEmptyTextComplexMessage() { + "'' + '' + '' + ''\n+'');"); assertThat(messages).hasSize(1); - assertThat(compiler.getWarnings()).hasSize(1); - assertThat(compiler.getWarnings().get(0).description) - .isEqualTo( + assertThat(compiler.getWarnings()) + .comparingElementsUsing(DESCRIPTION_EQUALITY) + .containsExactly( "Message value of MSG_BAR is just an empty string. " + "Empty messages are forbidden."); } @@ -527,9 +530,9 @@ public void testEmptyTextComplexMessage() { public void testMsgVarWithoutAssignment() { extractMessages("var MSG_SILLY;"); - assertThat(compiler.getErrors()).hasSize(1); - JSError error = compiler.getErrors().get(0); - assertThat(error.getType()).isEqualTo(JsMessageVisitor.MESSAGE_HAS_NO_VALUE); + assertThat(compiler.getErrors()) + .comparingElementsUsing(DIAGNOSTIC_EQUALITY) + .containsExactly(JsMessageVisitor.MESSAGE_HAS_NO_VALUE); } @Test @@ -544,19 +547,19 @@ public void testRegularVarWithoutAssignment() { public void testMsgPropertyWithoutAssignment() { extractMessages("goog.message.MSG_SILLY_PROP;"); - assertThat(compiler.getErrors()).hasSize(1); - JSError error = compiler.getErrors().get(0); - assertThat(error.description).isEqualTo("Message MSG_SILLY_PROP has no value"); + assertThat(compiler.getErrors()) + .comparingElementsUsing(DESCRIPTION_EQUALITY) + .containsExactly("Message MSG_SILLY_PROP has no value"); } @Test public void testMsgVarWithIncorrectRightSide() { extractMessages("var MSG_SILLY = 0;"); - assertThat(compiler.getErrors()).hasSize(1); - JSError error = compiler.getErrors().get(0); - assertThat(error.description) - .isEqualTo("Message parse tree malformed. Cannot parse value of " + "message MSG_SILLY"); + assertThat(compiler.getErrors()) + .comparingElementsUsing(DESCRIPTION_EQUALITY) + .containsExactly( + "Message parse tree malformed. Cannot parse value of " + "message MSG_SILLY"); } @Test @@ -564,10 +567,9 @@ public void testIncorrectMessage() { extractMessages("DP_DatePicker.MSG_DATE_SELECTION = {};"); assertThat(messages).isEmpty(); - assertThat(compiler.getErrors()).hasSize(1); - JSError error = compiler.getErrors().get(0); - assertThat(error.description) - .isEqualTo( + assertThat(compiler.getErrors()) + .comparingElementsUsing(DESCRIPTION_EQUALITY) + .containsExactly( "Message parse tree malformed." + " Message must be initialized using goog.getMsg function."); } @@ -578,10 +580,9 @@ public void testUnrecognizedFunction() { extractMessages("DP_DatePicker.MSG_DATE_SELECTION = somefunc('a')"); assertThat(messages).isEmpty(); - assertThat(compiler.getErrors()).hasSize(1); - JSError error = compiler.getErrors().get(0); - assertThat(error.description) - .isEqualTo( + assertThat(compiler.getErrors()) + .comparingElementsUsing(DESCRIPTION_EQUALITY) + .containsExactly( "Message parse tree malformed. Message initialized using unrecognized function. " + "Please use goog.getMsg() instead."); } @@ -890,8 +891,9 @@ private void assertNoErrors() { } private void assertOneError(DiagnosticType type) { - assertThat(compiler.getErrors()).hasSize(1); - assertError(compiler.getErrors().get(0)).hasType(type); + assertThat(compiler.getErrors()) + .comparingElementsUsing(DIAGNOSTIC_EQUALITY) + .containsExactly(type); } private void extractMessagesSafely(String input) { diff --git a/test/com/google/javascript/jscomp/TypeCheckTestCase.java b/test/com/google/javascript/jscomp/TypeCheckTestCase.java index 73911bb6f1e..9670391715a 100644 --- a/test/com/google/javascript/jscomp/TypeCheckTestCase.java +++ b/test/com/google/javascript/jscomp/TypeCheckTestCase.java @@ -18,6 +18,7 @@ import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; +import static com.google.javascript.jscomp.testing.JSCompCorrespondences.DESCRIPTION_EQUALITY; import com.google.common.collect.ImmutableList; import com.google.common.truth.Correspondence; diff --git a/test/com/google/javascript/jscomp/deps/DepsGeneratorTest.java b/test/com/google/javascript/jscomp/deps/DepsGeneratorTest.java index ca55e4fab3c..56d1b3d1f86 100644 --- a/test/com/google/javascript/jscomp/deps/DepsGeneratorTest.java +++ b/test/com/google/javascript/jscomp/deps/DepsGeneratorTest.java @@ -19,6 +19,7 @@ import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; +import static com.google.javascript.jscomp.testing.JSCompCorrespondences.DESCRIPTION_EQUALITY; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; @@ -427,28 +428,28 @@ public void testDepsAsSrcs() throws Exception { @Test public void testMergeStrategyAlways() throws Exception { String result = testMergeStrategyHelper(DepsGenerator.InclusionStrategy.ALWAYS); - assertContains("['a']", result); - assertContains("['b']", result); - assertContains("['c']", result); - assertContains("d.js", result); + assertThat(result).contains("['a']"); + assertThat(result).contains("['b']"); + assertThat(result).contains("['c']"); + assertThat(result).contains("d.js"); } @Test public void testMergeStrategyWhenInSrcs() throws Exception { String result = testMergeStrategyHelper(DepsGenerator.InclusionStrategy.WHEN_IN_SRCS); - assertNotContains("['a']", result); - assertContains("['b']", result); - assertContains("['c']", result); - assertNotContains("d.js", result); + assertThat(result).doesNotContain("['a']"); + assertThat(result).contains("['b']"); + assertThat(result).contains("['c']"); + assertThat(result).doesNotContain("d.js"); } @Test public void testMergeStrategyDoNotDuplicate() throws Exception { String result = testMergeStrategyHelper(DepsGenerator.InclusionStrategy.DO_NOT_DUPLICATE); - assertNotContains("['a']", result); - assertNotContains("['b']", result); - assertContains("['c']", result); - assertNotContains("d.js", result); + assertThat(result).doesNotContain("['a']"); + assertThat(result).doesNotContain("['b']"); + assertThat(result).contains("['c']"); + assertThat(result).doesNotContain("d.js"); } private String testMergeStrategyHelper(DepsGenerator.InclusionStrategy mergeStrategy) @@ -644,46 +645,24 @@ public void testUnknownEs6Module() throws Exception { "Could not find file \"./missing.js\"."); } - private void assertErrorWarningCount(int errorCount, int warningCount) { - if (errorManager.getErrorCount() != errorCount) { - assertWithMessage( - "Expected %d errors but got\n%s", - errorCount, Joiner.on("\n").join(errorManager.getErrors())) - .fail(); - } - if (errorManager.getWarningCount() != warningCount) { - assertWithMessage( - "Expected %d warnings but got\n%s", - warningCount, Joiner.on("\n").join(errorManager.getWarnings())) - .fail(); - } - } - private void assertNoWarnings() { - assertErrorWarningCount(0, 0); + assertThat(errorManager.getWarnings()).isEmpty(); + assertThat(errorManager.getErrors()).isEmpty(); } private void assertWarnings(String... messages) { - assertErrorWarningCount(0, messages.length); - for (int i = 0; i < messages.length; i++) { - assertThat(errorManager.getWarnings().get(i).description).isEqualTo(messages[i]); - } + assertThat(errorManager.getWarnings()) + .comparingElementsUsing(DESCRIPTION_EQUALITY) + .containsExactly(messages) + .inOrder(); + assertThat(errorManager.getErrors()).isEmpty(); } private void assertErrors(String... messages) { - assertErrorWarningCount(messages.length, 0); - for (int i = 0; i < messages.length; i++) { - assertThat(errorManager.getErrors().get(i).description).isEqualTo(messages[i]); - } - } - - private static void assertContains(String part, String whole) { - assertWithMessage("Expected string to contain: " + part).that(whole.contains(part)).isTrue(); - } - - private static void assertNotContains(String part, String whole) { - assertWithMessage("Expected string not to contain: " + part) - .that(whole.contains(part)) - .isFalse(); + assertThat(errorManager.getWarnings()).isEmpty(); + assertThat(errorManager.getErrors()) + .comparingElementsUsing(DESCRIPTION_EQUALITY) + .containsExactly(messages) + .inOrder(); } } diff --git a/test/com/google/javascript/jscomp/deps/JsFileParserTest.java b/test/com/google/javascript/jscomp/deps/JsFileParserTest.java index 45808a15790..0a8bd7b165f 100644 --- a/test/com/google/javascript/jscomp/deps/JsFileParserTest.java +++ b/test/com/google/javascript/jscomp/deps/JsFileParserTest.java @@ -19,6 +19,7 @@ import static com.google.common.truth.Truth.assertThat; import static com.google.javascript.jscomp.deps.DependencyInfo.Require.es6Import; import static com.google.javascript.jscomp.deps.DependencyInfo.Require.googRequireSymbol; +import static com.google.javascript.jscomp.testing.JSCompCorrespondences.DIAGNOSTIC_EQUALITY; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -727,15 +728,16 @@ public void testEs6AndWrappedGoogModuleIsError() { parser.parseFile(SRC_PATH, CLOSURE_PATH, contents); - assertThat(errorManager.getErrorCount()).isEqualTo(0); - assertThat(errorManager.getWarningCount()).isEqualTo(1); - assertThat(errorManager.getWarnings().get(0).getType()).isEqualTo(ModuleLoader.MODULE_CONFLICT); + assertThat(errorManager.getErrors()).isEmpty(); + assertThat(errorManager.getWarnings()) + .comparingElementsUsing(DIAGNOSTIC_EQUALITY) + .containsExactly(ModuleLoader.MODULE_CONFLICT); } /** Asserts the deps match without errors */ private void assertDeps(DependencyInfo expected, DependencyInfo actual) { assertThat(actual).isEqualTo(expected); - assertThat(errorManager.getErrorCount()).isEqualTo(0); - assertThat(errorManager.getWarningCount()).isEqualTo(0); + assertThat(errorManager.getErrors()).isEmpty(); + assertThat(errorManager.getWarnings()).isEmpty(); } }