package check
import (
"context"
"errors"
"net"
"testing"
"time"
"github.com/mercemay/portr/internal/config"
"github.com/mercemay/portr/internal/config/target"
)
type fakeConn struct{ net.Conn }
func (fakeConn) Close() error { return nil }
func dialOK(_ context.Context, _, _ string) (net.Conn, error) {
return fakeConn{}, nil
}
func dialFail(_ context.Context, _, _ string) (net.Conn, error) {
return nil, errors.New("refused")
}
func TestRun_allOpen(t *testing.T) {
cfg := config.Defaults()
cfg.Targets = []target.Target{
{Host: "a", Port: 1},
{Host: "b", Port: 2},
}
cfg.Retries = 0
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
rep, err := RunWithDial(ctx, cfg, dialOK)
if err != nil {
t.Fatalf("Run: %v", err)
}
open, closed := rep.Summary()
if open != 2 || closed != 0 {
t.Errorf("open=%d closed=%d, want 2/0", open, closed)
}
}
func TestRun_allClosed(t *testing.T) {
cfg := config.Defaults()
cfg.Targets = []target.Target{{Host: "x", Port: 1}}
cfg.Retries = 0
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
rep, _ := RunWithDial(ctx, cfg, dialFail)
open, closed := rep.Summary()
if open != 0 || closed != 1 {
t.Errorf("open=%d closed=%d, want 0/1", open, closed)
}
}
func TestFilterByTag(t *testing.T) {
in := []target.Target{
{Host: "a", Tags: []string{"core"}},
{Host: "b", Tags: []string{"lab"}},
{Host: "c", Tags: []string{"core", "db"}},
}
out := FilterByTag(in, "core")
if len(out) != 2 {
t.Errorf("len=%d, want 2", len(out))
}
if got := FilterByTag(in, ""); len(got) != 3 {
t.Errorf("empty tag should pass all, got %d", len(got))
}
}