如何在Go中测试系统命令

huangapple go评论73阅读模式
英文:

How to test system commands in go

问题

给定我有一个函数:

func getTotalMemory() string {
  out,_ := exec.Command("grep", "MemTotal", "/proc/meminfo").Output()
  t := strings.Split(string(out), ":")
  x := strings.TrimSpace(t[1])
  return x
}

我该如何编写一个测试函数来确保我正确解析了它?在 Ruby 中,我只需要做类似这样的事情:

os.expects(:Command).and_returns("string")

我目前正在使用 GoConvey,如果这对答案有任何影响,请告诉我。

谢谢!

英文:

Given I have a function like:

func getTotalMemory() string {
  out,_ := exec.Command("grep", "MemTotal", "/proc/meminfo").Output()
  t := strings.Split(string(out), ":")
  x := strings.TrimSpace(t[1])
  return x
}

How can I write a test for that function to make sure I'm parsing it properly? In ruby I would just do something like

os.expects(:Command).and_returns("string")

I'm currently using GoConvey if that has any impact on answers.

Thanks!

答案1

得分: 4

你可以从查看 os.exec 包的测试策略 开始:
请参考“src/pkg/os/exec/exec_test.go”。

注意:GoConvey 与标准的 Go 测试框架兼容,所以这不会对你想要进行的测试类型产生任何影响。

英文:

You could start by looking at the test policy for os.exec package:
see "src/pkg/os/exec/exec_test.go".

Note: GoConvey is compatible with standard Go testing framework, so that won't have any bearing on the kind of test you want to do.

huangapple
  • 本文由 发表于 2014年6月18日 21:20:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/24286683.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定