goipgrep: refactor into module; pure-Go ping/resolve; cache+CI; drop binary
This commit is contained in:
54
projects/go-tools/go/goipgrep/internal/cache/cache_test.go
vendored
Normal file
54
projects/go-tools/go/goipgrep/internal/cache/cache_test.go
vendored
Normal file
@@ -0,0 +1,54 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.ktf.ninja/tabledevil/gists/projects/go-tools/go/goipgrep/internal/ipinfo"
|
||||
)
|
||||
|
||||
func TestCacheSaveLoad(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "ipinfo.json")
|
||||
|
||||
s, err := Load(path, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
s.Put("1.2.3.4", ipinfo.Info{IP: "1.2.3.4", Country: "US"})
|
||||
if !s.Changed() {
|
||||
t.Fatalf("expected changed")
|
||||
}
|
||||
if err := s.Save(); err != nil {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
|
||||
s2, err := Load(path, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("Load2: %v", err)
|
||||
}
|
||||
info, ok := s2.Get("1.2.3.4")
|
||||
if !ok || info.Country != "US" {
|
||||
t.Fatalf("Get: ok=%v info=%#v", ok, info)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCacheTTL(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "ipinfo.json")
|
||||
|
||||
// Write a v1 cache with an old fetched_at.
|
||||
b := []byte(`{"version":1,"entries":{"1.2.3.4":{"info":{"ip":"1.2.3.4","country":"US"},"fetched_at":"2000-01-01T00:00:00Z"}}}`)
|
||||
if err := os.WriteFile(path, b, 0o644); err != nil {
|
||||
t.Fatalf("WriteFile: %v", err)
|
||||
}
|
||||
s, err := Load(path, 24*time.Hour, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if _, ok := s.Get("1.2.3.4"); ok {
|
||||
t.Fatalf("expected TTL miss")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user