github.com/while1malloc0/docdir@v0.0.0-20220830001304-722ec0f2cf3a/e2e/e2e_test.go (about)

     1  package e2e_test
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"os"
     7  	"os/exec"
     8  	"path/filepath"
     9  	"testing"
    10  
    11  	"github.com/while1malloc0/docdir/cmdtest"
    12  )
    13  
    14  func TestMain(m *testing.M) {
    15  	cleanup, err := setup()
    16  	if err != nil {
    17  		fmt.Printf("unexpected error in e2e setup: %v\n", err)
    18  		os.Exit(1)
    19  	}
    20  	exitCode := m.Run()
    21  	if err := cleanup(); err != nil {
    22  		fmt.Printf("unexpected error in e2e cleanup: %v\n", err)
    23  		os.Exit(1)
    24  	}
    25  	os.Exit(exitCode)
    26  }
    27  
    28  func TestE2E(t *testing.T) {
    29  	cases := []struct {
    30  		description string
    31  		testPath    string
    32  	}{
    33  		{"a directory with no subdirectories prints the directory", "e2e/testdata/simple.ct"},
    34  		{"a directory with subdirectories prints a-la tree", "e2e/testdata/nested.ct"},
    35  		{"a directory with description files prints the descriptions", "e2e/testdata/nested-description.ct"},
    36  		{"mixing described and nondescript directories prints both", "e2e/testdata/mixed-description.ct"},
    37  		{"the -skip-missing flag skips directories without descriptions", "e2e/testdata/skipped-missing.ct"},
    38  	}
    39  	for _, tc := range cases {
    40  		t.Run(tc.description, func(t *testing.T) {
    41  			run, cleanup, err := cmdtest.ReadFile(tc.testPath)
    42  			if err != nil {
    43  				t.Fatalf("unexpected error reading test data: %v", err)
    44  			}
    45  			run(t)
    46  			if err := cleanup(); err != nil {
    47  				t.Fatalf("unexpected error cleaning up after execution: %v", err)
    48  			}
    49  		})
    50  	}
    51  }
    52  
    53  func setup() (func() error, error) {
    54  	// cd into project root so all e2e tests assume same dir
    55  	if err := os.Chdir(".."); err != nil {
    56  		return nil, err
    57  	}
    58  
    59  	// build test version of binary
    60  	cmd := exec.Command("go", "build", "-o", "dist/test/docdir", "./cmd/main.go")
    61  	var stderr bytes.Buffer
    62  	cmd.Stderr = &stderr
    63  	if err := cmd.Run(); err != nil {
    64  		return nil, fmt.Errorf("%s", stderr.String())
    65  	}
    66  
    67  	// add test version of binary to PATH
    68  	cwd, err := os.Getwd()
    69  	if err != nil {
    70  		return nil, err
    71  	}
    72  	dist := filepath.Join(cwd, "dist/test")
    73  	os.Setenv("PATH", fmt.Sprintf("%s:%s", os.Getenv("PATH"), dist))
    74  
    75  	return func() error {
    76  		// remove test version of binary
    77  		// NB: no need to reset PATH, go tests are run in a subprocess, so PATH
    78  		// changes are temporary
    79  		return os.RemoveAll(dist)
    80  	}, nil
    81  }