aboutsummaryrefslogtreecommitdiff
path: root/flow-core/src/test/scala/ch/jodersky/flow/PseudoTerminal.scala
blob: 8e891ae585a2d01332b3324d6f65534651dc374c (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
package ch.jodersky.flow

import java.io.{File, IOException}
import java.nio.file.Files

import scala.concurrent.duration._
import scala.sys.process._
import scala.util.control.NonFatal

trait PseudoTerminal {

  final val SetupTimeout = 100.milliseconds

  def withEcho[A](action: (String, SerialSettings) => A): A = {
    val dir = Files.createTempDirectory("flow-pty").toFile
    val pty = new File(dir, "pty")

    val socat = try {
      val s = Seq(
        "socat",
        "-d -d",
        s"exec:cat,pty,raw,b115200,echo=0",
        s"pty,raw,b115200,echo=0,link=${pty.getAbsolutePath}"
      ).run(ProcessLogger(println(_)), false)
      Thread.sleep(SetupTimeout.toMillis) // allow ptys to set up
      s
    } catch {
      case NonFatal(ex) =>
        throw new IOException(
          "Error running echo service, make sure the program 'socat' is installed", ex)
    }

    try {
      val result = action(pty.getAbsolutePath, SerialSettings(baud = 115200))
      Thread.sleep(SetupTimeout.toMillis) // allow for async cleanup before destroying ptys
      result
    } finally {
      socat.destroy()
      dir.delete()
    }
  }

}