Can't Run `test` in Scala Test with SBT - scala

src/main/scala/Testing.scala
package common
object Add1Method {
def main(args: Array[String]) = 100+2
}
project/build.sbt
name := "Foo"
version := "1.0"
scalaVersion := "2.10.2"
libraryDependencies += "org.scalatest" % "scalatest_2.10" % "1.9.1" % "test"
resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots"
resolvers += "Sonatype Releases" at "http://oss.sonatype.org/content/repositories/releases"
src/test/scala/Test.scala
package test
import common.Testing
import org.scalatest._
class Test extends FlatSpec with Matchers {
"running main" should "return 102" in {
val result = Add1Method.main(Array("asdf"))
assert(result == 102)
}
}
But, when I run test from SBT, the following 4 compile-time errors:
[error] Test.scala:4: object scalatest is not a member of package org
[error] import org.scalatest._
[error] ^
[error] Test.scala:6: not found: type FlatSpec
[error] class Test extends FlatSpec with Matchers {
[error] ^
[error] Test.scala:6: not found: type Matchers
[error] class Test extends FlatSpec with Matchers {
[error] ^
[error] Test.scala:8: value should is not a member of String
[error] "running main" should "return 102" in {
[error] ^
[error] four errors found
Note that I tried the suggested answer in SBT not finding scalatest for scala 2.10.1 without success.
The ScalaTest example uses the same imports - http://www.scalatest.org/quick_start.

I think the problem is that your build.sbt is in the wrong place. It should not be in project/ but in the root directory, next to the src directory.
See Directories in the sbt documentation for more info.

Related

Issue in testing using scalatest

I just set up a new scala project with sbt in IntelliJ, and wrote the following basic class:
Person.scala:
package learning.functional
case class Person(
name: String
)
Main.scala:
package learning.functional
import learning.functional.person
object Main{
val p = Person("John")
}
PersonTest.scala:
import learning.functional.Person
import org.scalatest.FunSuite
class PersonTest extends FunSuite {
test("test person") {
val p = Person("John")
assert(p.name == "John")
}
}
When I try to run sbt test, it throws the following error:
## Exception when compiling 1 sources to /Users/johndooley/Desktop/Scala/scala-learning/target/scala-2.13/test-classes
[error] java.lang.AssertionError: assertion failed:
[error] unexpected value engine in trait FunSuite final <expandedname> private[this]
[error] while compiling: /Users/johndooley/Desktop/Scala/scala-learning/src/test/scala/PersonTest.scala
What could be the reason for this? My build.sbt file:
ThisBuild / scalaVersion := "2.13.10"
libraryDependencies += "org.scalatest" % "scalatest_2.10" % "1.9.1"
lazy val root = (project in file("."))
.settings(
name := "scala-learning"
)
Project structure:
I have tried invalidating cache and restarting, doing clean, update, compile, but nothing works.
I solved this by modifying my dependency to the following:
libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.14"
and completely reloading the sbt shell

sbt - object apache is not a member of package org

I want to deploy and submit a spark program using sbt but its throwing error.
Code:
package in.goai.spark
import org.apache.spark.{SparkContext, SparkConf}
object SparkMeApp {
def main(args: Array[String]) {
val conf = new SparkConf().setAppName("First Spark")
val sc = new SparkContext(conf)
val fileName = args(0)
val lines = sc.textFile(fileName).cache
val c = lines.count
println(s"There are $c lines in $fileName")
}
}
build.sbt
name := "First Spark"
version := "1.0"
organization := "in.goai"
scalaVersion := "2.11.8"
libraryDependencies += "org.apache.spark" %% "spark-core" % "1.6.1"
resolvers += Resolver.mavenLocal
Under first/project directory
build.properties
bt.version=0.13.9
When I am trying to run sbt package its throwing error given below.
[root#hadoop first]# sbt package
[info] Loading project definition from /home/training/workspace_spark/first/project
[info] Set current project to First Spark (in build file:/home/training/workspace_spark/first/)
[info] Compiling 1 Scala source to /home/training/workspace_spark/first/target/scala-2.11/classes...
[error] /home/training/workspace_spark/first/src/main/scala/LineCount.scala:3: object apache is not a member of package org
[error] import org.apache.spark.{SparkContext, SparkConf}
[error] ^
[error] /home/training/workspace_spark/first/src/main/scala/LineCount.scala:9: not found: type SparkConf
[error] val conf = new SparkConf().setAppName("First Spark")
[error] ^
[error] /home/training/workspace_spark/first/src/main/scala/LineCount.scala:11: not found: type SparkContext
[error] val sc = new SparkContext(conf)
[error] ^
[error] three errors found
[error] (compile:compile) Compilation failed
[error] Total time: 4 s, completed May 10, 2018 4:05:10 PM
I have tried with extends to App too but no change.
Please remove resolvers += Resolver.mavenLocal from build.sbt. Since spark-core is available on Maven, we don't need to use local resolvers.
After that, you can try sbt clean package.

Finch Hello World Error: Http not a member of com.twitter.finagle

I'm trying to use the scala finch library to build an API.
I have the following simple code:
package example
import io.finch._
import com.twitter.finagle.Http
object HelloWorld extends App {
val api: Endpoint[String] = get("hello") { Ok("Hello, World!") }
Http.serve(":8080", api.toService)
}
And a build.sbt file that looks like this:
name := "hello-finch"
version := "1.0"
scalaVersion := "2.10.6"
mainClass in (Compile, run) := Some("example.HelloWorld")
libraryDependencies ++= Seq(
"com.github.finagle" %% "finch-core" % "0.10.0"
)
// found here: https://github.com/finagle/finch/issues/604
addCompilerPlugin(
"org.scalamacros" % "paradise" % "2.1.0" cross CrossVersion.full
)
When I compile and run the code I get this error message:
object Http is not a member of package com.twitter.finagle
[error] import com.twitter.finagle.Http
[error] ^
[error] /Users/jamesk/Code/hello_finch/hello-finch/src/main/scala/example/Hello.scala:8: wrong number of type arguments for io.finch.Endpoint, should be 2
[error] val api: Endpoint[String] = get("hello") { Ok("Hello, World!") }
[error] ^
[error] /Users/jamesk/Code/hello_finch/hello-finch/src/main/scala/example/Hello.scala:8: not found: value get
[error] val api: Endpoint[String] = get("hello") { Ok("Hello, World!") }
[error] ^
[error] /Users/jamesk/Code/hello_finch/hello-finch/src/main/scala/example/Hello.scala:10: not found: value Http
[error] Http.serve(":8080", api.toService)
[error] ^
[error] four errors found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 1 s, completed Aug 15, 2017 12:56:01 PM
At this point I'm running out of ideas, it looks like a good library but it's a pain getting it working. Any help would be very much appreciated.
I have updated your example to work with the last version of Finch: "com.github.finagle" %% "finch-core" % "0.15.1" and also Scala 2.12
the build.sbt file:
name := "hello-finch"
version := "1.0"
scalaVersion := "2.12.2"
mainClass in (Compile, run) := Some("example.HelloWorld")
libraryDependencies ++= Seq(
"com.github.finagle" %% "finch-core" % "0.15.1"
)
then, the src/main/scala/example/HelloWorld.scala file:
package example
import io.finch._
import com.twitter.finagle.Http
import com.twitter.util.Await
object HelloWorld extends App {
val api: Endpoint[String] = get("hello") { Ok("Hello, World!") }
Await.ready(Http.server.serve(":8080", api.toServiceAs[Text.Plain]))
}
Notice also that having Await.ready() is mandatory - your program would exit right away otherwise.

How can I use the Play Framework in a multi-project?

I am struggling to find any information on how to use the Play Framework in a multi-project where the root project is a plain SBT one. Basically this is my project's layout:
/
- common
- some-other-projects
- my-play-project
- - app
- - - controllers
- - conf
- - - routes
- build.sbt
I can start the application by running my-play-project/run in the SBT console, but when I try to visit any page, I get a 500 and this error is logged:
[error] /someorg/backend/cms/conf/routes: package router does not exist
[error] /someorg/backend/cms/conf/routes: cannot find symbol
[error] symbol: class ReversePostController
[error] location: package controllers
[error] /someorg/backend/cms/conf/routes: package controllers.javascript does not exist
[error] /someorg/backend/cms/conf/routes: cannot find symbol
[error] symbol: class ReversePostController
[error] location: package controllers
[error] /someorg/backend/cms/conf/routes: cannot find symbol
[error] symbol: variable RoutesPrefix
[error] location: class controllers.routes
[error] /someorg/backend/cms/conf/routes: package controllers.javascript does not exist
[error] /someorg/backend/cms/conf/routes: cannot find symbol
[error] symbol: variable RoutesPrefix
[error] location: class controllers.routes.javascript
[error] (cms/compile:compileIncremental) javac returned nonzero exit code
[info] Compiling 6 Scala sources and 1 Java source to /someorg/backend/cms/target/classes...
[error] /someorg/backend/cms/conf/routes: package router does not exist
[error] /someorg/backend/cms/conf/routes: cannot find symbol
[error] symbol: class ReversePostController
[error] location: package controllers
[error] /someorg/backend/cms/conf/routes: package controllers.javascript does not exist
[error] /someorg/backend/cms/conf/routes: cannot find symbol
[error] symbol: class ReversePostController
[error] location: package controllers
[error] /someorg/backend/cms/conf/routes: cannot find symbol
[error] symbol: variable RoutesPrefix
[error] location: class controllers.routes
[error] /someorg/backend/cms/conf/routes: package controllers.javascript does not exist
[error] /someorg/backend/cms/conf/routes: cannot find symbol
[error] symbol: variable RoutesPrefix
[error] location: class controllers.routes.javascript
[error] (cms/compile:compileIncremental) javac returned nonzero exit code
[error] application -
! #6pi9jna82 - Internal server error, for (GET) [/posts] ->
play.sbt.PlayExceptions$CompilationException: Compilation error[package router does not exist]
at play.sbt.PlayExceptions$CompilationException$.apply(PlayExceptions.scala:27)
at play.sbt.PlayExceptions$CompilationException$.apply(PlayExceptions.scala:27)
at scala.Option.map(Option.scala:145)
at play.sbt.run.PlayReload$$anonfun$taskFailureHandler$1.apply(PlayReload.scala:49)
at play.sbt.run.PlayReload$$anonfun$taskFailureHandler$1.apply(PlayReload.scala:44)
at scala.Option.map(Option.scala:145)
at play.sbt.run.PlayReload$.taskFailureHandler(PlayReload.scala:44)
at play.sbt.run.PlayReload$.compileFailure(PlayReload.scala:40)
at play.sbt.run.PlayReload$$anonfun$compile$1.apply(PlayReload.scala:17)
at play.sbt.run.PlayReload$$anonfun$compile$1.apply(PlayReload.scala:17)
Is there anything obvious I am missing that breaks this project? The controller is defined in the simplest possible way as explained in the documentation. The same goes for the only route I provide:
# Route
GET /posts controllers.PostController.list
// Controller
package controllers
import play.api.mvc.{Action, Controller}
class PostController extends Controller {
def list = TODO
}
I'm using Play Framework 2.5.1 and the project build is defined as follows:
lazy val resolvers = ...
lazy val projectSettings = Seq(
organization := "some-organization",
scalaBinaryVersion := "2.11",
scalaVersion := "2.11.7",
externalResolvers := resolvers,
moduleConfigurations := Seq(),
retrieveManaged := true,
concurrentRestrictions in Global += Tags.limit(Tags.Test, 1),
transitiveClassifiers in Scope.GlobalScope := Seq("sources"),
ivyLoggingLevel := UpdateLogging.Quiet,
credentials += Credentials(Path.userHome / ".ivy2" / ".credentials"),
crossPaths := false,
publishMavenStyle := true,
publishArtifact in (Compile, packageDoc) := false,
publishArtifact in (Test, packageDoc) := false,
javacOptions := Seq("-source", "1.8", "-target", "1.8", "-encoding", "utf8"),
javaOptions := Seq("-server", "-XX:ReservedCodeCacheSize=192m", "-Xss2m"),
javaOptions in Test := Seq("-server", "-Xmx2g", "-XX:ReservedCodeCacheSize=192m", "-Xss2m"),
testFrameworks := Seq(TestFrameworks.ScalaTest, TestFrameworks.Specs2),
noTestCompletion(),
scalacOptions := Seq(
"-deprecation",
"-optimize",
"-unchecked",
"-encoding", "utf8",
"-target:jvm-1.8",
"-Xlog-reflective-calls",
"-feature",
"-language:_"
) ++ Seq(
"by-name-right-associative",
"delayedinit-select",
"doc-detached",
"inaccessible",
"missing-interpolator",
"nullary-override",
"option-implicit",
"package-object-classes",
"poly-implicit-overload",
"private-shadow",
"unsound-match"
).map(x => s"-Xlint:$x"),
compileOrder := CompileOrder.JavaThenScala,
fork in Test := true,
testOptions in Test := Seq(Tests.Filter(testName => testName.endsWith("Test") || testName.endsWith("Spec"))),
testOptions in Test += Tests.Argument("-oDF"),
testOptions in Test <+= (target in Test).map { t =>
val testDir = t / "test-reports"
val maybeJUnitXml = if (flag("sbt.test.nojunitxml")) Seq.empty else Seq("-u", testDir.getAbsolutePath)
Tests.Argument(TestFrameworks.ScalaTest, maybeJUnitXml: _*)
}
)
lazy val cms = (project in file("cms"))
.settings(projectSettings)
.dependsOn(common, commonTest % "test", model % compileTest)
.enablePlugins(PlayScala)
lazy val root = (project in file("."))
.settings(projectSettings)
.aggregate(common, some-other-projects, cms) // TODO: Remove web
Update:
Now that you've posted your build.sbt file, I think the problem is the compile order. javac fails because it cannot find the mentioned package.
Try to use the default Mixed compilation order.
I suspect that you didn't enable the sbt-play plugin in the my-play-project subproject and hence your routes file wasn't compiled to my-play-project/target/scala-2.11/routes/main/router
In my-play-project/build.sbt, add:
enablePlugins(PlayScala)
Try adding the Play plugin declaration to the root project at /project/plugins.sbt

SBT cannot resolve class declared in src/main/scala in a src/test/scala test class

I am trying to make my own custom CSV reader. I am using IntelliJ IDEA 14 with sbt and specs2 test framework.
The class I declared in src/main is as follows:
import java.io.FileInputStream
import scala.io.Source
class CSVStream(filePath:String) {
val csvStream = Source.fromInputStream(new FileInputStream(filePath)).getLines()
val headers = csvStream.next().split("\\,", -1)
}
The content of the test file in src/test is as follows:
import org.specs2.mutable._
object CSVStreamSpec {
val csvSourcePath = getClass.getResource("/csv_source.csv").getPath
}
class CSVStreamSpec extends Specification {
import CSVStreamLib.CSVStreamSpec._
"The CSV Stream reader" should {
"Extract the header" in {
val csvSource = CSVStream(csvSourcePath)
}
}
}
The build.sbt file contains the following:
name := "csvStreamLib"
version := "1.0"
scalaVersion := "2.11.4"
libraryDependencies ++= Seq("org.specs2" %% "specs2-core" % "2.4.15" % "test")
parallelExecution in Test := false
The error I am getting when I type test is as follows:
[error] /Users/raiyan/IdeaProjects/csvStreamLib/src/test/scala/csvStreamSpec.scala:18: not found: value CSVStream
[error] val csvSource = CSVStream(csvSourcePath)
[error] ^
[error] one error found
[error] (test:compile) Compilation failed
[error] Total time: 23 s, completed 30-Dec-2014 07:44:46
How do I make the CSVStream class accessible to the CSVStreamSpec class in the test file?
Update:
I tried it with sbt in the command line. The result is the same.
You forgot the new keyword. Without it, the compiler looks for the companion object named CSVStream, not the class. Since there is none, it complains. Add new and it'll work.