testify icon indicating copy to clipboard operation
testify copied to clipboard

Adjust number of context lines for diff

Open christopher-taormina-zocdoc opened this issue 2 years ago • 2 comments

Is it possible to adjust the amount of context lines around the offending lines in a diff?

I'm asserting on some structs that I don't fully own, and the diffs when using assert.EqualValues end up leaving out crucial information on which value needs to change, just that the value is different. Given the following example

func TestSomething(t *testing.T) {
	type ValueType struct {
		Value string
	}

	type KeyValue struct {
		Key   string
		Value ValueType
	}

	type MyType struct {
		KeyValues *[]KeyValue
	}

	myTypeA := MyType{
		KeyValues: &[]KeyValue{
			{
				Key: "something",
				Value: ValueType{
					Value: "somethingElse",
				},
			},
		},
	}

	myTypeB := MyType{
		KeyValues: &[]KeyValue{
			{
				Key: "something",
				Value: ValueType{
					Value: "somethingElseEntirely",
				},
			},
		},
	}

	assert.EqualValues(t, myTypeA, myTypeB)
}

The test will spit out the following message when it fails.

Error:      	Not equal: 
        	            	expected: e2e.MyType{KeyValues:(*[]e2e.KeyValue)(0x140001a8198)}
        	            	actual  : e2e.MyType{KeyValues:(*[]e2e.KeyValue)(0x140001a81e0)}
        	            	
        	            	Diff:
        	            	--- Expected
        	            	+++ Actual
        	            	@@ -5,3 +5,3 @@
        	            	    Value: (e2e.ValueType) {
        	            	-    Value: (string) (len=13) "somethingElse"
        	            	+    Value: (string) (len=21) "somethingElseEntirely"
        	            	    }
Test:       	TestSomething

From the output, knowing the specific entry in the KeyValues slice is not really possible. Obviously in this example there's only one element, but once more are added, it becomes increasingly difficult to figure out exactly which entry in the slice is causing the issue, especially if values end up duplicated for whatever reasons.

I expect this is related to go-difflib so #1327 is probably relevant.

dolmen avatar Jul 25 '23 02:07 dolmen

Could we make this configurable / a global option? https://github.com/stretchr/testify/blob/1b4fca7679ac5ddaf45491840c8a0cace9fc6d83/assert/assertions.go#L1890

Happy to open a PR

turbolent avatar Jun 03 '24 21:06 turbolent