github.com/mshitrit/go-mutesting@v0.0.0-20210528084812-ff81dcaedfea/cmd/go-mutesting/main_test.go (about)

     1  package main
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  	"os"
     7  	"testing"
     8  
     9  	"github.com/stretchr/testify/assert"
    10  )
    11  
    12  func TestMain(t *testing.T) {
    13  	testMain(
    14  		t,
    15  		"../../example",
    16  		[]string{"--debug", "--exec-timeout", "1"},
    17  		returnOk,
    18  		"The mutation score is 0.450000 (9 passed, 11 failed, 8 duplicated, 0 skipped, total is 20)",
    19  	)
    20  }
    21  
    22  func TestMainRecursive(t *testing.T) {
    23  	testMain(
    24  		t,
    25  		"../../example",
    26  		[]string{"--debug", "--exec-timeout", "1", "./..."},
    27  		returnOk,
    28  		"The mutation score is 0.476190 (10 passed, 11 failed, 8 duplicated, 0 skipped, total is 21)",
    29  	)
    30  }
    31  
    32  func TestMainFromOtherDirectory(t *testing.T) {
    33  	testMain(
    34  		t,
    35  		"../..",
    36  		[]string{"--debug", "--exec-timeout", "1", "github.com/zimmski/go-mutesting/example"},
    37  		returnOk,
    38  		"The mutation score is 0.450000 (9 passed, 11 failed, 8 duplicated, 0 skipped, total is 20)",
    39  	)
    40  }
    41  
    42  func TestMainMatch(t *testing.T) {
    43  	testMain(
    44  		t,
    45  		"../../example",
    46  		[]string{"--debug", "--exec", "../scripts/exec/test-mutated-package.sh", "--exec-timeout", "1", "--match", "baz", "./..."},
    47  		returnOk,
    48  		"The mutation score is 0.500000 (1 passed, 1 failed, 0 duplicated, 0 skipped, total is 2)",
    49  	)
    50  }
    51  
    52  func testMain(t *testing.T, root string, exec []string, expectedExitCode int, contains string) {
    53  	saveStderr := os.Stderr
    54  	saveStdout := os.Stdout
    55  	saveCwd, err := os.Getwd()
    56  	assert.Nil(t, err)
    57  
    58  	r, w, err := os.Pipe()
    59  	assert.Nil(t, err)
    60  
    61  	os.Stderr = w
    62  	os.Stdout = w
    63  	assert.Nil(t, os.Chdir(root))
    64  
    65  	bufChannel := make(chan string)
    66  
    67  	go func() {
    68  		buf := new(bytes.Buffer)
    69  		_, err = io.Copy(buf, r)
    70  		assert.Nil(t, err)
    71  		assert.Nil(t, r.Close())
    72  
    73  		bufChannel <- buf.String()
    74  	}()
    75  
    76  	exitCode := mainCmd(exec)
    77  
    78  	assert.Nil(t, w.Close())
    79  
    80  	os.Stderr = saveStderr
    81  	os.Stdout = saveStdout
    82  	assert.Nil(t, os.Chdir(saveCwd))
    83  
    84  	out := <-bufChannel
    85  
    86  	assert.Equal(t, expectedExitCode, exitCode)
    87  	assert.Contains(t, out, contains)
    88  }