fix KT-9441 Unable to Access Internal Classes from Test Code within Same Module

#KT-9441 Fixed
This commit is contained in:
Michael Nedzelsky
2015-10-23 12:48:11 +03:00
parent 395c0f12b1
commit 190bab099c
16 changed files with 325 additions and 12 deletions
@@ -52,7 +52,6 @@ public class K2JVMCompilerArguments extends CommonCompilerArguments {
public String moduleName;
// Advanced options
@Argument(value = "Xno-call-assertions", description = "Don't generate not-null assertion after each invocation of method returning not-null")
public boolean noCallAssertions;
@@ -65,6 +64,9 @@ public class K2JVMCompilerArguments extends CommonCompilerArguments {
@Argument(value = "Xreport-perf", description = "Report detailed performance statistics")
public boolean reportPerf;
// Paths to output directories for friend modules.
public String[] friendPaths;
@Override
@NotNull
public String executableScriptFileName() {
@@ -47,7 +47,12 @@ class ModuleVisibilityHelperImpl : ModuleVisibilityHelper {
val whatSource = getSourceElement(what)
if (whatSource is KotlinSourceElement) return true
val modules = moduleVisibilityManager.chunk.toList()
moduleVisibilityManager.friendPaths.forEach {
if (isContainedByCompiledPartOfOurModule(what, File(it))) return true
}
val modules = moduleVisibilityManager.chunk
val outputDirectories = modules.map { File(it.getOutputDirectory()) }
if (outputDirectories.isEmpty()) return isContainedByCompiledPartOfOurModule(what, null)
@@ -56,7 +61,7 @@ class ModuleVisibilityHelperImpl : ModuleVisibilityHelper {
}
// Hack in order to allow access to internal elements in production code from tests
if (modules.size() == 1 && modules[0].getModuleType() == ModuleXmlParser.TYPE_TEST) return true
if (modules.singleOrNull()?.getModuleType() == ModuleXmlParser.TYPE_TEST) return true
return false
}
@@ -68,11 +73,16 @@ class ModuleVisibilityHelperImpl : ModuleVisibilityHelper {
*/
class CliModuleVisibilityManagerImpl() : ModuleVisibilityManager, Disposable {
override val chunk: MutableList<Module> = arrayListOf()
override val friendPaths: MutableList <String> = arrayListOf()
override fun addModule(module: Module) {
chunk.add(module)
}
override fun addFriendPath(path: String) {
friendPaths.add(path)
}
override fun dispose() {
chunk.clear()
}
@@ -21,9 +21,7 @@ import com.intellij.openapi.Disposable
import org.jetbrains.kotlin.cli.common.CLICompiler
import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
import org.jetbrains.kotlin.cli.common.ExitCode
import org.jetbrains.kotlin.cli.common.ExitCode.COMPILATION_ERROR
import org.jetbrains.kotlin.cli.common.ExitCode.INTERNAL_ERROR
import org.jetbrains.kotlin.cli.common.ExitCode.OK
import org.jetbrains.kotlin.cli.common.ExitCode.*
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.cli.common.messages.*
import org.jetbrains.kotlin.cli.jvm.compiler.*
@@ -154,6 +152,8 @@ public open class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
}
val environment: KotlinCoreEnvironment
val friendPaths = arguments.friendPaths?.toList() ?: emptyList<String>()
if (arguments.module != null) {
val sanitizedCollector = FilteringMessageCollector(messageSeverityCollector, `in`(CompilerMessageSeverity.VERBOSE))
val moduleScript = CompileEnvironmentUtil.loadModuleDescriptions(arguments.module, sanitizedCollector)
@@ -169,7 +169,7 @@ public open class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
if (messageSeverityCollector.anyReported(CompilerMessageSeverity.ERROR)) return COMPILATION_ERROR
KotlinToJVMBytecodeCompiler.compileModules(environment, configuration, moduleScript.getModules(), directory, jar, arguments.includeRuntime)
KotlinToJVMBytecodeCompiler.compileModules(environment, configuration, moduleScript.getModules(), directory, jar, friendPaths, arguments.includeRuntime)
}
else if (arguments.script) {
val scriptArgs = arguments.freeArgs.subList(1, arguments.freeArgs.size())
@@ -189,7 +189,7 @@ public open class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
return COMPILATION_ERROR
}
KotlinToJVMBytecodeCompiler.compileBunchOfSources(environment, jar, outputDir, arguments.includeRuntime)
KotlinToJVMBytecodeCompiler.compileBunchOfSources(environment, jar, outputDir, friendPaths, arguments.includeRuntime)
}
if (arguments.reportPerf) {
@@ -114,14 +114,21 @@ public class KotlinToJVMBytecodeCompiler {
@NotNull List<Module> chunk,
@NotNull File directory,
@Nullable File jarPath,
@NotNull List<String> friendPaths,
boolean jarRuntime
) {
Map<Module, ClassFileFactory> outputFiles = Maps.newHashMap();
ProgressIndicatorAndCompilationCanceledStatus.checkCanceled();
ModuleVisibilityManager moduleVisibilityManager = ModuleVisibilityManager.SERVICE.getInstance(environment.getProject());
for (Module module: chunk) {
ModuleVisibilityManager.SERVICE.getInstance(environment.getProject()).addModule(module);
moduleVisibilityManager.addModule(module);
}
for (String path : friendPaths) {
moduleVisibilityManager.addFriendPath(path);
}
String targetDescription = "in targets [" + Joiner.on(", ").join(Collections2.transform(chunk, new Function<Module, String>() {
@@ -215,9 +222,16 @@ public class KotlinToJVMBytecodeCompiler {
@NotNull KotlinCoreEnvironment environment,
@Nullable File jar,
@Nullable File outputDir,
@NotNull List<String> friendPaths,
boolean includeRuntime
) {
ModuleVisibilityManager moduleVisibilityManager = ModuleVisibilityManager.SERVICE.getInstance(environment.getProject());
for (String path : friendPaths) {
moduleVisibilityManager.addFriendPath(path);
}
GenerationState generationState = analyzeAndGenerate(environment);
if (generationState == null) {
return false;
@@ -29,7 +29,9 @@ import java.io.File
interface ModuleVisibilityManager {
val chunk: Collection<Module>
val friendPaths: Collection<String>
fun addModule(module: Module)
fun addFriendPath(path: String)
public object SERVICE {
@JvmStatic
@@ -21,5 +21,7 @@ import org.jetbrains.kotlin.modules.Module
class IdeModuleVisibilityManagerImpl() : ModuleVisibilityManager {
override val chunk: Collection<Module> = emptyList()
override val friendPaths: Collection<String> = emptyList()
override fun addModule(module: Module) {}
override fun addFriendPath(path: String) {}
}
@@ -134,6 +134,21 @@ public open class KotlinCompile() : AbstractKotlinCompile<K2JVMCompilerArguments
args.noCallAssertions = kotlinOptions.noCallAssertions
args.noParamAssertions = kotlinOptions.noParamAssertions
args.moduleName = kotlinOptions.moduleName ?: extraProperties.getOrNull<String>("defaultModuleName")
if (this.name == "compileTestKotlin") {
getLogger().kotlinDebug("try to determine the output directory of corresponding compileKotlin task")
val tasks = project.getTasksByName("compileKotlin", false)
getLogger().kotlinDebug("tasks for compileKotlin: ${tasks}")
if (tasks.size == 1) {
val task = tasks.firstOrNull() as? KotlinCompile
if (task != null) {
getLogger().kotlinDebug("destinantion directory for production = ${task.destinationDir}")
args.friendPaths = arrayOf(task.destinationDir.absolutePath)
args.moduleName = task.kotlinOptions.moduleName ?: task.extensions.extraProperties.getOrNull<String>("defaultModuleName")
}
}
}
getLogger().kotlinDebug("args.moduleName = ${args.moduleName}")
}
@@ -90,6 +90,15 @@ class KotlinGradleIT: BaseGradleIT() {
}
}
@Test
fun testInternalTest() {
Project("internalTest", "1.6").build("build") {
assertSuccessful()
assertReportExists()
assertContains(":compileKotlin", ":compileTestKotlin")
}
}
@Test
fun testMultiprojectPluginClasspath() {
Project("multiprojectClassPathTest", "1.6").build("build") {
@@ -0,0 +1,34 @@
buildscript {
repositories {
mavenCentral()
maven {
url 'file://' + pathToKotlinPlugin
}
}
dependencies {
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:0.1-SNAPSHOT'
}
}
apply plugin: "kotlin"
repositories {
maven {
url 'file://' + pathToKotlinPlugin
}
mavenCentral()
}
dependencies {
testCompile 'org.testng:testng:6.8'
compile 'org.jetbrains.kotlin:kotlin-stdlib:0.1-SNAPSHOT'
}
test {
useTestNG()
}
task wrapper(type: Wrapper) {
gradleVersion="1.4"
}
@@ -0,0 +1,34 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* 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 demo
internal val CONST = "CONST"
class PublicClass {
internal fun foo(): String = "foo"
internal val bar: String = "bar"
}
internal data class InternalDataClass(val x: Int, val y: Int)
internal fun box(): String {
return "OK"
}
@@ -0,0 +1,36 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* 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 demo
import org.testng.Assert.*
import org.testng.annotations.Test as test
class TestSource() {
@test fun f() {
assertEquals("CONST", CONST)
assertEquals("foo", PublicClass().foo())
assertEquals("bar", PublicClass().bar)
val data = InternalDataClass(10, 20)
assertEquals(10, data.x)
assertEquals(20, data.y)
assertEquals(box(), "OK")
}
}
@@ -0,0 +1,75 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-project</artifactId>
<version>0.1-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<artifactId>test-accessToInternal</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-runtime</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.1.2</version>
</plugin>
</plugins>
</pluginManagement>
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${project.version}</version>
<executions>
<execution>
<id>compile</id>
<phase>process-sources</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<phase>process-test-sources</phase>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,35 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* 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 org.jetbrains
fun main(args : Array<String>) {
System.out?.println(getGreeting())
}
internal fun getGreeting() : String {
return "Hello, World!"
}
internal val CONST = "CONST"
class PublicClass {
internal fun foo(): String = "foo"
internal val bar: String = "bar"
}
internal data class InternalDataClass(val x: Int, val y: Int)
@@ -0,0 +1,41 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* 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 org.jetbrains
import org.junit.Test
import junit.framework.Assert.assertEquals
class HelloWorldTest {
@Test
fun greeting() {
assertEquals("Hello, World!", getGreeting())
}
@Test
fun accessToInternal() {
assertEquals("CONST", CONST)
assertEquals("foo", PublicClass().foo())
assertEquals("bar", PublicClass().bar)
val data = InternalDataClass(10, 20)
assertEquals(10, data.x)
assertEquals(20, data.y)
}
}
@@ -0,0 +1,6 @@
import java.io.*;
File file = new File(basedir, "target/test-accessToInternal-0.1-SNAPSHOT.jar");
if (!file.exists() || !file.isFile()) {
throw new FileNotFoundException("Could not find generated JAR: " + file);
}
@@ -24,7 +24,6 @@ import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments;
import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler;
import java.util.List;
@@ -86,9 +85,8 @@ public class KotlinTestCompileMojo extends K2JVMCompileMojo {
protected void configureSpecificCompilerArguments(@NotNull K2JVMCompilerArguments arguments) throws MojoExecutionException {
module = testModule;
classpath = testClasspath;
arguments.friendPaths = new String[] { output };
output = testOutput;
moduleName = testModuleName;
super.configureSpecificCompilerArguments(arguments);
}
}