| 1 | // Copyright 2019 The age Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package main |
| 6 | |
| 7 | import ( |
| 8 | "os" |
| 9 | "os/exec" |
| 10 | "path/filepath" |
| 11 | "strings" |
| 12 | "testing" |
| 13 | |
| 14 | "filippo.io/age" |
| 15 | "github.com/rogpeppe/go-internal/testscript" |
| 16 | ) |
| 17 | |
| 18 | func TestMain(m *testing.M) { |
| 19 | testscript.Main(m, map[string]func(){ |
| 20 | "age-keygen": main, |
| 21 | }) |
| 22 | } |
| 23 | |
| 24 | func unwritable(t *testing.T) *os.File { |
| 25 | t.Helper() |
| 26 | name := filepath.Join(t.TempDir(), "out") |
| 27 | if err := os.WriteFile(name, nil, 0600); err != nil { |
| 28 | t.Fatal(err) |
| 29 | } |
| 30 | f, err := os.Open(name) |
| 31 | if err != nil { |
| 32 | t.Fatal(err) |
| 33 | } |
| 34 | t.Cleanup(func() { f.Close() }) |
| 35 | if _, err := f.Write([]byte("x")); err == nil { |
| 36 | t.Skip("writes to a read-only file descriptor succeed") |
| 37 | } |
| 38 | return f |
| 39 | } |
| 40 | |
| 41 | func TestOutputWriteErrors(t *testing.T) { |
| 42 | identity, err := age.GenerateX25519Identity() |
| 43 | if err != nil { |
| 44 | t.Fatal(err) |
| 45 | } |
| 46 | tests := []struct { |
| 47 | name string |
| 48 | args []string |
| 49 | stdin string |
| 50 | }{ |
| 51 | {"generate", nil, ""}, |
| 52 | {"generate PQ", []string{"-pq"}, ""}, |
| 53 | {"convert", []string{"-y"}, identity.String() + "\n"}, |
| 54 | } |
| 55 | for _, tt := range tests { |
| 56 | t.Run(tt.name, func(t *testing.T) { |
| 57 | stderr := &strings.Builder{} |
| 58 | cmd := exec.Command("age-keygen", tt.args...) |
| 59 | cmd.Stdin = strings.NewReader(tt.stdin) |
| 60 | cmd.Stdout = unwritable(t) |
| 61 | cmd.Stderr = stderr |
| 62 | if err := cmd.Run(); err == nil { |
| 63 | t.Error("age-keygen succeeded") |
| 64 | } |
| 65 | if !strings.Contains(stderr.String(), "failed to write output") { |
| 66 | t.Errorf("stderr = %q", stderr) |
| 67 | } |
| 68 | }) |
| 69 | } |
| 70 | } |