go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/testing/assert/results/result_builder.go (about) 1 // Copyright 2024 The LUCI Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package results 16 17 import ( 18 "reflect" 19 ) 20 21 // A ResultBuilder builds a Result and has a fluent interface. 22 type ResultBuilder struct { 23 result *Result 24 } 25 26 // NewResultBuilder returns an empty ResultBuilder. 27 func NewResultBuilder() ResultBuilder { 28 return ResultBuilder{} 29 } 30 31 // Result returns the finished result from a builder. 32 func (builder ResultBuilder) Result() *Result { 33 return builder.result 34 } 35 36 // SetName sets the name of a Result. 37 func (builder ResultBuilder) SetName(comparison string, types ...reflect.Type) ResultBuilder { 38 if builder.result == nil { 39 builder.result = &Result{} 40 } 41 builder.result.failed = true 42 var typeNames []string 43 for _, typ := range types { 44 if typ == nil { 45 typeNames = append(typeNames, "<nil>") 46 continue 47 } 48 typeNames = append(typeNames, typ.String()) 49 } 50 builder.result.header.comparison = comparison 51 builder.result.header.types = typeNames 52 return builder 53 } 54 55 // Because sets the because field of a Result. 56 func (builder ResultBuilder) Because(format string, args ...interface{}) ResultBuilder{ 57 if builder.result == nil { 58 builder.result = &Result{} 59 } 60 builder.result.failed = true 61 addValuef(builder.result, "Because", format, args...) 62 return builder 63 } 64 65 // Actual sets the actual field of a Result. 66 func (builder ResultBuilder) Actual(actual interface{}) ResultBuilder{ 67 if builder.result == nil { 68 builder.result = &Result{} 69 } 70 builder.result.failed = true 71 addValue(builder.result, "Actual", actual) 72 return builder 73 } 74 75 // Expected sets the expected field of a Result. 76 func (builder ResultBuilder) Expected(actual interface{}) ResultBuilder{ 77 if builder.result == nil { 78 builder.result = &Result{} 79 } 80 builder.result.failed = true 81 addValue(builder.result, "Expected", actual) 82 return builder 83 }