github.com/decred/politeia@v1.4.0/util/unittest/unittest.go (about)

     1  // Copyright (c) 2021 The Decred developers
     2  // Use of this source code is governed by an ISC
     3  // license that can be found in the LICENSE file.
     4  
     5  package unittest
     6  
     7  import (
     8  	"fmt"
     9  	"reflect"
    10  	"strings"
    11  
    12  	"github.com/go-test/deep"
    13  )
    14  
    15  // TestGenericConstMap tests a map of an error constant type and verifies that
    16  // the error numbers are consecutive and represented in the human readable map.
    17  // This function is for UT only.
    18  func TestGenericConstMap(errorsMap interface{}, lastError uint64) error {
    19  	if reflect.TypeOf(errorsMap).Kind() != reflect.Map {
    20  		return fmt.Errorf("errorsMap not a map: %T", errorsMap)
    21  	}
    22  	val := reflect.ValueOf(errorsMap)
    23  
    24  	leftover := make(map[uint64]struct{}, len(val.MapKeys()))
    25  	for i := uint64(0); i < uint64(len(val.MapKeys())); i++ {
    26  		leftover[i] = struct{}{}
    27  
    28  	}
    29  	for _, mapKey := range val.MapKeys() {
    30  		var key uint64
    31  		switch mapKey.Kind() {
    32  		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32,
    33  			reflect.Uint64:
    34  			key = mapKey.Uint()
    35  		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32,
    36  			reflect.Int64:
    37  			key = uint64(mapKey.Int())
    38  		default:
    39  			return fmt.Errorf("unsupported key type: %v",
    40  				mapKey.Kind())
    41  		}
    42  		delete(leftover, key)
    43  	}
    44  	if len(leftover) != 0 {
    45  		return fmt.Errorf("leftover length not 0: %v", leftover)
    46  	}
    47  	if len(val.MapKeys()) != int(lastError) {
    48  		return fmt.Errorf("someone added a map code without adding a "+
    49  			"human readable description. Got %v, want %v",
    50  			len(val.MapKeys()), lastError)
    51  	}
    52  
    53  	return nil
    54  }
    55  
    56  // DeepEqual checks for deep equality between the provided structures. An empty
    57  // string is returned if the structures are deeply equal. A pretty printed
    58  // string that contains the differences is returned if the structures are not
    59  // deeply equal. The equality check goes a max of 10 levels deep.
    60  func DeepEqual(got, want interface{}) string {
    61  	diffs := deep.Equal(got, want)
    62  	if diffs == nil {
    63  		// got and want are deeply equal
    64  		return ""
    65  	}
    66  
    67  	// Not deeply equal. Pretty print the diffs.
    68  	var b strings.Builder
    69  	b.WriteString("value are not deeply equal; got != want: \n")
    70  	for _, v := range diffs {
    71  		b.WriteString(v)
    72  		b.WriteString("\n")
    73  	}
    74  
    75  	return b.String()
    76  }