Merge pull request #1316 from sbt/wip/fix-broken-build

This doesn't quite fix the build, but gets closer
This commit is contained in:
eugene yokota 2014-05-07 12:23:09 -04:00
commit d198ea4099
64 changed files with 3655 additions and 3726 deletions

View File

@ -1,17 +1,24 @@
language: scala
script:
- sbt "scripted $SCRIPTED_TEST"
- sbt "$SCRIPTED_TEST"
env:
- SCRIPTED_TEST=actions/*
- SCRIPTED_TEST=api/*
- SCRIPTED_TEST=compiler-project/*
- SCRIPTED_TEST=dependency-management/*
- SCRIPTED_TEST=java/*
- SCRIPTED_TEST=package/*
- SCRIPTED_TEST=reporter/*
- SCRIPTED_TEST=run/*
- SCRIPTED_TEST=source-dependencies/*
- SCRIPTED_TEST=tests/*
- SCRIPTED_TEST="scripted actions/*"
- SCRIPTED_TEST="scripted api/*"
- SCRIPTED_TEST="scripted compiler-project/*""
- SCRIPTED_TEST="scripted dependency-management/*1of2"
- SCRIPTED_TEST="scripted dependency-management/*2of2"
- SCRIPTED_TEST="scripted java/*"
- SCRIPTED_TEST="scripted package/*"
- SCRIPTED_TEST="scripted project/*"
- SCRIPTED_TEST="scripted reporter/*"
- SCRIPTED_TEST="scripted run/*"
- SCRIPTED_TEST="scripted source-dependencies/*1of3"
- SCRIPTED_TEST="scripted source-dependencies/*2of3"
- SCRIPTED_TEST="scripted source-dependencies/*3of3"
- SCRIPTED_TEST="scripted tests/*"
- SCRIPTED_TEST="all launcher/test main-settings/test main/test ivy/test logic/test completion/test"
- SCRIPTED_TEST="all actions/test classpath/test collections/test incremental-compiler/test logging/test run/test task-system/test"
# TODO - we'd like to actually test everything, but the process library has a deadlock right now
jdk:
- openjdk6
notifications:

View File

@ -12,8 +12,7 @@ object CacheTest// extends Properties("Cache test")
import FileInfo.hash._
import Ordering._
import sbinary.DefaultProtocol.FileFormat
def test
{
def test {
lazy val create = new File("test")
val length = cached(lengthCache) {

View File

@ -8,7 +8,6 @@ import org.scalacheck._
import Gen._
import Prop._
object AnalysisTest extends Properties("Analysis") {
// Merge and split a hard-coded trivial example.
property("Simple Merge and Split") = {

View File

@ -11,7 +11,6 @@ import sbt.Relation
import xsbti.api._
import xsbti.SafeLazy
/**
* Scalacheck generators for Analysis objects and their substructures.
* Fairly complex, as Analysis has interconnected state that can't be

View File

@ -80,7 +80,8 @@ class ScalaCompilerForUnitTesting(nameHashing: Boolean = false) {
def pairsToMultiMap[A, B](pairs: Seq[(A, B)]): Map[A, Set[B]] = {
import scala.collection.mutable.{ HashMap, MultiMap }
val emptyMultiMap = new HashMap[A, scala.collection.mutable.Set[B]] with MultiMap[A, B]
val multiMap = pairs.foldLeft(emptyMultiMap) { case (acc, (key, value)) =>
val multiMap = pairs.foldLeft(emptyMultiMap) {
case (acc, (key, value)) =>
acc.addBinding(key, value)
}
// convert all collections to immutable variants
@ -118,7 +119,8 @@ class ScalaCompilerForUnitTesting(nameHashing: Boolean = false) {
val files = for ((compilationUnit, unitId) <- groupedSrcs.zipWithIndex) yield {
val run = new compiler.Run
val srcFiles = compilationUnit.toSeq.zipWithIndex map { case (src, i) =>
val srcFiles = compilationUnit.toSeq.zipWithIndex map {
case (src, i) =>
val fileName = s"Test-$unitId-$i.scala"
prepareSrcFile(temp, fileName, src)
}

View File

@ -7,8 +7,7 @@ import IO.{createDirectory, delete, touch, withTemporaryDirectory}
import org.apache.ivy.util.ChecksumHelper
import IfMissing.Fail
object ComponentManagerTest extends Specification
{
object ComponentManagerTest extends Specification {
val TestID = "manager-test"
"Component manager" should {
"throw an exception if 'file' is called for a non-existing component" in {
@ -53,14 +52,12 @@ object ComponentManagerTest extends Specification
withTemporaryDirectory { ivyHome =>
withManagerHome(ivyHome) { definingManager =>
val hash = defineFile(definingManager, TestID, "a")
try
{
try {
definingManager.cache(TestID)
withManagerHome(ivyHome) { usingManager =>
checksum(usingManager.file(TestID)(Fail)) must beEqualTo(hash)
}
}
finally { definingManager.clearCache(TestID) }
} finally { definingManager.clearCache(TestID) }
}
}
}

View File

@ -4,8 +4,7 @@ import java.io.File
import org.specs2._
import mutable.Specification
object CrossVersionTest extends Specification
{
object CrossVersionTest extends Specification {
"Cross version" should {
"return sbt API for xyz as None" in {
CrossVersion.sbtApiVersion("xyz") must_== None

View File

@ -4,8 +4,7 @@ import java.io.File
import org.specs2._
import mutable.Specification
object MakePomTest extends Specification
{
object MakePomTest extends Specification {
val mp = new MakePom(ConsoleLogger())
import mp.{ makeDependencyVersion => v }
"MakePom makeDependencyVersion" should {

View File

@ -3,8 +3,7 @@ package xsbt.boot
import org.scalacheck._
import Prop._
object CacheTest extends Properties("Cache")
{
object CacheTest extends Properties("Cache") {
implicit val functions: Arbitrary[Int => Int] = Arbitrary { Gen.oneOf(Seq(identity[Int], i => -i, i => i / 2, i => i + 1)) }
property("Cache") = Prop.forAll { (key: Int, keys: List[Int], map: Int => Int) =>

View File

@ -8,8 +8,7 @@ import org.specs2._
import mutable.Specification
import sbt.IO.{ createDirectory, touch, withTemporaryDirectory }
object ConfigurationParserTest extends Specification
{
object ConfigurationParserTest extends Specification {
"Configuration Parser" should {
"Correctly parse bootOnly" in {

View File

@ -3,8 +3,7 @@ package xsbt.boot
import org.scalacheck._
import Prop.{ Exception => _, _ }
object EnumerationTest extends Properties("Enumeration")
{
object EnumerationTest extends Properties("Enumeration") {
property("MultiEnum.toValue") = checkToValue(MultiEnum, multiElements: _*)
property("MultiEnum.elements") = checkElements(MultiEnum, multiElements: _*)
property("EmptyEnum.toValue") = checkToValue(EmptyEnum)
@ -41,14 +40,12 @@ object EnumerationTest extends Properties("Enumeration")
case None => invalid(s)
})
}
object MultiEnum extends Enumeration
{
object MultiEnum extends Enumeration {
val a = value("A")
val b = value("B")
val c = value("C")
}
object SingleEnum extends Enumeration
{
object SingleEnum extends Enumeration {
val a = value("A")
}
object EmptyEnum extends Enumeration

View File

@ -2,8 +2,7 @@ package xsbt.boot
import org.scalacheck._
object ListMapProperties extends Properties("ListMap")
{
object ListMapProperties extends Properties("ListMap") {
implicit val genListMap = Arbitrary(for (list <- Arbitrary.arbitrary[List[(Int, Int)]]) yield ListMap(list: _*))
property("ListMap from List contains all members of that List") = Prop.forAll { (list: List[(Int, Int)]) =>
@ -27,8 +26,7 @@ object ListMapProperties extends Properties("ListMap")
}
}
object ListMapEmpty extends Properties("ListMap.empty")
{
object ListMapEmpty extends Properties("ListMap.empty") {
import ListMap.empty
property("isEmpty") = empty.isEmpty
property("toList.isEmpty") = empty.toList.isEmpty

View File

@ -5,10 +5,11 @@ import Prop._
import java.io.File
import sbt.IO.withTemporaryDirectory
/** These mainly test that things work in the uncontested case and that no OverlappingFileLockExceptions occur.
* There is no real locking testing, just the coordination of locking.*/
object LocksTest extends Properties("Locks")
{
/**
* These mainly test that things work in the uncontested case and that no OverlappingFileLockExceptions occur.
* There is no real locking testing, just the coordination of locking.
*/
object LocksTest extends Properties("Locks") {
property("Lock in nonexisting directory") = spec {
withTemporaryDirectory { dir =>
val lockFile = new File(dir, "doesntexist/lock")

View File

@ -4,8 +4,7 @@ import java.io.File
import java.util.Arrays.{ equals => arrEquals }
import org.scalacheck._
object PreTest extends Properties("Pre")
{
object PreTest extends Properties("Pre") {
import Pre._
property("isEmpty") = Prop.forAll((s: String) => (s.isEmpty == isEmpty(s)))
property("isNonEmpty") = Prop.forAll((s: String) => (isEmpty(s) != isNonEmpty(s)))

View File

@ -9,13 +9,14 @@ import mutable.Specification
import LaunchTest._
import sbt.IO.{ createDirectory, touch, withTemporaryDirectory }
object ScalaProviderTest extends Specification
{
object ScalaProviderTest extends Specification {
"Launch" should {
"provide ClassLoader for Scala 2.8.0" in { checkScalaLoader("2.8.0") }
//"provide ClassLoader for Scala 2.8.0" in { checkScalaLoader("2.8.0") }
"provide ClassLoader for Scala 2.8.2" in { checkScalaLoader("2.8.2") }
"provide ClassLoader for Scala 2.9.0" in { checkScalaLoader("2.9.0") }
"provide ClassLoader for Scala 2.9.2" in { checkScalaLoader("2.9.2") }
"provide ClassLoader for Scala 2.10.4" in { checkScalaLoader("2.10.4") }
"provide ClassLoader for Scala 2.11.0" in { checkScalaLoader("2.11.0") }
}
"Launch" should {
@ -69,8 +70,7 @@ object ScalaProviderTest extends Specification
}
private def tryScala(loader: ClassLoader): Unit = Class.forName("scala.Product", false, loader).getClassLoader must be(loader)
}
object LaunchTest
{
object LaunchTest {
def testApp(main: String): Application = testApp(main, Array[File]())
def testApp(main: String, extra: Array[File]): Application = Application("org.scala-sbt", "launch-test", new Explicit(AppVersion), main, Nil, CrossValue.Disabled, extra)
import Predefined._

View File

@ -10,8 +10,7 @@ import LaunchTest._
import sbt.IO.{ createDirectory, touch, withTemporaryDirectory }
import java.net.URI
object ServerLocatorTest extends Specification
{
object ServerLocatorTest extends Specification {
"ServerLocator" should {
// TODO - Maybe use scalacheck to randomnly generate URIs
"read and write server URI properties" in {

View File

@ -6,8 +6,7 @@ import Configuration._
import java.io.File
import java.net.URI
object URITests extends Properties("URI Tests")
{
object URITests extends Properties("URI Tests") {
// Need a platform-specific root, otherwise URI will not be absolute (e.g. if we use a "/a/b/c" path in Windows)
// Note:
// If I use "C:" instead of "/C:", then isAbsolute == true for the resulting URI, but resolve is broken:

View File

@ -3,8 +3,7 @@ package xsbt.boot
import org.scalacheck._
import Prop._
object VersionParts extends Properties("VersionParts")
{
object VersionParts extends Properties("VersionParts") {
property("Valid version, no qualifier") = Prop.forAll { (x0: Int, y0: Int, z0: Int) =>
val (x, y, z) = (norm(x0), norm(y0), norm(z0))
val str = s"$x.$y.$z"

View File

@ -6,8 +6,7 @@ package compiler
import Prop._
import scala.tools.nsc.reporters.StoreReporter
object EvalTest extends Properties("eval")
{
object EvalTest extends Properties("eval") {
private[this] val reporter = new StoreReporter
import reporter.{ ERROR, Info, Severity }
private[this] val eval = new Eval(_ => reporter, None)
@ -65,7 +64,6 @@ val p = {
label("Val names", res.valNames) |: (res.valNames.toSet == ValTestNames)
}
property("explicit import") = forAll(testImport("import math.abs" :: Nil))
property("wildcard import") = forAll(testImport("import math._" :: Nil))
property("comma-separated imports") = forAll(testImport("import util._, math._, xml._" :: Nil))

View File

@ -3,7 +3,6 @@ package std
import complete.{ DefaultParsers, Parsers }
/*object UseTask
{
import Def._
@ -18,8 +17,7 @@ package std
if(y.value) z else x
}
}*/
object Assign
{
object Assign {
import java.io.File
import Def.{ inputKey, settingKey, taskKey }
import Def.{ Initialize, macroValueT, parserToInput }

View File

@ -10,8 +10,7 @@ package sbt
import Prop._
import Gen._
object Delegates extends Properties("delegates")
{
object Delegates extends Properties("delegates") {
property("generate non-empty configs") = forAll { (c: Seq[Config]) => !c.isEmpty }
property("generate non-empty tasks") = forAll { (t: Seq[Taskk]) => !t.isEmpty }
@ -62,8 +61,7 @@ object Delegates extends Properties("delegates")
val modAndIdent = mods.map(_ :: idFun[Scope] :: Nil)
def loop(cur: Scope, acc: List[Scope], rem: List[Seq[Scope => Scope]]): Seq[Scope] =
rem match
{
rem match {
case Nil => acc
case x :: xs => x flatMap { mod =>
val s = mod(cur)

View File

@ -10,10 +10,11 @@ package sbt
import Prop._
import Arbitrary.arbBool
/** Tests that the scoped key parser in Act can correctly parse a ScopedKey converted by Def.show*Key.
* This includes properly resolving omitted components.*/
object ParseKey extends Properties("Key parser test")
{
/**
* Tests that the scoped key parser in Act can correctly parse a ScopedKey converted by Def.show*Key.
* This includes properly resolving omitted components.
*/
object ParseKey extends Properties("Key parser test") {
final val MaxKeys = 5
final val MaxScopedKeys = 100
@ -80,8 +81,7 @@ object ParseKey extends Properties("Key parser test")
for (scope <- TestBuild.scope(s.env); key <- oneOf(s.allAttributeKeys.toSeq)) yield ScopedKey(scope, key)
}
def structureKeyMask(genKey: Structure => Gen[ScopedKey[_]])(implicit maskGen: Gen[ScopeMask], structureGen: Gen[Structure]): Gen[StructureKeyMask] =
for(mask <- maskGen; structure <- structureGen; key <- genKey(structure)) yield
new StructureKeyMask(structure, key, mask)
for (mask <- maskGen; structure <- structureGen; key <- genKey(structure)) yield new StructureKeyMask(structure, key, mask)
final class StructureKeyMask(val structure: Structure, val key: ScopedKey[_], val mask: ScopeMask)
def resolve(structure: Structure, key: ScopedKey[_], mask: ScopeMask): ScopedKey[_] =
@ -121,8 +121,7 @@ object ParseKey extends Properties("Key parser test")
scopes <- pickN(loadFactor, env.allFullScopes)
current <- oneOf(env.allProjects.unzip._1)
structure <- f(scopes, env, current)
} yield
structure
} yield structure
def pickN[T](load: Double, from: Seq[T]): Gen[Seq[T]] =
pick((load * from.size).toInt, from)

View File

@ -5,8 +5,7 @@ package sbt
import Project.project
import java.io.File
class ProjectDefs
{
class ProjectDefs {
lazy val p = project
val x = project
@ -21,15 +20,14 @@ class ProjectDefs
lazy val aa: Project = project
}
object ProjectMacro extends Properties("ProjectMacro")
{
object ProjectMacro extends Properties("ProjectMacro") {
lazy val pd = new ProjectDefs
import pd._
def secure(f: => Prop): Prop = try {
Prop.secure(f)
} catch { case e: Throwable =>
} catch {
case e: Throwable =>
e.printStackTrace
throw e
}
@ -64,4 +62,3 @@ object ProjectMacro extends Properties("ProjectMacro")
(p.base.getName == dir)
}
}

View File

@ -5,8 +5,7 @@ import Gen.{listOf}
import Prop._
import Tags._
object TagsTest extends Properties("Tags")
{
object TagsTest extends Properties("Tags") {
final case class Size(value: Int)
def tagMap: Gen[TagMap] = for (ts <- listOf(tagAndFrequency)) yield ts.toMap

View File

@ -13,8 +13,7 @@ package sbt
// Notes:
// Generator doesn't produce cross-build project dependencies or do anything with the 'extra' axis
object TestBuild
{
object TestBuild {
val MaxTasks = 6
val MaxProjects = 7
val MaxConfigs = 5
@ -35,22 +34,18 @@ object TestBuild
implicit val cGen = Arbitrary { genConfigs(idGen, MaxDepsGen, MaxConfigsGen) }
implicit val tGen = Arbitrary { genTasks(idGen, MaxDepsGen, MaxTasksGen) }
final class Keys(val env: Env, val scopes: Seq[Scope])
{
final class Keys(val env: Env, val scopes: Seq[Scope]) {
override def toString = env + "\n" + scopes.mkString("Scopes:\n\t", "\n\t", "")
lazy val delegated = scopes map env.delegates
}
final case class Structure(env: Env, current: ProjectRef, data: Settings[Scope], keyIndex: KeyIndex, keyMap: Map[String, AttributeKey[_]])
{
final case class Structure(env: Env, current: ProjectRef, data: Settings[Scope], keyIndex: KeyIndex, keyMap: Map[String, AttributeKey[_]]) {
override def toString = env.toString + "\n" + "current: " + current + "\nSettings:\n\t" + showData + keyMap.keys.mkString("All keys:\n\t", ", ", "")
def showKeys(map: AttributeMap): String = map.keys.mkString("\n\t ", ",", "\n")
def showData: String =
{
val scopeStrings =
for( (scope, map) <- data.data ) yield
(Scope.display(scope, "<key>"), showKeys(map))
for ((scope, map) <- data.data) yield (Scope.display(scope, "<key>"), showKeys(map))
scopeStrings.toSeq.sorted.map(t => t._1 + t._2).mkString("\n\t")
}
val extra: BuildUtil[Proj] =
@ -67,21 +62,18 @@ object TestBuild
// task axis of Scope is set to Global and the value of the second map is the original task axis
val taskAxesMappings =
for( (scope, keys) <- data.data.toIterable; key <- keys.keys ) yield
(ScopedKey(scope.copy(task = Global), key), scope.task) : (ScopedKey[_], ScopeAxis[AttributeKey[_]])
for ((scope, keys) <- data.data.toIterable; key <- keys.keys) yield (ScopedKey(scope.copy(task = Global), key), scope.task): (ScopedKey[_], ScopeAxis[AttributeKey[_]])
val taskAxes = Relation.empty ++ taskAxesMappings
val global = new HashSet[ScopedKey[_]]
val single = new HashSet[ScopedKey[_]]
val multi = new HashSet[ScopedKey[_]]
for( (skey, tasks) <- taskAxes.forwardMap)
{
for ((skey, tasks) <- taskAxes.forwardMap) {
def makeKey(task: ScopeAxis[AttributeKey[_]]) = ScopedKey(skey.scope.copy(task = task), skey.key)
val hasGlobal = tasks(Global)
if (hasGlobal)
global += skey
else
{
else {
val keys = tasks map makeKey
if (keys.size == 1)
single ++= keys
@ -92,8 +84,7 @@ object TestBuild
(taskAxes, global.toSet, single.toSet, multi.toSet)
}
}
final class Env(val builds: Seq[Build], val tasks: Seq[Taskk])
{
final class Env(val builds: Seq[Build], val tasks: Seq[Taskk]) {
override def toString = "Env:\n " + " Tasks:\n " + tasks.mkString("\n ") + "\n" + builds.mkString("\n ")
val root = builds.head
val buildMap = mapBy(builds)(_.uri)
@ -123,31 +114,26 @@ object TestBuild
(ref, p) <- (Global, root.root) +: allProjects.map { case (ref, p) => (Select(ref), p) }
t <- Global +: tasks.map(t => Select(t.key))
c <- Global +: p.configurations.map(c => Select(ConfigKey(c.name)))
} yield
Scope(project = ref, config = c, task = t, extra = Global)
} yield Scope(project = ref, config = c, task = t, extra = Global)
}
def getKey: Taskk => AttributeKey[_] = _.key
def toConfigKey: Config => ConfigKey = c => ConfigKey(c.name)
final class Build(val uri: URI, val projects: Seq[Proj])
{
final class Build(val uri: URI, val projects: Seq[Proj]) {
override def toString = "Build " + uri.toString + " :\n " + projects.mkString("\n ")
val allProjects = projects map { p => (ProjectRef(uri, p.id), p) }
val root = projects.head
val projectMap = mapBy(projects)(_.id)
}
final class Proj(val id: String, val delegates: Seq[ProjectRef], val configurations: Seq[Config])
{
final class Proj(val id: String, val delegates: Seq[ProjectRef], val configurations: Seq[Config]) {
override def toString = "Project " + id + "\n Delegates:\n " + delegates.mkString("\n ") +
"\n Configurations:\n " + configurations.mkString("\n ")
val confMap = mapBy(configurations)(_.name)
}
final class Config(val name: String, val extended: Seq[Config])
{
final class Config(val name: String, val extended: Seq[Config]) {
override def toString = name + " (extends: " + extended.map(_.name).mkString(", ") + ")"
}
final class Taskk(val key: AttributeKey[String], val delegates: Seq[Taskk])
{
final class Taskk(val key: AttributeKey[String], val delegates: Seq[Taskk]) {
override def toString = key.label + " (delegates: " + delegates.map(_.key.label).mkString(", ") + ")"
}
@ -163,8 +149,7 @@ object TestBuild
cAxis <- oneOrGlobal(project.configurations map toConfigKey)
tAxis <- oneOrGlobal(env.tasks map getKey)
pAxis <- orGlobal(frequency((1, BuildRef(build.uri)), (3, ProjectRef(build.uri, project.id))))
} yield
Scope( pAxis, cAxis, tAxis, Global)
} yield Scope(pAxis, cAxis, tAxis, Global)
def orGlobal[T](gen: Gen[T]): Gen[ScopeAxis[T]] =
frequency((1, gen map Select.apply), (1, Global))
@ -203,8 +188,7 @@ object TestBuild
implicit def maskGen(implicit arbBoolean: Arbitrary[Boolean]): Gen[ScopeMask] =
{
val b = arbBoolean.arbitrary
for(p <- b; c <- b; t <- b; x <- b) yield
ScopeMask(project = p, config = c, task = t, extra = x)
for (p <- b; c <- b; t <- b; x <- b) yield ScopeMask(project = p, config = c, task = t, extra = x)
}
implicit lazy val idGen: Gen[String] = for (size <- chooseShrinkable(1, MaxIDSize); cs <- listOfN(size, alphaChar)) yield cs.mkString
@ -255,8 +239,7 @@ object TestBuild
make(key) map { (mk: Seq[A] => A) => (key, deps, mk) }
def genAcyclic[T](maxDeps: Gen[Int], names: List[T], acc: List[Gen[(T, Seq[T])]]): Gen[Seq[(T, Seq[T])]] =
names match
{
names match {
case Nil => sequence(acc)
case x :: xs =>
val next = for (depCount <- maxDeps; d <- pick(depCount min xs.size, xs)) yield (x, d.toList)

View File

@ -152,6 +152,7 @@ object Sbt extends Build {
)
private def doScripted(launcher: File, scriptedSbtClasspath: Seq[Attributed[File]], scriptedSbtInstance: ScalaInstance, sourcePath: File, args: Seq[String]) {
System.err.println(s"About to run tests: ${args.mkString("\n * ", "\n * ", "\n")}")
val noJLine = new classpath.FilteredLoader(scriptedSbtInstance.loader, "jline." :: Nil)
val loader = classpath.ClasspathUtilities.toLoader(scriptedSbtClasspath.files, noJLine)
val m = ModuleUtilities.getObject("sbt.test.ScriptedTests", loader)
@ -174,6 +175,8 @@ object Sbt extends Build {
import sbt.complete._
import DefaultParsers._
// Paging, 1-index based.
case class ScriptedTestPage(page: Int, total: Int)
def scriptedParser(scriptedBase: File): Parser[Seq[String]] =
{
val pairs = (scriptedBase * AllPassFilter * AllPassFilter * "test").get map { (f: File) =>
@ -184,9 +187,36 @@ object Sbt extends Build {
val id = charClass(c => !c.isWhitespace && c != '/').+.string
val groupP = token(id.examples(pairMap.keySet.toSet)) <~ token('/')
def nameP(group: String) = token("*".id | id.examples(pairMap(group)))
val testID = for (group <- groupP; name <- nameP(group)) yield (group, name)
(token(Space) ~> matched(testID)).*
// A parser for page definitions
val pageP: Parser[ScriptedTestPage] = ("*" ~ NatBasic ~ "of" ~ NatBasic) map {
case _ ~ page ~ _ ~ total => ScriptedTestPage(page, total)
}
// Grabs the filenames from a given test group in the current page definition.
def pagedFilenames(group: String, page: ScriptedTestPage): Seq[String] = {
val files = pairMap(group).toSeq.sortBy(_.toLowerCase)
val pageSize = files.size / page.total
// The last page may loose some values, so we explicitly keep them
val dropped = files.drop(pageSize * (page.page - 1))
if (page.page == page.total) dropped
else dropped.take(pageSize)
}
def nameP(group: String) = {
token("*".id | id.examples(pairMap(group)))
}
val PagedIds: Parser[Seq[String]] =
for {
group <- groupP
page <- pageP
files = pagedFilenames(group, page)
// TODO - Fail the parser if we don't have enough files for the given page size
//if !files.isEmpty
} yield files map (f => group + '/' + f)
val testID = (for (group <- groupP; name <- nameP(group)) yield (group, name))
val testIdAsGroup = matched(testID) map (test => Seq(test))
//(token(Space) ~> matched(testID)).*
(token(Space) ~> (PagedIds | testIdAsGroup)).* map (_.flatten)
}
lazy val scripted = InputKey[Unit]("scripted")

View File

@ -5,11 +5,12 @@ import Prop.{Exception => _, _}
import Gen.{ alphaNumChar, frequency, listOf1, oneOf }
import java.io.File
object ForkTest extends Properties("Fork")
{
/** Heuristic for limiting the length of the classpath string.
object ForkTest extends Properties("Fork") {
/**
* Heuristic for limiting the length of the classpath string.
* Longer than this will hit hard limits in the total space
* allowed for process initialization, which includes environment variables, at least on linux. */
* allowed for process initialization, which includes environment variables, at least on linux.
*/
final val MaximumClasspathLength = 100000
lazy val genOptionName = frequency((9, Some("-cp")), (9, Some("-classpath")), (1, None))
@ -27,7 +28,8 @@ object ForkTest extends Properties("Fork")
Nil
property("Arbitrary length classpath successfully passed.") = forAllNoShrink(genOptionName, genRelClasspath) { (optionName: Option[String], relCP: List[String]) =>
IO.withTemporaryDirectory { dir => TestLogger { log =>
IO.withTemporaryDirectory { dir =>
TestLogger { log =>
val withScala = requiredEntries ::: relCP.map(rel => new File(dir, rel))
val absClasspath = trimClasspath(Path.makeString(withScala))
val args = optionName.map(_ :: absClasspath :: Nil).toList.flatten ++ mainAndArgs
@ -40,7 +42,8 @@ object ForkTest extends Properties("Fork")
s"args length: ${args.mkString(" ").length}" |:
s"exitCode: $exitCode, expected: $expectedCode" |:
(exitCode == expectedCode)
}}
}
}
}
private[this] def trimClasspath(cp: String): String =

View File

@ -8,8 +8,7 @@ import Prop._
import TaskGen._
import Task._
object ExecuteSpec extends Properties("Execute")
{
object ExecuteSpec extends Properties("Execute") {
val iGen = Arbitrary.arbInt.arbitrary
property("evaluates simple task") = forAll(iGen, MaxWorkersGen) { (i: Int, workers: Int) =>
("Workers: " + workers) |:

View File

@ -6,8 +6,7 @@ package sbt
import org.scalacheck._
import Gen.choose
object TaskGen extends std.TaskExtra
{
object TaskGen extends std.TaskExtra {
// upper bounds to make the tests finish in reasonable time
val MaxTasks = 100
val MaxWorkers = 29

View File

@ -5,8 +5,7 @@ import Prop._
import TaskGen._
import Task._
object TaskRunnerCircularTest extends Properties("TaskRunner Circular")
{
object TaskRunnerCircularTest extends Properties("TaskRunner Circular") {
property("Catches circular references") = forAll(MaxTasksGen, MaxWorkersGen) { checkCircularReferences _ }
property("Allows references to completed tasks") = forAllNoShrink(MaxTasksGen, MaxWorkersGen) { allowedReference _ }
final def allowedReference(intermediate: Int, workers: Int) =

View File

@ -6,8 +6,7 @@ import Task._
import TaskGen._
import math.abs
object TaskRunnerForkTest extends Properties("TaskRunner Fork")
{
object TaskRunnerForkTest extends Properties("TaskRunner Fork") {
property("fork m tasks and wait for all to complete") = forAll(MaxTasksGen, MaxWorkersGen) { (m: Int, workers: Int) =>
val values = (0 until m).toList
checkResult(tryRun(values.fork(f => ()).join.map(_.toList), false, workers), values)
@ -23,8 +22,7 @@ object TaskRunnerForkTest extends Properties("TaskRunner Fork")
runDoubleJoin(abs(a), abs(b), workers)
true
}
def runDoubleJoin(a: Int, b: Int, workers: Int)
{
def runDoubleJoin(a: Int, b: Int, workers: Int) {
def inner(i: Int) = List.range(0, b).map(j => task(j).named(j.toString)).join
tryRun(List.range(0, a).map(inner).join, false, workers)
}

View File

@ -13,8 +13,7 @@ package std
import java.util.concurrent.{ CountDownLatch, TimeUnit }
object TaskSerial extends Properties("task serial")
{
object TaskSerial extends Properties("task serial") {
val checkCycles = true
val Timeout = 100 // in milliseconds
@ -61,8 +60,7 @@ object TaskSerial extends Properties("task serial")
tryRun[T](t, checkCycles, restrictions)
}
object TaskTest
{
object TaskTest {
def run[T](root: Task[T], checkCycles: Boolean, restrictions: ConcurrentRestrictions[Task[_]]): Result[T] =
{
val (service, shutdown) = completionService[Task[_], Completed](restrictions, (x: String) => System.err.println(x))

View File

@ -7,8 +7,7 @@ import Types._
import Task._
import Execute._
object Test extends std.TaskExtra
{
object Test extends std.TaskExtra {
def t2[A, B](a: Task[A], b: Task[B]) = multInputTask[({ type l[L[x]] = (L[A], L[B]) })#l]((a, b))(AList.tuple2)
def t3[A, B, C](a: Task[A], b: Task[B], c: Task[C]) = multInputTask[({ type l[L[x]] = (L[A], L[B], L[C]) })#l]((a, b, c))(AList.tuple3)
@ -42,8 +41,7 @@ object Test extends std.TaskExtra
def d4(i: Int): Task[Int] = nop flatMap { _ => val x = math.random; if (x < 0.01) task(i); else d4(i + 1) }
def go()
{
def go() {
def run[T](root: Task[T]) =
println("Result : " + TaskGen.run(root, true, 2))

View File

@ -5,8 +5,7 @@ import Prop._
import TaskGen._
import Task._
object TaskRunnerCallTest extends Properties("TaskRunner Call")
{
object TaskRunnerCallTest extends Properties("TaskRunner Call") {
property("calculates fibonacci") = forAll(MaxTasksGen, MaxWorkersGen) { (i: Int, workers: Int) =>
(i > 0) ==> {
val f = fibDirect(i)

View File

@ -9,8 +9,7 @@ import TaskGen._
import Task._
import Types._
object TaskRunnerSortTest extends Properties("TaskRunnerSort")
{
object TaskRunnerSortTest extends Properties("TaskRunnerSort") {
property("sort") = forAll(TaskListGen, MaxWorkersGen) { (list: List[Int], workers: Int) =>
val a = list.toArray
val sorted = a.toArray
@ -25,8 +24,7 @@ object TaskRunnerSortTest extends Properties("TaskRunnerSort")
{
if (a.length < 2)
a
else
{
else {
val pivot = a(0)
val (lt, gte) = a.view.drop(1).partition(_ < pivot)
sortDirect(lt) ++ List(pivot) ++ sortDirect(gte)
@ -36,8 +34,7 @@ object TaskRunnerSortTest extends Properties("TaskRunnerSort")
{
if (a.length < 200)
task(sortDirect(a))
else
{
else {
task(a) flatMap { a =>
val pivot = a(0)
val (lt, gte) = a.view.drop(1).partition(_ < pivot)

View File

@ -5,18 +5,14 @@ package sbt
import org.scalacheck.Prop._
object checkResult
{
object checkResult {
def apply[T](run: => T, expected: T) =
{
("Expected: " + expected) |:
(try
{
(try {
val actual = run
("Actual: " + actual) |: (actual == expected)
}
catch
{
} catch {
case i: Incomplete =>
println(i)
"One or more tasks failed" |: false

View File

@ -5,8 +5,7 @@ import org.scalacheck._
import Prop._
import java.io.File
object ConcurrentCache extends Properties("ClassLoaderCache concurrent access")
{
object ConcurrentCache extends Properties("ClassLoaderCache concurrent access") {
implicit lazy val concurrentArb: Arbitrary[Int] = Arbitrary(Gen.choose(1, 1000))
implicit lazy val filenameArb: Arbitrary[String] = Arbitrary(Gen.alphaStr)

View File

@ -8,8 +8,7 @@ import Prop._
import scala.collection.mutable.HashSet
object DagSpecification extends Properties("Dag")
{
object DagSpecification extends Properties("Dag") {
property("No repeated nodes") = forAll { (dag: TestDag) => isSet(dag.topologicalSort) }
property("Sort contains node") = forAll { (dag: TestDag) => dag.topologicalSort.contains(dag) }
property("Dependencies precede node") = forAll { (dag: TestDag) => dependenciesPrecedeNodes(dag.topologicalSort) }
@ -22,8 +21,7 @@ object DagSpecification extends Properties("Dag")
{
for (i <- 0 until nodeCount; nextDeps <- Gen.someOf(nodes).apply(p))
nodes += new TestDag(i, nextDeps)
for(nextDeps <- Gen.someOf(nodes)) yield
new TestDag(nodeCount, nextDeps)
for (nextDeps <- Gen.someOf(nodes)) yield new TestDag(nodeCount, nextDeps)
}
Gen.parameterized(nonterminalGen)
}
@ -34,23 +32,19 @@ object DagSpecification extends Properties("Dag")
val seen = new HashSet[TestDag]
def iterate(remaining: List[TestDag]): Boolean =
{
remaining match
{
remaining match {
case Nil => true
case node :: tail =>
if(node.dependencies.forall(seen.contains) && !seen.contains(node))
{
if (node.dependencies.forall(seen.contains) && !seen.contains(node)) {
seen += node
iterate(tail)
}
else
} else
false
}
}
iterate(sort)
}
}
class TestDag(id: Int, val dependencies: Iterable[TestDag]) extends Dag[TestDag]
{
class TestDag(id: Int, val dependencies: Iterable[TestDag]) extends Dag[TestDag] {
override def toString = id + "->" + dependencies.mkString("[", ",", "]")
}

View File

@ -3,8 +3,7 @@ package sbt
import org.scalacheck._
import Prop._
object KeyTest extends Properties("AttributeKey")
{
object KeyTest extends Properties("AttributeKey") {
property("equality") = {
compare(AttributeKey[Int]("test"), AttributeKey[Int]("test"), true) &&
compare(AttributeKey[Int]("test"), AttributeKey[Int]("test", "description"), true) &&
@ -25,11 +24,9 @@ object KeyTest extends Properties("AttributeKey")
compare0(a, b, same)
def compare0(a: AttributeKey[_], b: AttributeKey[_], same: Boolean) =
if(same)
{
if (same) {
("equality" |: (a == b)) &&
("hash" |: (a.hashCode == b.hashCode))
}
else
} else
("equality" |: (a != b))
}

View File

@ -6,8 +6,7 @@ package sbt
import Types._
// compilation test
object PMapTest
{
object PMapTest {
val mp = new DelegatingPMap[Some, Id](new collection.mutable.HashMap)
mp(Some("asdf")) = "a"
mp(Some(3)) = 9

View File

@ -10,15 +10,15 @@ final case class Scope(nestIndex: Int, idAtIndex: Int = 0)
// Lots of type constructors would become binary, which as you may know requires lots of type lambdas
// when you want a type function with only one parameter.
// That would be a general pain.)
object SettingsExample extends Init[Scope]
{
object SettingsExample extends Init[Scope] {
// Provides a way of showing a Scope+AttributeKey[_]
val showFullKey: Show[ScopedKey[_]] = new Show[ScopedKey[_]] {
def apply(key: ScopedKey[_]) = s"${key.scope.nestIndex}(${key.scope.idAtIndex})/${key.key.label}"
}
// A sample delegation function that delegates to a Scope with a lower index.
val delegates: Scope => Seq[Scope] = { case s @ Scope(index, proj) =>
val delegates: Scope => Seq[Scope] = {
case s @ Scope(index, proj) =>
s +: (if (index <= 0) Nil else { (if (proj > 0) List(Scope(index)) else Nil) ++: delegates(Scope(index - 1)) })
}
@ -30,8 +30,7 @@ object SettingsExample extends Init[Scope]
/** Usage Example **/
object SettingsUsage
{
object SettingsUsage {
import SettingsExample._
import Types._
@ -63,7 +62,8 @@ object SettingsUsage
println( k.label + i + " = " + applied.get( Scope(i), k) )
}*/
/** Output:
/**
* Output:
* For the None results, we never defined the value and there was no value to delegate to.
* For a3, we explicitly defined it to be 3.
* a4 wasn't defined, so it delegates to a3 according to our delegates function.
@ -71,17 +71,17 @@ object SettingsUsage
* a5 is defined as the previous value of a5 + 1 and
* since no previous value of a5 was defined, it delegates to a4, resulting in 3+1=4.
* b5 isn't defined explicitly, so it delegates to b4 and is therefore equal to 9 as well
a0 = None
b0 = None
a1 = None
b1 = None
a2 = None
b2 = None
a3 = Some(3)
b3 = None
a4 = Some(3)
b4 = Some(9)
a5 = Some(4)
b5 = Some(9)
**/
* a0 = None
* b0 = None
* a1 = None
* b1 = None
* a2 = None
* b2 = None
* a3 = Some(3)
* b3 = None
* a4 = Some(3)
* b4 = Some(9)
* a5 = Some(4)
* b5 = Some(9)
*/
}

View File

@ -5,8 +5,7 @@ import Prop._
import SettingsUsage._
import SettingsExample._
object SettingsTest extends Properties("settings")
{
object SettingsTest extends Properties("settings") {
import scala.reflect.Manifest
@ -101,7 +100,8 @@ object SettingsTest extends Properties("settings")
property("DerivedSetting in ThisBuild scopes derived settings under projects thus allowing safe +=") = forAllNoShrink(Gen.choose(1, 100)) { derivedSettingsScope }
final def derivedSettingsScope(nrProjects: Int): Prop =
{
forAll(mkAttrKeys[Int](2)) { case List(key, derivedKey) =>
forAll(mkAttrKeys[Int](2)) {
case List(key, derivedKey) =>
val projectKeys = for { proj <- 1 to nrProjects } yield ScopedKey(Scope(1, proj), key)
val projectDerivedKeys = for { proj <- 1 to nrProjects } yield ScopedKey(Scope(1, proj), derivedKey)
val globalKey = ScopedKey(Scope(0), key)
@ -166,8 +166,7 @@ object SettingsTest extends Properties("settings")
catch { case e: Throwable => e.printStackTrace; throw e }
}
// This setup is a workaround for module synchronization issues
final class CCR(intermediate: Int)
{
final class CCR(intermediate: Int) {
lazy val top = iterate(value(intermediate), intermediate)
def iterate(init: Initialize[Int], i: Int): Initialize[Int] =
bind(init) { t =>

View File

@ -1,7 +1,6 @@
package sbt.complete
object JLineTest
{
object JLineTest {
import DefaultParsers._
val one = "blue" | "green" | "black"
@ -16,8 +15,7 @@ object JLineTest
}
val parsers = Map("1" -> one, "2" -> two, "3" -> three, "4" -> four, "5" -> five)
def main(args: Array[String])
{
def main(args: Array[String]) {
import jline.TerminalFactory
import jline.console.ConsoleReader
val reader = new ConsoleReader()
@ -39,8 +37,7 @@ object JLineTest
import Parser._
import org.scalacheck._
object ParserTest extends Properties("Completing Parser")
{
object ParserTest extends Properties("Completing Parser") {
import Parsers._
import DefaultParsers.matches
@ -111,8 +108,7 @@ object ParserTest extends Properties("Completing Parser")
property("repeatDep accepts one token") = matches(repeat, colors.toSeq.head)
property("repeatDep accepts two tokens") = matches(repeat, colors.toSeq.take(2).mkString(" "))
}
object ParserExample
{
object ParserExample {
val ws = charClass(_.isWhitespace)+
val notws = charClass(!_.isWhitespace)+
@ -134,8 +130,7 @@ object ParserExample
println(apply(t)("test w").resultEmpty)
println(apply(t)("test was were").resultEmpty)
def run(n: Int)
{
def run(n: Int) {
val a = 'a'.id
val aq = a.?
val aqn = repeat(aq, min = n, max = n)
@ -145,8 +140,7 @@ object ParserExample
def r = apply(ann)("a" * (n * 2)).resultEmpty
println(r.isValid)
}
def run2(n: Int)
{
def run2(n: Int) {
val ab = "ab".?.*
val r = apply(ab)("a" * n).resultEmpty
println(r)

View File

@ -6,8 +6,7 @@ import sbt.IO.withTemporaryDirectory
import java.io.File
import sbt.IO._
class FileExamplesTest extends Specification
{
class FileExamplesTest extends Specification {
"listing all files in an absolute base directory" should {
"produce the entire base directory's contents" in new directoryStructure {
@ -49,8 +48,7 @@ class FileExamplesTest extends Specification
}
}
class directoryStructure(withCompletionPrefix: String = "") extends Scope with DelayedInit
{
class directoryStructure(withCompletionPrefix: String = "") extends Scope with DelayedInit {
var fileExamples: FileExamples = _
var baseDir: File = _
var childFiles: List[File] = _

View File

@ -6,8 +6,7 @@ import org.scalacheck._
import Prop._
import Arbitrary.arbLong
object CopySpec extends Properties("Copy")
{
object CopySpec extends Properties("Copy") {
// set to 0.25 GB by default for success on most systems without running out of space.
// when modifying IO.copyFile, verify against 1 GB or higher, preferably > 4 GB
final val MaxFileSizeBits = 28

View File

@ -8,8 +8,7 @@ import Prop._
import Arbitrary.{ arbString => _, arbChar => _, _ }
import java.io.{ File, IOException }
object WriteContentSpecification extends Properties("Write content")
{
object WriteContentSpecification extends Properties("Write content") {
property("Roundtrip string") = forAll(writeAndCheckString _)
property("Roundtrip bytes") = forAll(writeAndCheckBytes _)
property("Write string overwrites") = forAll(overwriteAndCheckStrings _)

View File

@ -6,11 +6,11 @@ package sbt
import org.scalacheck._
import Prop._
object NameFilterSpecification extends Properties("NameFilter")
{
object NameFilterSpecification extends Properties("NameFilter") {
property("All pass accepts everything") = forAll { (s: String) => AllPassFilter.accept(s) }
property("Exact filter matches provided string") = forAll {
(s1: String, s2: String) => (new ExactFilter(s1)).accept(s2) == (s1 == s2) }
(s1: String, s2: String) => (new ExactFilter(s1)).accept(s2) == (s1 == s2)
}
property("Exact filter matches valid string") = forAll { (s: String) => (new ExactFilter(s)).accept(s) }
property("Glob filter matches provided string if no *s") = forAll {
@ -18,23 +18,28 @@ object NameFilterSpecification extends Properties("NameFilter")
{
val stripped = stripAsterisksAndControl(s1)
(GlobFilter(stripped).accept(s2) == (stripped == s2))
} }
}
}
property("Glob filter matches valid string if no *s") = forAll {
(s: String) =>
{
val stripped = stripAsterisksAndControl(s)
GlobFilter(stripped).accept(stripped)
}}
}
}
property("Glob filter matches valid") = forAll {
(list: List[String]) =>
{
val stripped = list.map(stripAsterisksAndControl)
GlobFilter(stripped.mkString("*")).accept(stripped.mkString)
}}
}
}
/** Raw control characters are stripped because they are not allowed in expressions.
* Asterisks are stripped because they are added under the control of the tests.*/
/**
* Raw control characters are stripped because they are not allowed in expressions.
* Asterisks are stripped because they are added under the control of the tests.
*/
private def stripAsterisksAndControl(s: String) = (s filter validChar).toString
private[this] def validChar(c: Char) =
!java.lang.Character.isISOControl(c) &&

View File

@ -23,10 +23,11 @@ object RichURISpecification extends Properties("Rich URI") {
implicit val arbitraryURI: Arbitrary[URI] =
Arbitrary(
for (scheme <- identifier;
for (
scheme <- identifier;
path <- pathGen;
fragment <- nullable(strGen))
yield new URI(scheme, "file:" + path, fragment)
fragment <- nullable(strGen)
) yield new URI(scheme, "file:" + path, fragment)
)
property("withoutFragment should drop fragment") = forAll { (uri: URI) =>

View File

@ -10,8 +10,7 @@ import IO._
import java.io.File
import Function.tupled
object CheckStash extends Specification
{
object CheckStash extends Specification {
"stash" should {
"handle empty files" in {
stash(Set()) {}
@ -27,8 +26,7 @@ object CheckStash extends Specification
}
}
def checkRestore(seq: Seq[File])
{
def checkRestore(seq: Seq[File]) {
allCorrect(seq)
stash0(seq, throw new TestRuntimeException) must beFalse
@ -40,22 +38,19 @@ object CheckStash extends Specification
stash0(seq, throw new TestError) must beFalse
noneExist(seq)
}
def checkMove(seq: Seq[File])
{
def checkMove(seq: Seq[File]) {
allCorrect(seq)
stash0(seq, ()) must beTrue
noneExist(seq)
}
def stash0(seq: Seq[File], post: => Unit): Boolean =
try
{
try {
stash(Set() ++ seq) {
noneExist(seq)
post
}
true
}
catch {
} catch {
case _: TestError | _: TestException | _: TestRuntimeException => false
}

View File

@ -3,17 +3,17 @@ package sbt
import java.io.File
import IO.{ withTemporaryDirectory, write }
object WithFiles
{
/** Takes the relative path -> content pairs and writes the content to a file in a temporary directory. The written file
object WithFiles {
/**
* Takes the relative path -> content pairs and writes the content to a file in a temporary directory. The written file
* path is the relative path resolved against the temporary directory path. The provided function is called with the resolved file paths
* in the same order as the inputs. */
* in the same order as the inputs.
*/
def apply[T](sources: (File, String)*)(f: Seq[File] => T): T =
{
withTemporaryDirectory { dir =>
val sourceFiles =
for((file, content) <- sources) yield
{
for ((file, content) <- sources) yield {
assert(!file.isAbsolute)
val to = new File(dir, file.getPath)
write(to, content)

View File

@ -6,8 +6,7 @@ import Gen.{listOf, oneOf}
import ConsoleLogger.{ ESC, hasEscapeSequence, isEscapeTerminator, removeEscapeSequences }
object Escapes extends Properties("Escapes")
{
object Escapes extends Properties("Escapes") {
property("genTerminator only generates terminators") =
forAllNoShrink(genTerminator) { (c: Char) => isEscapeTerminator(c) }
@ -47,8 +46,7 @@ object Escapes extends Properties("Escapes")
}
final case class EscapeAndNot(escape: EscapeSequence, notEscape: String)
final case class EscapeSequence(content: String, terminator: Char)
{
final case class EscapeSequence(content: String, terminator: Char) {
assert(content.forall(c => !isEscapeTerminator(c)), "Escape sequence content contains an escape terminator: '" + content + "'")
assert(isEscapeTerminator(terminator))
def makeString: String = ESC + content + terminator
@ -60,8 +58,7 @@ object Escapes extends Properties("Escapes")
lazy val genEscapePairs: Gen[List[EscapeAndNot]] = listOf(genEscapePair)
lazy val genArbitraryEscapeSequence: Gen[EscapeSequence] =
for(content <- genWithoutTerminator; term <- genTerminator) yield
new EscapeSequence(content, term)
for (content <- genWithoutTerminator; term <- genTerminator) yield new EscapeSequence(content, term)
lazy val genKnownSequence: Gen[EscapeSequence] =
oneOf((misc ++ setGraphicsMode ++ setMode ++ resetMode).map(toEscapeSequence))
@ -71,8 +68,7 @@ object Escapes extends Properties("Escapes")
lazy val misc = Seq("14;23H", "5;3f", "2A", "94B", "19C", "85D", "s", "u", "2J", "K")
lazy val setGraphicsMode: Seq[String] =
for(txt <- 0 to 8; fg <- 30 to 37; bg <- 40 to 47) yield
txt.toString + ";" + fg.toString + ";" + bg.toString + "m"
for (txt <- 0 to 8; fg <- 30 to 37; bg <- 40 to 47) yield txt.toString + ";" + fg.toString + ";" + bg.toString + "m"
lazy val resetMode = setModeLike('I')
lazy val setMode = setModeLike('h')
@ -84,8 +80,7 @@ object Escapes extends Properties("Escapes")
lazy val genWithoutEscape: Gen[String] = genRawString.map(noEscape)
def genWithRandomEscapes: Gen[String] =
for(ls <- listOf(genRawString); end <- genRawString) yield
ls.mkString("", ESC.toString, ESC.toString + end)
for (ls <- listOf(genRawString); end <- genRawString) yield ls.mkString("", ESC.toString, ESC.toString + end)
private def genRawString = Arbitrary.arbString.arbitrary
}

View File

@ -10,8 +10,7 @@ import Prop._
import java.io.Writer
object LogWriterTest extends Properties("Log Writer")
{
object LogWriterTest extends Properties("Log Writer") {
final val MaxLines = 100
final val MaxSegments = 10
@ -27,21 +26,22 @@ object LogWriterTest extends Properties("Log Writer")
check(toLines(lines), events, level)
}
/** Displays a LogEvent in a useful format for debugging. In particular, we are only interested in `Log` types
* and non-printable characters should be escaped*/
/**
* Displays a LogEvent in a useful format for debugging. In particular, we are only interested in `Log` types
* and non-printable characters should be escaped
*/
def show(event: LogEvent): String =
event match
{
event match {
case l: Log => "Log('" + Escape(l.msg) + "', " + l.level + ")"
case _ => "Not Log"
}
/** Writes the given lines to the Writer. `lines` is taken to be a list of lines, which are
/**
* Writes the given lines to the Writer. `lines` is taken to be a list of lines, which are
* represented as separately written segments (ToLog instances). ToLog.`byCharacter`
* indicates whether to write the segment by character (true) or all at once (false)*/
def logLines(writer: Writer, lines: List[List[ToLog]], newLine: String)
{
for(line <- lines; section <- line)
{
* indicates whether to write the segment by character (true) or all at once (false)
*/
def logLines(writer: Writer, lines: List[List[ToLog]], newLine: String) {
for (line <- lines; section <- line) {
val content = section.content
val normalized = Escape.newline(content, newLine)
if (section.byCharacter)
@ -75,26 +75,22 @@ object LogWriterTest extends Properties("Log Writer")
implicit lazy val arbLevel: Arbitrary[Level.Value] = Arbitrary(genLevel)
implicit def genLine(implicit logG: Gen[ToLog]): Gen[List[ToLog]] =
for(l <- listOf[ToLog](MaxSegments); last <- logG) yield
(addNewline(last) :: l.filter(!_.content.isEmpty)).reverse
for (l <- listOf[ToLog](MaxSegments); last <- logG) yield (addNewline(last) :: l.filter(!_.content.isEmpty)).reverse
implicit def genLog(implicit content: Arbitrary[String], byChar: Arbitrary[Boolean]): Gen[ToLog] =
for(c <- content.arbitrary; by <- byChar.arbitrary) yield
{
for (c <- content.arbitrary; by <- byChar.arbitrary) yield {
assert(c != null)
new ToLog(removeNewlines(c), by)
}
implicit lazy val genNewLine: Gen[NewLine] =
for(str <- oneOf("\n", "\r", "\r\n")) yield
new NewLine(str)
for (str <- oneOf("\n", "\r", "\r\n")) yield new NewLine(str)
implicit lazy val genLevel: Gen[Level.Value] =
oneOf(Level.values.toSeq)
implicit lazy val genOutput: Gen[Output] =
for(ls <- listOf[List[ToLog]](MaxLines); lv <- genLevel) yield
new Output(ls, lv)
for (ls <- listOf[List[ToLog]](MaxLines); lv <- genLevel) yield new Output(ls, lv)
def removeNewlines(s: String) = s.replaceAll("""[\n\r]+""", "")
def addNewline(l: ToLog): ToLog =
@ -106,29 +102,24 @@ object LogWriterTest extends Properties("Log Writer")
/* Helper classes*/
final class Output(val lines: List[List[ToLog]], val level: Level.Value) extends NotNull
{
final class Output(val lines: List[List[ToLog]], val level: Level.Value) extends NotNull {
override def toString =
"Level: " + level + "\n" + lines.map(_.mkString).mkString("\n")
}
final class NewLine(val str: String) extends NotNull
{
final class NewLine(val str: String) extends NotNull {
override def toString = Escape(str)
}
final class ToLog(val content: String, val byCharacter: Boolean) extends NotNull
{
final class ToLog(val content: String, val byCharacter: Boolean) extends NotNull {
def contentOnly = Escape.newline(content, "")
override def toString = if (content.isEmpty) "" else "ToLog('" + Escape(contentOnly) + "', " + byCharacter + ")"
}
/** Defines some utility methods for escaping unprintable characters.*/
object Escape
{
object Escape {
/** Escapes characters with code less than 20 by printing them as unicode escapes.*/
def apply(s: String): String =
{
val builder = new StringBuilder(s.length)
for(c <- s)
{
for (c <- s) {
def escaped = pad(c.toInt.toHexString.toUpperCase, 4, '0')
if (c < 20) builder.append("\\u").append(escaped) else builder.append(c)
}
@ -144,8 +135,7 @@ object Escape
if (s.endsWith("\n")) s.substring(0, s.length - 1) + nl else s
}
/** Records logging events for later retrieval.*/
final class RecordingLogger extends BasicLogger
{
final class RecordingLogger extends BasicLogger {
private var events: List[LogEvent] = Nil
def getEvents = events.reverse

View File

@ -1,7 +1,6 @@
package sbt
object TestLogger
{
object TestLogger {
def apply[T](f: Logger => T): T =
{
val log = new BufferedLogger(ConsoleLogger())

View File

@ -5,8 +5,7 @@ package logic
import Prop.secure
import Logic.{ LogicException, Matched }
object LogicTest extends Properties("Logic")
{
object LogicTest extends Properties("Logic") {
import TestClauses._
property("Handles trivial resolution.") = secure(expect(trivial, Set(A)))
@ -32,8 +31,7 @@ object LogicTest extends Properties("Logic")
}
}
object TestClauses
{
object TestClauses {
val A = Atom("A")
val B = Atom("B")

View File

@ -6,13 +6,12 @@ import Prop._
import Process._
object ProcessSpecification extends Properties("Process I/O")
{
object ProcessSpecification extends Properties("Process I/O") {
implicit val exitCodeArb: Arbitrary[Array[Byte]] = Arbitrary(
for(size <- Gen.choose(0, 10);
l <- Gen.listOfN[Byte](size, Arbitrary.arbByte.arbitrary))
yield
l.toArray
for (
size <- Gen.choose(0, 10);
l <- Gen.listOfN[Byte](size, Arbitrary.arbByte.arbitrary)
) yield l.toArray
)
/*property("Correct exit code") = forAll( (exitCode: Byte) => checkExit(exitCode))
@ -112,8 +111,7 @@ object ProcessSpecification extends Properties("Process I/O")
val temporaryFile1 = temp()
val temporaryFile2 = temp()
try f(temporaryFile1, temporaryFile2)
finally
{
finally {
temporaryFile1.delete()
temporaryFile2.delete()
}

View File

@ -2,17 +2,13 @@ package sbt
import java.io.{ File, FileNotFoundException, IOException }
object exit
{
def main(args: Array[String])
{
object exit {
def main(args: Array[String]) {
System.exit(java.lang.Integer.parseInt(args(0)))
}
}
object cat
{
def main(args: Array[String])
{
object cat {
def main(args: Array[String]) {
try {
if (args.length == 0)
IO.transfer(System.in, System.out)
@ -28,29 +24,24 @@ object cat
}
private def catFiles(filenames: List[String]): Option[String] =
{
filenames match
{
filenames match {
case head :: tail =>
val file = new File(head)
if (file.isDirectory)
throw new IOException("Is directory: " + file)
else if(file.exists)
{
else if (file.exists) {
Using.fileInputStream(file) { stream =>
IO.transfer(stream, System.out)
}
catFiles(tail)
}
else
} else
throw new FileNotFoundException("No such file or directory: " + file)
case Nil => None
}
}
}
object echo
{
def main(args: Array[String])
{
object echo {
def main(args: Array[String]) {
System.out.println(args.mkString(" "))
}
}

View File

@ -6,8 +6,7 @@ package sbt
import org.scalacheck._
import Prop._
object RelationTest extends Properties("Relation")
{
object RelationTest extends Properties("Relation") {
property("Added entry check") = forAll { (pairs: List[(Int, Double)]) =>
val r = Relation.empty[Int, Double] ++ pairs
check(r, pairs)
@ -19,7 +18,8 @@ object RelationTest extends Properties("Relation")
r._1s == _1s && r.forwardMap.keySet == _1s &&
r._2s == _2s && r.reverseMap.keySet == _2s &&
pairs.forall { case (a, b) =>
pairs.forall {
case (a, b) =>
(r.forward(a) contains b) &&
(r.reverse(b) contains a) &&
(r.forwardMap(a) contains b) &&
@ -43,7 +43,8 @@ object RelationTest extends Properties("Relation")
("Forward map does not contain removed" |: !r.forwardMap.contains(rem)) &&
("Removed is not a value in reverse map" |: !r.reverseMap.values.toSet.contains(rem))
} &&
all(removeFine) { case (a, b) =>
all(removeFine) {
case (a, b) =>
("Forward does not contain removed" |: (!r.forward(a).contains(b))) &&
("Reverse does not contain removed" |: (!r.reverse(b).contains(a))) &&
("Forward map does not contain removed" |: (notIn(r.forwardMap, a, b))) &&
@ -71,8 +72,7 @@ object RelationTest extends Properties("Relation")
if (s.isEmpty) true else s.map(p).reduceLeft(_ && _)
}
object EmptyRelationTest extends Properties("Empty relation")
{
object EmptyRelationTest extends Properties("Empty relation") {
lazy val e = Relation.empty[Int, Double]
property("Forward empty") = forAll { (i: Int) => e.forward(i).isEmpty }