github.com/git-ogawa/go-dbyml@v1.2.1/dbyml/cli_test.go (about)

     1  package dbyml
     2  
     3  import (
     4  	"bytes"
     5  	"os"
     6  	"path/filepath"
     7  	"strings"
     8  	"testing"
     9  
    10  	"github.com/stretchr/testify/assert"
    11  )
    12  
    13  func TestConfigNotFound(t *testing.T) {
    14  	pwd, _ := os.Getwd()
    15  	root, _ := filepath.Abs("../")
    16  	os.Chdir(root)
    17  
    18  	options := CLIoptions{"", false}
    19  	stdout := extractStdout(t, options.Parse)
    20  	expected := "Config file not found in the current directory.\n"
    21  	expected += "Run the following commands to generate config file.\n\n"
    22  	expected += "$ dbyml --init"
    23  	assert.Equal(t, expected, stdout)
    24  
    25  	options = CLIoptions{"notexists.yml", false}
    26  	options.Parse()
    27  	stdout = extractStdout(t, options.Parse)
    28  	expected = "notexists.yml not found. Check the file exists."
    29  	assert.Equal(t, expected, stdout)
    30  
    31  	os.Chdir(pwd)
    32  }
    33  
    34  func TestShowVersion(t *testing.T) {
    35  	org := os.Args
    36  	testArgs := []string{"dbyml", "-v"}
    37  	os.Args = testArgs
    38  
    39  	options, _ := GetArgs()
    40  	options.Parse()
    41  	os.Args = org
    42  }
    43  
    44  func TestCLIBuild(t *testing.T) {
    45  	pwd, _ := os.Getwd()
    46  	root, _ := filepath.Abs("../")
    47  	os.Chdir(root)
    48  
    49  	// Set args
    50  	org := os.Args
    51  	path, _ := filepath.Abs("testdata/dockerfile_standard/dbyml.yml")
    52  	testArgs := []string{"dbyml", "-c", path}
    53  	os.Args = testArgs
    54  
    55  	options, _ := GetArgs()
    56  	options.Parse()
    57  
    58  	os.Args = org
    59  	os.Chdir(pwd)
    60  }
    61  
    62  func TestCLIWithContext(t *testing.T) {
    63  	pwd, _ := os.Getwd()
    64  	root, _ := filepath.Abs("../")
    65  	os.Chdir(root)
    66  
    67  	// Set args
    68  	org := os.Args
    69  	path, _ := filepath.Abs("testdata/dockerfile_ignore/dbyml.yml")
    70  	testArgs := []string{"dbyml", "-c", path}
    71  	os.Args = testArgs
    72  
    73  	options, _ := GetArgs()
    74  	options.Parse()
    75  
    76  	os.Args = org
    77  	os.Chdir(pwd)
    78  }
    79  
    80  func extractStdout(t *testing.T, fnc func()) string {
    81  	t.Helper()
    82  
    83  	orgStdout := os.Stdout
    84  	defer func() {
    85  		os.Stdout = orgStdout
    86  	}()
    87  	r, w, _ := os.Pipe()
    88  	os.Stdout = w
    89  	fnc()
    90  	w.Close()
    91  	var buf bytes.Buffer
    92  	if _, err := buf.ReadFrom(r); err != nil {
    93  		t.Fatalf("failed to read buf: %v", err)
    94  	}
    95  	return strings.TrimRight(buf.String(), "\n")
    96  }