2022-06-09 15:20:06 +00:00
|
|
|
package validation
|
|
|
|
|
2022-06-09 20:12:45 +00:00
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"math"
|
|
|
|
)
|
2022-06-09 15:20:06 +00:00
|
|
|
|
|
|
|
const equalityThreshold = 0.00000001
|
|
|
|
|
|
|
|
var (
|
|
|
|
_ ValueComparator = (*GenericComparator[int])(nil)
|
|
|
|
_ ValueComparator = FloatComparator(0)
|
|
|
|
)
|
|
|
|
|
|
|
|
type ValueComparator interface {
|
2022-06-09 20:12:45 +00:00
|
|
|
Equals(got any) error
|
2022-06-09 15:20:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type GenericComparator[T int | string] struct {
|
|
|
|
Want T
|
|
|
|
Parser func(got any) (T, error)
|
|
|
|
}
|
|
|
|
|
2022-06-09 20:12:45 +00:00
|
|
|
func (g GenericComparator[T]) Equals(got any) error {
|
2022-06-09 15:20:06 +00:00
|
|
|
parsed, err := g.Parser(got)
|
|
|
|
if err != nil {
|
2022-06-09 20:12:45 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if parsed != g.Want {
|
|
|
|
return fmt.Errorf("want %v but got %v", g.Want, parsed)
|
2022-06-09 15:20:06 +00:00
|
|
|
}
|
|
|
|
|
2022-06-09 20:12:45 +00:00
|
|
|
return nil
|
2022-06-09 15:20:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type FloatComparator float64
|
|
|
|
|
2022-06-09 20:12:45 +00:00
|
|
|
func (f FloatComparator) Equals(got any) error {
|
2022-06-09 15:20:06 +00:00
|
|
|
val, err := ParseJSONFloat(got)
|
|
|
|
if err != nil {
|
2022-06-09 20:12:45 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if math.Abs(float64(f)-val) > equalityThreshold {
|
|
|
|
return fmt.Errorf("want %f but got %f", float64(f), val)
|
2022-06-09 15:20:06 +00:00
|
|
|
}
|
|
|
|
|
2022-06-09 20:12:45 +00:00
|
|
|
return nil
|
2022-06-09 15:20:06 +00:00
|
|
|
}
|