File: iostream_test.go

package info (click to toggle)
goawk 1.29.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 10,560 kB
  • sloc: awk: 3,060; yacc: 198; fortran: 189; python: 131; sh: 58; makefile: 12
file content (73 lines) | stat: -rw-r--r-- 1,546 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package interp

import (
	"errors"
	"os"
	"os/exec"
	"path/filepath"
	"testing"
)

const (
	outputStreamBufferSize = 1024
)

func TestStreamDoubleClose(t *testing.T) {
	dir := t.TempDir()
	t.Run("InFile", func(t *testing.T) {
		f, err := os.Create(filepath.Join(dir, "infile"))
		if err != nil {
			t.Fatal(err)
		}
		in := newInFileStream(f)
		checkDoubleClose(t, in)
	})
	t.Run("OutFile", func(t *testing.T) {
		f, err := os.Create(filepath.Join(dir, "outfile"))
		if err != nil {
			t.Fatal(err)
		}
		out := newOutFileStream(f, outputStreamBufferSize)
		checkDoubleClose(t, out)
	})
	t.Run("InCmd", func(t *testing.T) {
		cmd := execDefaultShell("echo close me")
		in, err := newInCmdStream(cmd)
		if err != nil {
			t.Fatal(err)
		}
		checkDoubleClose(t, in)
	})
	t.Run("OutCmd", func(t *testing.T) {
		cmd := execDefaultShell("echo close me")
		out, err := newOutCmdStream(cmd)
		if err != nil {
			t.Fatal(err)
		}
		checkDoubleClose(t, out)
	})
}

func execDefaultShell(scriptlet string) *exec.Cmd {
	cmdline := append(defaultShellCommand, scriptlet)
	return exec.Command(cmdline[0], cmdline[1:]...)
}

type streamCloser interface {
	ExitCode() int
	Close() error
}

func checkDoubleClose(t *testing.T, sc streamCloser) {
	t.Helper()
	if err := sc.Close(); err != nil {
		t.Fatal(err)
	}
	exitCode := sc.ExitCode()
	if err := sc.Close(); !errors.Is(err, errDoubleClose) {
		t.Error("expected stream.Close() to return error on double close")
	}
	if sc.ExitCode() != exitCode {
		t.Error("expected stream.ExitCode() to stay the same")
	}
}