github.com/s7techlab/cckit@v0.10.5/testing/must.go (about)

     1  package testing
     2  
     3  import (
     4  	"encoding/json"
     5  	"time"
     6  
     7  	"github.com/golang/protobuf/proto"
     8  	"github.com/golang/protobuf/ptypes"
     9  	"github.com/golang/protobuf/ptypes/timestamp"
    10  	"github.com/s7techlab/cckit/convert"
    11  )
    12  
    13  // PanicIfError
    14  func PanicIfError(err error) {
    15  	if err != nil {
    16  		panic(err)
    17  	}
    18  }
    19  
    20  // MustProtoMarshal marshals proto.Message, panics if error
    21  func MustProtoMarshal(pb proto.Message) []byte {
    22  	bb, err := proto.Marshal(pb)
    23  	PanicIfError(err)
    24  
    25  	return bb
    26  }
    27  
    28  func MustJSONMarshal(val interface{}) []byte {
    29  	bb, err := json.Marshal(val)
    30  	PanicIfError(err)
    31  	return bb
    32  }
    33  
    34  // MustProtoUnmarshal unmarshals proto.Message, panics if error
    35  func MustProtoUnmarshal(bb []byte, pm proto.Message) proto.Message {
    36  	p := proto.Clone(pm)
    37  	PanicIfError(proto.Unmarshal(bb, p))
    38  	return p
    39  }
    40  
    41  // MustProtoTimestamp, creates proto.Timestamp, panics if error
    42  func MustProtoTimestamp(t time.Time) *timestamp.Timestamp {
    43  	ts, err := ptypes.TimestampProto(t)
    44  	PanicIfError(err)
    45  	return ts
    46  }
    47  
    48  func MustConvertFromBytes(bb []byte, target interface{}) interface{} {
    49  	v, err := convert.FromBytes(bb, target)
    50  	PanicIfError(err)
    51  	return v
    52  }
    53  
    54  // MustTime returns Timestamp for date string or panic
    55  func MustTime(s string) *timestamp.Timestamp {
    56  	t, err := time.Parse(time.RFC3339, s)
    57  	if err != nil {
    58  		panic(err)
    59  	}
    60  
    61  	ts, err := ptypes.TimestampProto(t)
    62  	if err != nil {
    63  		panic(err)
    64  	}
    65  
    66  	return ts
    67  }