英文:
Running a test in golang that only works for some versions
问题
我这里有一个库(https://github.com/turtlemonvh/altscanner),其中包含一个测试,比较了自定义扫描器与bufio.Scanner
的功能。特别是,我正在比较我的方法与 Buffer
方法,该方法直到go1.6才添加。
我的实际代码适用于go1.4及更高版本,但我想包含这个测试(我还想添加一个基准测试),使用bufio.Scanner
对象的Buffer
函数。
如何在允许代码在go1.4和1.5上运行的同时,包含使用go1.6+功能的这些测试呢?
我想答案是使用构建标志,只有在明确请求时才触发执行这些测试(并且我可以通过travis环境变量在我的CI流水线中访问go版本)。我也可以在这里滥用短标志。
有没有更简洁的方法?
英文:
I have a library here (https://github.com/turtlemonvh/altscanner) that includes a test comparing functionality of a custom scanner to bufio.Scanner
. In particular, I am comparing my approach to the Buffer
method which wasn't added until go1.6.
My actual code works with versions of go back to 1.4, but I wanted to include this test (and I'd like to add a benchmark as well) that uses the Buffer
function of the bufio.Scanner
object.
How can I include these tests that use features of go1.6+ while still allowing code to run for go1.4 and 1.5?
I imagine the answer is using a build flag to trigger the execution of these tests only if explicitly requested (and I do have access to the go version in my CI pipeline via a travis environment variable). I could also abuse the short flag here.
Is there a cleaner approach?
答案1
得分: 1
在发布这个问题几分钟后,我想起了构建约束。Go语言内置了一个处理这种情况的约束条件,即"go的版本必须>= X"。
将该测试移动到单独的文件,并在顶部添加//+build go1.6
,问题就解决了。
英文:
A few minutes after posting this I remembered about build constraints. Go has a built in constraint that handles this exact case, i.e. "version of go must be >= X".
Moving that test into a separate file and adding //+build go1.6
at the top fixed it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论