Skip to content

Commit

Permalink
#patch: improve error testing
Browse files Browse the repository at this point in the history
  • Loading branch information
circa10a committed Feb 26, 2022
1 parent 01e41c8 commit d273271
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 29 deletions.
15 changes: 3 additions & 12 deletions geofence.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package geofence

import (
"fmt"
"net"
"time"

Expand All @@ -11,7 +12,6 @@ import (

const (
freeGeoIPBaseURL = "https://api.freegeoip.app/json"
invalidIPAddressString = "invalid IP address provided"
deleteExpiredCacheItemsInternal = 10 * time.Minute
)

Expand Down Expand Up @@ -57,21 +57,12 @@ func (e *FreeGeoIPError) Error() string {
}

// ErrInvalidIPAddress is the error raised when an invalid IP address is provided
type ErrInvalidIPAddress struct {
msg string
}

func (e *ErrInvalidIPAddress) Error() string {
return e.msg
}
var ErrInvalidIPAddress = fmt.Errorf("invalid IP address provided")

// validateIPAddress ensures valid ip address
func validateIPAddress(ipAddress string) error {
ipAddressErr := &ErrInvalidIPAddress{
msg: invalidIPAddressString,
}
if net.ParseIP(ipAddress) == nil {
return ipAddressErr
return ErrInvalidIPAddress
}
return nil
}
Expand Down
33 changes: 16 additions & 17 deletions geofence_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,34 +12,33 @@ import (
)

func TestValidateIPAddress(t *testing.T) {
type test struct {
Expected error
Input string
}
tests := []test{
tests := []struct {
expected error
input string
}{
{
Input: "8.8.8.8",
Expected: nil,
input: "8.8.8.8",
expected: nil,
},
{
Input: "8.8.88",
Expected: &ErrInvalidIPAddress{},
input: "8.8.88",
expected: ErrInvalidIPAddress,
},
{
Input: "2001:db8:3333:4444:5555:6666:7777:8888",
Expected: nil,
input: "2001:db8:3333:4444:5555:6666:7777:8888",
expected: nil,
},
{
Input: "2001:db8:3333:4444:5555:6666:7777:88888",
Expected: &ErrInvalidIPAddress{},
input: "2001:db8:3333:4444:5555:6666:7777:88888",
expected: ErrInvalidIPAddress,
},
}
for _, test := range tests {
actual := validateIPAddress(test.Input)
if test.Expected != nil {
assert.EqualErrorf(t, actual, invalidIPAddressString, "Error should be: %v, got: %v", invalidIPAddressString, actual)
actual := validateIPAddress(test.input)
if test.expected != nil {
assert.ErrorIs(t, actual, test.expected)
} else {
if !errors.Is(actual, test.Expected) {
if !errors.Is(actual, test.expected) {
t.Fail()
}
}
Expand Down

0 comments on commit d273271

Please sign in to comment.