dimanche 28 juin 2020

Testing a function that contains stderr, stdout and os.Exit()

I'm building an UI for cli apps. I completed the functions but I couldn't figure out how to test it.

Repo: https://github.com/erdaltsksn/cui

func Success(message string) {
    color.Success.Println("√", message)
    os.Exit(0)
}

// Error prints a success message and exit status 1
func Error(message string, err ...error) {
    color.Danger.Println("X", message)
    if len(err) > 0 {
        for _, e := range err {
            fmt.Println(" ", e.Error())
        }
    }
    os.Exit(1)
}

I want to write unit tests for functions. The problem is functions contains print and os.Exit(). I couldn't figure out how to write test for both.

This topic: How to test a function's output (stdout/stderr) in unit tests helps me test print function. I need to add os.Exit()

My Solution for now:

func captureOutput(f func()) string {
    var buf bytes.Buffer
    log.SetOutput(&buf)
    f()
    log.SetOutput(os.Stderr)
    return buf.String()
}

func TestSuccess(t *testing.T) {
    type args struct {
        message string
    }
    tests := []struct {
        name   string
        args   args
        output string
    }{
        {"Add test cases.", args{message: "my message"}, "ESC[1;32m"},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            want := tt.output
            got := captureOutput(func() {
                cui.Success(tt.args.message)
            })
            got := err
            if got.Error() != want {
                t.Error("Got:", got, ",", "Want:", want)
            }
        })
    }
}

Aucun commentaire:

Enregistrer un commentaire