github.com/cosmos/cosmos-sdk@v0.50.10/codec/types/any_test.go (about)

     1  package types_test
     2  
     3  import (
     4  	"fmt"
     5  	"runtime"
     6  	"testing"
     7  
     8  	"github.com/cosmos/gogoproto/proto"
     9  
    10  	"github.com/cosmos/cosmos-sdk/codec/types"
    11  	"github.com/cosmos/cosmos-sdk/testutil/testdata"
    12  )
    13  
    14  type errOnMarshal struct {
    15  	testdata.Dog
    16  }
    17  
    18  var _ proto.Message = (*errOnMarshal)(nil)
    19  
    20  var errAlways = fmt.Errorf("always erroring")
    21  
    22  func (eom *errOnMarshal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { //nolint:revive // XXX_ prefix is intentional
    23  	return nil, errAlways
    24  }
    25  
    26  var eom = &errOnMarshal{}
    27  
    28  // Ensure that returning an error doesn't suddenly allocate and waste bytes.
    29  // See https://github.com/cosmos/cosmos-sdk/issues/8537
    30  func TestNewAnyWithCustomTypeURLWithErrorNoAllocation(t *testing.T) {
    31  	// This tests continues to fail inconsistently.
    32  	//
    33  	// Example: https://github.com/cosmos/cosmos-sdk/pull/9246/checks?check_run_id=2643313958#step:6:118
    34  	// Ref: https://github.com/cosmos/cosmos-sdk/issues/9010
    35  	t.SkipNow()
    36  
    37  	// make sure we're not in the middle of a GC.
    38  	runtime.GC()
    39  
    40  	var ms1, ms2 runtime.MemStats
    41  	runtime.ReadMemStats(&ms1)
    42  	any, err := types.NewAnyWithValue(eom)
    43  	runtime.ReadMemStats(&ms2)
    44  	// Ensure that no fresh allocation was made.
    45  	if diff := ms2.HeapAlloc - ms1.HeapAlloc; diff > 0 {
    46  		t.Errorf("Unexpected allocation of %d bytes", diff)
    47  	}
    48  	if err == nil {
    49  		t.Fatal("err wasn't returned")
    50  	}
    51  	if any != nil {
    52  		t.Fatalf("Unexpectedly got a non-nil Any value: %v", any)
    53  	}
    54  }
    55  
    56  var sink interface{}
    57  
    58  func BenchmarkNewAnyWithCustomTypeURLWithErrorReturned(b *testing.B) {
    59  	b.ResetTimer()
    60  	b.ReportAllocs()
    61  	for i := 0; i < b.N; i++ {
    62  		any, err := types.NewAnyWithValue(eom)
    63  		if err == nil {
    64  			b.Fatal("err wasn't returned")
    65  		}
    66  		if any != nil {
    67  			b.Fatalf("Unexpectedly got a non-nil Any value: %v", any)
    68  		}
    69  		sink = any
    70  	}
    71  	if sink == nil {
    72  		b.Fatal("benchmark didn't run")
    73  	}
    74  	sink = (interface{})(nil)
    75  }