gitlab.com/zaquestion/lab@v0.14.0/internal/config/config_test.go (about) 1 package config 2 3 import ( 4 "bytes" 5 "fmt" 6 "io" 7 "io/ioutil" 8 "math/rand" 9 "os" 10 "path" 11 "strconv" 12 "testing" 13 14 "github.com/stretchr/testify/assert" 15 ) 16 17 func TestNewConfig(t *testing.T) { 18 testconf := "/tmp/testconf-" + strconv.Itoa(int(rand.Uint64())) 19 os.Mkdir(testconf, os.FileMode(0700)) 20 21 t.Run("create config", func(t *testing.T) { 22 old := os.Stdout // keep backup of the real stdout 23 r, w, _ := os.Pipe() 24 os.Stdout = w 25 26 var buf bytes.Buffer 27 fmt.Fprintln(&buf, "https://gitlab.zaquestion.io") 28 fmt.Fprintln(&buf, "zaq") 29 30 oldreadPassword := readPassword 31 readPassword = func() (string, error) { 32 return "abcde12345", nil 33 } 34 defer func() { 35 readPassword = oldreadPassword 36 }() 37 38 err := New(path.Join(testconf, "lab.hcl"), &buf) 39 if err != nil { 40 t.Fatal(err) 41 } 42 43 outC := make(chan string) 44 // copy the output in a separate goroutine so printing can't block indefinitely 45 go func() { 46 var buf bytes.Buffer 47 io.Copy(&buf, r) 48 outC <- buf.String() 49 }() 50 51 // back to normal state 52 w.Close() 53 os.Stdout = old // restoring the real stdout 54 out := <-outC 55 56 assert.Contains(t, out, "Enter default GitLab host (default: https://gitlab.com): ") 57 assert.Contains(t, out, "Enter default GitLab user:") 58 assert.Contains(t, out, "Create a token here: https://gitlab.zaquestion.io/profile/personal_access_tokens\nEnter default GitLab token (scope: api):") 59 60 cfg, err := os.Open(path.Join(testconf, "lab.hcl")) 61 if err != nil { 62 t.Fatal(err) 63 } 64 65 cfgData, err := ioutil.ReadAll(cfg) 66 if err != nil { 67 t.Fatal(err) 68 } 69 assert.Equal(t, string(cfgData), `"core" = { 70 "host" = "https://gitlab.zaquestion.io" 71 72 "token" = "abcde12345" 73 74 "user" = "zaq" 75 }`) 76 }) 77 os.RemoveAll(testconf) 78 }