github.com/vpayno/adventofcode-2022-golang-workspace@v0.0.0-20230605190011-dbafed5593de/cmd/day01/aoc-day01_test.go (about)

     1  package main
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  	"os"
     7  	"path/filepath"
     8  	"testing"
     9  
    10  	"github.com/stretchr/testify/assert"
    11  )
    12  
    13  // This is the main test function. This is the gatekeeper of all the tests in the main package.
    14  func TestMain(m *testing.M) {
    15  	exitCode := m.Run()
    16  	os.Exit(exitCode)
    17  }
    18  
    19  // The functions in main() are already tested. Just running them together with zero test questions.
    20  func TestMain_app(t *testing.T) {
    21  	os.Args = []string{}
    22  
    23  	testStdout, writer, err := os.Pipe()
    24  	if err != nil {
    25  		t.Errorf("os.Pipe() err %v; want %v", err, nil)
    26  	}
    27  
    28  	osStdout := os.Stdout // keep backup of the real stdout
    29  	os.Stdout = writer
    30  
    31  	defer func() {
    32  		// Undo what we changed when this test is done.
    33  		os.Stdout = osStdout
    34  	}()
    35  
    36  	want := "67633\n199628\n"
    37  
    38  	// Run the function who's output we want to capture.
    39  	main()
    40  
    41  	// Stop capturing stdout.
    42  	writer.Close()
    43  
    44  	var buf bytes.Buffer
    45  	_, err = io.Copy(&buf, testStdout)
    46  	if err != nil {
    47  		t.Error(err)
    48  	}
    49  	got := buf.String()
    50  	if got != want {
    51  		t.Errorf("main(); want %q, got %q", want, got)
    52  	}
    53  }
    54  
    55  // Test Run() failures in main()
    56  func TestMain_runError(t *testing.T) {
    57  	os.Args = []string{}
    58  
    59  	testStdout, writer, err := os.Pipe()
    60  	if err != nil {
    61  		t.Errorf("os.Pipe() err %v; want %v", err, nil)
    62  	}
    63  
    64  	osStdout := os.Stdout // keep backup of the real stdout
    65  	os.Stdout = writer
    66  
    67  	defer func() {
    68  		// Undo what we changed when this test is done.
    69  		os.Stdout = osStdout
    70  	}()
    71  
    72  	fileRoot, err := os.Getwd()
    73  	assert.Nil(t, err, "failed to get CWD")
    74  
    75  	fileRoot = filepath.Clean(fileRoot + "/../../")
    76  
    77  	want := "Encountered error while running app.Run()\n\n"
    78  	want += "open " + fileRoot
    79  	want += "/data/day00/day00-input.txt: no such file or directory\n"
    80  
    81  	// This challenge doesn't exist.
    82  	challengeName = "day00"
    83  
    84  	// Run the function who's output we want to capture.
    85  	main()
    86  
    87  	// Stop capturing stdout.
    88  	writer.Close()
    89  
    90  	var buf bytes.Buffer
    91  	_, err = io.Copy(&buf, testStdout)
    92  	if err != nil {
    93  		t.Error(err)
    94  	}
    95  	got := buf.String()
    96  	if got != want {
    97  		t.Errorf("main(); want %q, got %q", want, got)
    98  	}
    99  }