internal/tls/cert_test.go

package tls

import (
	"log/slog"
	"os"
	"testing"
)

func TestGetLocalIPAddresses(t *testing.T) {
	tests := []struct {
		name       string
		listenAddr string
		wantErr    bool
	}{
		{"empty listen addr", "", false},
		{"all interfaces ipv4", "0.0.0.0", false},
		{"all interfaces ipv6", "::", false},
		{"specific ip", "127.0.0.1", false},
		{"invalid ip", "999.999.999.999", false}, // net.ParseIP returns nil, should handle it
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			ips, err := GetLocalIPAddresses(tt.listenAddr)
			if (err != nil) != tt.wantErr {
				t.Errorf("GetLocalIPAddresses(%v) error = %v, wantErr %v", tt.listenAddr, err, tt.wantErr)
				return
			}
			if len(ips) == 0 {
				t.Errorf("GetLocalIPAddresses(%v) returned no IPs", tt.listenAddr)
			}
		})
	}
}

func TestGenerateSelfSignedCert(t *testing.T) {
	logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
	config := CertConfig{
		Organization: "Test Org",
		Country:      "US",
		Province:     "CA",
		Locality:     "San Francisco",
		CommonName:   "localhost",
	}

	tests := []struct {
		name       string
		listenAddr string
		config     CertConfig
		wantErr    bool
	}{
		{"valid config", "0.0.0.0", config, false},
		{"empty config", "0.0.0.0", CertConfig{}, false},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			cert, err := GenerateSelfSignedCert(tt.listenAddr, tt.config, logger)
			if (err != nil) != tt.wantErr {
				t.Errorf("GenerateSelfSignedCert() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if !tt.wantErr && cert == nil {
				t.Error("GenerateSelfSignedCert() returned nil cert without error")
			}
			if cert != nil {
				if len(cert.Certificate) == 0 {
					t.Error("GenerateSelfSignedCert() returned cert with no data")
				}
				if cert.PrivateKey == nil {
					t.Error("GenerateSelfSignedCert() returned cert with no private key")
				}
			}
		})
	}
}