go.etcd.io/etcd@v3.3.27+incompatible/client/main_test.go (about)

     1  // Copyright 2017 The etcd Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package client_test
    16  
    17  import (
    18  	"fmt"
    19  	"net/http"
    20  	"os"
    21  	"regexp"
    22  	"strings"
    23  	"testing"
    24  	"time"
    25  
    26  	"github.com/coreos/etcd/integration"
    27  	"github.com/coreos/etcd/pkg/testutil"
    28  	"github.com/coreos/etcd/pkg/transport"
    29  )
    30  
    31  var exampleEndpoints []string
    32  var exampleTransport *http.Transport
    33  
    34  // TestMain sets up an etcd cluster if running the examples.
    35  func TestMain(m *testing.M) {
    36  	useCluster, hasRunArg := false, false // default to running only Test*
    37  	for _, arg := range os.Args {
    38  		if strings.HasPrefix(arg, "-test.run=") {
    39  			exp := strings.Split(arg, "=")[1]
    40  			match, err := regexp.MatchString(exp, "Example")
    41  			useCluster = (err == nil && match) || strings.Contains(exp, "Example")
    42  			hasRunArg = true
    43  			break
    44  		}
    45  	}
    46  	if !hasRunArg {
    47  		// force only running Test* if no args given to avoid leak false
    48  		// positives from having a long-running cluster for the examples.
    49  		os.Args = append(os.Args, "-test.run=Test")
    50  	}
    51  
    52  	var v int
    53  	if useCluster {
    54  		tr, trerr := transport.NewTransport(transport.TLSInfo{}, time.Second)
    55  		if trerr != nil {
    56  			fmt.Fprintf(os.Stderr, "%v", trerr)
    57  			os.Exit(1)
    58  		}
    59  		cfg := integration.ClusterConfig{Size: 1}
    60  		clus := integration.NewClusterV3(nil, &cfg)
    61  		exampleEndpoints = []string{clus.Members[0].URL()}
    62  		exampleTransport = tr
    63  		v = m.Run()
    64  		clus.Terminate(nil)
    65  		if err := testutil.CheckAfterTest(time.Second); err != nil {
    66  			fmt.Fprintf(os.Stderr, "%v", err)
    67  			os.Exit(1)
    68  		}
    69  	} else {
    70  		v = m.Run()
    71  	}
    72  
    73  	if v == 0 && testutil.CheckLeakedGoroutine() {
    74  		os.Exit(1)
    75  	}
    76  	os.Exit(v)
    77  }