[Test] Don't generate throws Exception on methods of generated tests

This is needed to reduce the size of generated test files, which started
 to exceed default IDE limit
Also update some (mostly old) test utilities to remove exceptions from
 java signatures
This commit is contained in:
Dmitriy Novozhilov
2024-02-16 13:04:40 +02:00
committed by Space Team
parent 7ad371b215
commit 9b5a9ccba8
16 changed files with 170 additions and 73 deletions
@@ -84,7 +84,7 @@ public class KtTestUtil {
return doLoadFile(new File(fullName));
}
public static String doLoadFile(@NotNull File file) throws IOException {
public static String doLoadFile(@NotNull File file) {
try {
return FileUtil.loadFile(file, CharsetToolkit.UTF8, true);
}
@@ -94,11 +94,16 @@ public class KtTestUtil {
* This clarifies the exception by showing the full path.
*/
String messageWithFullPath = file.getAbsolutePath() + " (No such file or directory)";
throw new IOException(
"Ensure you have your 'Working Directory' configured correctly as the root " +
"Kotlin project directory in your test configuration\n\t" +
messageWithFullPath,
fileNotFoundException);
throw new RuntimeException(
new IOException(
"Ensure you have your 'Working Directory' configured correctly as the root " +
"Kotlin project directory in your test configuration\n\t" +
messageWithFullPath,
fileNotFoundException
)
);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@@ -49,12 +49,20 @@ import java.util.List;
import java.util.Set;
public abstract class AbstractPseudocodeTest extends KotlinTestWithEnvironmentManagement {
protected void doTestWithStdLib(String fileName) throws Exception {
doTestWithEnvironment(fileName, createEnvironmentWithMockJdk(ConfigurationKind.NO_KOTLIN_REFLECT));
protected void doTestWithStdLib(String fileName) {
try {
doTestWithEnvironment(fileName, createEnvironmentWithMockJdk(ConfigurationKind.NO_KOTLIN_REFLECT));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected void doTest(String fileName) throws Exception {
doTestWithEnvironment(fileName, createEnvironmentWithMockJdk(ConfigurationKind.JDK_ONLY));
protected void doTest(String fileName) {
try {
doTestWithEnvironment(fileName, createEnvironmentWithMockJdk(ConfigurationKind.JDK_ONLY));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void doTestWithEnvironment(String fileName, KotlinCoreEnvironment environment) throws Exception {
@@ -106,7 +106,6 @@ abstract class KotlinMultiFileTestWithJava<M : KotlinBaseTest.TestModule, F : Ko
return File(filePath)
}
@Throws(Exception::class)
public override fun doTest(filePath: String) {
val file = createTestFileFromPath(filePath)
val expectedText = KtTestUtil.doLoadFile(file)
@@ -39,7 +39,7 @@ import static org.jetbrains.kotlin.codegen.BytecodeTextUtilsKt.readExpectedOccur
public abstract class AbstractTopLevelMembersInvocationTest extends AbstractBytecodeTextTest {
@Override
public void doTest(@NotNull String filename) throws Exception {
public void doTest(@NotNull String filename) {
File root = new File(filename);
List<String> sourceFiles = SequencesKt.toList(SequencesKt.map(
SequencesKt.filter(FilesKt.walkTopDown(root).maxDepth(1), File::isFile),
@@ -513,17 +513,21 @@ public abstract class CodegenTestCase extends KotlinBaseTest<KotlinBaseTest.Test
}
@Override
protected void doTest(@NotNull String filePath) throws Exception {
protected void doTest(@NotNull String filePath) {
doTestWithTransformer(filePath, s -> s);
}
protected void doTestWithTransformer(@NotNull String filePath, @NotNull Function<String, String> sourceTransformer) throws Exception {
protected void doTestWithTransformer(@NotNull String filePath, @NotNull Function<String, String> sourceTransformer) {
File file = new File(filePath);
String expectedText = sourceTransformer.apply(KtTestUtil.doLoadFile(file));
List<TestFile> testFiles = createTestFilesFromFile(file, expectedText);
doMultiFileTest(file, testFiles);
try {
doMultiFileTest(file, testFiles);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
@@ -36,7 +36,16 @@ public abstract class AbstractDefaultArgumentsReflectionTest extends CodegenTest
}
@Override
protected void doTest(@NotNull String path) throws IOException {
protected void doTest(@NotNull String path) {
try {
doTestImpl(path);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
private void doTestImpl(@NotNull String path) throws IOException {
loadFileByFullPath(path);
File file = new File(path);
@@ -34,6 +34,6 @@ object RunTestMethodGenerator : MethodGenerator<RunTestMethodModel>() {
override fun generateSignature(method: RunTestMethodModel, p: Printer) {
val optionalTransformer = if (method.withTransformer) ", ${Function::class.java.canonicalName}<String, String> transformer" else ""
p.print("private void ${method.name}(String testDataFilePath${optionalTransformer}) throws Exception")
p.print("private void ${method.name}(String testDataFilePath${optionalTransformer})")
}
}
@@ -23,7 +23,7 @@ import org.jetbrains.kotlin.codegen.forTestCompile.ForTestCompileRuntime;
import java.io.File;
public abstract class AbstractAntTaskTest extends KotlinIntegrationTestBase {
protected void doTest(String testFile) throws Exception {
protected void doTest(String testFile) {
String testDataDir = new File(testFile).getAbsolutePath();
String antClasspath = System.getProperty("kotlin.ant.classpath");
@@ -53,13 +53,18 @@ public abstract class KotlinIntegrationTestBase extends TestCaseWithTmpdir {
KotlinTestUtils.runTestWithThrowable(this, () -> super.runTest());
}
protected int runJava(@NotNull String testDataDir, @Nullable String logName, @NotNull String... arguments) throws Exception {
protected int runJava(@NotNull String testDataDir, @Nullable String logName, @NotNull String... arguments) {
GeneralCommandLine commandLine = new GeneralCommandLine().withWorkDirectory(testDataDir);
commandLine.setExePath(getJavaRuntime().getAbsolutePath());
commandLine.addParameters(arguments);
StringBuilder executionLog = new StringBuilder();
int exitCode = runProcess(commandLine, executionLog);
int exitCode;
try {
exitCode = runProcess(commandLine, executionLog);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
if (logName == null) {
assertEquals("Non-zero exit code", 0, exitCode);
@@ -47,17 +47,14 @@ import java.lang.annotation.Retention
abstract class AbstractCompileJavaAgainstKotlinTest : TestCaseWithTmpdir() {
@Throws(IOException::class)
protected fun doTestWithJavac(ktFilePath: String) {
doTest(ktFilePath, true)
}
@Throws(IOException::class)
protected fun doTestWithoutJavac(ktFilePath: String) {
doTest(ktFilePath, false)
}
@Throws(IOException::class)
protected open fun doTest(ktFilePath: String, useJavac: Boolean) {
Assert.assertTrue(ktFilePath.endsWith(".kt"))
val ktFile = File(ktFilePath)
@@ -62,12 +62,16 @@ public abstract class AbstractLoadJavaTest extends TestCaseWithTmpdir {
protected boolean withForeignAnnotations() { return false; }
protected void doTestCompiledJava(@NotNull String javaFileName) throws Exception {
doTestCompiledJava(javaFileName, COMPARATOR_CONFIGURATION);
protected void doTestCompiledJava(@NotNull String javaFileName) {
try {
doTestCompiledJava(javaFileName, COMPARATOR_CONFIGURATION);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// Java-Kotlin dependencies are not supported in this method for simplicity
protected void doTestCompiledJavaAndKotlin(@NotNull String expectedFileName) throws Exception {
protected void doTestCompiledJavaAndKotlin(@NotNull String expectedFileName) {
File expectedFile = new File(expectedFileName);
File sourcesDir = new File(expectedFileName.replaceFirst("\\.txt$", ""));
@@ -110,24 +114,38 @@ public abstract class AbstractLoadJavaTest extends TestCaseWithTmpdir {
return Collections.emptyList();
}
protected void doTestCompiledJavaIncludeObjectMethods(@NotNull String javaFileName) throws Exception {
protected void doTestCompiledJavaIncludeObjectMethods(@NotNull String javaFileName) {
doTestCompiledJava(javaFileName, RECURSIVE.renderDeclarationsFromOtherModules(true));
}
protected void doTestCompiledKotlin(@NotNull String ktFileName) throws Exception {
protected void doTestCompiledKotlin(@NotNull String ktFileName) {
doTestCompiledKotlin(ktFileName, ConfigurationKind.JDK_ONLY, false);
}
protected void doTestCompiledKotlinWithTypeTable(@NotNull String ktFileName) throws Exception {
protected void doTestCompiledKotlinWithTypeTable(@NotNull String ktFileName) {
doTestCompiledKotlin(ktFileName, ConfigurationKind.JDK_ONLY, true);
}
protected void doTestCompiledKotlinWithStdlib(@NotNull String ktFileName) throws Exception {
doTestCompiledKotlin(ktFileName, ConfigurationKind.ALL, false);
protected void doTestCompiledKotlinWithStdlib(@NotNull String ktFileName) {
try {
doTestCompiledKotlin(ktFileName, ConfigurationKind.ALL, false);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void doTestCompiledKotlin(
@NotNull String ktFileName, @NotNull ConfigurationKind configurationKind, boolean useTypeTableInSerializer
) {
try {
doTestCompiledKotlinImpl(ktFileName, configurationKind, useTypeTableInSerializer);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void doTestCompiledKotlinImpl(
@NotNull String ktFileName, @NotNull ConfigurationKind configurationKind, boolean useTypeTableInSerializer
) throws Exception {
File ktFile = new File(ktFileName);
File txtFile = getTxtFileFromKtFile(ktFileName);
@@ -200,7 +218,16 @@ public abstract class AbstractLoadJavaTest extends TestCaseWithTmpdir {
protected void updateConfiguration(CompilerConfiguration configuration) {}
protected void doTestJavaAgainstKotlin(String expectedFileName) throws Exception {
protected void doTestJavaAgainstKotlin(String expectedFileName) {
try {
doTestJavaAgainstKotlinImpl(expectedFileName);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
private void doTestJavaAgainstKotlinImpl(String expectedFileName) throws Exception {
File expectedFile = new File(expectedFileName);
File sourcesDir = new File(expectedFileName.replaceFirst("\\.txt$", ""));
@@ -225,8 +252,16 @@ public abstract class AbstractLoadJavaTest extends TestCaseWithTmpdir {
checkJavaPackage(expectedFile, packageView, result.getBindingContext(), COMPARATOR_CONFIGURATION);
}
protected void doTestKotlinAgainstCompiledJavaWithKotlin(@NotNull String expectedFileName) {
try {
doTestKotlinAgainstCompiledJavaWithKotlinImpl(expectedFileName);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// TODO: add more tests on inherited parameter names, but currently impossible because of KT-4509
protected void doTestKotlinAgainstCompiledJavaWithKotlin(@NotNull String expectedFileName) throws Exception {
private void doTestKotlinAgainstCompiledJavaWithKotlinImpl(@NotNull String expectedFileName) throws Exception {
File kotlinSrc = new File(expectedFileName);
File librarySrc = new File(expectedFileName.replaceFirst("\\.kt$", ""));
File expectedFile = new File(expectedFileName.replaceFirst("\\.kt$", ".txt"));
@@ -263,33 +298,43 @@ public abstract class AbstractLoadJavaTest extends TestCaseWithTmpdir {
return TestJdkKind.MOCK_JDK;
}
protected void doTestSourceJava(@NotNull String javaFileName) throws Exception {
File originalJavaFile = new File(javaFileName);
File expectedFile = getTxtFile(javaFileName);
protected void doTestSourceJava(@NotNull String javaFileName) {
try {
File originalJavaFile = new File(javaFileName);
File expectedFile = getTxtFile(javaFileName);
File testPackageDir = new File(tmpdir, "test");
assertTrue(testPackageDir.mkdir());
FileUtil.copy(originalJavaFile, new File(testPackageDir, originalJavaFile.getName()));
File testPackageDir = new File(tmpdir, "test");
assertTrue(testPackageDir.mkdir());
FileUtil.copy(originalJavaFile, new File(testPackageDir, originalJavaFile.getName()));
Directives directives = KotlinTestUtils.parseDirectives(FileUtil.loadFile(originalJavaFile));
LanguageVersionSettings languageVersionSettings = parseLanguageVersionSettings(directives);
Directives directives = KotlinTestUtils.parseDirectives(FileUtil.loadFile(originalJavaFile));
LanguageVersionSettings languageVersionSettings = parseLanguageVersionSettings(directives);
Pair<PackageViewDescriptor, BindingContext> javaPackageAndContext = loadTestPackageAndBindingContextFromJavaRoot(
tmpdir, getTestRootDisposable(), getJdkKind(), ConfigurationKind.JDK_ONLY, false,
false, useJavacWrapper(), withForeignAnnotations(), languageVersionSettings);
Pair<PackageViewDescriptor, BindingContext> javaPackageAndContext = loadTestPackageAndBindingContextFromJavaRoot(
tmpdir, getTestRootDisposable(), getJdkKind(), ConfigurationKind.JDK_ONLY, false,
false, useJavacWrapper(), withForeignAnnotations(), languageVersionSettings);
checkJavaPackage(
expectedFile, javaPackageAndContext.first, javaPackageAndContext.second,
COMPARATOR_CONFIGURATION.withValidationStrategy(errorTypesAllowed())
);
checkJavaPackage(
expectedFile, javaPackageAndContext.first, javaPackageAndContext.second,
COMPARATOR_CONFIGURATION.withValidationStrategy(errorTypesAllowed())
);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
private void doTestCompiledJava(@NotNull String javaFileName, Configuration configuration) throws Exception {
private void doTestCompiledJava(@NotNull String javaFileName, Configuration configuration) {
File srcDir = new File(tmpdir, "src");
File compiledDir = new File(tmpdir, "compiled");
assertTrue(srcDir.mkdir());
assertTrue(compiledDir.mkdir());
String fileContent = FileUtil.loadFile(new File(javaFileName));
String fileContent;
try {
fileContent = FileUtil.loadFile(new File(javaFileName));
} catch (IOException e) {
throw new RuntimeException(e);
}
List<File> srcFiles = TestFiles.createTestFiles(
new File(javaFileName).getName(), fileContent,
@@ -335,11 +380,15 @@ public abstract class AbstractLoadJavaTest extends TestCaseWithTmpdir {
@NotNull File outDir,
@NotNull ConfigurationKind configurationKind,
@Nullable LanguageVersionSettings explicitLanguageVersionSettings
) throws IOException {
compileJavaWithAnnotationsJar(javaFiles, outDir, getAdditionalJavacArgs(), getJdkHomeForJavac(), withForeignAnnotations());
return loadTestPackageAndBindingContextFromJavaRoot(outDir, getTestRootDisposable(), getJdkKind(), configurationKind, true,
usePsiClassFilesReading(), useJavacWrapper(), withForeignAnnotations(), explicitLanguageVersionSettings,
getExtraClasspath(), this::configureEnvironment);
) {
try {
compileJavaWithAnnotationsJar(javaFiles, outDir, getAdditionalJavacArgs(), getJdkHomeForJavac(), withForeignAnnotations());
return loadTestPackageAndBindingContextFromJavaRoot(outDir, getTestRootDisposable(), getJdkKind(), configurationKind, true,
usePsiClassFilesReading(), useJavacWrapper(), withForeignAnnotations(), explicitLanguageVersionSettings,
getExtraClasspath(), this::configureEnvironment);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
protected List<String> getAdditionalJavacArgs() {
@@ -42,7 +42,7 @@ public abstract class ExtensibleResolveTestCase extends KotlinTestWithEnvironmen
protected abstract ExpectedResolveData getExpectedResolveData();
protected void doTest(@NonNls String filePath) throws Exception {
protected void doTest(@NonNls String filePath) {
File file = new File(filePath);
String text = KtTestUtil.doLoadFile(file);
List<KtFile> files = TestFiles.createTestFiles("file.kt", text, new TestFiles.TestFileFactoryNoModules<KtFile>() {
@@ -433,10 +433,10 @@ public class KotlinTestUtils {
}
public interface DoTest {
void invoke(@NotNull String filePath) throws Exception;
void invoke(@NotNull String filePath);
}
public static void runTest(@NotNull DoTest test, @NotNull TestCase testCase, @TestDataFile String testDataFile) throws Exception {
public static void runTest(@NotNull DoTest test, @NotNull TestCase testCase, @TestDataFile String testDataFile) {
runTestImpl(testWithCustomIgnoreDirective(test, TargetBackend.ANY, IGNORE_BACKEND_DIRECTIVE_PREFIXES), testCase, testDataFile);
}
@@ -458,11 +458,11 @@ public class KotlinTestUtils {
// In this test runner version the `testDataFile` parameter is annotated by `TestDataFile`.
// So only file paths passed to this parameter will be used in navigation actions, like "Navigate to testdata" and "Related Symbol..."
public static void runTest(DoTest test, TargetBackend targetBackend, @TestDataFile String testDataFile) throws Exception {
public static void runTest(DoTest test, TargetBackend targetBackend, @TestDataFile String testDataFile) {
runTest0(test, targetBackend, testDataFile);
}
public static void runTestWithCustomIgnoreDirective(DoTest test, TargetBackend targetBackend, @TestDataFile String testDataFile, String ignoreDirective) throws Exception {
public static void runTestWithCustomIgnoreDirective(DoTest test, TargetBackend targetBackend, @TestDataFile String testDataFile, String ignoreDirective) {
runTestImpl(testWithCustomIgnoreDirective(test, targetBackend, ignoreDirective), null, testDataFile);
}
@@ -474,11 +474,11 @@ public class KotlinTestUtils {
// Cons:
// * sometimes, for too common/general names, it shows many variants to navigate
// * it adds an additional step for navigation -- you must choose an exact file to navigate
public static void runTest0(DoTest test, TargetBackend targetBackend, String testDataFilePath) throws Exception {
public static void runTest0(DoTest test, TargetBackend targetBackend, String testDataFilePath) {
runTestImpl(testWithCustomIgnoreDirective(test, targetBackend, IGNORE_BACKEND_DIRECTIVE_PREFIXES), null, testDataFilePath);
}
private static void runTestImpl(@NotNull DoTest test, @Nullable TestCase testCase, String testDataFilePath) throws Exception {
private static void runTestImpl(@NotNull DoTest test, @Nullable TestCase testCase, String testDataFilePath) {
if (testCase != null && !isRunTestOverridden(testCase)) {
Function0<Unit> wrapWithMuteInDatabase = MuteWithDatabaseKt.wrapWithMuteInDatabase(testCase, () -> {
try {
@@ -510,7 +510,7 @@ public class KotlinTestUtils {
return false;
}
private static DoTest testWithCustomIgnoreDirective(DoTest test, TargetBackend targetBackend, String... ignoreDirectives) throws Exception {
private static DoTest testWithCustomIgnoreDirective(DoTest test, TargetBackend targetBackend, String... ignoreDirectives) {
return filePath -> {
File testDataFile = new File(filePath);
@@ -551,7 +551,11 @@ public class KotlinTestUtils {
if (!newText.equals(text)) {
System.err.println("\"" + directive + "\" was added to \"" + testDataFile + "\"");
FileUtil.writeToFile(testDataFile, newText);
try {
FileUtil.writeToFile(testDataFile, newText);
} catch (IOException ioException) {
throw new RuntimeException(ioException);
}
}
}
@@ -578,7 +582,11 @@ public class KotlinTestUtils {
String newText = Pattern.compile("^" + directive + "\n", Pattern.MULTILINE).matcher(text).replaceAll("");
if (!newText.equals(text)) {
System.err.println("\"" + directive + "\" was removed from \"" + testDataFile + "\"");
FileUtil.writeToFile(testDataFile, newText);
try {
FileUtil.writeToFile(testDataFile, newText);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
@@ -35,7 +35,7 @@ import java.io.IOException;
public abstract class AbstractModuleXmlParserTest extends TestCase {
@SuppressWarnings("MethodMayBeStatic")
protected void doTest(String xmlPath) throws IOException {
protected void doTest(String xmlPath) {
File txtFile = new File(FileUtil.getNameWithoutExtension(xmlPath) + ".txt");
ModuleChunk result = ModuleXmlParser.parseModuleScript(xmlPath, new MessageCollector() {
@@ -65,7 +65,12 @@ public abstract class AbstractModuleXmlParserTest extends TestCase {
String actual = sb.toString();
if (!txtFile.exists()) {
FileUtil.writeToFile(txtFile, actual);
try {
FileUtil.writeToFile(txtFile, actual);
}
catch (IOException e) {
throw new RuntimeException(e);
}
fail("Expected data file does not exist. A new file created: " + txtFile);
}
@@ -78,23 +78,31 @@ public abstract class AbstractParsingTest extends KtParsingTestCase {
}
}
protected void doParsingTest(@NotNull String filePath) throws Exception {
protected void doParsingTest(@NotNull String filePath) {
doBaseTest(filePath, KtNodeTypes.KT_FILE, null);
}
protected void doParsingTest(@NotNull String filePath, Function1<String, String> contentFilter) throws Exception {
protected void doParsingTest(@NotNull String filePath, Function1<String, String> contentFilter) {
doBaseTest(filePath, KtNodeTypes.KT_FILE, contentFilter);
}
protected void doExpressionCodeFragmentParsingTest(@NotNull String filePath) throws Exception {
protected void doExpressionCodeFragmentParsingTest(@NotNull String filePath) {
doBaseTest(filePath, KtNodeTypes.EXPRESSION_CODE_FRAGMENT, null);
}
protected void doBlockCodeFragmentParsingTest(@NotNull String filePath) throws Exception {
protected void doBlockCodeFragmentParsingTest(@NotNull String filePath) {
doBaseTest(filePath, KtNodeTypes.BLOCK_CODE_FRAGMENT, null);
}
private void doBaseTest(@NotNull String filePath, @NotNull IElementType fileType, Function1<String, String> contentFilter) throws Exception {
private void doBaseTest(@NotNull String filePath, @NotNull IElementType fileType, Function1<String, String> contentFilter) {
try {
doBaseTestImpl(filePath, fileType, contentFilter);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void doBaseTestImpl(@NotNull String filePath, @NotNull IElementType fileType, Function1<String, String> contentFilter) throws Exception {
String fileContent = loadFile(filePath);
myFileExt = FileUtilRt.getExtension(PathUtil.getFileName(filePath));
@@ -11,7 +11,7 @@ import org.jetbrains.kotlin.utils.Printer
abstract class MethodGenerator<in T : MethodModel> {
companion object {
fun generateDefaultSignature(method: MethodModel, p: Printer) {
p.print("public void ${method.name}() throws Exception")
p.print("public void ${method.name}()")
}
}