summaryrefslogtreecommitdiff
path: root/src/partest/scala/tools/partest/nest/RunnerManager.scala
blob: d4b9feecce11d2e9cfaeaaf26cebd5ea7198b853 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
/* NEST (New Scala Test)
 * Copyright 2007-2012 LAMP/EPFL
 * @author Philipp Haller
 */

package scala.tools.partest
package nest

import java.io._
import java.net.URL
import java.util.{ Timer, TimerTask }

import scala.tools.nsc.Properties.{ jdkHome, javaHome, propOrElse }
import scala.util.Properties.{ envOrElse, isWin }
import scala.tools.nsc.{ Settings, CompilerCommand, Global }
import scala.tools.nsc.io.{ AbstractFile, PlainFile, Path, Directory, File => SFile }
import scala.tools.nsc.reporters.ConsoleReporter
import scala.tools.nsc.util.{ ClassPath, FakePos, ScalaClassLoader, stackTraceString }
import ClassPath.{ join, split }
import scala.tools.scalap.scalax.rules.scalasig.ByteCode
import scala.collection.{ mutable, immutable }
import scala.tools.nsc.interactive.{ BuildManager, RefinedBuildManager }
import scala.sys.process._
import java.util.concurrent.{ Executors, TimeUnit, TimeoutException }
import PartestDefaults.{ javaCmd, javacCmd }

class LogContext(val file: File, val writers: Option[(StringWriter, PrintWriter)])

object LogContext {
  def apply(file: File, swr: StringWriter, wr: PrintWriter): LogContext = {
    require (file != null)
    new LogContext(file, Some((swr, wr)))
  }
  def apply(file: File): LogContext = new LogContext(file, None)
}

object Output {
  object outRedirect extends Redirecter(out)
  object errRedirect extends Redirecter(err)

  System.setOut(outRedirect)
  System.setErr(errRedirect)

  import scala.util.DynamicVariable
  private def out = java.lang.System.out
  private def err = java.lang.System.err
  private val redirVar = new DynamicVariable[Option[PrintStream]](None)

  class Redirecter(stream: PrintStream) extends PrintStream(new OutputStream {
    def write(b: Int) = withStream(_ write b)

    private def withStream(f: PrintStream => Unit) = f(redirVar.value getOrElse stream)

    override def write(b: Array[Byte]) = withStream(_ write b)
    override def write(b: Array[Byte], off: Int, len: Int) = withStream(_.write(b, off, len))
    override def flush = withStream(_.flush)
    override def close = withStream(_.close)
  })

  // this supports thread-safe nested output redirects
  def withRedirected[T](newstream: PrintStream)(func: => T): T = {
    // note down old redirect destination
    // this may be None in which case outRedirect and errRedirect print to stdout and stderr
    val saved = redirVar.value
    // set new redirecter
    // this one will redirect both out and err to newstream
    redirVar.value = Some(newstream)

    try func
    finally {
      newstream.flush()
      redirVar.value = saved
    }
  }
}

class RunnerManager(kind: String, val fileManager: FileManager, params: TestRunParams) {
  import fileManager._

  val compileMgr = new CompileManager(fileManager)
  fileManager.CLASSPATH += File.pathSeparator + PathSettings.scalaCheck

  private def compareFiles(f1: File, f2: File): String =
    try fileManager.compareFiles(f1, f2)
    catch { case t: Exception => t.toString }

  /** This does something about absolute paths and file separator
   *  chars before diffing.
   */
  private def replaceSlashes(dir: File, s: String): String = {
    val base = (dir.getAbsolutePath + File.separator).replace('\\', '/')
    var regex = """\Q%s\E""" format base
    if (isWin) regex = "(?i)" + regex
    s.replace('\\', '/').replaceAll(regex, "")
  }

  private def workerError(msg: String): Unit = System.err.println("Error: " + msg)

  private def printInfoStart(file: File, printer: PrintWriter) {
    NestUI.outline("testing: ", printer)
    val filesdir = file.getAbsoluteFile.getParentFile.getParentFile
    val testdir = filesdir.getParentFile
    val totalWidth = 56
    val name = {
      // 1. try with [...]/files/run/test.scala
      val name = file.getAbsolutePath drop testdir.getAbsolutePath.length
      if (name.length <= totalWidth) name
      // 2. try with [...]/run/test.scala
      else file.getAbsolutePath drop filesdir.getAbsolutePath.length
    }
    NestUI.normal("[...]%s%s".format(name, " " * (totalWidth - name.length)), printer)
  }

  private def printInfoEnd(success: Boolean, printer: PrintWriter) {
    NestUI.normal("[", printer)
    if (success) NestUI.success("  OK  ", printer)
    else NestUI.failure("FAILED", printer)
    NestUI.normal("]\n", printer)
  }

  private def printInfoTimeout(printer: PrintWriter) {
    NestUI.normal("[", printer)
    NestUI.failure("TIMOUT", printer)
    NestUI.normal("]\n", printer)
  }

  private def javac(outDir: File, files: List[File], output: File): CompilationOutcome = {
    // compile using command-line javac compiler
    val args = Seq(
      javacCmd,
      "-d",
      outDir.getAbsolutePath,
      "-classpath",
      join(outDir.toString, CLASSPATH)
    ) ++ files.map("" + _)

    try if (runCommand(args, output)) CompileSuccess else CompileFailed
    catch exHandler(output, "javac command failed:\n" + args.map("  " + _ + "\n").mkString + "\n", CompilerCrashed)
  }

  /** Runs command redirecting standard out and error out to output file.
   *  Overloaded to accept a sequence of arguments.
   */
  private def runCommand(args: Seq[String], outFile: File): Boolean = {
    NestUI.verbose("running command:\n"+args.map("  " + _ + "\n").mkString)
    runCommandImpl(Process(args), outFile)
  }

  /** Runs command redirecting standard out and error out to output file.
   *  Overloaded to accept a single string = concatenated command + arguments.
   */
  private def runCommand(command: String, outFile: File): Boolean = {
    NestUI.verbose("running command:"+command)
    runCommandImpl(Process(command), outFile)
  }

  private def runCommandImpl(process: => ProcessBuilder, outFile: File): Boolean = {
    val exitCode = (process #> outFile !)
    // normalize line endings
    // System.getProperty("line.separator") should be "\n" here
    // so reading a file and writing it back should convert all CRLFs to LFs
    SFile(outFile).printlnAll(SFile(outFile).lines.toList: _*)
    exitCode == 0
  }

  @inline private def isJava(f: File) = SFile(f) hasExtension "java"
  @inline private def isScala(f: File) = SFile(f) hasExtension "scala"
  @inline private def isJavaOrScala(f: File) = isJava(f) || isScala(f)

  private def outputLogFile(logFile: File) {
    val lines = SFile(logFile).lines
    if (lines.nonEmpty) {
      NestUI.normal("Log file '" + logFile + "': \n")
      lines foreach (x => NestUI.normal(x + "\n"))
    }
  }
  private def logStackTrace(logFile: File, t: Throwable, msg: String): Boolean = {
    SFile(logFile).writeAll(msg, stackTraceString(t))
    outputLogFile(logFile) // if running the test threw an exception, output log file
    false
  }

  private def exHandler[T](logFile: File, msg: String, value: T): PartialFunction[Throwable, T] = {
    case e: Exception => logStackTrace(logFile, e, msg) ; value
  }

  class Runner(testFile: File) {
    var testDiff: String = ""
    var passed: Option[Boolean] = None

    val fileBase = basename(testFile.getName)
    val logFile  = fileManager.getLogFile(testFile, kind)
    val parent   = testFile.getParentFile
    val outDir   = new File(parent, "%s-%s.obj".format(fileBase, kind))
    def toDelete = if (isPartestDebug) Nil else List(
      if (passed exists (x => x)) Some(logFile) else None,
      if (outDir.isDirectory) Some(outDir) else None
    ).flatten

    private def createOutputDir(): File = {
      outDir.mkdirs()
      outDir
    }

    private def execTest(outDir: File, logFile: File, classpathPrefix: String = "", javaOpts: String = ""): Boolean = {
      // check whether there is a ".javaopts" file
      val argsFile  = new File(logFile.getParentFile, fileBase + ".javaopts")
      val argString = file2String(argsFile)
      if (argString != "")
        NestUI.verbose("Found javaopts file '%s', using options: '%s'".format(argsFile, argString))

      val testFullPath = {
        val d = new File(logFile.getParentFile, fileBase)
        if (d.isDirectory) d.getAbsolutePath
        else {
          val f = new File(logFile.getParentFile, fileBase + ".scala")
          if (f.isFile) f.getAbsolutePath
          else ""
        }
      }

      // Note! As this currently functions, JAVA_OPTS must precede argString
      // because when an option is repeated to java only the last one wins.
      // That means until now all the .javaopts files were being ignored because
      // they all attempt to change options which are also defined in
      // partest.java_opts, leading to debug output like:
      //
      // debug: Found javaopts file 'files/shootout/message.scala-2.javaopts', using options: '-Xss32k'
      // debug: java -Xss32k -Xss2m -Xms256M -Xmx1024M -classpath [...]
      val extras = if (isPartestDebug) List("-Dpartest.debug=true") else Nil
      val propertyOptions = List(
        "-Dfile.encoding=UTF-8",
        "-Djava.library.path="+logFile.getParentFile.getAbsolutePath,
        "-Dpartest.output="+outDir.getAbsolutePath,
        "-Dpartest.lib="+LATEST_LIB,
        "-Dpartest.reflect="+LATEST_REFLECT,
        "-Dpartest.comp="+LATEST_COMP,
        "-Dpartest.cwd="+outDir.getParent,
        "-Dpartest.test-path="+testFullPath,
        "-Dpartest.testname="+fileBase,
        "-Djavacmd="+javaCmd,
        "-Djavaccmd="+javacCmd,
        "-Duser.language=en",
        "-Duser.country=US"
      ) ++ extras

      val classpath = if (classpathPrefix != "") join(classpathPrefix, CLASSPATH) else CLASSPATH
      val cmd = javaCmd +: (
        (JAVA_OPTS.split(' ') ++ javaOpts.split(' ') ++ argString.split(' ')).map(_.trim).filter(_ != "") ++ Seq(
          "-classpath",
          join(outDir.toString, classpath)
        ) ++ propertyOptions ++ Seq(
          "scala.tools.nsc.MainGenericRunner",
          "-usejavacp",
          "Test",
          "jvm"
        )
      )

      runCommand(cmd, logFile)
    }

    private def getCheckFilePath(dir: File, suffix: String = "") = {
      def chkFile(s: String) = (Directory(dir) / "%s%s.check".format(fileBase, s)).toFile

      if (chkFile("").isFile || suffix == "") chkFile("")
      else chkFile("-" + suffix)
    }
    private def getCheckFile(dir: File) = Some(getCheckFilePath(dir, kind)) filter (_.canRead)

    private def compareOutput(dir: File, logFile: File): String = {
      val checkFile = getCheckFilePath(dir, kind)
      val diff =
        if (checkFile.canRead) compareFiles(logFile, checkFile.jfile)
        else file2String(logFile)

      // if check file exists, compare with log file
      if (diff != "" && fileManager.updateCheck) {
        NestUI.verbose("Updating checkfile " + checkFile.jfile)
        val toWrite = if (checkFile.exists) checkFile else getCheckFilePath(dir, "")
        toWrite writeAll file2String(logFile)
        ""
      }
      else diff
    }

    def newTestWriters() = {
      val swr = new StringWriter
      val wr  = new PrintWriter(swr, true)
      // diff    = ""

      ((swr, wr))
    }

    def fail(what: Any) = {
      NestUI.verbose("scalac: compilation of "+what+" failed\n")
      false
    }
    def diffCheck(testFile: File, diff: String) = {
      testDiff = diff
      testDiff == ""
    }

    /** 1. Creates log file and output directory.
     *  2. Runs script function, providing log file and output directory as arguments.
     */
    def runInContext(file: File, script: (File, File) => Boolean): (Boolean, LogContext) = {
      val (swr, wr) = newTestWriters()
      printInfoStart(file, wr)

      NestUI.verbose(this+" running test "+fileBase)
      val outDir = createOutputDir()
      NestUI.verbose("output directory: "+outDir)

      // run test-specific code
      val succeeded = try {
        if (isPartestDebug) {
          val (result, millis) = timed(script(logFile, outDir))
          fileManager.recordTestTiming(file.getPath, millis)
          result
        }
        else script(logFile, outDir)
      }
      catch exHandler(logFile, "", false)

      (succeeded, LogContext(logFile, swr, wr))
    }

    def groupedFiles(dir: File): List[List[File]] = {
      val testFiles = dir.listFiles.toList filter isJavaOrScala

      def isInGroup(f: File, num: Int) = SFile(f).stripExtension endsWith ("_" + num)
      val groups = (0 to 9).toList map (num => (testFiles filter (f => isInGroup(f, num))).sorted)
      val noGroupSuffix = (testFiles filterNot (groups.flatten contains)).sorted

      noGroupSuffix :: groups filterNot (_.isEmpty)
    }

    def compileFilesIn(dir: File, logFile: File, outDir: File): CompilationOutcome = {
      def compileGroup(g: List[File]): CompilationOutcome = {
        val (scalaFiles, javaFiles) = g partition isScala
        val allFiles = javaFiles ++ scalaFiles

        /* The test can contain both java and scala files, each of which should be compiled with the corresponding
         * compiler. Since the source files can reference each other both ways (java referencing scala classes and
         * vice versa, the partest compilation routine attempts to reach a "bytecode fixpoint" between the two
         * compilers -- that's when bytecode generated by each compiler implements the signatures expected by the other.
         *
         * In theory this property can't be guaranteed, as neither compiler can know what signatures the other
         * compiler expects and how to implement them. (see SI-1240 for the full story)
         *
         * In practice, this happens in 3 steps:
         * STEP1: feed all the files to scalac
         *        it will parse java files and obtain their expected signatures and generate bytecode for scala files
         * STEP2: feed the java files to javac
         *        it will generate the bytecode for the java files and link to the scalac-generated bytecode for scala
         * STEP3: only if there are both scala and java files, recompile the scala sources so they link to the correct
         *        java signatures, in case the signatures deduced by scalac from the source files were wrong. Since the
         *        bytecode for java is already in place, we only feed the scala files to scalac so it will take the
         *        java signatures from the existing javac-generated bytecode
         */
        List(1, 2, 3).foldLeft(CompileSuccess: CompilationOutcome) {
          case (CompileSuccess, 1) if scalaFiles.nonEmpty =>
            compileMgr.attemptCompile(Some(outDir), allFiles, kind, logFile)
          case (CompileSuccess, 2) if javaFiles.nonEmpty =>
            javac(outDir, javaFiles, logFile)
          case (CompileSuccess, 3) if scalaFiles.nonEmpty && javaFiles.nonEmpty =>
            // TODO: Do we actually need this? SI-1240 is known to require this, but we don't know if other tests
            // require it: https://groups.google.com/forum/?fromgroups#!topic/scala-internals/rFDKAcOKciU
            compileMgr.attemptCompile(Some(outDir), scalaFiles, kind, logFile)

          case (outcome, _)                               => outcome
        }
      }
      groupedFiles(dir).foldLeft(CompileSuccess: CompilationOutcome) {
        case (CompileSuccess, files) => compileGroup(files)
        case (outcome, _)            => outcome
      }
    }

    def runTestCommon(file: File, expectFailure: Boolean)(
      onSuccess: (File, File) => Boolean,
      onFail: (File, File) => Unit = (_, _) => ()): (Boolean, LogContext) =
    {
      runInContext(file, (logFile: File, outDir: File) => {
        val outcome = (
          if (file.isDirectory) compileFilesIn(file, logFile, outDir)
          else compileMgr.attemptCompile(None, List(file), kind, logFile)
        )
        val result = (
          if (expectFailure) outcome.isNegative
          else outcome.isPositive
        )

        if (result) onSuccess(logFile, outDir)
        else { onFail(logFile, outDir) ; false }
      })
    }

    def runJvmTest(file: File): (Boolean, LogContext) =
      runTestCommon(file, expectFailure = false)((logFile, outDir) => {
        val dir      = file.getParentFile

        // adding codelib.jar to the classpath
        // codelib provides the possibility to override standard reify
        // this shields the massive amount of reification tests from changes in the API
        execTest(outDir, logFile, PathSettings.srcCodeLib.toString) && {
          // cannot replace paths here since this also inverts slashes
          // which affects a bunch of tests
          //fileManager.mapFile(logFile, replaceSlashes(dir, _))
          diffCheck(file, compareOutput(dir, logFile))
        }
      })

    // Apache Ant 1.6 or newer
    def ant(args: Seq[String], output: File): Boolean = {
      val antDir = Directory(envOrElse("ANT_HOME", "/opt/ant/"))
      val antLibDir = Directory(antDir / "lib")
      val antLauncherPath = SFile(antLibDir / "ant-launcher.jar").path
      val antOptions =
        if (NestUI._verbose) List("-verbose", "-noinput")
        else List("-noinput")
      val cmd = javaCmd +: (
        JAVA_OPTS.split(' ').map(_.trim).filter(_ != "") ++ Seq(
          "-classpath",
          antLauncherPath,
          "org.apache.tools.ant.launch.Launcher"
        ) ++ antOptions ++ args
      )

      try runCommand(cmd, output)
      catch exHandler(output, "ant command '" + cmd + "' failed:\n", false)
    }

    def runAntTest(file: File): (Boolean, LogContext) = {
      val (swr, wr) = newTestWriters()
      printInfoStart(file, wr)

      NestUI.verbose(this+" running test "+fileBase)

      val succeeded = try {
        val binary = "-Dbinary="+(
          if      (fileManager.LATEST_LIB endsWith "build/quick/classes/library") "quick"
          else if (fileManager.LATEST_LIB endsWith "build/pack/lib/scala-library.jar") "pack"
          else if (fileManager.LATEST_LIB endsWith "dists/latest/lib/scala-library.jar/") "latest"
          else "installed"
        )
        val args = Array(binary, "-logfile", logFile.path, "-file", file.path)
        NestUI.verbose("ant "+args.mkString(" "))
        ant(args, logFile) && diffCheck(file, compareOutput(file.getParentFile, logFile))
      }
      catch { // *catch-all*
        case e: Exception =>
          NestUI.verbose("caught "+e)
          false
      }

      (succeeded, LogContext(logFile, swr, wr))
    }

    def runSpecializedTest(file: File): (Boolean, LogContext) =
      runTestCommon(file, expectFailure = false)((logFile, outDir) => {
        val dir       = file.getParentFile

        // adding the instrumented library to the classpath
        ( execTest(outDir, logFile, PathSettings.srcSpecLib.toString) &&
          diffCheck(file, compareOutput(dir, logFile))
        )
      })

    def runInstrumentedTest(file: File): (Boolean, LogContext) =
      runTestCommon(file, expectFailure = false)((logFile, outDir) => {
        val dir       = file.getParentFile

        // adding the javagent option with path to instrumentation agent
        execTest(outDir, logFile, javaOpts = "-javaagent:"+PathSettings.instrumentationAgentLib) &&
        diffCheck(file, compareOutput(dir, logFile))
      })

    def processSingleFile(file: File): (Boolean, LogContext) = kind match {
      case "scalacheck" =>
        val succFn: (File, File) => Boolean = { (logFile, outDir) =>
          NestUI.verbose("compilation of "+file+" succeeded\n")

          val outURL    = outDir.getAbsoluteFile.toURI.toURL
          val logWriter = new PrintStream(new FileOutputStream(logFile), true)

          Output.withRedirected(logWriter) {
            // this classloader is test specific: its parent contains library classes and others
            ScalaClassLoader.fromURLs(List(outURL), params.scalaCheckParentClassLoader).run("Test", Nil)
          }

          NestUI.verbose(file2String(logFile))
          // obviously this must be improved upon
          val lines = SFile(logFile).lines map (_.trim) filterNot (_ == "") toBuffer;
          lines.forall(x => !x.startsWith("!")) || {
            NestUI.normal("ScalaCheck test failed. Output:\n")
            lines foreach (x => NestUI.normal(x + "\n"))
            false
          }
        }
        runTestCommon(file, expectFailure = false)(
          succFn,
          (logFile, outDir) => outputLogFile(logFile)
        )

      case "pos" =>
        runTestCommon(file, expectFailure = false)(
          (logFile, outDir) => true,
          (_, _) => ()
        )

      case "neg" =>
        runTestCommon(file, expectFailure = true)((logFile, outDir) => {
          // compare log file to check file
          val dir      = file.getParentFile

          // diff is contents of logFile
          fileManager.mapFile(logFile, replaceSlashes(dir, _))
          diffCheck(file, compareOutput(dir, logFile))
        })

      case "run" | "jvm" =>
        runJvmTest(file)

      case "specialized" =>
        runSpecializedTest(file)

      case "instrumented" =>
        runInstrumentedTest(file)

      case "presentation" =>
        runJvmTest(file) // for the moment, it's exactly the same as for a run test

      case "ant" =>
        runAntTest(file)

      case "buildmanager" =>
        val (swr, wr) = newTestWriters()
        printInfoStart(file, wr)
        val (outDir, testFile, changesDir) = {
          if (!file.isDirectory)
            (null, null, null)
          else {
            NestUI.verbose(this+" running test "+fileBase)
            val outDir = createOutputDir()
            val testFile = new File(file, fileBase + ".test")
            val changesDir = new File(file, fileBase + ".changes")

            if (changesDir.isFile || !testFile.isFile) {
              // if changes exists then it has to be a dir
              if (!testFile.isFile) NestUI.verbose("invalid build manager test file")
              if (changesDir.isFile) NestUI.verbose("invalid build manager changes directory")
              (null, null, null)
            }
            else {
              copyTestFiles(file, outDir)
              NestUI.verbose("outDir:  "+outDir)
              NestUI.verbose("logFile: "+logFile)
              (outDir, testFile, changesDir)
            }
          }
        }
        if (outDir == null)
          return (false, LogContext(logFile))

        // Pre-conditions satisfied
        val sourcepath = outDir.getAbsolutePath+File.separator

        // configure input/output files
        val logWriter = new PrintStream(new FileOutputStream(logFile), true)
        val testReader = new BufferedReader(new FileReader(testFile))
        val logConsoleWriter = new PrintWriter(logWriter, true)

        // create proper settings for the compiler
        val settings = new Settings(workerError)
        settings.outdir.value = outDir.getAbsoluteFile.getAbsolutePath
        settings.sourcepath.value = sourcepath
        settings.classpath.value = fileManager.CLASSPATH
        settings.Ybuildmanagerdebug.value = true

        // simulate Build Manager loop
        val prompt = "builder > "
        val reporter = new ConsoleReporter(settings, scala.Console.in, logConsoleWriter)
        val bM: BuildManager =
            new RefinedBuildManager(settings) {
              override protected def newCompiler(settings: Settings) =
                  new BuilderGlobal(settings, reporter)
            }

        def testCompile(line: String): Boolean = {
          NestUI.verbose("compiling " + line)
          val args = (line split ' ').toList
          val command = new CompilerCommand(args, settings)
          command.ok && {
            bM.update(filesToSet(settings.sourcepath.value, command.files), Set.empty)
            !reporter.hasErrors
          }
        }

        val updateFiles = (line: String) => {
          NestUI.verbose("updating " + line)
          (line split ' ').toList forall (u =>
            (u split "=>").toList match {
                case origFileName::(newFileName::Nil) =>
                  val newFile = new File(changesDir, newFileName)
                  if (newFile.isFile) {
                    val v = overwriteFileWith(new File(outDir, origFileName), newFile)
                    if (!v)
                      NestUI.verbose("'update' operation on " + u + " failed")
                    v
                  } else {
                    NestUI.verbose("File " + newFile + " is invalid")
                    false
                  }
                case a =>
                  NestUI.verbose("Other =: " + a)
                  false
            }
          )
        }

        def loop(): Boolean = {
          testReader.readLine() match {
            case null | ""    =>
              NestUI.verbose("finished")
              true
            case s if s startsWith ">>update "  =>
              updateFiles(s stripPrefix ">>update ") && loop()
            case s if s startsWith ">>compile " =>
              val files = s stripPrefix ">>compile "
              logWriter.println(prompt + files)
              // In the end, it can finish with an error
              if (testCompile(files)) loop()
              else {
                val t = testReader.readLine()
                (t == null) || (t == "")
              }
            case s =>
              NestUI.verbose("wrong command in test file: " + s)
              false
          }
        }

        Output.withRedirected(logWriter) {
          try loop()
          finally testReader.close()
        }
        fileManager.mapFile(logFile, replaceSlashes(new File(sourcepath), _))

        (diffCheck(file, compareOutput(file, logFile)), LogContext(logFile, swr, wr))

      case "res" => {
          // simulate resident compiler loop
          val prompt = "\nnsc> "

          val (swr, wr) = newTestWriters()
          printInfoStart(file, wr)

          NestUI.verbose(this+" running test "+fileBase)
          val dir = file.getParentFile
          val outDir = createOutputDir()
          val resFile = new File(dir, fileBase + ".res")
          NestUI.verbose("outDir:  "+outDir)
          NestUI.verbose("logFile: "+logFile)
          //NestUI.verbose("logFileErr: "+logFileErr)
          NestUI.verbose("resFile: "+resFile)

          // run compiler in resident mode
          // $SCALAC -d "$os_dstbase".obj -Xresident -sourcepath . "$@"
          val sourcedir  = logFile.getParentFile.getAbsoluteFile
          val sourcepath = sourcedir.getAbsolutePath+File.separator
          NestUI.verbose("sourcepath: "+sourcepath)

          val argList = List(
            "-d", outDir.getAbsoluteFile.getPath,
            "-Xresident",
            "-sourcepath", sourcepath)

          // configure input/output files
          val logOut    = new FileOutputStream(logFile)
          val logWriter = new PrintStream(logOut, true)
          val resReader = new BufferedReader(new FileReader(resFile))
          val logConsoleWriter = new PrintWriter(new OutputStreamWriter(logOut), true)

          // create compiler
          val settings = new Settings(workerError)
          settings.sourcepath.value = sourcepath
          settings.classpath.value = fileManager.CLASSPATH
          val reporter = new ConsoleReporter(settings, scala.Console.in, logConsoleWriter)
          val command = new CompilerCommand(argList, settings)
          object compiler extends Global(command.settings, reporter)

          val resCompile = (line: String) => {
            NestUI.verbose("compiling "+line)
            val cmdArgs = (line split ' ').toList map (fs => new File(dir, fs).getAbsolutePath)
            NestUI.verbose("cmdArgs: "+cmdArgs)
            val sett = new Settings(workerError)
            sett.sourcepath.value = sourcepath
            val command = new CompilerCommand(cmdArgs, sett)
            command.ok && {
              (new compiler.Run) compile command.files
              !reporter.hasErrors
            }
          }

          def loop(action: String => Boolean): Boolean = {
            logWriter.print(prompt)
            resReader.readLine() match {
              case null | ""  => logWriter.flush() ; true
              case line       => action(line) && loop(action)
            }
          }

          Output.withRedirected(logWriter) {
            try loop(resCompile)
            finally resReader.close()
          }
          fileManager.mapFile(logFile, replaceSlashes(dir, _))

          (diffCheck(file, compareOutput(dir, logFile)), LogContext(logFile, swr, wr))
        }

      case "shootout" =>
        val (swr, wr) = newTestWriters()
        printInfoStart(file, wr)

        NestUI.verbose(this+" running test "+fileBase)
        val outDir = createOutputDir()

        // 2. define file {outDir}/test.scala that contains code to compile/run
        val testFile = new File(outDir, "test.scala")
        NestUI.verbose("outDir:   "+outDir)
        NestUI.verbose("logFile:  "+logFile)
        NestUI.verbose("testFile: "+testFile)

        // 3. cat {test}.scala.runner {test}.scala > testFile
        val runnerFile = new File(parent, fileBase+".scala.runner")
        val bodyFile   = new File(parent, fileBase+".scala")
        SFile(testFile).writeAll(
          file2String(runnerFile),
          file2String(bodyFile)
        )

        // 4. compile testFile
        val ok = compileMgr.attemptCompile(None, List(testFile), kind, logFile) eq CompileSuccess
        NestUI.verbose("compilation of " + testFile + (if (ok) "succeeded" else "failed"))
        val result = ok && {
          execTest(outDir, logFile) && {
            NestUI.verbose(this+" finished running "+fileBase)
            diffCheck(file, compareOutput(parent, logFile))
          }
        }

        (result, LogContext(logFile, swr, wr))

      case "scalap" =>
        runInContext(file, (logFile: File, outDir: File) => {
          val sourceDir = Directory(if (file.isFile) file.getParent else file)
          val sources   = sourceDir.files filter (_ hasExtension "scala") map (_.jfile) toList
          val results   = sourceDir.files filter (_.name == "result.test") map (_.jfile) toList

          if (sources.length != 1 || results.length != 1) {
            NestUI.warning("Misconfigured scalap test directory: " + sourceDir + " \n")
            false
          }
          else {
            val resFile = results.head
            // 2. Compile source file

            if (!compileMgr.attemptCompile(Some(outDir), sources, kind, logFile).isPositive) {
              NestUI.normal("compilerMgr failed to compile %s to %s".format(sources mkString ", ", outDir))
              false
            }
            else {
              // 3. Decompile file and compare results
              val isPackageObject = sourceDir.name startsWith "package"
              val className       = sourceDir.name.capitalize + (if (!isPackageObject) "" else ".package")
              val url             = outDir.toURI.toURL
              val loader          = ScalaClassLoader.fromURLs(List(url), this.getClass.getClassLoader)
              val clazz           = loader.loadClass(className)

              val byteCode = ByteCode.forClass(clazz)
              val result   = scala.tools.scalap.Main.decompileScala(byteCode.bytes, isPackageObject)

              SFile(logFile) writeAll result
              diffCheck(file, compareFiles(logFile, resFile))
            }
          }
        })

      case "script" =>
        val (swr, wr) = newTestWriters()
        printInfoStart(file, wr)

        NestUI.verbose(this+" running test "+fileBase)

        // check whether there is an args file
        val argsFile = new File(file.getParentFile, fileBase+".args")
        NestUI.verbose("argsFile: "+argsFile)
        val argString = file2String(argsFile)
        val succeeded = try {
          val cmdString =
            if (isWin) {
              val batchFile = new File(file.getParentFile, fileBase+".bat")
              NestUI.verbose("batchFile: "+batchFile)
              batchFile.getAbsolutePath
            }
            else file.getAbsolutePath

          val ok = runCommand(cmdString+argString, logFile)
          ( ok && diffCheck(file, compareOutput(file.getParentFile, logFile)) )
        }
        catch { case e: Exception => NestUI.verbose("caught "+e) ; false }

        (succeeded, LogContext(logFile, swr, wr))
    }

    private def crashContext(t: Throwable): LogContext = {
      try {
        logStackTrace(logFile, t, "Possible compiler crash during test of: " + testFile + "\n")
        LogContext(logFile)
      }
      catch { case t: Throwable => LogContext(null) }
    }

    def run(): (Boolean, LogContext) = {
      val result = try processSingleFile(testFile) catch { case t: Throwable => (false, crashContext(t)) }
      passed = Some(result._1)
      result
    }

    def reportResult(writers: Option[(StringWriter, PrintWriter)]) {
      writers foreach { case (swr, wr) =>
        if (passed.isEmpty) printInfoTimeout(wr)
        else printInfoEnd(passed.get, wr)
        wr.flush()
        swr.flush()
        NestUI.normal(swr.toString)

        if (passed exists (x => !x)) {
          if (fileManager.showDiff || isPartestDebug)
            NestUI.normal(testDiff)
          else if (fileManager.showLog)
            showLog(logFile)
        }
      }
      toDelete foreach (_.deleteRecursively())
    }
  }

  def runTest(testFile: File): TestState = {
    val runner = new Runner(testFile)
    // when option "--failed" is provided execute test only if log
    // is present (which means it failed before)
    if (fileManager.failed && !runner.logFile.canRead)
      return TestState.Ok

    // sys addShutdownHook cleanup()
    val ((success, ctx), elapsed) = timed(runner.run())
    val state                     = if (success) TestState.Ok else TestState.Fail

    runner.reportResult(ctx.writers)
    state
  }

  private def filesToSet(pre: String, fs: List[String]): Set[AbstractFile] =
    fs flatMap (s => Option(AbstractFile getFile (pre + s))) toSet

  private def copyTestFiles(testDir: File, destDir: File) {
    val invalidExts = List("changes", "svn", "obj")
    testDir.listFiles.toList filter (
            f => (isJavaOrScala(f) && f.isFile) ||
                 (f.isDirectory && !(invalidExts.contains(SFile(f).extension)))) foreach
      { f => fileManager.copyFile(f, destDir) }
  }

  private def showLog(logFile: File) {
    file2String(logFile) match {
      case "" if logFile.canRead  => ()
      case ""                     => NestUI.failure("Couldn't open log file: " + logFile + "\n")
      case s                      => NestUI.normal(s)
    }
  }
}