messagediff

repository·master·Indexed 42 days ago

https://github.com/d4l3k/messagediff

A Go library for deep diffing of arbitrary Golang structs. It generates human-readable descriptions of differences between expected and actual values, supporting unexported field comparison via the unsafe package and field exclusion using the `testdiff:"ignore"` struct tag.

Tokens
555
Snippets
3
Records
3
Agent score
4%

What's inside messagediff

  1. Use messagediff to compare Golang structs

    master

    The messagediff library provides tools to perform deep comparisons between arbitrary Golang structs. It returns both a human-readable string describing the differences and a boolean indicating if the structs are equal.

    Key features:

    • Unexported Fields: If the unsafe package is available, messagediff will diff unexported fields in addition to exported fields, which is useful for detailed testing error messages.
    • Field Ignoring: You can skip specific fields during comparison by adding the `testdiff:"ignore"` struct tag.
    package main
    
    import "gopkg.in/d4l3k/messagediff.v1"
    
    type someStruct struct {
        A, b int
        C []int
    }
    
    func main() {
        a := someStruct{1, 2, []int{1}}
        b := someStruct{1, 3, []int{1, 2}}
        diff, equal := messagediff.PrettyDiff(a, b)
        /*
            diff =
            `added: .C[1] = 2
            modified: .b = 3`
    
            equal = false
        */
    }
  2. Ignore struct fields with testdiff:"ignore"

    master

    To prevent messagediff from comparing a specific field in a struct, annotate that field with the `testdiff:"ignore"` tag. This is useful for fields containing timestamps, random IDs, or other non-deterministic data that should not trigger a diff failure.

    type someStruct struct {
        A int
        B int `testdiff:"ignore"` 
    }
    
    // When comparing instances of someStruct, changes to field B will be ignored.
  3. PrettyDiff

    master

    The PrettyDiff function performs a comparison between two values and returns a human-readable string representing the differences and a boolean indicating equality. This is the primary function for generating informative error messages in tests.

    diff, equal := messagediff.PrettyDiff(want, got)