go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/testing/assert/structuraldiff/structural_diff_test.go (about) 1 // Copyright 2024 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 structuraldiff 16 17 import ( 18 "strings" 19 "testing" 20 21 "github.com/google/go-cmp/cmp" 22 "github.com/sergi/go-diff/diffmatchpatch" 23 24 "go.chromium.org/luci/common/testing/typed" 25 ) 26 27 // TestDebugCompare compares two values and checks to see if the result is what we expect. 28 // 29 // This test is sensitive to small changes in how the Result is represented. 30 func TestDebugCompare(t *testing.T) { 31 t.Parallel() 32 33 cases := []struct { 34 name string 35 left any 36 right any 37 result *Result 38 }{ 39 { 40 name: "equal", 41 left: 10, 42 right: 10, 43 result: nil, 44 }, 45 { 46 name: "different", 47 left: 10, 48 right: 27, 49 result: &Result{ 50 diffs: []diffmatchpatch.Diff{ 51 {Type: diffmatchpatch.DiffDelete, Text: "10"}, 52 {Type: diffmatchpatch.DiffInsert, Text: "27"}, 53 }, 54 }, 55 }, 56 { 57 name: "different types but similar string representation.", 58 left: 10, 59 right: "10", 60 result: &Result{ 61 diffs: []diffmatchpatch.Diff{ 62 {Type: diffmatchpatch.DiffInsert, Text: `"`}, 63 {Text: "10"}, 64 {Type: diffmatchpatch.DiffInsert, Text: `"`}, 65 }, 66 }, 67 }, 68 } 69 70 for _, tt := range cases { 71 tt := tt 72 t.Run(tt.name, func(t *testing.T) { 73 t.Parallel() 74 75 got := DebugCompare[any](tt.left, tt.right) 76 want := tt.result 77 78 if diff := typed.Got(got).Want(want).Options(cmp.AllowUnexported(Result{})).Diff(); diff != "" { 79 t.Errorf("unexpected diff (-want +got): %s", diff) 80 } 81 }) 82 } 83 } 84 85 // TestToString tests rendering a result as a string 86 func TestToString(t *testing.T) { 87 t.Parallel() 88 89 cases := []struct { 90 name string 91 result *Result 92 output string 93 }{ 94 { 95 name: "empty", 96 result: nil, 97 output: "", 98 }, 99 { 100 name: "simple", 101 result: DebugCompare[string]("a", "b"), 102 output: strings.Join([]string{ 103 "Delete a\n", 104 "Insert b\n", 105 }, ""), 106 }, 107 } 108 109 for _, tt := range cases { 110 tt := tt 111 t.Run(tt.name, func(t *testing.T) { 112 t.Parallel() 113 114 if diff := typed.Got(tt.result.String()).Want(tt.output).Diff(); diff != "" { 115 t.Errorf("unexpected diff (-want +got): %s", diff) 116 } 117 }) 118 } 119 }