duanqiang2977 2019-05-20 10:07
浏览 73

如何在测试中构建程序

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.

  • 写回答

1条回答 默认 最新

  • drhib62644 2019-05-20 10:22
    关注

    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?

    评论

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥15 帮我写一个c++工程