Skip to content

Commit 54d6d30

Browse files
committed
Emit Scala.js JUnit bootstrappers for JUnit test classes.
This allows Scala.js for dotty to support normal JUnit tests.
1 parent 3556991 commit 54d6d30

File tree

6 files changed

+418
-1
lines changed

6 files changed

+418
-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: 341 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,341 @@
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 objects for Scala.js.
23+
*
24+
* On the JVM, JUnit uses run-time reflection to list and invoke JUnit-related
25+
* methods. They are identified by annotations such as `@Test`, `@Before`,
26+
* etc. In Scala.js, there is no such reflection for methods and annotations,
27+
* so a different strategy is used: this phase performs the necessary
28+
* inspections at compile-time, and generates a so-called bootstrapper object
29+
* where all those metadata have been reified.
30+
*
31+
* With an example: given the following JUnit test class:
32+
*
33+
* ```
34+
* class MyTest {
35+
* @Before def myBefore(): Unit = ...
36+
* @Before def otherBefore(): Unit = ...
37+
*
38+
* @Test def syncTest(): Unit = ...
39+
* @Test def asyncTest(): Future[Try[Unit]] = ...
40+
*
41+
* @Ignore @Test def ignoredTest(): Unit = ...
42+
* }
43+
*
44+
* object MyTest {
45+
* @AfterClass def myAfterClass(): Unit = ...
46+
* }
47+
* ```
48+
*
49+
* this phase generates the following bootstrapper module class:
50+
*
51+
* ```
52+
* object MyTest$scalajs$junit$bootstrapper extends Object with Bootstrapper {
53+
* def beforeClass(): Unit = {
54+
* // nothing, since there is no @BeforeClass method in object MyTest
55+
* }
56+
*
57+
* def afterClass(): Unit = {
58+
* MyTest.myAfterClass()
59+
* }
60+
*
61+
* def before(instance: Object): Unit = {
62+
* // typically 0 or 1, but also support 2 or more
63+
* instance.asInstanceOf[MyTest].myBefore()
64+
* instance.asInstanceOf[MyTest].otherBefore()
65+
* }
66+
*
67+
* def after(instance: Object): Unit = {
68+
* // nothing, since there is no @After method in class MyTest
69+
* }
70+
*
71+
* def tests(): Array[TestMetadata] = Array(
72+
* new TestMetadata("syncTest", false, new org.junit.Test()),
73+
* new TestMetadata("asyncTest", false, new org.junit.Test()),
74+
* new TestMetadata("ignoredTest", true, new org.junit.Test()),
75+
* )
76+
*
77+
* def invokeTest(instance: Object, name: String): Future[Unit] = {
78+
* val castInstance: MyTest = instance.asInstanceOf[MyTest]
79+
* if ("syncTest".equals(name))
80+
* Future.successful(scala.util.Success(castInstance.syncTest()))
81+
* else if ("asyncTest".equals(name))
82+
* castInstance.asyncTest() // asyncTest() already returns a Future[Try[Unit]]
83+
* else if ("ignoredTest".equals(name))
84+
* Future.successful(scala.util.Success(castInstance.ignoredTest()))
85+
* else
86+
* throw new NoSuchMethodException(name)
87+
* }
88+
*
89+
* def newInstance(): Object = new MyTest()
90+
* }
91+
* ```
92+
*
93+
* Note that the support for test methods returning `Future`s is specific to
94+
* Scala.js, and not advertised as a public feature. It is necessary to test
95+
* some things in Scala.js itself, but outside users should use a testing
96+
* framework with official asynchronous support instead.
97+
*
98+
* Because `Booststrapper` is annotated with `@EnableReflectiveInstantiation`,
99+
* the run-time implementation of JUnit for Scala.js can load the boostrapper
100+
* module using `scala.scalajs.reflect.Reflect`, and then use the methods of
101+
* Bootstrapper, which are implemented in the bootstrapper object, to perform
102+
* test discovery and invocation.
103+
*
104+
* TODO At the moment, this phase does not handle `@Test` annotations with
105+
* parameters, notably the expected exception class. This should be handled at
106+
* some point in the future.
107+
*/
108+
class JUnitBootstrappers extends MiniPhase {
109+
import ast.tpd._
110+
111+
def phaseName: String = "junitBootstrappers"
112+
113+
override def isEnabled(implicit ctx: Context): Boolean =
114+
super.isEnabled && ctx.settings.scalajs.value
115+
116+
private object Names {
117+
val beforeClass: TermName = termName("beforeClass")
118+
val afterClass: TermName = termName("afterClass")
119+
val before: TermName = termName("before")
120+
val after: TermName = termName("after")
121+
val tests: TermName = termName("tests")
122+
val invokeTest: TermName = termName("invokeTest")
123+
val newInstance: TermName = termName("newInstance")
124+
125+
val instance: TermName = termName("instance")
126+
val name: TermName = termName("name")
127+
val castInstance: TermName = termName("castInstance")
128+
}
129+
130+
private class MyDefinitions()(implicit ctx: Context) {
131+
lazy val TestAnnotType: TypeRef = ctx.requiredClassRef("org.junit.Test")
132+
def TestAnnotClass(implicit ctx: Context): ClassSymbol = TestAnnotType.symbol.asClass
133+
134+
lazy val BeforeAnnotType: TypeRef = ctx.requiredClassRef("org.junit.Before")
135+
def BeforeAnnotClass(implicit ctx: Context): ClassSymbol = BeforeAnnotType.symbol.asClass
136+
137+
lazy val AfterAnnotType: TypeRef = ctx.requiredClassRef("org.junit.After")
138+
def AfterAnnotClass(implicit ctx: Context): ClassSymbol = AfterAnnotType.symbol.asClass
139+
140+
lazy val BeforeClassAnnotType: TypeRef = ctx.requiredClassRef("org.junit.BeforeClass")
141+
def BeforeClassAnnotClass(implicit ctx: Context): ClassSymbol = BeforeClassAnnotType.symbol.asClass
142+
143+
lazy val AfterClassAnnotType: TypeRef = ctx.requiredClassRef("org.junit.AfterClass")
144+
def AfterClassAnnotClass(implicit ctx: Context): ClassSymbol = AfterClassAnnotType.symbol.asClass
145+
146+
lazy val IgnoreAnnotType: TypeRef = ctx.requiredClassRef("org.junit.Ignore")
147+
def IgnoreAnnotClass(implicit ctx: Context): ClassSymbol = IgnoreAnnotType.symbol.asClass
148+
149+
lazy val BootstrapperType: TypeRef = ctx.requiredClassRef("org.scalajs.junit.Bootstrapper")
150+
151+
lazy val TestMetadataType: TypeRef = ctx.requiredClassRef("org.scalajs.junit.TestMetadata")
152+
153+
lazy val NoSuchMethodExceptionType: TypeRef = ctx.requiredClassRef("java.lang.NoSuchMethodException")
154+
155+
lazy val FutureType: TypeRef = ctx.requiredClassRef("scala.concurrent.Future")
156+
def FutureClass(implicit ctx: Context): ClassSymbol = FutureType.symbol.asClass
157+
158+
private lazy val FutureModule_successfulR = ctx.requiredModule("scala.concurrent.Future").requiredMethodRef("successful")
159+
def FutureModule_successful(implicit ctx: Context): Symbol = FutureModule_successfulR.symbol
160+
161+
private lazy val SuccessModule_applyR = ctx.requiredModule("scala.util.Success").requiredMethodRef(nme.apply)
162+
def SuccessModule_apply(implicit ctx: Context): Symbol = SuccessModule_applyR.symbol
163+
}
164+
165+
// The actual transform -------------------------------
166+
167+
override def transformPackageDef(tree: PackageDef)(implicit ctx: Context): Tree = {
168+
// TODO Can we cache this better?
169+
implicit val mydefn: MyDefinitions = new MyDefinitions()
170+
171+
@tailrec
172+
def hasTests(sym: ClassSymbol): Boolean = {
173+
sym.info.decls.exists(m => m.is(Method) && m.hasAnnotation(mydefn.TestAnnotClass)) ||
174+
sym.superClass.exists && hasTests(sym.superClass.asClass)
175+
}
176+
177+
def isTestClass(sym: Symbol): Boolean = {
178+
sym.isClass &&
179+
!sym.is(ModuleClass | Abstract | Trait) &&
180+
hasTests(sym.asClass)
181+
}
182+
183+
val bootstrappers = tree.stats.collect {
184+
case clDef: TypeDef if isTestClass(clDef.symbol) =>
185+
genBootstrapper(clDef.symbol.asClass)
186+
}
187+
188+
if (bootstrappers.isEmpty) tree
189+
else cpy.PackageDef(tree)(tree.pid, tree.stats ::: bootstrappers)
190+
}
191+
192+
private def genBootstrapper(testClass: ClassSymbol)(
193+
implicit ctx: Context, mydefn: MyDefinitions): TypeDef = {
194+
195+
val owner = testClass.owner
196+
val moduleSym = ctx.newCompleteModuleSymbol(owner,
197+
(testClass.name ++ "$scalajs$junit$bootstrapper").toTermName,
198+
Synthetic, Synthetic,
199+
List(defn.ObjectType, mydefn.BootstrapperType), newScope,
200+
coord = testClass.span, assocFile = testClass.assocFile).entered
201+
val classSym = moduleSym.moduleClass.asClass
202+
203+
val constr = genConstructor(classSym)
204+
205+
val testMethods = annotatedMethods(testClass, mydefn.TestAnnotClass)
206+
207+
val defs = List(
208+
genCallOnModule(classSym, Names.beforeClass, testClass.companionModule, mydefn.BeforeClassAnnotClass),
209+
genCallOnModule(classSym, Names.afterClass, testClass.companionModule, mydefn.AfterClassAnnotClass),
210+
genCallOnParam(classSym, Names.before, testClass, mydefn.BeforeAnnotClass),
211+
genCallOnParam(classSym, Names.after, testClass, mydefn.AfterAnnotClass),
212+
genTests(classSym, testMethods),
213+
genInvokeTest(classSym, testClass, testMethods),
214+
genNewInstance(classSym, testClass)
215+
)
216+
217+
if (ctx.sbtCallback != null)
218+
sbt.APIUtils.registerDummyClass(classSym)
219+
220+
ClassDef(classSym, constr, defs)
221+
}
222+
223+
private def genConstructor(owner: ClassSymbol)(implicit ctx: Context): DefDef = {
224+
val sym = ctx.newDefaultConstructor(owner).entered
225+
DefDef(sym, {
226+
Block(
227+
Super(This(owner), nme.EMPTY.toTypeName, inConstrCall = true).select(defn.ObjectClass.primaryConstructor).appliedToNone :: Nil,
228+
unitLiteral
229+
)
230+
})
231+
}
232+
233+
private def genCallOnModule(owner: ClassSymbol, name: TermName, module: Symbol, annot: Symbol)(implicit ctx: Context): DefDef = {
234+
val sym = ctx.newSymbol(owner, name, Synthetic | Method,
235+
MethodType(Nil, Nil, defn.UnitType)).entered
236+
237+
DefDef(sym, {
238+
if (module.exists) {
239+
val calls = annotatedMethods(module.moduleClass.asClass, annot)
240+
.map(m => Apply(ref(module).select(m), Nil))
241+
Block(calls, unitLiteral)
242+
} else {
243+
unitLiteral
244+
}
245+
})
246+
}
247+
248+
private def genCallOnParam(owner: ClassSymbol, name: TermName, testClass: ClassSymbol, annot: Symbol)(implicit ctx: Context): DefDef = {
249+
val sym = ctx.newSymbol(owner, name, Synthetic | Method,
250+
MethodType(Names.instance :: Nil, defn.ObjectType :: Nil, defn.UnitType)).entered
251+
252+
DefDef(sym, { (paramRefss: List[List[Tree]]) =>
253+
val List(List(instanceParamRef)) = paramRefss
254+
val calls = annotatedMethods(testClass, annot)
255+
.map(m => Apply(instanceParamRef.cast(testClass.typeRef).select(m), Nil))
256+
Block(calls, unitLiteral)
257+
})
258+
}
259+
260+
private def genTests(owner: ClassSymbol, tests: List[Symbol])(
261+
implicit ctx: Context, mydefn: MyDefinitions): DefDef = {
262+
263+
val sym = ctx.newSymbol(owner, Names.tests, Synthetic | Method,
264+
MethodType(Nil, defn.ArrayOf(mydefn.TestMetadataType))).entered
265+
266+
DefDef(sym, {
267+
val metadata = for (test <- tests) yield {
268+
val name = Literal(Constant(test.name.toString))
269+
val ignored = Literal(Constant(test.hasAnnotation(mydefn.IgnoreAnnotClass)))
270+
// TODO Handle @Test annotations with arguments
271+
// val reifiedAnnot = New(mydefn.TestAnnotType, test.getAnnotation(mydefn.TestAnnotClass).get.arguments)
272+
val testAnnot = test.getAnnotation(mydefn.TestAnnotClass).get
273+
if (testAnnot.arguments.nonEmpty)
274+
ctx.error("@Test annotations with arguments are not yet supported in Scala.js for dotty", testAnnot.tree.sourcePos)
275+
val noArgConstr = mydefn.TestAnnotType.member(nme.CONSTRUCTOR).suchThat(_.info.paramInfoss.head.isEmpty).symbol.asTerm
276+
val reifiedAnnot = New(mydefn.TestAnnotType, noArgConstr, Nil)
277+
New(mydefn.TestMetadataType, List(name, ignored, reifiedAnnot))
278+
}
279+
JavaSeqLiteral(metadata, TypeTree(mydefn.TestMetadataType))
280+
})
281+
}
282+
283+
private def genInvokeTest(owner: ClassSymbol, testClass: ClassSymbol, tests: List[Symbol])(
284+
implicit ctx: Context, mydefn: MyDefinitions): DefDef = {
285+
286+
val sym = ctx.newSymbol(owner, Names.invokeTest, Synthetic | Method,
287+
MethodType(List(Names.instance, Names.name), List(defn.ObjectType, defn.StringType), mydefn.FutureType)).entered
288+
289+
DefDef(sym, { (paramRefss: List[List[Tree]]) =>
290+
val List(List(instanceParamRef, nameParamRef)) = paramRefss
291+
val castInstanceSym = ctx.newSymbol(sym, Names.castInstance, Synthetic, testClass.typeRef, coord = owner.span)
292+
Block(
293+
ValDef(castInstanceSym, instanceParamRef.cast(testClass.typeRef)) :: Nil,
294+
tests.foldRight[Tree] {
295+
val tp = mydefn.NoSuchMethodExceptionType
296+
val constr = tp.member(nme.CONSTRUCTOR).suchThat { c =>
297+
c.info.paramInfoss.head.size == 1 &&
298+
c.info.paramInfoss.head.head.isRef(defn.StringClass)
299+
}.symbol.asTerm
300+
Throw(New(tp, constr, nameParamRef :: Nil))
301+
} { (test, next) =>
302+
If(Literal(Constant(test.name.toString)).select(defn.Any_equals).appliedTo(nameParamRef),
303+
genTestInvocation(testClass, test, ref(castInstanceSym)),
304+
next)
305+
}
306+
)
307+
})
308+
}
309+
310+
private def genTestInvocation(testClass: ClassSymbol, testMethod: Symbol, instance: Tree)(
311+
implicit ctx: Context, mydefn: MyDefinitions): Tree = {
312+
313+
val resultType = testMethod.info.resultType
314+
if (resultType.isRef(defn.UnitClass)) {
315+
val newSuccess = ref(mydefn.SuccessModule_apply).appliedTo(ref(defn.BoxedUnit_UNIT))
316+
Block(
317+
instance.select(testMethod).appliedToNone :: Nil,
318+
ref(mydefn.FutureModule_successful).appliedTo(newSuccess)
319+
)
320+
} else if (resultType.isRef(mydefn.FutureClass)) {
321+
instance.select(testMethod).appliedToNone
322+
} else {
323+
// We lie in the error message to not expose that we support async testing.
324+
ctx.error("JUnit test must have Unit return type", testMethod.sourcePos)
325+
EmptyTree
326+
}
327+
}
328+
329+
private def genNewInstance(owner: ClassSymbol, testClass: ClassSymbol)(implicit ctx: Context): DefDef = {
330+
val sym = ctx.newSymbol(owner, Names.newInstance, Synthetic | Method,
331+
MethodType(Nil, defn.ObjectType)).entered
332+
333+
DefDef(sym, New(testClass.typeRef, Nil))
334+
}
335+
336+
private def castParam(param: Symbol, clazz: Symbol)(implicit ctx: Context): Tree =
337+
ref(param).cast(clazz.typeRef)
338+
339+
private def annotatedMethods(owner: ClassSymbol, annot: Symbol)(implicit ctx: Context): List[Symbol] =
340+
owner.info.decls.filter(m => m.is(Method) && m.hasAnnotation(annot))
341+
}

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

0 commit comments

Comments
 (0)