package ip

import (
	"errors"
	"net"
	"reflect"
	"testing"

	"github.com/stretchr/testify/assert"
)

func mockResolver(t *testing.T, expected_name string, ip net.IP, err error) NetInterfaceIPResolver {
	return func(name string) (net.IP, error) {
		assert.Equal(t, expected_name, name)
		return ip, err
	}
}

func TestCache_Get(t *testing.T) {
	tests := []struct {
		name    string
		c       *Cache
		iface   string
		want    net.IP
		wantErr bool
	}{
		{"FromCache", &Cache{resolver: nil, items: map[string]net.IP{"eth0": net.IPv4(10, 4, 0, 1)}}, "eth0", net.IPv4(10, 4, 0, 1), false},
		{"FromResolver", NewCache(mockResolver(t, "eth1", net.IPv4(192, 172, 44, 25), nil)), "eth1", net.IPv4(192, 172, 44, 25), false},
		{"NoInterface", NewCache(mockResolver(t, "eth2", nil, errors.New("Invalid interface"))), "eth2", nil, true},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := tt.c.Get(tt.iface)
			if (err != nil) != tt.wantErr {
				t.Errorf("Cache.Get() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if !reflect.DeepEqual(got, tt.want) {
				t.Errorf("Cache.Get() = %v, want %v", got, tt.want)
			}
		})
	}
}
