/ internal / flag / boolptrvalue_test.go
boolptrvalue_test.go
  1  package flag_test
  2  
  3  import (
  4  	"flag"
  5  	"slices"
  6  	"testing"
  7  
  8  	internalFlag "codeflow.dananglin.me.uk/apollo/enbas/internal/flag"
  9  )
 10  
 11  func TestBoolPtrValue(t *testing.T) {
 12  	tests := []struct {
 13  		input string
 14  		want  string
 15  	}{
 16  		{
 17  			input: "True",
 18  			want:  "true",
 19  		},
 20  		{
 21  			input: "true",
 22  			want:  "true",
 23  		},
 24  		{
 25  			input: "1",
 26  			want:  "true",
 27  		},
 28  		{
 29  			input: "False",
 30  			want:  "false",
 31  		},
 32  		{
 33  			input: "false",
 34  			want:  "false",
 35  		},
 36  		{
 37  			input: "0",
 38  			want:  "false",
 39  		},
 40  	}
 41  
 42  	for _, test := range slices.All(tests) {
 43  		args := []string{"--boolean-value=" + test.input}
 44  
 45  		t.Run("Flag parsing test: "+test.input, testBoolPtrValueParsing(args, test.want))
 46  	}
 47  }
 48  
 49  func testBoolPtrValueParsing(args []string, want string) func(t *testing.T) {
 50  	return func(t *testing.T) {
 51  		flagset := flag.NewFlagSet("test", flag.ExitOnError)
 52  		boolVal := internalFlag.NewBoolPtrValue()
 53  
 54  		flagset.Var(&boolVal, "boolean-value", "Boolean value")
 55  
 56  		if err := flagset.Parse(args); err != nil {
 57  			t.Fatalf("Received an error parsing the flag: %v", err)
 58  		}
 59  
 60  		got := boolVal.String()
 61  
 62  		if got != want {
 63  			t.Errorf(
 64  				"Unexpected boolean value found after parsing BoolPtrValue: want %s, got %s",
 65  				want,
 66  				got,
 67  			)
 68  		} else {
 69  			t.Logf(
 70  				"Expected boolean value found after parsing BoolPtrValue: got %s",
 71  				got,
 72  			)
 73  		}
 74  	}
 75  }
 76  
 77  func TestNotSetBoolPtrValue(t *testing.T) {
 78  	flagset := flag.NewFlagSet("test", flag.ExitOnError)
 79  	boolVal := internalFlag.NewBoolPtrValue()
 80  
 81  	var otherVal string
 82  
 83  	flagset.Var(&boolVal, "boolean-value", "Boolean value")
 84  	flagset.StringVar(&otherVal, "other-value", "", "Another value")
 85  
 86  	args := []string{"--other-value", "other-value"}
 87  
 88  	if err := flagset.Parse(args); err != nil {
 89  		t.Fatalf("Received an error parsing the flag: %v", err)
 90  	}
 91  
 92  	want := "NOT SET"
 93  	got := boolVal.String()
 94  
 95  	if got != want {
 96  		t.Errorf("Unexpected string returned from the nil value; want %s, got %s", want, got)
 97  	} else {
 98  		t.Logf("Expected string returned from the nil value; got %s", got)
 99  	}
100  }