...

Source file src/gotest.tools/v3/x/subtest/example_test.go

Documentation: gotest.tools/v3/x/subtest

     1  package subtest_test
     2  
     3  import (
     4  	"io"
     5  	"net/http"
     6  	"strings"
     7  	"testing"
     8  
     9  	"gotest.tools/v3/assert"
    10  	"gotest.tools/v3/x/subtest"
    11  )
    12  
    13  var t = &testing.T{}
    14  
    15  func ExampleRun_tableTest() {
    16  	var testcases = []struct {
    17  		data     io.Reader
    18  		expected int
    19  	}{
    20  		{
    21  			data:     strings.NewReader("invalid input"),
    22  			expected: 400,
    23  		},
    24  		{
    25  			data:     strings.NewReader("valid input"),
    26  			expected: 200,
    27  		},
    28  	}
    29  
    30  	for _, tc := range testcases {
    31  		subtest.Run(t, "test-service-call", func(t subtest.TestContext) {
    32  			// startFakeService can shutdown using t.AddCleanup
    33  			url := startFakeService(t)
    34  
    35  			req, err := http.NewRequest("POST", url, tc.data)
    36  			assert.NilError(t, err)
    37  			req = req.WithContext(t.Ctx())
    38  
    39  			client := newClient(t)
    40  			resp, err := client.Do(req)
    41  			assert.NilError(t, err)
    42  			assert.Equal(t, resp.StatusCode, tc.expected)
    43  		})
    44  	}
    45  }
    46  
    47  func startFakeService(_ subtest.TestContext) string {
    48  	return "url"
    49  }
    50  
    51  func newClient(_ subtest.TestContext) *http.Client {
    52  	return &http.Client{}
    53  }
    54  
    55  func ExampleRun_testSuite() {
    56  	// do suite setup before subtests
    57  
    58  	subtest.Run(t, "test-one", func(t subtest.TestContext) {
    59  		assert.Equal(t, 1, 1)
    60  	})
    61  	subtest.Run(t, "test-two", func(t subtest.TestContext) {
    62  		assert.Equal(t, 2, 2)
    63  	})
    64  
    65  	// do suite teardown after subtests
    66  }
    67  

View as plain text