Code Monkey home page Code Monkey logo

scalac-scoverage-plugin's Introduction

scalac-scoverage-plugin

build Gitter Maven Central Maven Central Maven Central Maven Central License

scoverage is a free Apache licensed code coverage tool for Scala that offers statement and branch coverage. scoverage is available for sbt, Maven, Mill, and Gradle.

NOTE: That this repository contains the Scala compiler plugin for Code coverage in Scala 2 and other coverage utilities for generating reports. For Scala 3 code coverage the compiler natively produces code coverage output, but the reporting logic utilities are then shared with the Scala 2 code coverage utilities in this repo.

Screenshot of scoverage report html

Statement Coverage

In traditional code coverage tools, line coverage has been the main metric. This is fine for languages such as Java which are very verbose and very rarely have more than one statement per line, and more usually have one statement spread across multiple lines.

In powerful, expressive languages like Scala, quite often multiple statements, or even branches are included on a single line, eg a very simple example:

val status = if (Color == Red) Stop else Go

If you had a unit test that ran through the Color Red you would get 100% line coverage yet you only have 50% statement coverage.

Let's expand this example out to be multifaceted, albeit somewhat contrived:

val status = if (Color == Red) Stop else if (Sign == Stop) Stop else Go

Now we would get 100% code coverage for passing in the values (Green, SpeedLimit).

That's why in scoverage we focus on statement coverage, and don't even include line coverage as a metric. This is a paradigm shift that we hope will take hold.

Branch Coverage

Branch coverage is very useful to ensure all code paths are covered. Scoverage produces branch coverage metrics as a percentage of the total branches. Symbols that are deemed as branch statements are:

  • If / else statements
  • Match statements
  • Partial function cases
  • Try / catch / finally clauses

In this screenshot you can see the coverage HTML report that shows one branch of the if statement was not executed during the test run. In addition two of the cases in the partial function were not executed. Screenshot of scoverage report html

How to use

This project is the base library for instrumenting code via a scalac compiler plugin. To use scoverage in your project you will need to use one of the build plugins:

Scoverage support is available for the following tools:

If you want to write a tool that uses this code coverage library then it is available on maven central. Search for scalac-scoverage-plugin.

Excluding code from coverage stats

You can exclude whole classes or packages by name. Pass a semicolon separated list of regexes to the excludedPackages option.

For example:

-P:scoverage:excludedPackages:.*\.utils\..*;.*\.SomeClass;org\.apache\..*

The regular expressions are matched against the fully qualified class name, and must match the entire string to take effect.

Any matched classes will not be instrumented or included in the coverage report.

You can also exclude files from being considered for instrumentation.

-P:scoverage:excludedFiles:.*\/two\/GoodCoverage;.*\/three\/.*

Note: The .scala file extension needs to be omitted from the filename, if one is given.

Note: These two options only work for Scala2. Right now Scala3 does not support a way to exclude packages or files from being instrumented.

You can also mark sections of code with comments like:

// $COVERAGE-OFF$
...
// $COVERAGE-ON$

Any code between two such comments will not be instrumented or included in the coverage report.

Further details are given in the plugin readme's.

Release History

For a full release history please see the releases page.

scalac-scoverage-plugin's People

Contributors

0xroch avatar armanbilge avatar ckipp01 avatar dependabot[bot] avatar domizei385 avatar gbasler avatar gslowikowski avatar joshrosen avatar jrglee avatar kwestor avatar lefou avatar lustefaniak avatar maiflai avatar mtkopone avatar pbatko avatar philippus avatar radoburansky avatar richardbradley avatar rigoford avatar rolandtritsch avatar rorygraves avatar ruippeixotog avatar scala-steward avatar sksamuel avatar still-dreaming-1 avatar sullis avatar takayahilton avatar thepler avatar vincentdehaan avatar xuwei-k avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

scalac-scoverage-plugin's Issues

If condition/pattern matching inconsistent highlighting

Couple of inconsistencies related to just fixed issue #1

  1. As you see on line 18 on the screenshot, if condition is not met and the whole if is marked as red. This seems right to me. Do not mark if condition as green if it was not met.
  2. Line 32 is marked green though the condition is not met. The same goes for line 39.

screen shot 2014-01-05 at 19 00 48

When replacing that if with pattern matching nothing changes.

screen shot 2014-01-05 at 19 10 06

You can find lines 26-45 below to paste into tests.

private val aList: List[String] = List("1", "2", "3")

private val boolOption: Option[Boolean] = Some(true)

def method2() {
  if (aList.size > 0) {
    if (boolOption == None) {
      println("none")
      throw new RuntimeException(s"None matched")
    }
    if (boolOption == Some(true)) {
      println("some")
      for (key <- aList) {
        if (key == "0") {
          throw new RuntimeException(s"Some matched, setting is none")
        }
      }
    }
  }
}

scala 2.9 branch

we're tied to scala 2.9 at my work. It would be fantastic if you could create a scala-2.9 branch with compatibility with the sbt plugin.

scoverage fails when added as Build-level setting in SBT

I just tried to add the SCoverage settings to Build.settings from a .scala build definition in SBT, i.e.

object MyBuild {
  override lazy val settings = super.settings ++ SCoverageSbtPlugin.instrumentSettings

  // ...
}

but that epicaly fails with a lot of spurious errors like

[error]   {.}/test:sources from {.}/scoverage-test:sources (/home/sam/development/workspace/scoverage/sbt-scoverage/src/main/scala/ScoverageSbtPlugin.scala:54)
[error]      Did you mean importer/test:sources ?
[error] 
[error]   {.}/scoverage:thisProject from {.}/scoverage:cacheDirectory ((sbt.Defaults) Defaults.scala:184)
[error] 
[error]   {.}/scoverage:crossTarget from {.}/scoverage:cacheDirectory ((sbt.Defaults) Defaults.scala:184)
[error] 
[error]   {.}/*:sourceManaged from {.}/scoverage-test:sourceManaged ((sbt.Defaults) Defaults.scala:158)
[error]      Did you mean tester/*:sourceManaged ?

My workarround is to define my own Project Builder that adds the SCoverage settings to each project individually, but is the above behaviour expected or is it a bug? Is there a way to add the SCoverage settings to the Build globally?

scoverage.xml contains invalid characters

Hi,

"name" and "symbol" attributes in scoverage.xml contain "<" and ">" characters which are illegal by definition. They should be replaced by &lt; and &gt;

For example:

<method name="aaa/MyServiceClientError/<none>" statement-rate="0.00" branch-rate="100.00">

<statement package="aaa" class="$anon" method="apply" start="443" line="15" symbol="aaa.MakeRectangleModelFromFile.$anon.<init>" tree="Apply" branch="false" invocation-count="0">new $anon()</statement>

How do I pass java options to coveralls task?

I use coveralls to instrument my play app. I have (javaOptions in Test) += "-Dconfig.file=conf/test.conf" in build.sbt. But coveralls (or for that matter scoverage) does not seem to depend on the test task so it does not pick up that config file. How do I specify it in my build.sbt?

Support for multi-project builds

It would be great to add support for multi-project builds. Currently I haven't found a way to aggregate all test coverage data from multiple modules into a single report.

Bad links in HTML report

Links to view source code with coverage markup are not generated correctly. In my case I had a class in package com.jugjane.controllers.GymController, but it was in file app/controllers/GymController.scala.

Link to view the report was .../controllers/GymController.scala.html but it should be .../com/jugjane/controllers/GymController.scala.html

inlined โ€œprivate final valโ€ constants cannot be covered

โ€œprivate final valโ€ constants which have been inlined are not reported correctly by scoverage. If I declare a string constant in this way, then the declaration is marked as uncovered, even if code references and uses the value.

If you examine the "statement list" in the report, then there are multiple statements corresponding to the string value; one for each place in which it is being used (all covered), and one for the declaration itself (not covered).

I might be able to prepare an isolated test case and possibly a fix, but not for at least a few days. I have worked around this for now by removing the "final" annotation in my source.

Two classes with the same simple name confuse scoverage

If a project has two classes with the same simple name in different packages, then the front page of the report will have only one line for that class, and the stats reported on that line will be the aggregate of the two classes. The link will go to the file report for the first of the two classes.

There will be two separate per-file reports correctly generated for the two classes, but they will only be available via the package links.

(This seems pretty minor to me; and it's not actually causing me problems, as we only had two classes with the same simple name due to an oversight, but I thought I'd document it here.)

Cannot build project: java.lang.ClassNotFoundException: java.lang.ProcessEnvironment$Variable

Hi,

I need to modify your plugin to make it work with our compiler plugin, but when I try to build it it fails:

C:\Users\Jerzy\Workspaces\GitHub\scalac-scoverage-plugin>sbt
[info] Loading global plugins from C:\Users\Jerzy\.sbt\0.13\plugins
[info] Loading project definition from C:\Users\Jerzy\Workspaces\GitHub\scalac-scoverage-plugin\project
java.lang.ClassNotFoundException: java.lang.ProcessEnvironment$Variable
        at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:190)
        at EnvSupport$.setEnv(EnvSupport.scala:12)
        at $2245f92b324f1a620b7f$$anonfun$$sbtdef$1.apply(C:\Users\Jerzy\Workspaces\GitHub\scalac-scoverage-plugin\build.sbt:33)
        at $2245f92b324f1a620b7f$$anonfun$$sbtdef$1.apply(C:\Users\Jerzy\Workspaces\GitHub\scalac-scoverage-plugin\build.sbt:30)
        at scala.Function1$$anonfun$compose$1.apply(Function1.scala:47)
        at sbt.EvaluateSettings$MixedNode.evaluate0(INode.scala:177)
        at sbt.EvaluateSettings$INode.evaluate(INode.scala:135)
        at sbt.EvaluateSettings$$anonfun$sbt$EvaluateSettings$$submitEvaluate$1.apply$mcV$sp(INode.scala:67)
        at sbt.EvaluateSettings.sbt$EvaluateSettings$$run0(INode.scala:76)
        at sbt.EvaluateSettings$$anon$3.run(INode.scala:72)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:745)
[error] java.lang.ClassNotFoundException: java.lang.ProcessEnvironment$Variable
[error] Use 'last' for the full log.
Project loading failed: (r)etry, (q)uit, (l)ast, or (i)gnore?

I'm using javac 1.7.0_60. Do you have any ideas how to fix this?

Incorrect coverage report for multi-module maven builds

Hi, I have closed my pull request and opened up an issue instead.

The problem we have is the following: when using scoverage in a multi-module maven project with dependencies between the sub-modules (such as classes in one module inheriting from classes in another module) coverage reports are incorrect for the project containing the inheriting class. I have put together a very small maven project that illustrates the problem. I cannot upload it here but I can send it to anyone who is interested in having a look at the issue.

I also submitted a potential solution as a pull request, but as Sam pointed out, it is not an optimal solution as it probably does not solve the problem in a multi-threaded build (or worse, it may introduce new issues). The fundamental problem seems to be that the relationships between the modules mean that scoverage writes the coverage data to the wrong directory when testing the submodule containing the inheriting class.

Google group is private

Does it need to be? For reasons I won't bother going into, logging into my google account is painful and I'd still like to be able to keep up on the mailing list for this project.

Does not work with macros

Got this error:

See this project: https://github.com/pathikrit/scalgos

sbt test passes but sbt coveralls fails

sbt $SBT_OPTS coveralls
[info] Loading global plugins from /Users/pbhowmick/.sbt/0.13/plugins
[info] Loading project definition from /Users/pbhowmick/Projects/scalgos/project
[info] Set current project to scalgos (in build file:/Users/pbhowmick/Projects/scalgos/)
[warn] The - command is deprecated in favor of onFailure and will be removed in 0.14.0
[info] Compiling 20 Scala sources to /Users/pbhowmick/Projects/scalgos/target/scala-2.10/scoverage-classes...
[warn] /Users/pbhowmick/Projects/scalgos/src/main/scala/com/github/pathikrit/scalgos/DynamicType.scala:18: non-variable type argument Any in type pattern Any => Any is unchecked since it is eliminated by erasure
[warn] case fn1: Function1[Any, Any] => methods(key) = fn1
[warn] ^
[warn] /Users/pbhowmick/Projects/scalgos/src/main/scala/com/github/pathikrit/scalgos/DynamicType.scala:19: non-variable type argument Any in type pattern (Any, Any) => Any is unchecked since it is eliminated by erasure
[warn] case fn2: Function2[Any, Any, Any] => methods(key) = fn2
[warn] ^
[scoverage]: Begin profiling phase
[scoverage]: Profiling completed: 1493 statements profiled
[scoverage]: Written profile-file to /Users/pbhowmick/Projects/scalgos/target/scala-2.10/scoverage.coverage
[scoverage]: Will write measurement data to /Users/pbhowmick/Projects/scalgos/target/scala-2.10/scoverage.measurement
[error] /Users/pbhowmick/Projects/scalgos/src/main/scala/com/github/pathikrit/scalgos/Macros.scala:43: erroneous or inaccessible type
[error] def debug(params: Any*) = macro debugImpl
[error] ^
[warn] two warnings found
[error] one error found
error Compilation failed
[error] Total time: 8 s, completed Feb 1, 2014 5:29:37 PM
[error] Could not find any cobertura.xml files. Has the coverage plugin run?
[success] Total time: 9 s, completed Feb 1, 2014 5:29:38 PM

HTML report generatio fails on classes in default package

Exception thrown:

java.io.IOException: Directory 'I:\scm\github.git\scoverage\scoverage-samples\trunk-sbt.gs\target\scala-2.11\scoverage-report\<empty>' could not be created
    at org.apache.commons.io.FileUtils.openOutputStream(FileUtils.java:363)
    at org.apache.commons.io.FileUtils.writeStringToFile(FileUtils.java:1928)
    at org.apache.commons.io.FileUtils.write(FileUtils.java:2045)
    at org.apache.commons.io.FileUtils.write(FileUtils.java:1988)
    at scoverage.report.ScoverageHtmlWriter.write(ScoverageHtmlWriter.scala:28)
    at scoverage.report.ScoverageHtmlWriter$$anonfun$write$1.apply(ScoverageHtmlWriter.scala:22)
    at scoverage.report.ScoverageHtmlWriter$$anonfun$write$1.apply(ScoverageHtmlWriter.scala:22)
    at scala.collection.immutable.List.foreach(List.scala:318)
    at scoverage.report.ScoverageHtmlWriter.write(ScoverageHtmlWriter.scala:22)
    at scoverage.ScoverageSbtPlugin$$anonfun$testsCleanup$1$$anonfun$apply$2.apply$mcV$sp(ScoverageSbtPlugin.scala:142)
    at sbt.Tests$$anonfun$Cleanup$1.apply(Tests.scala:53)
    at sbt.Tests$$anonfun$Cleanup$1.apply(Tests.scala:53)
    at sbt.Tests$$anonfun$sbt$Tests$$partApp$1$1$$anonfun$apply$1.apply$mcV$sp(Tests.scala:160)
    at sbt.Tests$$anonfun$sbt$Tests$$fj$1$1.apply(Tests.scala:159)
    at sbt.Tests$$anonfun$sbt$Tests$$fj$1$1.apply(Tests.scala:159)
    at sbt.std.TaskExtra$$anon$1$$anonfun$fork$1$$anonfun$apply$1.apply(TaskExtra.scala:99)
    at sbt.std.Transform$$anon$3$$anonfun$apply$2.apply(System.scala:45)
    at sbt.std.Transform$$anon$3$$anonfun$apply$2.apply(System.scala:45)
    at sbt.std.Transform$$anon$4.work(System.scala:64)
    at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:237)
    at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:237)
    at sbt.ErrorHandling$.wideConvert(ErrorHandling.scala:18)
    at sbt.Execute.work(Execute.scala:244)
    at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:237)
    at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:237)
    at sbt.ConcurrentRestrictions$$anon$4$$anonfun$1.apply(ConcurrentRestrictions.scala:160)
    at sbt.CompletionService$$anon$2.call(CompletionService.scala:30)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)
[error] (scoverage-test:executeTests) java.io.IOException: Directory 'I:\scm\github.git\scoverage\scoverage-samples\trunk-sbt.gs\target\scala-2.11\scoverage-report\<empty>' could not be created
```code

The simplest solution would be to replace "<empty>" with "(empty)".

Broken links in coverage report if directory structure doesn't match package structure

The directory structure of the highlighted-source HTML files follows the files' declared package, but the URLs in the coverage report page follow the original source files' directory structure. For example, if I have a file at src/main/foo.scala with a package com.example.foo declaration, the resulting highlighted-source file will be generated at target/scoverage-report/com/example/foo.scala.html. However, the HTML report at target/scoverage-report/index.html will contain a broken link pointing at target/scoverage-report/foo.scala.

"java.lang.NumberFormatException" Race condition in coverage file

I'm seeing intermittent errors like the following when running coverage reports with "scoverage" on Windows:

java.lang.NumberFormatException: For input string: "143911841188188"

I think this is because of a race condition in Invoker.invoked which is causing the "id" and the ";" to be written non-atomically.

This may only be a problem on Windows. Perhaps two adjacent small appends are atomic on POSIX but not on Windows?

I will submit a patch to consolidate the two writes into one. This seems to fix the issue on Windows, and it seems like a good idea on POSIX as well.

Proposal: Change code rendering from table to pre

The code display currently outputs the code in a table which means you get slow rendering on large files and cannot select names from the text (you get .

I propose changing it to use html pre tag (you can use tags within the pre-block to do the highlighting (this is how scala x-ray did it) which should improve rendering speed and usability

I'm happy to do this when I get time :)

default method arguments which refer to methods are not instrumented correctly

If you add method with a default argument, and the expression for the argument's default value refers to a method or val, then it is always shown as uncovered even if you invoke it.

For example:

object DefaultArgumentsObject {

  val defaultName = "world"

  def makeGreeting(name: String = defaultName): String = {
    s"Hello, $name"
  }
}

class DefaultArgumentsObjectTest extends FlatSpec with OneInstancePerTest {

  "DefaultArgumentsObject" should "execute the default block if no arg is given" in {
    val result = DefaultArgumentsObject.makeGreeting()
    assert(result === "Hello, world")
  }
}

Then "defaultName" is always shown in red.

I have looked into this, but I haven't been able to figure out what's wrong, so I can't submit a fix at this time. I will submit a PR to the scoverage-samples project with a demo.

Scoverage crashes for code that contains "\uFFFF" (or Char.MaxValue)

org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 364; An invalid XML character (Unicode: 0xffff) was found in the element content of the document.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:177)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:441)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(XMLScanner.java:1436)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2927)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocume

See scoverage/sbt-scoverage#40

Report generation is broken on Windows

All the links in the overview and the line endings in the code grid view are broken if you generate the report on a Windows machine (some of us have to use them ;-)

(I'm about to submit a patch...)

bad link in generated html report

when I generate report link to classes generated for "All packages" page fail to open due to wrong url. When I click correct package in menu on left, links work.

For example, I have class CoreHelper in package com.specdevs.specgine.macros - when I click class on "All packages" page, I get that it cannot find "scoverage-report//core.scala.html" (404 on right).

When I click "com.specdevs.specgine.macros" package and then class CoreHelper, the link points to "scoverage-report/com/specdevs/specgine/macros/core.scala.html" and works.

Do you want to see some configuration or generated report? It is for 0.2-M1 of my teams project - https://bitbucket.org/specdevs/specgine - we use sbt scoverage plugin in version 0.99.5.1, but we tried 0.99.7.1 as well with same result. I'd be happy to provide more details if needed.

Incorrect (probably) coverage (or highlighting)

See screenshot. Seems like there could not be such situation when line 344 is red and 345 is green.

Also it looks kinda strange those single green white spaces on most of the lines except the last one.

screen shot 2014-01-09 at 4 18 45

scoverage reports annotations must be constant when they are already final vals

Scalac is able to compile annotations that are specified as final vals because those are acually constant (unlike a val or anything else). For example, this compiles:

object Foo {
  final val foo = 1L
}

@SerialVersionUID(value = Foo.foo)
class Bar

However, running scoverage:test on the above generates:

$ ./sbt scoverage:test 
[info] Loading project definition from ~/project
[info] Set current project to example 
[info] Compiling 2 Scala sources to ~/project/target/scala-2.11/scoverage-classes...
[scoverage]: Begin pre-instrumentation phase
[scoverage]: Pre-instrumentation complete
[error] ~/project/src/main/scala/com/coinposit/Foo.scala:7: annotation argument needs to be a constant; found: Foo.foo
[error] @SerialVersionUID(value = Foo.foo)
[error] 1 errors found
[error] (project/scoverage:compile) Compilation failed

Shouldn't scoverage be able to understand final vals as constant in annotations?

@unchecked annotations are not carried over to instrumented code

(Low priority)

Code which has partial match functions which are annotated with @unchecked will raise a false compiler warning when instrumented with scoverage.

For example:

object PartialMatchObject {
  def partialMatchExample(s: Option[String]): Unit = {
    (s: @unchecked) match {
      case Some(str) => println(str)
    }
  }
}

The above code will give a "match may not be exhaustive" false compiler warning on sbt scoverage:compile (it will not give a compiler warning when compiled normally).

Test code not calling Main code results in FileNotFoundException

Hi,

I had trouble with running scoverage (via sbt) on a basic project, as detailed here: scoverage/sbt-scoverage#11. It stopped being an issue when I called the main(Array[String]) function from the test code. (see the project http://gist.github.com/ThorinII/9521478)

The exception was caused by the sbt plugin looking for a scoverage.measurement file when it wasn't there.

Is it possible to generate an empty scoverage.measurement file in the event there are no measurements? (I have no idea what goes into that file so I don't know if that's possible)
The other solution I guess would be to have the sbt plugin recognise when there is no scoverage.measurement and know how to handle it.

Thanks,
Lachlan

checkScoverage fails to generate a report

This is what I see on the console:

....
[Fatal Error] cobertura.xml:2:10: DOCTYPE is disallowed when the feature "http://apache.org/xml/features/disallow-doctype-decl" set to true.
:checkScoverage FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':checkScoverage'.
> org.xml.sax.SAXParseException; systemId: file:///Users/zsolt/.../build/reports/scoverage/cobertura.xml; lineNumber: 2; columnNumber: 10; DOCTYPE is disallowed when the feature "http://apache.org/xml/features/disallow-doctype-decl" set to true.

It seems that grails had a similar issue and they fixed it like this:
beckje01/grails-code-coverage@19b2259

Scoverage marks code as covered when it really is not

Created very basic project (working copy of it is here https://dl.dropboxusercontent.com/u/3962786/scoverage-issue.tar.gz but actually there are two files).

SimpleObject

package sample

import scala.concurrent.{ExecutionContext, Future}
import ExecutionContext.Implicits.global

object SimpleObject {

  private def getSomething = Future.successful(3)

  private def getOtherSomething = Future.successful(5)

  def method(input1: Boolean, input2: Boolean): Future[Option[Boolean]] = {
    for {
      b <- if (input1) getSomething else getOtherSomething // this else should not be covered
    } yield {
      if (input1 && input2) {
        Some(true)
      } else if (input1 && !input2) {
        Some(false) // this too
      } else {
        None // this too
      }
    }
  }

}

and a test for it

import java.util.concurrent.TimeUnit
import org.specs2.mutable.Specification
import sample.SimpleObject
import scala.concurrent.Await
import scala.concurrent.duration._

class SimpleClassTest extends Specification {

  "SimpleClassTest" should {

    "test 1" in {
      Await.result(SimpleObject.method(true, true), Duration(1, TimeUnit.SECONDS)) mustEqual Some(true)
    }

  }

}

As you see on the screenshot below there are at least 3 branches that are falsely marked as green.

screen shot 2014-01-05 at 5 22 37

Cannot build project

Trying to build Cypher with scoverage fails with the following output: https://gist.github.com/systay/bd948820a2b0ca7647bd

Here is the branch that I have where I try to make it work:
https://github.com/systay/neo4j/tree/scoverage

The last commit there is me adding scoverage to our pom.

Doing mvn test fails with the output in that gist.

mvn --version
Apache Maven 3.2.1 (ea8b2b07643dbb1b84b6d16e1f08391b666bc1e9; 2014-02-14T18:37:52+01:00)
Maven home: /usr/local/Cellar/maven/3.2.1/libexec
Java version: 1.7.0_65, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.7.0_65.jdk/Contents/Home/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.9.5", arch: "x86_64", family: "mac"

CoberturaXmlWriter produces % output

Hi,

I'm trying to test the gradle-scoverage plugin, which parses the coberatura output from the scoverage core library.

This example https://raw.githubusercontent.com/jenkinsci/cobertura-plugin/master/src/test/resources/hudson/plugins/cobertura/coverage-with-data.xml shows a cobertura file with decimal output for rates (e.g. line-rate="0.5")

The scoverage CoberturaXmlWriter seems to format rates in % form (e.g. line-rate="50.00"). This appears to be a regression against the previous SCCT output, which was decimal.

I tried to find a specification for the format, but have struck a blank so far. Is the publishing of % by scoverage accidental, or does the cobertura format provide for both styles of output?

Thanks,
Stu

Error instrumenting Typeclasses

We're using gkit, and the following code:


trait JSONPicklerInstances {
  import org.joda.time.DateTime

  implicit def BSONObjectIDPickler: JSONPickler[BSONObjectID] =
    new JSONPickler[BSONObjectID] {
      def pickle(boid: BSONObjectID): JsValue = JsString(boid.stringify)

      def unpickle(v: JsValue, path: List[String]): String \/ BSONObjectID = {
        def parse(s: String) =
          try { BSONObjectID(s).right } catch { case e: Throwable => e.getMessage.left }

        for {
          js <- typecheck[JsString](v, path)(identity)
          id <- parse(js.value).leftMap(e => s"""error at: `${path.mkString(".")}`: $e""")
        } yield id
      }
    }

  implicit def DateTimeJSONPickler: JSONPickler[DateTime] =
    new JSONPickler[DateTime] {
      def pickle(dt: DateTime): JsValue = JsNumber(dt.getMillis)

      def unpickle(v: JsValue, path: List[String]): String \/ DateTime = for {
        js <- typecheck[JsNumber](v, path)(identity)
      } yield new DateTime(js.value.toLong)
    }
}

break when compiling with the following error:


[error]   last tree to typer: Ident($anon)
[error]               symbol: anonymous class $anon (flags: final)
[error]    symbol definition: final class $anon extends JSONPickler[org.joda.time.DateTime]
[error]                  tpe: play.modules.gjson.JSONPickler[org.joda.time.DateTime]
[error]        symbol owners: anonymous class $anon -> method DateTimeJSONPickler -> trait JSONPicklerInstances -> package app
[error]       context owners: method DateTimeJSONPickler -> trait JSONPicklerInstances -> package app
[error] 
[error] == Enclosing template or block ==
[error] 
[error] Apply( // def (): play.modules.gjson.JSONPickler[org.joda.time.DateTime], tree.tpe=play.modules.gjson.JSONPickler[org.joda.time.DateTime]
[error]   new $anon."" // def (): play.modules.gjson.JSONPickler[org.joda.time.DateTime], tree.tpe=()play.modules.gjson.JSONPickler[org.joda.time.DateTime]
[error]   Nil
[error] )
[error] 
[error] == Expanded type of tree ==
[error] 
[error] TypeRef(
[error]   TypeSymbol(
[error]     final class $anon extends JSONPickler[org.joda.time.DateTime]
[error]   )
[error] )

EnvSupport throws "ClassNotFoundException: java.lang.ProcessEnvironment$Variable" on JRE 1.6.0_21

The "EnvSupport" class hacks about inside the JRE ProcessEnvironment class, but it is apparently specific to a JRE version which I do not have:

java.lang.ClassNotFoundException: java.lang.ProcessEnvironment$Variable

My JRE is:

java version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM) 64-Bit Server VM (build 17.0-b17, mixed mode)

My ProcessEnvironment class looks like:

private static final ProcessEnvironment theEnvironment;
private static final Map<String,String> theUnmodifiableEnvironment;
private static final Map<String,String> theCaseInsensitiveEnvironment;

whereas I think the version this code is targeting looks more like this one:

 private static final HashMap<Variable,Value> theEnvironment;
 private static final Map<String,String> theUnmodifiableEnvironment;

Use relative href for source view

In the overview.html file, the links to the report file showing hightlighted code for each file are absolute:

        <a href="/Users/mortimer/..../core/target/scala-2.10/scoverage-report/com/quantifind/sumac/FieldArgs.scala.html">
          AnnotationValidationFunction
        </a>

This breaks the links when the report is server over http or consulted on a different file system. For instant, I generate the report on a server and read them on a mounted partition on my local computer, so the index.html root is at file:///Volumes/mort-serv/.../core/target/scala-2.10/scoverage-report/index.html but will try to load other files with the link shown above.

If the links were relative to the index root:

        <a href="./com/quantifind/sumac/FieldArgs.scala.html">
          AnnotationValidationFunction
        </a>

there would be no problem.

CodeGrid showing entries for scoverage code (0.99.7.1)

line: 130   
statement Id: 1935  
symbol: <nosymbol>
code: { scoverage.Invoker.invoked(1934, "/workspace/ensime-src/target/scala-2.11/scoverage-data"); SwankProtocol.this.log.error({ scoverage.Invoker.invoked(1933, "/workspace/ensime-src/target/scala-2.11/scoverage-data"); "Unexpected message type: ".+(msg) })}

looks like it is not filtering the scoverage inserted code. (there are many entries).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.