github.com/yuk1ty/readygo@v0.2.1-0.20220502041311-7a0cf7a1a1aa/cmd/root_test.go (about)

     1  package cmd
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"os"
     7  	"strings"
     8  	"testing"
     9  
    10  	"github.com/spf13/cobra"
    11  )
    12  
    13  func execute(t *testing.T, c *cobra.Command, tmpDirPath string, args ...string) (string, error) {
    14  	t.Helper()
    15  
    16  	buf := new(bytes.Buffer)
    17  	c.SetOut(buf)
    18  	c.SetErr(buf)
    19  	c.SetArgs(args)
    20  
    21  	err := os.Chdir(tmpDirPath)
    22  	if err != nil {
    23  		return "", err
    24  	}
    25  
    26  	err = c.Execute()
    27  	if err != nil {
    28  		return "", err
    29  	}
    30  
    31  	return strings.TrimSpace(buf.String()), nil
    32  }
    33  
    34  func TestPackageNameCommand(t *testing.T) {
    35  	pkgName := "github.com/yuk1ty/example1"
    36  	dirName := "example1"
    37  
    38  	tmpDirPath := os.TempDir()
    39  
    40  	_, err := execute(t, rootCmd, tmpDirPath, "-p", pkgName)
    41  	if err != nil {
    42  		t.Fatal(err)
    43  	}
    44  
    45  	t.Run("exists a directory named `example`", func(t *testing.T) {
    46  		if _, err := os.Stat(fmt.Sprintf("%s/%s", tmpDirPath, "example1")); err != nil {
    47  			t.Fatal(err)
    48  		}
    49  	})
    50  
    51  	t.Cleanup(func() {
    52  		os.RemoveAll(fmt.Sprintf("%s/%s", tmpDirPath, dirName))
    53  	})
    54  }
    55  
    56  func TestNameCommand(t *testing.T) {
    57  	pkgName := "github.com/yuk1ty/example2"
    58  	dirName := "another"
    59  
    60  	tmpDirPath := os.TempDir()
    61  
    62  	_, err := execute(t, rootCmd, tmpDirPath, "-p", pkgName, "-n", dirName)
    63  	if err != nil {
    64  		t.Fatal(err)
    65  	}
    66  
    67  	t.Run("exists a directory named `another`", func(t *testing.T) {
    68  		if _, err := os.Stat(fmt.Sprintf("%s/%s", tmpDirPath, "another")); err != nil {
    69  			t.Fatal(err)
    70  		}
    71  	})
    72  
    73  	t.Cleanup(func() {
    74  		os.RemoveAll(fmt.Sprintf("%s/%s", tmpDirPath, dirName))
    75  	})
    76  }