github.com/filecoin-project/specs-actors/v4@v4.0.2/actors/builtin/testing.go (about) 1 package builtin 2 3 import ( 4 "fmt" 5 ) 6 7 // Accumulates a sequence of messages (e.g. validation failures). 8 type MessageAccumulator struct { 9 // Accumulated messages. 10 // This is a pointer to support accumulators derived from `WithPrefix()` accumulating to 11 // the same underlying collection. 12 msgs *[]string 13 // Optional prefix to all new messages, e.g. describing higher level context. 14 prefix string 15 } 16 17 // Returns a new accumulator backed by the same collection, that will prefix each new message with 18 // a formatted string. 19 func (ma *MessageAccumulator) WithPrefix(format string, args ...interface{}) *MessageAccumulator { 20 ma.initialize() 21 return &MessageAccumulator{ 22 msgs: ma.msgs, 23 prefix: ma.prefix + fmt.Sprintf(format, args...), 24 } 25 } 26 27 func (ma *MessageAccumulator) IsEmpty() bool { 28 return ma.msgs == nil || len(*ma.msgs) == 0 29 } 30 31 func (ma *MessageAccumulator) Messages() []string { 32 if ma.msgs == nil { 33 return nil 34 } 35 return (*ma.msgs)[:] 36 } 37 38 // Adds messages to the accumulator. 39 func (ma *MessageAccumulator) Add(msg string) { 40 ma.initialize() 41 *ma.msgs = append(*ma.msgs, ma.prefix+msg) 42 } 43 44 // Adds a message to the accumulator 45 func (ma *MessageAccumulator) Addf(format string, args ...interface{}) { 46 ma.Add(fmt.Sprintf(format, args...)) 47 } 48 49 // Adds messages from another accumulator to this one. 50 func (ma *MessageAccumulator) AddAll(other *MessageAccumulator) { 51 if other.msgs == nil { 52 return 53 } 54 for _, msg := range *other.msgs { 55 ma.Add(msg) 56 } 57 } 58 59 // Adds a message if predicate is false. 60 func (ma *MessageAccumulator) Require(predicate bool, msg string, args ...interface{}) { 61 if !predicate { 62 ma.Add(fmt.Sprintf(msg, args...)) 63 } 64 } 65 66 func (ma *MessageAccumulator) RequireNoError(err error, msg string, args ...interface{}) { 67 if err != nil { 68 msg = msg + ": %v" 69 args = append(args, err) 70 ma.Addf(msg, args...) 71 } 72 } 73 74 func (ma *MessageAccumulator) initialize() { 75 if ma.msgs == nil { 76 ma.msgs = &[]string{} 77 } 78 }