package main

import (
	"errors"
	"net"
	"net/http"
	"testing"
	"time"
)

func TestCheckPortAvailable(t *testing.T) {
	port := 19826

	err := checkPortAvailable(port)
	if err != nil {
		t.Fatalf("端口 %d 应该可用: %v", port, err)
	}

	t.Log("端口可用测试通过")
}

func TestCheckPortOccupied(t *testing.T) {
	port := 19827

	listener, err := net.Listen("tcp", ":19827")
	if err != nil {
		t.Fatalf("无法启动测试服务器: %v", err)
	}
	defer listener.Close()

	time.Sleep(100 * time.Millisecond)

	err = checkPortAvailable(port)
	if err == nil {
		t.Fatal("端口被占用时应该返回错误")
	}

	t.Log("端口占用检测测试通过")
}

func TestCheckPortAvailableAfterClose(t *testing.T) {
	port := 19828

	listener, err := net.Listen("tcp", "127.0.0.1:19828")
	if err != nil {
		t.Fatalf("无法启动测试服务器: %v", err)
	}

	server := &http.Server{ReadHeaderTimeout: time.Second}
	defer server.Close()
	go func() {
		err := server.Serve(listener)
		if err != nil && err != http.ErrServerClosed && !errors.Is(err, net.ErrClosed) {
			t.Errorf("serve failed: %v", err)
		}
	}()

	time.Sleep(100 * time.Millisecond)

	listener.Close()
	time.Sleep(100 * time.Millisecond)

	err = checkPortAvailable(port)
	if err != nil {
		t.Fatalf("端口关闭后应该可用: %v", err)
	}

	t.Log("端口关闭后可用测试通过")
}
