go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/testing/typed/diff_test.go (about)

     1  // Copyright 2023 The LUCI 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 typed
    16  
    17  import "testing"
    18  
    19  // TestDiff tests whether two things are equal or not.
    20  //
    21  // TestDiff is implemented using cmp.Diff and thus the only part of the API
    22  // that's stable is whether the result of cmp.Diff(...) is an empty string or
    23  // not. cmp.Diff will insert random spaces at the ends of lines to make it
    24  // impossible to test against its output. The reason that they do that,
    25  // though, is to give them the freedom to display diffs more informatively in
    26  // the future without breaking people's tests. That seems reasonable to me.
    27  func TestDiff(t *testing.T) {
    28  	t.Parallel()
    29  
    30  	cases := []struct {
    31  		name string
    32  		want string
    33  		got  string
    34  		ok   bool
    35  	}{
    36  		{
    37  			name: "empty",
    38  			want: "",
    39  			got:  "",
    40  			ok:   true,
    41  		},
    42  		{
    43  			name: "empty",
    44  			want: "a",
    45  			got:  "",
    46  			ok:   false,
    47  		},
    48  	}
    49  
    50  	for _, tt := range cases {
    51  		res := (Diff(tt.want, tt.got) == "")
    52  		switch {
    53  		case res && !tt.ok:
    54  			t.Errorf("case %s unexpectedly true", tt.name)
    55  		case !res && tt.ok:
    56  			t.Errorf("case %s unexpectedly false", tt.name)
    57  		}
    58  	}
    59  }
    60  
    61  // Test that the got-before-want syntax does what we intend it to.
    62  func TestGot(t *testing.T) {
    63  	t.Parallel()
    64  
    65  	diff := Got(4).Want(7).Diff()
    66  
    67  	if diff == "" {
    68  		t.Error("expected diff to be empty")
    69  	}
    70  }