summaryrefslogtreecommitdiffhomepage
path: root/types/opt/bool_test.go
blob: f7bfc910c83e1b8fd0a482f01a0b4c39a3f397c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package opt

import (
	"encoding/json"
	"reflect"
	"testing"
)

func TestBool(t *testing.T) {
	tests := []struct {
		name string
		in   interface{}
		want string // JSON
	}{
		{
			name: "null_for_unset",
			in: struct {
				True  Bool
				False Bool
				Unset Bool
			}{
				True:  "true",
				False: "false",
			},
			want: `{"True":true,"False":false,"Unset":null}`,
		},
		{
			name: "omitempty_unset",
			in: struct {
				True  Bool
				False Bool
				Unset Bool `json:",omitempty"`
			}{
				True:  "true",
				False: "false",
			},
			want: `{"True":true,"False":false}`,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			j, err := json.Marshal(tt.in)
			if err != nil {
				t.Fatal(err)
			}
			if string(j) != tt.want {
				t.Errorf("wrong JSON:\n got: %s\nwant: %s\n", j, tt.want)
			}

			// And back again:
			newVal := reflect.New(reflect.TypeOf(tt.in))
			out := newVal.Interface()
			if err := json.Unmarshal(j, out); err != nil {
				t.Fatalf("Unmarshal %#q: %v", j, err)
			}
			got := newVal.Elem().Interface()
			if !reflect.DeepEqual(tt.in, got) {
				t.Errorf("value mismatch\n got: %+v\nwant: %+v\n", got, tt.in)
			}
		})
	}
}

func TestBoolEqualBool(t *testing.T) {
	tests := []struct {
		b    Bool
		v    bool
		want bool
	}{
		{"", true, false},
		{"", false, false},
		{"sdflk;", true, false},
		{"sldkf;", false, false},
		{"true", true, true},
		{"true", false, false},
		{"false", true, false},
		{"false", false, true},
	}
	for _, tt := range tests {
		if got := tt.b.EqualBool(tt.v); got != tt.want {
			t.Errorf("(%q).EqualBool(%v) = %v; want %v", string(tt.b), tt.v, got, tt.want)
		}
	}

}