go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/analysis/internal/testverdicts/export_test.go (about)

     1  // Copyright 2023 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 testverdicts
    16  
    17  import (
    18  	"strings"
    19  	"testing"
    20  
    21  	"google.golang.org/protobuf/types/known/structpb"
    22  
    23  	resultpb "go.chromium.org/luci/resultdb/proto/v1"
    24  
    25  	. "github.com/smartystreets/goconvey/convey"
    26  )
    27  
    28  func TestVariantJSON(t *testing.T) {
    29  	Convey(`variantJSON`, t, func() {
    30  		Convey(`empty`, func() {
    31  			result, err := variantJSON(nil)
    32  			So(err, ShouldBeNil)
    33  			So(result, ShouldEqual, "{}")
    34  		})
    35  		Convey(`non-empty`, func() {
    36  			variant := &resultpb.Variant{
    37  				Def: map[string]string{
    38  					"builder":           "linux-rel",
    39  					"os":                "Ubuntu-18.04",
    40  					"pathological-case": "\000\001\n\r\f",
    41  				},
    42  			}
    43  			result, err := variantJSON(variant)
    44  			So(err, ShouldBeNil)
    45  			So(result, ShouldEqual, `{"builder":"linux-rel","os":"Ubuntu-18.04","pathological-case":"\u0000\u0001\n\r\u000c"}`)
    46  		})
    47  	})
    48  	Convey(`MarshalStructPB`, t, func() {
    49  		Convey(`empty`, func() {
    50  			result, err := MarshalStructPB(nil)
    51  			So(err, ShouldBeNil)
    52  			So(result, ShouldEqual, "{}")
    53  		})
    54  		Convey(`non-empty`, func() {
    55  			values := make(map[string]any)
    56  			values["stringkey"] = "abcdef\000\001\n"
    57  			values["numberkey"] = 123
    58  			values["boolkey"] = true
    59  			values["listkey"] = []any{"a", 9, true}
    60  			pb, err := structpb.NewStruct(values)
    61  			So(err, ShouldBeNil)
    62  			result, err := MarshalStructPB(pb)
    63  			So(err, ShouldBeNil)
    64  
    65  			// Different implementations may use different spacing between
    66  			// json elements. Ignore this.
    67  			result = strings.ReplaceAll(result, " ", "")
    68  			So(result, ShouldEqual, `{"boolkey":true,"listkey":["a",9,true],"numberkey":123,"stringkey":"abcdef\u0000\u0001\n"}`)
    69  		})
    70  	})
    71  }