Files
Roger a734e777a8 refactor(app): export one function per command (#712)
* refactor(app): export one function per command

Step 2 of #710. A command's logic was split between cmd and stage-shaped app calls; cmd now parses flags, calls one function and prints what it returns. An error means the command never ran, and a run that ended early says so in Summary.Err.

* fix(app): check dumpkeys and archive -o up front

A missing output directory was reported only after the keys were retrieved or the files copied.

* docs(rfcs): move restore's input out of the command layer

Restore now discovers its directories in an archive itself, so the command layer no longer holds the data it reads.
2026-11-22 14:45:39 +08:00

59 lines
1.8 KiB
Go

package main
import (
"context"
"errors"
"io"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestKeychainPasswordFunc(t *testing.T) {
tests := []struct {
name string
flags passwordFlags
stdin string
want string
err error
}{
{name: "flag", flags: passwordFlags{value: "from-flag"}, stdin: "from-stdin\n", want: "from-flag"},
{name: "stdin", flags: passwordFlags{fromStdin: true}, stdin: "from-stdin\r\nnext\n", want: "from-stdin"},
{name: "stdin without newline", flags: passwordFlags{fromStdin: true}, stdin: "from-stdin", want: "from-stdin"},
{name: "none off a terminal", stdin: "from-stdin\n", err: errNoPassword},
}
for _, testCase := range tests {
testCase := testCase
t.Run(testCase.name, func(t *testing.T) {
pipeReader, pipeWriter, err := os.Pipe()
require.NoError(t, err)
defer pipeReader.Close()
_, err = pipeWriter.WriteString(testCase.stdin)
require.NoError(t, errors.Join(err, pipeWriter.Close()))
got, err := keychainPasswordFunc(testCase.flags, pipeReader)(context.Background())
require.ErrorIs(t, err, testCase.err)
assert.Equal(t, testCase.want, got)
})
}
}
// TestKeychainPasswordFlagsAreExclusive covers the root command too, which runs dump with dump's flags.
func TestKeychainPasswordFlagsAreExclusive(t *testing.T) {
setHome(t, t.TempDir())
out := t.TempDir()
for _, args := range [][]string{
{"-d", out, "--keychain-pw", "pw", "--keychain-pw-stdin"},
{"dump", "-d", out, "--keychain-pw", "pw", "--keychain-pw-stdin"},
{"dumpkeys", "--keychain-pw", "pw", "--keychain-pw-stdin"},
} {
root := newRootCommand()
root.SetOut(io.Discard)
root.SetErr(io.Discard)
root.SetArgs(args)
assert.ErrorContains(t, root.Execute(), "keychain-pw", args)
}
}