github.com/ericwq/aprilsh@v0.0.0-20240517091432-958bc568daa0/frontend/message_test.go (about)

     1  // Copyright 2022~2024 wangqi. All rights reserved.
     2  // Use of this source code is governed by a MIT-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package frontend
     6  
     7  import (
     8  	"io"
     9  	"log/slog"
    10  	"os"
    11  	"strings"
    12  	"testing"
    13  
    14  	"github.com/ericwq/aprilsh/util"
    15  )
    16  
    17  func TestPrintVersion(t *testing.T) {
    18  	stderr := os.Stderr
    19  	stdout := os.Stdout
    20  	r, w, _ := os.Pipe()
    21  	// replace stdout,stderr with pipe writer
    22  	// all the output to stdout,stderr is captured
    23  	os.Stderr = w
    24  	os.Stdout = w
    25  
    26  	util.Logger.CreateLogger(w, true, slog.LevelDebug)
    27  
    28  	PrintVersion()
    29  
    30  	// close pipe writer
    31  	w.Close()
    32  	// get the output
    33  	out, _ := io.ReadAll(r)
    34  	os.Stderr = stderr
    35  	os.Stdout = stdout
    36  	r.Close()
    37  
    38  	output := string(out)
    39  	expect := []string{"version\t", "go version", "git commit", "git branch"}
    40  	found := 0
    41  	for _, v := range expect {
    42  		if strings.Contains(output, v) {
    43  			found++
    44  		}
    45  	}
    46  
    47  	if found != len(expect) {
    48  		t.Errorf("%s expect \n%s, got \n%s\n", "PrintVersion", expect, output)
    49  	}
    50  }
    51  
    52  func TestPrintUsage(t *testing.T) {
    53  	tc := []struct {
    54  		label  string
    55  		hints  string
    56  		usage  []string
    57  		expect []string
    58  	}{
    59  		{"has hint, has usage", "hint", []string{"usage"}, []string{"Hints: hint", "usage"}},
    60  		{"no hint, has usage", "", []string{"usage"}, []string{"usage"}},
    61  		{"has hint, no usage", "hint", []string{}, []string{"hint"}},
    62  	}
    63  
    64  	for _, v := range tc {
    65  		stderr := os.Stderr
    66  		stdout := os.Stdout
    67  		r, w, _ := os.Pipe()
    68  		// replace stdout,stderr with pipe writer
    69  		// all the output to stdout,stderr is captured
    70  		os.Stderr = w
    71  		os.Stdout = w
    72  
    73  		util.Logger.CreateLogger(w, true, slog.LevelDebug)
    74  
    75  		PrintUsage(v.hints, v.usage...)
    76  
    77  		// close pipe writer
    78  		w.Close()
    79  		// get the output
    80  		out, _ := io.ReadAll(r)
    81  		os.Stderr = stderr
    82  		os.Stdout = stdout
    83  		r.Close()
    84  
    85  		output := string(out)
    86  		found := 0
    87  		for _, v := range v.expect {
    88  			if strings.Contains(output, v) {
    89  				found++
    90  			}
    91  		}
    92  
    93  		if found != len(v.expect) {
    94  			t.Errorf("%s expect \n%s, got \n%s\n", v.label, v.expect, output)
    95  		}
    96  	}
    97  }