Add MAC validation checker and tests to v2. (#139)

# Describe Request

Add MAC validation checker and tests to v2.

# Change Type

New code.
This commit is contained in:
Onur Cinar 2024-12-26 19:10:33 -08:00 committed by GitHub
commit 29a1a9ba0d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 118 additions and 0 deletions

41
v2/mac.go Normal file
View file

@ -0,0 +1,41 @@
// Copyright (c) 2023-2024 Onur Cinar.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// https://github.com/cinar/checker
package v2
import (
"net"
"reflect"
)
const (
// nameMAC is the name of the MAC check.
nameMAC = "mac"
)
var (
// ErrNotMAC indicates that the given value is not a valid MAC address.
ErrNotMAC = NewCheckError("MAC")
)
// IsMAC checks if the value is a valid MAC address.
func IsMAC(value string) (string, error) {
_, err := net.ParseMAC(value)
if err != nil {
return value, ErrNotMAC
}
return value, nil
}
// checkMAC checks if the value is a valid MAC address.
func checkMAC(value reflect.Value) (reflect.Value, error) {
_, err := IsMAC(value.Interface().(string))
return value, err
}
// makeMAC makes a checker function for the MAC checker.
func makeMAC(_ string) CheckFunc[reflect.Value] {
return checkMAC
}

76
v2/mac_test.go Normal file
View file

@ -0,0 +1,76 @@
// Copyright (c) 2023-2024 Onur Cinar.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// https://github.com/cinar/checker
package v2_test
import (
"fmt"
"testing"
v2 "github.com/cinar/checker/v2"
)
func ExampleIsMAC() {
_, err := v2.IsMAC("00:1A:2B:3C:4D:5E")
if err != nil {
fmt.Println(err)
}
}
func TestIsMACInvalid(t *testing.T) {
_, err := v2.IsMAC("invalid-mac")
if err == nil {
t.Fatal("expected error")
}
}
func TestIsMACValid(t *testing.T) {
_, err := v2.IsMAC("00:1A:2B:3C:4D:5E")
if err != nil {
t.Fatal(err)
}
}
func TestCheckMACNonString(t *testing.T) {
defer FailIfNoPanic(t, "expected panic")
type Device struct {
MAC int `checkers:"mac"`
}
device := &Device{}
v2.CheckStruct(device)
}
func TestCheckMACInvalid(t *testing.T) {
type Device struct {
MAC string `checkers:"mac"`
}
device := &Device{
MAC: "invalid-mac",
}
_, ok := v2.CheckStruct(device)
if ok {
t.Fatal("expected error")
}
}
func TestCheckMACValid(t *testing.T) {
type Device struct {
MAC string `checkers:"mac"`
}
device := &Device{
MAC: "00:1A:2B:3C:4D:5E",
}
_, ok := v2.CheckStruct(device)
if !ok {
t.Fatal("expected valid")
}
}

View file

@ -27,6 +27,7 @@ var makers = map[string]MakeCheckFunc{
nameIPv6: makeIPv6,
nameISBN: makeISBN,
nameLUHN: makeLUHN,
nameMAC: makeMAC,
nameMaxLen: makeMaxLen,
nameMinLen: makeMinLen,
nameRequired: makeRequired,