如何测试运行命令的Go函数?

问题描述 投票:0回答:3

按照https://golang.org/pkg/os/exec/#Cmd.StdoutPipe处的示例,假设我具有如下定义的函数getPerson()

package stdoutexample

import (
    "encoding/json"
    "os/exec"
)

// Person represents a person
type Person struct {
    Name string
    Age  int
}

func getPerson() (Person, error) {
    person := Person{}
    cmd := exec.Command("echo", "-n", `{"Name": "Bob", "Age": 32}`)
    stdout, err := cmd.StdoutPipe()
    if err != nil {
        return person, err
    }
    if err := cmd.Start(); err != nil {
        return person, err
    }
    if err := json.NewDecoder(stdout).Decode(&person); err != nil {
        return person, err
    }
    if err := cmd.Wait(); err != nil {
        return person, err
    }
    return person, nil
}

在我的“真实”应用程序中,命令运行可以具有不同的输出,我想针对每种情况编写测试用例。但是,我不确定该如何处理。

到目前为止,我所拥有的只是一个案例的测试用例:

package stdoutexample

import (
    "testing"

    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/require"
)

func TestGetPerson(t *testing.T) {
    person, err := getPerson()
    require.NoError(t, err)
    assert.Equal(t, person.Name, "Bob")
    assert.Equal(t, person.Age, 32)
}

也许执行此操作的方法是将该函数分为两部分,一部分将命令的输出写入字符串,而另一部分将字符串的输出解码?

unit-testing go stdout
3个回答
0
投票

我通过将函数分为两部分来添加单元测试:一部分将输出读取为字节的一部分,另一部分将输出解析为Person

package stdoutexample

import (
    "bytes"
    "encoding/json"
    "os/exec"
)

// Person represents a person
type Person struct {
    Name string
    Age  int
}

func getCommandOutput() ([]byte, error) {
    cmd := exec.Command("echo", "-n", `{"Name": "Bob", "Age": 32}`)
    return cmd.Output()
}

func getPerson(commandOutput []byte) (Person, error) {
    person := Person{}
    if err := json.NewDecoder(bytes.NewReader(commandOutput)).Decode(&person); err != nil {
        return person, err
    }
    return person, nil
}

以下测试用例通过:

package stdoutexample

import (
    "testing"

    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/require"
)

func TestGetPerson(t *testing.T) {
    commandOutput, err := getCommandOutput()
    require.NoError(t, err)
    person, err := getPerson(commandOutput)
    require.NoError(t, err)
    assert.Equal(t, person.Name, "Bob")
    assert.Equal(t, person.Age, 32)
}

func TestGetPersonBob(t *testing.T) {
    commandOutput := []byte(`{"Name": "Bob", "Age": 32}`)
    person, err := getPerson(commandOutput)
    require.NoError(t, err)
    assert.Equal(t, person.Name, "Bob")
    assert.Equal(t, person.Age, 32)
}

func TestGetPersonAlice(t *testing.T) {
    commandOutput := []byte(`{"Name": "Alice", "Age": 25}`)
    person, err := getPerson(commandOutput)
    require.NoError(t, err)
    assert.Equal(t, person.Name, "Alice")
    assert.Equal(t, person.Age, 25)
}

BobAlice测试用例模拟可通过命令生成的不同输出。


0
投票

添加到https://stackoverflow.com/a/58107208/9353289

而不是为每个测试编写单独的Test函数,建议您改用表驱动测试方法。这是一个例子,

func Test_getPerson(t *testing.T) {
    tests := []struct {
        name          string
        commandOutput []byte
        want          Person
        wantErr       bool
    }{
        {
            name:          "Get Bob",
            commandOutput: []byte(`{"Name": "Bob", "Age": 32}`),
            want: Person{
                Name: "Bob",
                Age:  32,
            },
            wantErr: false,
        },

        {
            name:          "Get Alice",
            commandOutput: []byte(`{"Name": "Alice", "Age": 25}`),
            want: Person{
                Name: "Alice",
                Age:  25,
            },
            wantErr: false,
        },
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := getPerson(tt.commandOutput)
            require.NoError(t, err)
            assert.Equal(t, tt.want.Name, got.Name)
            assert.Equal(t, tt.want.Age, got.Age)

        })
    }
}

仅将测试用例添加到切片中,将运行所有测试用例。


0
投票

您的实现设计会主动拒绝细粒度测试,因为它不允许任何注入。

但是,给出示例,除了使用TestTable之外,没有太多改进。

现在,在实际的工作负载下,调用外部二进制文件可能会遇到无法接受的速度下降。这可能证明了另一种方法的合理性,该方法涉及模拟的设计重构以及多个测试桩的设置。

为了模拟您的实现,您使用了interface功能。要存根您的执行,您创建一个模拟,该模拟输出您要检查的内容。

package main

import (
    "encoding/json"
    "fmt"
    "os/exec"
)

type Person struct{}

type PersonProvider struct {
    Cmd outer
}

func (p PersonProvider) Get() (Person, error) {
    person := Person{}
    b, err := p.Cmd.Out()
    if err != nil {
        return person, err
    }
    err = json.Unmarshal(b, &person)
    return person, err
}

type outer interface{ Out() ([]byte, error) }

type echo struct {
    input string
}

func (e echo) Out() ([]byte, error) {
    cmd := exec.Command("echo", "-n", e.input)
    return cmd.Output()
}

type mockEcho struct {
    output []byte
    err    error
}

func (m mockEcho) Out() ([]byte, error) {
    return m.output, m.err
}

func main() {

    fmt.Println(PersonProvider{Cmd: echo{input: `{"Name": "Bob", "Age": 32}`}}.Get())
    fmt.Println(PersonProvider{Cmd: mockEcho{output: nil, err: fmt.Errorf("invalid json")}}.Get())

}
© www.soinside.com 2019 - 2024. All rights reserved.