github.com/kubri/kubri@v0.5.1-0.20240317001612-bda2aaef967e/internal/test/cmp.go (about)

     1  package test
     2  
     3  import (
     4  	"crypto/rsa"
     5  	"log"
     6  	"reflect"
     7  
     8  	"github.com/ProtonMail/gopenpgp/v2/crypto"
     9  	"github.com/google/go-cmp/cmp"
    10  )
    11  
    12  // CompareErrorMessages compares errors by message.
    13  func CompareErrorMessages() cmp.Option {
    14  	return cmp.FilterValues(
    15  		func(x, y any) bool {
    16  			_, ok1 := x.(error)
    17  			_, ok2 := y.(error)
    18  			return ok1 && ok2
    19  		},
    20  		cmp.Comparer(func(a, b any) bool {
    21  			if a == nil || b == nil {
    22  				return a == b
    23  			}
    24  			return a.(error).Error() == b.(error).Error() //nolint:forcetypeassert
    25  		}),
    26  	)
    27  }
    28  
    29  // CompareLoggers compares instances of [log.Logger].
    30  func CompareLoggers() cmp.Option {
    31  	return cmp.Comparer(func(a, b *log.Logger) bool {
    32  		return a.Prefix() == b.Prefix() && a.Flags() == b.Flags() && a.Writer() == b.Writer()
    33  	})
    34  }
    35  
    36  // ComparePGPKeys compares PGP keys' fingerprints.
    37  func ComparePGPKeys() cmp.Option {
    38  	return cmp.Comparer(func(a, b *crypto.Key) bool {
    39  		if a == nil || b == nil {
    40  			return a == b
    41  		}
    42  		return a.GetFingerprint() == b.GetFingerprint()
    43  	})
    44  }
    45  
    46  // CompareRSAPrivateKeys compares RSA private keys.
    47  func CompareRSAPrivateKeys() cmp.Option {
    48  	return cmp.Comparer(func(a, b *rsa.PrivateKey) bool {
    49  		if a == nil || b == nil {
    50  			return a == b
    51  		}
    52  		return a.Equal(b)
    53  	})
    54  }
    55  
    56  // ExportAll exports all unexported fields.
    57  func ExportAll() cmp.Option {
    58  	return cmp.Exporter(func(reflect.Type) bool {
    59  		return true
    60  	})
    61  }
    62  
    63  // IgnoreFunctions ignores all functions.
    64  func IgnoreFunctions() cmp.Option {
    65  	return cmp.FilterPath(func(p cmp.Path) bool {
    66  		sf, ok := p.Index(-1).(cmp.StructField)
    67  		return ok && sf.Type().Kind() == reflect.Func
    68  	}, cmp.Ignore())
    69  }