Unresolved reference: mockk - junit

I have imported mockk library in commonTest -> shared module. There are no import errors in the test classes, but when I run the test I get errors like:
Unresolved reference: every
Unresolved reference: mockk
Unresolved reference: verify
in all places where i use mock library methods. What could be the reason for the errors?
example of my test with errors in console:
class DefaultAppPreferenceStorageTest {
val appPreference = mockk<AppPreference>() //Unresolved reference: mockk
val jsonService = mockk<JsonService>() //Unresolved reference: mockk
val jsonKey = "key"
val value = 1
val stringValue = "$value"
val defaultIntValue = Random.nextInt()
val storage = DefaultAppPreferenceStorage(
appPreference,
jsonService
)
inner class PutJsonTest {
#BeforeTest
fun beforeEachTest() {
every { jsonService.mapToString(value) } returns stringValue //Unresolved reference: every
storage.putJson(jsonKey, value)
}
#Test
fun testPutJson() {
verify(verifyBlock = { jsonService.mapToString(value) }) //Unresolved reference: verify
verify(verifyBlock = { appPreference.putString(jsonKey, stringValue) }) //Unresolved reference: verify
}
}
...
}
UPDATE
Dependencies
const val mockk = "1.12.5"
const val mockk = "io.mockk:mockk-common:${Version.mockk}"
val commonTest by getting {
dependencies {
implementation(kotlin("test"))
implementation(kotlin("test-common"))
implementation(kotlin("test-annotations-common"))
implementation(ShareTestDependencies.mockk)
implementation(ShareTestDependencies.coroutinesTest)
}
}

I see the mentioned errors (Unresolved reference: every and other) when upgrading from mockk 1.12.5 to 1.13.2. I can work around it by adding a dependency to mockk-jvm (instead of or next to the existing mockk dependency).
<dependency>
<groupId>io.mockk</groupId>
<artifactId>mockk-jvm</artifactId>
<version>${mockk.version}</version>
</dependency>
The problem was addressed earlier (see https://github.com/mockk/mockk/issues/889) and assumed to be solved. Apparently this is not yet so in all cases.

If you are using KMP to build native targets (iOS, Linux, Windows, etc), mockk doesn't support native. It does support JVM and JS, and has a common source definition to support those 2 platforms. The IDE may not have an error because there is a common mockk definition (although I've never tried that).
Look at the test task that's actually being run. If it's for a native target, that's definitely what's happening.

Related

Create a generic Bundle in Chisel3

In Chisel3, I want to create a generic Bundle ParamsBus with parameterized type.
Then I follow the example on the Chisel3 website:
class ParamBus[T <: Data](gen: T) extends Bundle {
val dat1 = gen
val dat2 = gen
override def cloneType = (new ParamBus(gen)).asInstanceOf[this.type]
}
class TestMod[T <: Data](gen: T) extends Module {
val io = IO(new Bundle {
val o_out = Output(gen)
})
val reg_d = Reg(new ParamBus(gen))
io.o_out := 0.U
//io.o_out := reg_d.dat1 + reg_d.dat2
dontTouch(reg_d)
}
However, during code generation, I have the following error:
chisel3.AliasedAggregateFieldException: Aggregate ParamBus(Reg in TestMod) contains aliased fields List(UInt<8>)...
at fpga.examples.TestMod.<init>(test.scala:20)
Moreover, if I exchange the two lines to connect io.o_out, another error appears:
/home/escou64/Projects/fpga-io/src/main/scala/examples/test.scala:23:34: type mismatch;
found : T
required: String
io.o_out := reg_d.dat1 + reg_d.dat2
^
Any idea of the issue ?
Thanks for the help!
The issue you're running into is that the argument gen to ParamBus is a single object that is used for both dat1 and dat2. Scala (and thus Chisel) has reference semantics (like Java and Python), and thus dat1 and dat2 are both referring to the exact same object. Chisel needs the fields of Bundles to be different objects, thus the aliasing error you are seeing.
The easiest way to deal with this is to call .cloneType on gen when using it multiple times within a Bundle:
class ParamBus[T <: Data](gen: T) extends Bundle {
val dat1 = gen.cloneType
val dat2 = gen.cloneType
// Also note that you shouldn't need to implement cloneType yourself anymore
}
(Scastie link: https://scastie.scala-lang.org/mJmSdq8xSqayOceSjxHkRQ)
This is definitely a bit of a wart in the Chisel3 API because we try to hide the need to call .cloneType yourself, but least as of v3.4.3, this remains the case.
Alternatively, you could wrap the uses of gen in Output. It may seem weird to use a direction here but if all directions are Output, it's essentially the same as having no directions:
class ParamBus[T <: Data](gen: T) extends Bundle {
val dat1 = Output(gen)
val dat2 = Output(gen)
}
(Scastie link: https://scastie.scala-lang.org/TWajPNItRX6qOKDGDPnMmw)
A third (and slightly more advanced) technique is to make gen a 0-arity function (ie. a function that takes no arguments). Instead of gen being an object to use as a type template, it's instead a function that will create fresh types for you when called. Scala is a functional programming language so functions can be passed around as values just like objects can:
class ParamBus[T <: Data](gen: () => T) extends Bundle {
val dat1 = gen()
val dat2 = gen()
}
// You can call it like so:
// new ParamBus(() => UInt(8.W))
(Scastie link: https://scastie.scala-lang.org/JQ7D8VZsSCWP2i6DWJ4cLA)
I tend to prefer this final version, but I understand it can be more daunting for new users. Eventually I'd like to fix the issue you're seeing with a more direct use of gen, but these are ways to deal with the issue for the time being.

Generating waveforms with ChiselTest framework

I have a ChiselTest tester written as follows:
class EccTester extends FlatSpec with ChiselScalatestTester with Matchers {
behavior of "Testers2"
it should "send data without errors" in {
test(new EccPair(width=8)) {
c => {
val rnd = new Random()
for (i <- 0 to 20) {
val testVal = rnd.nextInt(1 << c.getWidthParam)
c.io.dataIn.poke(testVal.U)
c.io.errorLocation.poke(0.U)
c.io.injectError.poke(false.B)
c.io.injectSecondError.poke(false.B)
c.clock.step(1)
c.io.dataOut.expect(testVal.U)
c.io.outputNotEqual.expect(false.B)
}
}
}
}
}
I am able to run the test in the shell with
testOnly chisel.lib.ecc.EccTester
But when I try to generate waveforms per the ChiselTest documentation,
testOnly chisel.lib.ecc.EccTester -- -DvwriteVcd=1
The test executes OK but does not dump a waveform.
Documentation I referenced is https://github.com/ucb-bar/chisel-testers2, and the full source code is at https://github.com/hutch31/ip-contributions/blob/ecc/src/test/scala/chisel/lib/ecc/EccTester.scala
I don’t think there is a formal answer to this yet, but here’s what I do. First I add the two following imports.
import chiseltest.experimental.TestOptionBuilder._
import chiseltest.internal.WriteVcdAnnotation
then add the annotation to the test like this
it should "send data without errors" in {
test(new EccPair(width=8)).withAnnotations(Seq(WriteVcdAnnotation)) {
c => {
Note: there are two definitions of WriteVcdAnnotation, one is in package treadle
and the other is in package chiseltest.internal. Use the latter, as it will work
for both treadle and verilator backends.

Why can't 'kotlin.Result' be used as a return type?

I've created a method, and the return is Result<R> in a class of MyClass<R>, but the error message is: 'kotlin.Result' cannot be used as a return type
I've also looked into the Result source code for some hints; why is this so?
Test code (using v. 1.3-RC).
class MyClass<R>(val r: R) {
fun f(): Result<R> { // error here
return Result.success(r)
}
}
fun main(args: Array<String>) {
val s = Result.success(1)
val m = MyClass(s)
}
From the Kotlin KEEP:
The rationale behind these limitations is that future versions of
Kotlin may expand and/or change semantics of functions that return
Result type and null-safety operators may change their semantics when
used on values of Result type. In order to avoid breaking existing
code in the future releases of Kotin and leave door open for those
changes, the corresponding uses produce an error now. Exceptions to
this rule are made for carefully-reviewed declarations in the standard
library that are part of the Result type API itself.
Note: if you just want to experiment with the Result type you can bypass this limitation by supplying a Kotlin compiler argument -Xallow-result-return-type.
When using Gradle on Java or Android project:
Define the compiler argument on Kotlin compilation task. It applies both for production code and tests.
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
kotlinOptions {
freeCompilerArgs = freeCompilerArgs + "-Xallow-result-return-type"
}
}
When using Gradle on Multiplatform project:
Define the compiler argument for each target compilation. It applies both for production code and tests.
kotlin {
targets.all {
compilations.all {
kotlinOptions {
freeCompilerArgs = freeCompilerArgs + "-Xallow-result-return-type"
}
}
}
}
android {
kotlinOptions {
freeCompilerArgs = ["-Xallow-result-return-type"]
}
}
If you using android this solution for gradle
If using maven:
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<configuration>
<jvmTarget>1.8</jvmTarget>
<args>
<arg>-Xallow-result-return-type</arg>
</args>
</configuration>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
If using gradle:
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
kotlinOptions.freeCompilerArgs = ["-Xallow-result-return-type"]
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
kotlinOptions.freeCompilerArgs = ["-Xallow-result-return-type"]
}
Source: http://rustyrazorblade.com/post/2018/2018-12-06-kotlin-result/
Update the kotlin version to 1.5 or above. See:
https://github.com/Kotlin/KEEP/blob/master/proposals/stdlib/result.md#limitations-legacy

Are Akka .conf dispatcher configuration working?

I'm using Akka 2.2-RC1 and I'm not able to get Akka to load dispatcher configuration from application.conf:
my-dispatcher {
type = PinnedDispatcher
executor = "thread-pool-executor"
}
akka.actor.deployment {
/test {
dispatcher = my-dispatcher
}
}
When instantiated from code like
val test = system.actorOf(Props[Test], "test")
by logs it is still using akka.actor.default-dispatcher.
When I'm adding .withDispatcher("my-dispatcher") to Props all is working properly and my-dispatcher is used. But I do not like idea of adding .withDispatcher(...) to all my actors...
Do anyone know where could be a problem? I was thinking that actor path may be wrong, but apllication.conf routing configuration works properly (with exception of custom routee dispatcher, again).
After some testing I've found that this effect is caused by use of RemoteActorRefProvider. As soon as I disabled it and changed to default
akka.actor.provider = "akka.actor.LocalActorRefProvider"
dispatchers were configuring from config properly.
I guess with remoting enabled Akka looks elsewhere for configuration of actor dispatchers or maybe remote refs have different logical paths?
This worked fine for me on the same version of akka that you were using. My config:
test{
my-dispatcher {
type = PinnedDispatcher
executor = "thread-pool-executor"
}
akka.actor.deployment {
/test-actor {
dispatcher = my-dispatcher
}
}
}
My code:
object ActorTest{
def main(args: Array[String]) {
val conf = ConfigFactory.load()
val system = ActorSystem("test", conf.getConfig("test"))
val ref = system.actorOf(Props[TestActor], "test-actor")
}
}
class TestActor extends Actor{
def receive = {
case _ =>
}
}
I used jconsole and shows that the pinned dispatcher was listed under the Threads tab

Accessing java.awt.Container.getComponents from scala

I'm trying to write automated tests for a gui application written in scala with swing. I'm adapting the code from this article which leverages getName() to find the right ui element in the tree.
This is a self-contained version of my code. It's incomplete, untested, and probably broken and/or non-idiomatic and/or suboptimal in various ways, but my question is regarding the compiler error listed below.
import scala.swing._
import java.awt._
import ListView._
import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith
import org.scalatest.FunSpec
import org.scalatest.matchers.ShouldMatchers
object MyGui extends SimpleSwingApplication {
def top = new MainFrame {
title = "MyGui"
val t = new Table(3, 3)
t.peer.setName("my-table")
contents = t
}
}
object TestUtils {
def getChildNamed(parent: UIElement, name: String): UIElement = {
// Debug line
println("Class: " + parent.peer.getClass() +
" Name: " + parent.peer.getName())
if (name == parent.peer.getName()) { return parent }
if (parent.peer.isInstanceOf[java.awt.Container]) {
val children = parent.peer.getComponents()
/// COMPILER ERROR HERE ^^^
for (child <- children) {
val matching_child = getChildNamed(child, name)
if (matching_child != null) { return matching_child }
}
}
return null
}
}
#RunWith(classOf[JUnitRunner])
class MyGuiSpec extends FunSpec {
describe("My gui window") {
it("should have a table") {
TestUtils.getChildNamed(MyGui.top, "my-table")
}
}
}
When I compile this file I get:
29: error: value getComponents is not a member of java.awt.Component
val children = parent.peer.getComponents()
^
one error found
As far as I can tell, getComponents is in fact a member of java.awt.Component. I used the code in this answer to dump the methods on parent.peer, and I can see that getComponents is in the list.
Answers that provide another approach to the problem (automated gui testing in a similar manner) are welcome, but I'd really like to understand why I can't access getComponents.
The issue is that you're looking at two different classes. Your javadoc link points to java.awt.Container, which indeed has getComponents method. On the other hand, the compiler is looking for getComponents on java.awt.Component (the parent class), which is returned by parent.peer, and can't find it.
Instead of if (parent.peer.isInstanceOf[java.awt.Container]) ..., you can verify the type of parent.peer and cast it like this:
parent.peer match {
case container: java.awt.Container =>
// the following works because container isA Container
val children = container.getComponents
// ...
case _ => // ...
}