internal/output/prometheus/textfile_test.go

package prometheus

import (
	"bytes"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"github.com/mercemay/portr/internal/check"
	"github.com/mercemay/portr/internal/check/result"
	"github.com/mercemay/portr/internal/config/target"
)

func TestWrite_text(t *testing.T) {
	rep := check.Report{
		Results: []result.Result{
			result.Success(target.Target{Host: "h", Port: 22, Name: "ssh"}, 5*time.Millisecond, 1),
		},
	}
	var buf bytes.Buffer
	if err := New("").Write(&buf, rep); err != nil {
		t.Fatalf("Write: %v", err)
	}
	out := buf.String()
	if !strings.Contains(out, `portr_target_open{host="h",port="22",name="ssh"} 1`) {
		t.Errorf("missing open metric: %s", out)
	}
	if !strings.Contains(out, "portr_target_latency_seconds") {
		t.Errorf("missing latency metric: %s", out)
	}
}

func TestFlush_atomic(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "portr.prom")
	if err := New(path).Flush(check.Report{}); err != nil {
		t.Fatalf("Flush: %v", err)
	}
	if _, err := os.Stat(path); err != nil {
		t.Errorf("expected %s: %v", path, err)
	}
}