go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/data/cmpbin/float_test.go (about) 1 // Copyright 2015 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 cmpbin 16 17 import ( 18 "bytes" 19 "io" 20 "math/rand" 21 "sort" 22 "testing" 23 24 . "github.com/smartystreets/goconvey/convey" 25 ) 26 27 func TestFloats(t *testing.T) { 28 t.Parallel() 29 30 Convey("floats", t, func() { 31 b := &bytes.Buffer{} 32 33 Convey("good", func() { 34 f1 := float64(1.234) 35 n, err := WriteFloat64(b, f1) 36 So(err, ShouldBeNil) 37 So(n, ShouldEqual, 8) 38 f, n, err := ReadFloat64(b) 39 So(err, ShouldBeNil) 40 So(n, ShouldEqual, 8) 41 So(f, ShouldEqual, f1) 42 }) 43 44 Convey("bad", func() { 45 _, n, err := ReadFloat64(b) 46 So(err, ShouldEqual, io.EOF) 47 So(n, ShouldEqual, 0) 48 }) 49 }) 50 } 51 52 func TestFloatSortability(t *testing.T) { 53 t.Parallel() 54 55 Convey("floats maintain sort order", t, func() { 56 vec := make(sort.Float64Slice, randomTestSize) 57 r := rand.New(rand.NewSource(*seed)) 58 for i := range vec { 59 vec[i] = r.Float64() 60 } 61 62 bin := make(sort.StringSlice, len(vec)) 63 b := &bytes.Buffer{} 64 for i := range bin { 65 b.Reset() 66 n, err := WriteFloat64(b, vec[i]) 67 So(err, ShouldBeNil) 68 So(n, ShouldEqual, 8) 69 bin[i] = b.String() 70 } 71 72 vec.Sort() 73 bin.Sort() 74 75 for i := range vec { 76 r, _, err := ReadFloat64(bytes.NewBufferString(bin[i])) 77 So(err, ShouldBeNil) 78 So(vec[i], ShouldEqual, r) 79 } 80 }) 81 }