Debian Codegraph @

td/td_nan.go

raw
1 // Copyright (c) 2018, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package td
8
9 import (
10 "math"
11 "reflect"
12
13 "github.com/maxatome/go-testdeep/internal/ctxerr"
14 "github.com/maxatome/go-testdeep/internal/types"
15 )
16
17 type tdNaN struct {
18 base
19 }
20
21 var _ TestDeep = &tdNaN{}
22
23 // summary(NaN): checks a floating number is [`math.NaN`]
24 // input(NaN): float
25
26 // NaN operator checks that data is a float and is not-a-number.
27 //
28 // got := math.NaN()
29 // td.Cmp(t, got, td.NaN()) // succeeds
30 // td.Cmp(t, 4.2, td.NaN()) // fails
31 //
32 // See also [NotNaN].
33 func NaN() TestDeep {
34 return &tdNaN{
35 base: newBase(3),
36 }
37 }
38
39 func (n *tdNaN) Match(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error {
40 switch got.Kind() {
41 case reflect.Float32, reflect.Float64:
42 if math.IsNaN(got.Float()) {
43 return nil
44 }
45
46 return ctx.CollectError(&ctxerr.Error{
47 Message: "values differ",
48 Got: got,
49 Expected: n,
50 })
51 }
52
53 return ctx.CollectError(&ctxerr.Error{
54 Message: "type mismatch",
55 Got: types.RawString(got.Type().String()),
56 Expected: types.RawString("float32 OR float64"),
57 })
58 }
59
60 func (n *tdNaN) String() string {
61 return "NaN"
62 }
63
64 type tdNotNaN struct {
65 base
66 }
67
68 var _ TestDeep = &tdNotNaN{}
69
70 // summary(NotNaN): checks a floating number is not [`math.NaN`]
71 // input(NotNaN): float
72
73 // NotNaN operator checks that data is a float and is not not-a-number.
74 //
75 // got := math.NaN()
76 // td.Cmp(t, got, td.NotNaN()) // fails
77 // td.Cmp(t, 4.2, td.NotNaN()) // succeeds
78 // td.Cmp(t, 4, td.NotNaN()) // fails, as 4 is not a float
79 //
80 // See also [NaN].
81 func NotNaN() TestDeep {
82 return &tdNotNaN{
83 base: newBase(3),
84 }
85 }
86
87 func (n *tdNotNaN) Match(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error {
88 switch got.Kind() {
89 case reflect.Float32, reflect.Float64:
90 if !math.IsNaN(got.Float()) {
91 return nil
92 }
93
94 return ctx.CollectError(&ctxerr.Error{
95 Message: "values differ",
96 Got: got,
97 Expected: n,
98 })
99 }
100
101 return ctx.CollectError(&ctxerr.Error{
102 Message: "type mismatch",
103 Got: types.RawString(got.Type().String()),
104 Expected: types.RawString("float32 OR float64"),
105 })
106 }
107
108 func (n *tdNotNaN) String() string {
109 return "not NaN"
110 }