|
| 1 | +package protocbridge.frontend |
| 2 | + |
| 3 | +import org.apache.commons.io.IOUtils |
| 4 | +import org.scalatest.flatspec.AnyFlatSpec |
| 5 | +import org.scalatest.matchers.must.Matchers |
| 6 | +import protocbridge.{ExtraEnv, ProtocCodeGenerator} |
| 7 | + |
| 8 | +import java.io.ByteArrayOutputStream |
| 9 | +import scala.sys.process.ProcessIO |
| 10 | +import scala.util.Random |
| 11 | + |
| 12 | +class OsSpecificFrontendSpec extends AnyFlatSpec with Matchers { |
| 13 | + |
| 14 | + protected def testPluginFrontend( |
| 15 | + frontend: PluginFrontend, |
| 16 | + generator: ProtocCodeGenerator, |
| 17 | + env: ExtraEnv, |
| 18 | + request: Array[Byte] |
| 19 | + ): Array[Byte] = { |
| 20 | + val (path, state) = frontend.prepare( |
| 21 | + generator, |
| 22 | + env |
| 23 | + ) |
| 24 | + val actualOutput = new ByteArrayOutputStream() |
| 25 | + val process = sys.process |
| 26 | + .Process(path.toAbsolutePath.toString) |
| 27 | + .run(new ProcessIO(writeInput => { |
| 28 | + writeInput.write(request) |
| 29 | + writeInput.close() |
| 30 | + }, processOutput => { |
| 31 | + IOUtils.copy(processOutput, actualOutput) |
| 32 | + processOutput.close() |
| 33 | + }, _.close())) |
| 34 | + process.exitValue() |
| 35 | + frontend.cleanup(state) |
| 36 | + actualOutput.toByteArray |
| 37 | + } |
| 38 | + |
| 39 | + protected def testSuccess(frontend: PluginFrontend): Unit = { |
| 40 | + val random = new Random() |
| 41 | + val toSend = Array.fill(123)(random.nextInt(256).toByte) |
| 42 | + val toReceive = Array.fill(456)(random.nextInt(256).toByte) |
| 43 | + val env = new ExtraEnv(secondaryOutputDir = "tmp") |
| 44 | + |
| 45 | + val fakeGenerator = new ProtocCodeGenerator { |
| 46 | + override def run(request: Array[Byte]): Array[Byte] = { |
| 47 | + request mustBe (toSend ++ env.toByteArrayAsField) |
| 48 | + toReceive |
| 49 | + } |
| 50 | + } |
| 51 | + val response = testPluginFrontend(frontend, fakeGenerator, env, toSend) |
| 52 | + response mustBe toReceive |
| 53 | + } |
| 54 | + |
| 55 | + protected def testFailure(frontend: PluginFrontend): Unit = { |
| 56 | + val random = new Random() |
| 57 | + val toSend = Array.fill(123)(random.nextInt(256).toByte) |
| 58 | + val env = new ExtraEnv(secondaryOutputDir = "tmp") |
| 59 | + |
| 60 | + val fakeGenerator = new ProtocCodeGenerator { |
| 61 | + override def run(request: Array[Byte]): Array[Byte] = { |
| 62 | + throw new OutOfMemoryError("test error") |
| 63 | + } |
| 64 | + } |
| 65 | + val response = testPluginFrontend(frontend, fakeGenerator, env, toSend) |
| 66 | + response.length must be > 0 |
| 67 | + } |
| 68 | +} |
0 commit comments