Skip to content

Commit e376e2a

Browse files
committed
WiP Emit Scala.js JUnit bootstrappers for JUnit test classes.
1 parent bb5a921 commit e376e2a

File tree

5 files changed

+294
-1
lines changed

5 files changed

+294
-1
lines changed

.drone.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ pipeline:
3131
image: lampepfl/dotty:2019-02-06
3232
commands:
3333
- cp -R . /tmp/2/ && cd /tmp/2/
34-
- ./project/scripts/sbt ";dotty-bootstrapped/compile ;dotty-bootstrapped/test; dotty-semanticdb/compile; dotty-semanticdb/test:compile;sjsSandbox/run"
34+
- ./project/scripts/sbt ";dotty-bootstrapped/compile ;dotty-bootstrapped/test; dotty-semanticdb/compile; dotty-semanticdb/test:compile;sjsSandbox/run;sjsSandbox/test"
3535
- ./project/scripts/bootstrapCmdTests
3636

3737
community_build:
Lines changed: 273 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,273 @@
1+
package dotty.tools.backend.sjs
2+
3+
import scala.annotation.tailrec
4+
5+
import dotty.tools.dotc._
6+
7+
import dotty.tools.dotc.core._
8+
import Constants._
9+
import Contexts._
10+
import Decorators._
11+
import Flags._
12+
import Names._
13+
import NameOps._
14+
import Phases._
15+
import Scopes._
16+
import Symbols._
17+
import StdNames._
18+
import Types._
19+
20+
import dotty.tools.dotc.transform.MegaPhase._
21+
22+
/** Generates JUnit bootstrapper classes for Scala.js. */
23+
class JUnitBootstrappers extends MiniPhase {
24+
import ast.tpd._
25+
26+
def phaseName: String = "junitBootstrappers"
27+
28+
override def isEnabled(implicit ctx: Context): Boolean =
29+
super.isEnabled && ctx.settings.scalajs.value
30+
31+
private object Names {
32+
val beforeClass: TermName = termName("beforeClass")
33+
val afterClass: TermName = termName("afterClass")
34+
val before: TermName = termName("before")
35+
val after: TermName = termName("after")
36+
val tests: TermName = termName("tests")
37+
val invokeTest: TermName = termName("invokeTest")
38+
val newInstance: TermName = termName("newInstance")
39+
40+
val instance: TermName = termName("instance")
41+
val name: TermName = termName("name")
42+
}
43+
44+
private class MyDefinitions()(implicit ctx: Context) {
45+
lazy val TestAnnotType: TypeRef = ctx.requiredClassRef("org.junit.Test")
46+
def TestAnnotClass(implicit ctx: Context): ClassSymbol = TestAnnotType.symbol.asClass
47+
48+
lazy val BeforeAnnotType: TypeRef = ctx.requiredClassRef("org.junit.Before")
49+
def BeforeAnnotClass(implicit ctx: Context): ClassSymbol = BeforeAnnotType.symbol.asClass
50+
51+
lazy val AfterAnnotType: TypeRef = ctx.requiredClassRef("org.junit.After")
52+
def AfterAnnotClass(implicit ctx: Context): ClassSymbol = AfterAnnotType.symbol.asClass
53+
54+
lazy val BeforeClassAnnotType: TypeRef = ctx.requiredClassRef("org.junit.BeforeClass")
55+
def BeforeClassAnnotClass(implicit ctx: Context): ClassSymbol = BeforeClassAnnotType.symbol.asClass
56+
57+
lazy val AfterClassAnnotType: TypeRef = ctx.requiredClassRef("org.junit.AfterClass")
58+
def AfterClassAnnotClass(implicit ctx: Context): ClassSymbol = AfterClassAnnotType.symbol.asClass
59+
60+
lazy val IgnoreAnnotType: TypeRef = ctx.requiredClassRef("org.junit.Ignore")
61+
def IgnoreAnnotClass(implicit ctx: Context): ClassSymbol = IgnoreAnnotType.symbol.asClass
62+
63+
lazy val BootstrapperType: TypeRef = ctx.requiredClassRef("org.scalajs.junit.Bootstrapper")
64+
def BootstrapperClass(implicit ctx: Context): ClassSymbol = BootstrapperType.symbol.asClass
65+
66+
lazy val TestMetadataType: TypeRef = ctx.requiredClassRef("org.scalajs.junit.TestMetadata")
67+
def TestMetadataClass(implicit ctx: Context): ClassSymbol = TestMetadataType.symbol.asClass
68+
69+
lazy val NoSuchMethodExceptionType: TypeRef = ctx.requiredClassRef("java.lang.NoSuchMethodException")
70+
71+
lazy val FutureType: TypeRef = ctx.requiredClassRef("scala.concurrent.Future")
72+
def FutureClass(implicit ctx: Context): ClassSymbol = FutureType.symbol.asClass
73+
74+
private lazy val FutureModule_successfulR = ctx.requiredModule("scala.concurrent.Future").requiredMethodRef("successful")
75+
def FutureModule_successful(implicit ctx: Context): Symbol = FutureModule_successfulR.symbol
76+
77+
private lazy val SuccessModule_applyR = ctx.requiredModule("scala.util.Success").requiredMethodRef(nme.apply)
78+
def SuccessModule_apply(implicit ctx: Context): Symbol = SuccessModule_applyR.symbol
79+
}
80+
81+
// The actual transform -------------------------------
82+
83+
override def transformPackageDef(tree: PackageDef)(implicit ctx: Context): Tree = {
84+
// TODO Can we cache this better?
85+
implicit val mydefn: MyDefinitions = new MyDefinitions()
86+
87+
@tailrec
88+
def hasTests(sym: ClassSymbol): Boolean = {
89+
sym.asClass.info.decls.exists(m => m.is(Method) && m.hasAnnotation(mydefn.TestAnnotClass)) ||
90+
sym.superClass.exists && hasTests(sym.superClass.asClass)
91+
}
92+
93+
def isTestClass(sym: Symbol): Boolean = {
94+
sym.isClass &&
95+
!sym.is(ModuleClass | Abstract | Trait) &&
96+
hasTests(sym.asClass)
97+
}
98+
99+
val bootstrappers = tree.stats.collect {
100+
case clDef: TypeDef if isTestClass(clDef.symbol) =>
101+
genBootstrapper(clDef.symbol.asClass)
102+
}
103+
104+
if (bootstrappers.isEmpty) tree
105+
else cpy.PackageDef(tree)(tree.pid, tree.stats ::: bootstrappers)
106+
}
107+
108+
private def genBootstrapper(testClass: ClassSymbol)(
109+
implicit ctx: Context, mydefn: MyDefinitions): TypeDef = {
110+
111+
val owner = testClass.owner
112+
val moduleSym = ctx.newCompleteModuleSymbol(owner,
113+
(testClass.name ++ "$scalajs$junit$bootstrapper").toTermName,
114+
Synthetic, Synthetic,
115+
List(defn.ObjectType, mydefn.BootstrapperType), newScope,
116+
coord = testClass.span, assocFile = testClass.assocFile).entered
117+
val classSym = moduleSym.moduleClass.asClass
118+
119+
val constr = genConstructor(classSym)
120+
121+
val testMethods = annotatedMethods(testClass, mydefn.TestAnnotClass)
122+
123+
val defs = List(
124+
genCallOnModule(classSym, Names.beforeClass, testClass.companionModule, mydefn.BeforeClassAnnotClass),
125+
genCallOnModule(classSym, Names.afterClass, testClass.companionModule, mydefn.AfterClassAnnotClass),
126+
genCallOnParam(classSym, Names.before, testClass, mydefn.BeforeAnnotClass),
127+
genCallOnParam(classSym, Names.after, testClass, mydefn.AfterAnnotClass),
128+
genTests(classSym, testMethods),
129+
genInvokeTest(classSym, testClass, testMethods),
130+
genNewInstance(classSym, testClass)
131+
)
132+
133+
val sbtCallback = ctx.sbtCallback
134+
if (sbtCallback != null) {
135+
// See computeClass() in ExtractAPI.scala
136+
import xsbti.api
137+
val name = classSym.fullName.stripModuleClassSuffix.toString
138+
val acc = api.Public.create()
139+
val mods = new api.Modifiers(false, false, /* final = */ true, false, false, false, false, false)
140+
val anns = Array[api.Annotation]()
141+
val defType = api.DefinitionType.Module
142+
def apiThis(sym: Symbol): api.Singleton = {
143+
val pathComponents = sym.ownersIterator.takeWhile(!_.isEffectiveRoot)
144+
.map(s => api.Id.of(s.name.toString))
145+
api.Singleton.of(api.Path.of(pathComponents.toArray.reverse ++ Array(api.This.create())))
146+
}
147+
val selfType = apiThis(classSym)
148+
val structure = {
149+
// TODO the first parameter is wrong, it should contain java.lang.Object
150+
api.Structure.of(api.SafeLazy.strict(Array()), api.SafeLazy.strict(Array()), api.SafeLazy.strict(Array()))
151+
}
152+
val topLevel = true
153+
val childrenOfSealedClass = Array[api.Type]()
154+
val tparams = Array[api.TypeParameter]()
155+
val classLike =
156+
api.ClassLike.of(name, acc, mods, anns, defType, api.SafeLazy.strict(selfType), api.SafeLazy.strict(structure), Array[String](),
157+
childrenOfSealedClass, topLevel, tparams)
158+
sbtCallback.api(ctx.compilationUnit.source.file.file, classLike)
159+
}
160+
161+
ClassDef(classSym, constr, defs)
162+
}
163+
164+
private def genConstructor(owner: ClassSymbol)(implicit ctx: Context): DefDef = {
165+
val sym = ctx.newConstructor(owner, Synthetic, Nil, Nil).entered
166+
DefDef(sym, {
167+
val objectType = defn.ObjectType
168+
Super(This(owner), nme.EMPTY.toTypeName, inConstrCall = true).select(defn.ObjectClass.primaryConstructor).appliedToNone
169+
})
170+
}
171+
172+
private def genCallOnModule(owner: ClassSymbol, name: TermName, module: Symbol, annot: Symbol)(implicit ctx: Context): DefDef = {
173+
val sym = ctx.newSymbol(owner, name, Synthetic | Method,
174+
MethodType(Nil, Nil, defn.UnitType)).entered
175+
176+
DefDef(sym, {
177+
if (module.exists) {
178+
val calls = annotatedMethods(module.moduleClass.asClass, annot)
179+
.map(m => Apply(ref(module).select(m), Nil))
180+
Block(calls, unitLiteral)
181+
} else {
182+
unitLiteral
183+
}
184+
})
185+
}
186+
187+
private def genCallOnParam(owner: ClassSymbol, name: TermName, testClass: ClassSymbol, annot: Symbol)(implicit ctx: Context): DefDef = {
188+
val sym = ctx.newSymbol(owner, name, Synthetic | Method,
189+
MethodType(Names.instance :: Nil, defn.ObjectType :: Nil, defn.UnitType)).entered
190+
191+
DefDef(sym, { (paramRefss: List[List[Tree]]) =>
192+
val List(List(instanceParamRef)) = paramRefss
193+
val calls = annotatedMethods(testClass, annot)
194+
.map(m => Apply(instanceParamRef.cast(testClass.typeRef).select(m), Nil))
195+
Block(calls, unitLiteral)
196+
})
197+
}
198+
199+
private def genTests(owner: ClassSymbol, tests: List[Symbol])(
200+
implicit ctx: Context, mydefn: MyDefinitions): DefDef = {
201+
202+
val sym = ctx.newSymbol(owner, Names.tests, Synthetic | Method,
203+
MethodType(Nil, defn.ArrayOf(mydefn.TestMetadataType))).entered
204+
205+
DefDef(sym, {
206+
val metadata = for (test <- tests) yield {
207+
val name = Literal(Constant(test.name.toString))
208+
val ignored = Literal(Constant(test.hasAnnotation(mydefn.IgnoreAnnotClass)))
209+
//val reifiedAnnot = New(mydefn.TestAnnotType, test.getAnnotation(mydefn.TestAnnotClass).get.arguments)
210+
val reifiedAnnot = New(mydefn.TestAnnotType, mydefn.TestAnnotType.member(nme.CONSTRUCTOR).suchThat(_.info.paramInfoss.head.isEmpty).symbol.asTerm, Nil)
211+
New(mydefn.TestMetadataType, List(name, ignored, reifiedAnnot))
212+
}
213+
JavaSeqLiteral(metadata, TypeTree(mydefn.TestMetadataType))
214+
})
215+
}
216+
217+
private def genInvokeTest(owner: ClassSymbol, testClass: ClassSymbol, tests: List[Symbol])(
218+
implicit ctx: Context, mydefn: MyDefinitions): DefDef = {
219+
220+
val sym = ctx.newSymbol(owner, Names.invokeTest, Synthetic | Method,
221+
MethodType(List(Names.instance, Names.name), List(defn.ObjectType, defn.StringType), mydefn.FutureType)).entered
222+
223+
DefDef(sym, { (paramRefss: List[List[Tree]]) =>
224+
val List(List(instanceParamRef, nameParamRef)) = paramRefss
225+
tests.foldRight[Tree] {
226+
val tp = mydefn.NoSuchMethodExceptionType
227+
val constr = tp.member(nme.CONSTRUCTOR).suchThat { c =>
228+
c.info.paramInfoss.head.size == 1 &&
229+
c.info.paramInfoss.head.head.isRef(defn.StringClass)
230+
}.symbol.asTerm
231+
Throw(New(tp, constr, nameParamRef :: Nil))
232+
} { (test, next) =>
233+
If(Literal(Constant(test.name.toString)).select(defn.Any_equals).appliedTo(nameParamRef),
234+
genTestInvocation(testClass, test, instanceParamRef),
235+
next)
236+
}
237+
})
238+
}
239+
240+
private def genTestInvocation(testClass: ClassSymbol, testMethod: Symbol, instance: Tree)(
241+
implicit ctx: Context, mydefn: MyDefinitions): Tree = {
242+
243+
def castInstance = instance.cast(testClass.typeRef)
244+
245+
val resultType = testMethod.info.resultType
246+
if (resultType.isRef(defn.UnitClass)) {
247+
val newSuccess = ref(mydefn.SuccessModule_apply).appliedTo(ref(defn.BoxedUnit_UNIT))
248+
Block(
249+
castInstance.select(testMethod).appliedToNone :: Nil,
250+
ref(mydefn.FutureModule_successful).appliedTo(newSuccess)
251+
)
252+
} else if (resultType.isRef(mydefn.FutureClass)) {
253+
castInstance.select(testMethod).appliedToNone
254+
} else {
255+
// We lie in the error message to not expose that we support async testing.
256+
ctx.error("JUnit test must have Unit return type", testMethod.sourcePos)
257+
EmptyTree
258+
}
259+
}
260+
261+
private def genNewInstance(owner: ClassSymbol, testClass: ClassSymbol)(implicit ctx: Context): DefDef = {
262+
val sym = ctx.newSymbol(owner, Names.newInstance, Synthetic | Method,
263+
MethodType(Nil, defn.ObjectType)).entered
264+
265+
DefDef(sym, New(testClass.typeRef, Nil))
266+
}
267+
268+
private def castParam(param: Symbol, clazz: Symbol)(implicit ctx: Context): Tree =
269+
ref(param).cast(clazz.typeRef)
270+
271+
private def annotatedMethods(owner: ClassSymbol, annot: Symbol)(implicit ctx: Context): List[Symbol] =
272+
owner.info.decls.filter(m => m.is(Method) && m.hasAnnotation(annot))
273+
}

compiler/src/dotty/tools/dotc/Compiler.scala

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ class Compiler {
112112
new ExpandPrivate, // Widen private definitions accessed from nested classes
113113
new RestoreScopes, // Repair scopes rendered invalid by moving definitions in prior phases of the group
114114
new SelectStatic, // get rid of selects that would be compiled into GetStatic
115+
new sjs.JUnitBootstrappers, // Generate JUnit-specific bootstrapper classes for Scala.js (not enabled by default)
115116
new CollectEntryPoints, // Find classes with main methods
116117
new CollectSuperCalls) :: // Find classes that are called with super
117118
Nil

project/Build.scala

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -802,6 +802,14 @@ object Build {
802802
},
803803
scalacOptions += "-scalajs",
804804

805+
libraryDependencies ~= {
806+
_.filter(!_.name.startsWith("junit-interface"))
807+
},
808+
//"com.novocode" % "junit-interface" % "0.11" % Test,
809+
810+
libraryDependencies +=
811+
"org.scala-js" % "scalajs-junit-test-runtime_2.12" % scalaJSVersion % "test",
812+
805813
// The main class cannot be found automatically due to the empty inc.Analysis
806814
mainClass in Compile := Some("hello.HelloWorld"),
807815

sandbox/scalajs/test/HelloTest.scala

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package hello
2+
3+
import org.junit.Test
4+
import org.junit.Assert._
5+
6+
class HelloTest {
7+
@Test
8+
def simpleTest(): Unit = {
9+
assertEquals(1, 1)
10+
}
11+
}

0 commit comments

Comments
 (0)