github.com/hrntknr/ntf@v1.0.2-0.20220725163249-d52a7861d93d/utils_test.go (about)

     1  package main
     2  
     3  import (
     4  	"errors"
     5  	"math/rand"
     6  	"os"
     7  	"path"
     8  	"regexp"
     9  	"testing"
    10  	"time"
    11  )
    12  
    13  func TestFormatDuration(t *testing.T) {
    14  	tests := []struct {
    15  		in  time.Duration
    16  		out string
    17  	}{
    18  		{0, "0s"},
    19  		{1 * time.Second, "1s"},
    20  		{1 * time.Minute, "1m 0s"},
    21  		{1*time.Minute + 30*time.Second, "1m 30s"},
    22  		{1*time.Hour + 1*time.Minute + 30*time.Second, "1h 1m 30s"},
    23  		{25*time.Hour + 1*time.Minute + 30*time.Second, "1d 1h 1m 30s"},
    24  	}
    25  	for _, test := range tests {
    26  		if out := formatDuration(test.in); out != test.out {
    27  			t.Errorf("formatDuration(%d) = %s, want %s", test.in, out, test.out)
    28  			return
    29  		}
    30  	}
    31  }
    32  
    33  func TestGetContext(t *testing.T) {
    34  	home, err := os.UserHomeDir()
    35  	if err != nil {
    36  		t.Fatal(err)
    37  	}
    38  	if err := os.Chdir(home); err != nil {
    39  		t.Fatal(err)
    40  	}
    41  	expect := regexp.MustCompile(`^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+:~$`)
    42  	str, err := getContext()
    43  	if err != nil {
    44  		t.Fatal(err)
    45  	}
    46  	if !expect.MatchString(str) {
    47  		t.Errorf("getContext() = %s, want regex %s", str, expect.String())
    48  		return
    49  	}
    50  }
    51  
    52  func TestTryConfig(t *testing.T) {
    53  	rnd := MakeRandomStr(8)
    54  	home, err := os.UserHomeDir()
    55  	if err != nil {
    56  		t.Fatal(err)
    57  	}
    58  	fp, err := os.Create(path.Join(home, rnd))
    59  	if err != nil {
    60  		t.Fatal(err)
    61  	}
    62  	defer func() {
    63  		fp.Close()
    64  		os.Remove(path.Join(home, rnd))
    65  	}()
    66  	fp.WriteString(`
    67  backends: ["dummy"]
    68  dummy:
    69    item: dummy
    70  `)
    71  
    72  	cfg, err := tryConfig(path.Join(home, rnd))
    73  	if err != nil {
    74  		t.Errorf("tryConfig(%s) = %s, want nil", path.Join(home, rnd), err)
    75  		return
    76  	}
    77  	if cfg == nil {
    78  		t.Errorf("tryConfig(%s) = nil, want non-nil", path.Join(home, rnd))
    79  		return
    80  	}
    81  }
    82  
    83  func MakeRandomStr(digit uint32) string {
    84  	const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    85  
    86  	b := make([]byte, digit)
    87  	if _, err := rand.Read(b); err != nil {
    88  		panic(errors.New("unexpected error..."))
    89  	}
    90  
    91  	var result string
    92  	for _, v := range b {
    93  		result += string(letters[int(v)%len(letters)])
    94  	}
    95  	return result
    96  }