1+ package godump
2+
3+ import (
4+ "os"
5+ "os/exec"
6+ "strings"
7+ "testing"
8+ )
9+
10+ // TestAnsiInNonTty verifies that no ANSI codes are produced when output is redirected.
11+ func TestAnsiInNonTty (t * testing.T ) {
12+ // ANSI escape character. We expect this to be ABSENT from the output.
13+ const escape = "\x1b "
14+
15+ // The source code for the program we're going to run.
16+ const sourceCode = `
17+ package main
18+ import "github.com/goforj/godump"
19+ func main() {
20+ s := struct{ Name string }{"test"}
21+ godump.Dump(s)
22+ }
23+ `
24+
25+ // Create a temporary directory to avoid package main collision.
26+ tempDir := t .TempDir ()
27+ tempFile , err := os .CreateTemp (tempDir , "test_*.go" )
28+ if err != nil {
29+ t .Fatalf ("failed to create temp file: %v" , err )
30+ }
31+
32+ if _ , err := tempFile .WriteString (sourceCode ); err != nil {
33+ t .Fatalf ("failed to write temp file: %v" , err )
34+ }
35+ tempFile .Close ()
36+
37+ // Run the program using `go run`. By capturing the output, we ensure
38+ // that the program's stdout is not a TTY.
39+ cmd := exec .Command ("go" , "run" , tempFile .Name ())
40+ output , err := cmd .CombinedOutput ()
41+ if err != nil {
42+ t .Fatalf ("failed to run test program: %v\n Output:\n %s" , err , string (output ))
43+ }
44+
45+ if strings .Contains (string (output ), escape ) {
46+ t .Errorf ("expected output to NOT contain ANSI escape codes when not in a TTY, but it did. Output:\n %s" , string (output ))
47+ }
48+ }
49+
50+ // TestAnsiInTty verifies that ANSI codes are produced when FORCE_COLOR is set.
51+ func TestAnsiInTty (t * testing.T ) {
52+ // ANSI escape character. We expect this to be PRESENT in the output.
53+ const escape = "\x1b "
54+
55+ // The source code for the program we're going to run.
56+ const sourceCode = `
57+ package main
58+ import "github.com/goforj/godump"
59+ func main() {
60+ s := struct{ Name string }{"test"}
61+ godump.Dump(s)
62+ }
63+ `
64+ // Create a temporary directory to avoid package main collision.
65+ tempDir := t .TempDir ()
66+ tempFile , err := os .CreateTemp (tempDir , "test_*.go" )
67+ if err != nil {
68+ t .Fatalf ("failed to create temp file: %v" , err )
69+ }
70+
71+ if _ , err := tempFile .WriteString (sourceCode ); err != nil {
72+ t .Fatalf ("failed to write temp file: %v" , err )
73+ }
74+ tempFile .Close ()
75+
76+ // Run the program using `go run`. By capturing the output, we ensure
77+ // that the program's stdout is not a TTY.
78+ cmd := exec .Command ("go" , "run" , tempFile .Name ())
79+
80+ cmd .Env = append (os .Environ (), "FORCE_COLOR=1" )
81+ output , err := cmd .CombinedOutput ()
82+ if err != nil {
83+ t .Fatalf ("failed to run test program: %v\n Output:\n %s" , err , string (output ))
84+ }
85+
86+ if ! strings .Contains (string (output ), escape ) {
87+ t .Errorf ("expected output to contain ANSI escape codes when FORCE_COLOR is set, but it didn't. Output:\n %s" , string (output ))
88+ }
89+ }
0 commit comments