github.com/hxx258456/fabric-ca-gm@v0.0.3-0.20221111064038-a268ad7e3a37/internal/pkg/util/args_test.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package util
     8  
     9  import (
    10  	"os"
    11  	"testing"
    12  
    13  	"github.com/stretchr/testify/assert"
    14  )
    15  
    16  func TestGetCommandLineOptValue(t *testing.T) {
    17  	testGetCommandLineOptValue(t,
    18  		[]string{"fabric-ca", "client", "-config", "myconfig.json", "enroll"},
    19  		"-config",
    20  		"myconfig.json",
    21  		[]string{"fabric-ca", "client", "-config", "myconfig.json", "enroll"})
    22  }
    23  
    24  func TestSetDefaultServerPort(t *testing.T) {
    25  	testSetDefaultServerPort(t,
    26  		[]string{"fabric-ca", "client", "enroll"},
    27  		[]string{"fabric-ca", "client", "enroll", "-port", "7054"})
    28  	testSetDefaultServerPort(t,
    29  		[]string{"fabric-ca", "client", "enroll", "-port", "1234"},
    30  		[]string{"fabric-ca", "client", "enroll", "-port", "1234"})
    31  }
    32  
    33  func TestOpts(t *testing.T) {
    34  	testOpt(t, "-protocol", "protocol", "protocol")
    35  	testOpt(t, "-protocol", "", "http")
    36  	testOpt(t, "-address", "addr", "addr")
    37  	testOpt(t, "-address", "", "localhost")
    38  	testOpt(t, "-port", "port", "port")
    39  	testOpt(t, "-port", "", "7054")
    40  }
    41  
    42  func testGetCommandLineOptValue(t *testing.T, args []string, opt string, expectedVal string, expectedArgs []string) {
    43  	defer func(args []string) { os.Args = args }(os.Args)
    44  
    45  	os.Args = args
    46  	val := getCommandLineOptValue(opt)
    47  	assert.Equal(t, expectedVal, val)
    48  	assert.Equal(t, expectedArgs, os.Args)
    49  }
    50  
    51  func testSetDefaultServerPort(t *testing.T, inputArgs []string, expectedOutputArgs []string) {
    52  	defer func(args []string) { os.Args = args }(os.Args)
    53  
    54  	os.Args = inputArgs
    55  	setDefaultServerPort()
    56  	assert.Equal(t, expectedOutputArgs, os.Args)
    57  }
    58  
    59  func testOpt(t *testing.T, opt, val, expectedVal string) {
    60  	defer func(args []string) { os.Args = args }(os.Args)
    61  
    62  	if val != "" {
    63  		os.Args = []string{"fabric-ca", "client", "enroll", opt, val}
    64  	} else {
    65  		os.Args = []string{"fabric-ca", "client", "enroll"}
    66  	}
    67  	switch opt {
    68  	case "-protocol":
    69  		val = getServerProtocol()
    70  	case "-address":
    71  		val = getServerAddr()
    72  	case "-port":
    73  		val = GetServerPort()
    74  	default:
    75  		panic("bad opt value")
    76  	}
    77  	assert.Equal(t, expectedVal, val, "unexpected value for option '%s'", opt)
    78  }