Reputation: 14071
I want to test, that a function callProgram
executes a binary and handles the output correctly.
For that my initial thought would be to compile raw code like:
package mytest
import (
"testing"
)
const (
binary_code = `
package main
func main() {
// Glorious processing ...
}
`
)
func TestCall(t *testing.T) {
p := buildTestProgram(binary_code, "~/testbinary")
defer p.Delete()
callProgram("~/testbinary")
}
I looked into the build command (runBuild
) and its' implementation is sufficiently easy. Problem is, that it lives in the internal
namespace and cmd/go
does not seem to expose any way of calling runBuild
or similar.
So my question is how to test a certain binary and also having to interact with the hosting system as little as possible.
Yes, I could download a prebuilt binary, execute go build
, etc. but I would be really glad to minimize the chances of potential errors/complexity and also be as portable as possible.
Upvotes: 1
Views: 38
Reputation: 418137
There is no public compiler API.
The easiest way to test you app would be to call / run an existing binary on the system.
If you don't want to rely on this, another option is to have your test create / write a binary file into a temporary folder, test your function and then remove the temporary file. This can be done easily / automatically using the ioutil.TempFile()
function.
Creating this temporary binary may or may not be a Go compiling process. Since this is part of a Go test, the Go SDK should already be installed in your system, so calling go
shouldn't be a problem.
Your test may also self-contain the content of a tiny, runnable executable which the test could "dump" to a temporary file. Such tiny binaries may be as small as 100 bytes, for an example, see Smallest x86 ELF Hello World. For how to bundle data into a Go app, see What's the best way to bundle static resources in a Go program?
Upvotes: 1