mirror of
https://github.com/therootcompany/golib.git
synced 2026-11-04 06:55:00 +00:00
Ensure cohort is never nil: - NewDomainSet stores an empty Cohort before rebuildCohort, so a parse failure leaves an empty (non-nil) cohort instead of nil - Contains uses CompareAndSwap to lazily self-initialise a zero-value struct, making nil impossible after first access — no explicit nil check needed Extract the cache-validity check into a testable cachedCohortValid() helper and add filesPresent() to detect when data files exist on disk. Use strings.Builder in commaify() for efficiency. Tests: - TestPrefixSetContainsZeroValue: zero-value self-heals via CAS, cohort is non-nil after first Contains call - TestCachedCohortValidRequiresFiles: cache invalidation logic
52 lines
1.3 KiB
Go
52 lines
1.3 KiB
Go
package ipgate
|
|
|
|
import (
|
|
"net/netip"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
|
|
"github.com/therootcompany/golib/net/ipcohort"
|
|
)
|
|
|
|
func TestPrefixSetContainsZeroValue(t *testing.T) {
|
|
var ps PrefixSet
|
|
// Zero-value must not panic — Contains self-initialises via CAS.
|
|
if ps.Contains(netip.MustParseAddr("192.0.2.1")) {
|
|
t.Fatal("zero-value PrefixSet must not contain an address")
|
|
}
|
|
// After first call the cohort should be non-nil.
|
|
if ps.cohort.Load() == nil {
|
|
t.Fatal("cohort should be non-nil after Contains")
|
|
}
|
|
}
|
|
|
|
func TestCachedCohortValidRequiresFiles(t *testing.T) {
|
|
dir := t.TempDir()
|
|
present := filepath.Join(dir, "present")
|
|
if err := writeFile(present); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
cohort, err := ipcohort.Parse([]string{"192.0.2.0/24"})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
if !cachedCohortValid(false, cohort, []string{present}) {
|
|
t.Fatal("fresh metadata and present files should use the cache")
|
|
}
|
|
if cachedCohortValid(false, cohort, []string{present, filepath.Join(dir, "gone")}) {
|
|
t.Fatal("missing data file must invalidate the cache")
|
|
}
|
|
if cachedCohortValid(false, nil, []string{present}) {
|
|
t.Fatal("nil cohort must not be used")
|
|
}
|
|
if cachedCohortValid(true, cohort, []string{present}) {
|
|
t.Fatal("updated repo must reload")
|
|
}
|
|
}
|
|
|
|
func writeFile(path string) error {
|
|
return os.WriteFile(path, nil, 0o600)
|
|
}
|