From 48b6bc9a24367962b1a97e5d6647c51e6f42dbb1 Mon Sep 17 00:00:00 2001 From: svn37 Date: Wed, 10 Jan 2024 13:54:12 +0400 Subject: [PATCH] add more informative error for empty values (#40) --- ip/ip.go | 4 +++- ip/ip_test.go | 3 ++- ip/ip_v4.go | 2 +- ip/ip_v6.go | 2 +- ip/ip_v6_test.go | 3 ++- 5 files changed, 9 insertions(+), 5 deletions(-) diff --git a/ip/ip.go b/ip/ip.go index ef4d5cd..ec95c9d 100644 --- a/ip/ip.go +++ b/ip/ip.go @@ -7,6 +7,8 @@ import ( "fmt" ) +var ErrEmptyValue = errors.New("ip address cannot be empty") + type IP struct { v4 IPv4 v6 IPv6 @@ -84,7 +86,7 @@ func (ip IP) IsIPv6() bool { func FromString(value string) (IP, error) { if value == "" { - return IP{}, fmt.Errorf("empty value") + return IP{}, ErrEmptyValue } var v4Addr, err = V4FromString(value) diff --git a/ip/ip_test.go b/ip/ip_test.go index b70dd4b..0a684e8 100644 --- a/ip/ip_test.go +++ b/ip/ip_test.go @@ -79,7 +79,7 @@ func TestIP_Value(t *testing.T) { name: "IPv6", ip: IP{ isV6: true, - v6: IPv6("2001:0db8:85a3:0000:0000:8a2e:0370:7334"), + v6: IPv6("2001:db8:85a3::8a2e:370:7334"), raw: "2001:0db8:85a3:0000:0000:8a2e:0370:7334", }, wantValue: "2001:0db8:85a3:0000:0000:8a2e:0370:7334", @@ -302,6 +302,7 @@ func TestParseIPFromString(t *testing.T) { t.Errorf("ParseIPFromString() error = %v, wantErr %v", err, tt.wantErr) return } + if got != tt.wantValue { t.Errorf("ParseIPFromString() got = %v, want %v", got, tt.wantValue) } diff --git a/ip/ip_v4.go b/ip/ip_v4.go index e73ae28..a69a4f6 100644 --- a/ip/ip_v4.go +++ b/ip/ip_v4.go @@ -52,7 +52,7 @@ func (ip IPv4) String() string { func V4FromString(value string) (IPv4, error) { if value == "" { - return "", fmt.Errorf("empty value") + return "", ErrEmptyValue } var addr, err = netip.ParseAddr(value) diff --git a/ip/ip_v6.go b/ip/ip_v6.go index 606f1d2..dcf6ae2 100644 --- a/ip/ip_v6.go +++ b/ip/ip_v6.go @@ -52,7 +52,7 @@ func (ip IPv6) String() string { func V6FromString(value string) (IPv6, error) { if value == "" { - return "", fmt.Errorf("empty value") + return "", ErrEmptyValue } var addr, err = netip.ParseAddr(value) diff --git a/ip/ip_v6_test.go b/ip/ip_v6_test.go index d264fb3..b037272 100644 --- a/ip/ip_v6_test.go +++ b/ip/ip_v6_test.go @@ -3,6 +3,7 @@ package ip import ( "database/sql/driver" "encoding/json" + "fmt" "reflect" "testing" ) @@ -83,7 +84,7 @@ func TestIPv6_UnmarshalJSON(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var ipv6 IPv6 - err := json.Unmarshal([]byte(tt.ip), &ipv6) + err := json.Unmarshal([]byte(fmt.Sprintf(`"%s"`, tt.ip)), &ipv6) if (err != nil) != tt.wantErr { t.Errorf("UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr) }