jeudi 3 janvier 2019

Golang patterns for stdin testing

I have a CLI app using cobra, but I'm having trouble figuring out how to test methods that use stdin.

I have some code that looks like this:

import (
    "fmt"
    "log"
    "os"

    "github.com/spf13/cobra"
    "github.com/spf13/viper"
    input "github.com/tcnksm/go-input"
)

var configureCmd = &cobra.Command{
    Use:   "configure",
    Short: "Configure your TFE credentials",
    Long:  `Prompts for your TFE API credentials, then writes them to
    a configuration file (defaults to ~/.tgc.yaml`,
    Run: func(cmd *cobra.Command, args []string) {

        ui := &input.UI{
            Writer: os.Stdout,
            Reader: os.Stdin,
        }

        tfeURL, err := ui.Ask("TFE URL:", &input.Options{
            Default:  "https://app.terraform.io",
            Required: true,
            Loop:     true,
        })

        // etc 

I'm new to golang, and mostly a Rubyist. In Ruby I would just do something like expect($stdin).to receive(:gets).and_return('y'), but I know that things aren't that easy in Golang...

So how do I do this? Do I create a helper method and wrap the stdin fetching in that? Can I mock out the os.Stdin calls?

Aucun commentaire:

Enregistrer un commentaire