Skip to content

Commit 3077e62

Browse files
authored
Merge pull request #7 from oranda/illtyped
TypeCheckingExercises
2 parents b0af4c4 + ff3d19f commit 3077e62

File tree

3 files changed

+75
-1
lines changed

3 files changed

+75
-1
lines changed

src/main/scala/shapeless/ShapelessLib.scala

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ object ShapelessLib extends exercise.Library {
2424
AutoTypeClassExercises,
2525
LazyExercises,
2626
SizedExercises,
27-
TypeSafeCastExercises
27+
TypeSafeCastExercises,
28+
TypeCheckingExercises
2829
)
2930
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package shapelessex
2+
3+
import org.scalatest._
4+
import shapeless._
5+
6+
import scala.util.Try
7+
8+
/** == Testing for non-compilation ==
9+
*
10+
* Libraries like shapeless which make extensive use of type-level computation and implicit resolution often need to
11+
* provide guarantees that certain expressions *don't* typecheck. Testing these guarantees is supported in shapeless via
12+
* the `illTyped` macro,
13+
* {{{
14+
* import shapeless.test.illTyped
15+
*
16+
* scala> illTyped { """1+1 : Boolean""" }
17+
*
18+
* scala> illTyped { """1+1 : Int""" }
19+
* <console>:19: error: Type-checking succeeded unexpectedly.
20+
* Expected some error.
21+
* illTyped { """1+1 : Int""" }
22+
* }}}
23+
*
24+
* @param name type_checking
25+
*/
26+
object TypeCheckingExercises extends FlatSpec with Matchers with exercise.Section {
27+
28+
/** The testing library ScalaTest also has a way of checking that a snippet of code
29+
* does not compile: pass it in to `assertTypeError`. What will happen if we combine
30+
* `illTyped` and `assertTypeError`? (Hint: it's like applying a double negative.)
31+
*/
32+
def typeCheckingTest(res0: Boolean, res1: Boolean) = {
33+
34+
import shapeless.test.illTyped
35+
36+
val matchedTypes = Try {
37+
assertTypeError("illTyped { \"val a: Int = 1\" }")
38+
true
39+
} getOrElse {
40+
false
41+
}
42+
matchedTypes should be(res0)
43+
44+
val mismatchedTypes = Try {
45+
assertTypeError("illTyped { \"val a: String = 1\" }")
46+
true
47+
} getOrElse {
48+
false
49+
}
50+
mismatchedTypes should be(res1)
51+
}
52+
53+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package exercises
2+
3+
import shapelessex._
4+
import shapeless.HNil
5+
6+
import org.scalatest.Spec
7+
import org.scalatest.prop.Checkers
8+
9+
import org.scalacheck.Shapeless._
10+
11+
class TypeCheckingExercisesSpec extends Spec with Checkers {
12+
def `testing for non-compilation` = {
13+
check(
14+
Test.testSuccess(
15+
TypeCheckingExercises.typeCheckingTest _,
16+
true :: false :: HNil
17+
)
18+
)
19+
}
20+
}

0 commit comments

Comments
 (0)