54 lines
1.6 KiB
Go
54 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestCLI(t *testing.T) {
|
|
for _, entry := range os.Environ() {
|
|
key, _, _ := strings.Cut(entry, "=")
|
|
if strings.HasPrefix(key, "TEST_MQTT5_") {
|
|
t.Setenv(key, "")
|
|
os.Unsetenv(key)
|
|
}
|
|
}
|
|
for _, tc := range []struct {
|
|
args []string
|
|
code int
|
|
contains string
|
|
}{
|
|
{[]string{"--help"}, 0, "Usage:"},
|
|
{[]string{"check-config"}, 0, "configuration valid"},
|
|
{[]string{"--device-id", "bad/+", "check-config"}, 1, "topics.device_id"},
|
|
{[]string{"--password=SECRET", "check-config"}, 2, "invalid CLI arguments"},
|
|
{[]string{"command", "dangerous"}, 2, "command requires"},
|
|
} {
|
|
var out, errOut bytes.Buffer
|
|
code := run(context.Background(), tc.args, &out, &errOut)
|
|
all := out.String() + errOut.String()
|
|
if code != tc.code || !strings.Contains(all, tc.contains) || strings.Contains(all, "SECRET") {
|
|
t.Fatalf("code=%d output=%s", code, all)
|
|
}
|
|
}
|
|
p := filepath.Join(t.TempDir(), "test.toml")
|
|
if err := os.WriteFile(p, []byte("[logging]\nformat='json'\nlevel='error'\n"), 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var out, errOut bytes.Buffer
|
|
if code := run(context.Background(), []string{"--config", p, "check-config"}, &out, &errOut); code != 0 || !strings.Contains(out.String(), `"event":"config_valid"`) {
|
|
t.Fatalf("JSON mode: %d %s %s", code, out.String(), errOut.String())
|
|
}
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
cancel()
|
|
out.Reset()
|
|
errOut.Reset()
|
|
if code := run(ctx, []string{"check-config"}, &out, &errOut); code != 1 || !strings.Contains(errOut.String(), "interrupted") {
|
|
t.Fatal("cancellation ignored")
|
|
}
|
|
}
|