Refactor test files for improved readability and consistency

This commit is contained in:
eyedeekay
2025-10-18 22:59:29 -04:00
parent bf44e03d24
commit 374030f564
2 changed files with 189 additions and 187 deletions

View File

@@ -1,129 +1,129 @@
package controller package controller
import ( import (
"fmt" "fmt"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"testing" "testing"
) )
// createTestConfig creates a temporary config file with the given parameters // createTestConfig creates a temporary config file with the given parameters
func createTestConfig(t *testing.T, name, tunnelType, target string, port int) string { func createTestConfig(t *testing.T, name, tunnelType, target string, port int) string {
configDir := t.TempDir() configDir := t.TempDir()
configFile := filepath.Join(configDir, fmt.Sprintf("%s.yaml", name)) configFile := filepath.Join(configDir, fmt.Sprintf("%s.yaml", name))
// YAML format requires tunnels: map with tunnel name as key // YAML format requires tunnels: map with tunnel name as key
configContent := fmt.Sprintf(`tunnels: configContent := fmt.Sprintf(`tunnels:
%s: %s:
name: %s name: %s
type: %s type: %s
interface: 127.0.0.1 interface: 127.0.0.1
port: %d`, name, name, tunnelType, port) port: %d`, name, name, tunnelType, port)
if target != "" { if target != "" {
configContent += fmt.Sprintf(` configContent += fmt.Sprintf(`
target: %s`, target) target: %s`, target)
} }
configContent += "\n" configContent += "\n"
if err := os.WriteFile(configFile, []byte(configContent), 0644); err != nil { if err := os.WriteFile(configFile, []byte(configContent), 0644); err != nil {
t.Fatalf("Failed to write config file: %v", err) t.Fatalf("Failed to write config file: %v", err)
} }
return configFile return configFile
} }
// TestConfigServeHTTPGet tests the GET request for configuration display // TestConfigServeHTTPGet tests the GET request for configuration display
func TestConfigServeHTTPGet(t *testing.T) { func TestConfigServeHTTPGet(t *testing.T) {
configFile := createTestConfig(t, "test-tcp-client", "tcpclient", "example.i2p", 8080) configFile := createTestConfig(t, "test-tcp-client", "tcpclient", "example.i2p", 8080)
cfg, err := NewConfig(configFile) cfg, err := NewConfig(configFile)
if err != nil { if err != nil {
t.Fatalf("Failed to create config: %v", err) t.Fatalf("Failed to create config: %v", err)
} }
req := httptest.NewRequest(http.MethodGet, "/test-tcp-client/config", nil) req := httptest.NewRequest(http.MethodGet, "/test-tcp-client/config", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
cfg.ServeHTTP(w, req) cfg.ServeHTTP(w, req)
if w.Code != http.StatusOK { if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code) t.Errorf("Expected status 200, got %d", w.Code)
} }
body := w.Body.String() body := w.Body.String()
if !strings.Contains(body, "test-tcp-client") { if !strings.Contains(body, "test-tcp-client") {
t.Errorf("Response should contain tunnel name") t.Errorf("Response should contain tunnel name")
} }
} }
// TestConfigServeHTTPPost tests saving configuration changes // TestConfigServeHTTPPost tests saving configuration changes
func TestConfigServeHTTPPost(t *testing.T) { func TestConfigServeHTTPPost(t *testing.T) {
configFile := createTestConfig(t, "test-tcp-client", "tcpclient", "example.i2p", 8080) configFile := createTestConfig(t, "test-tcp-client", "tcpclient", "example.i2p", 8080)
cfg, err := NewConfig(configFile) cfg, err := NewConfig(configFile)
if err != nil { if err != nil {
t.Fatalf("Failed to create config: %v", err) t.Fatalf("Failed to create config: %v", err)
} }
// Test POST request with new config // Test POST request with new config
formData := url.Values{} formData := url.Values{}
formData.Set("host", "localhost") formData.Set("host", "localhost")
formData.Set("port", "9090") formData.Set("port", "9090")
req := httptest.NewRequest(http.MethodPost, "/test-tcp-client/config", strings.NewReader(formData.Encode())) req := httptest.NewRequest(http.MethodPost, "/test-tcp-client/config", strings.NewReader(formData.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
w := httptest.NewRecorder() w := httptest.NewRecorder()
cfg.ServeHTTP(w, req) cfg.ServeHTTP(w, req)
// Should redirect on success // Should redirect on success
if w.Code != http.StatusSeeOther { if w.Code != http.StatusSeeOther {
t.Logf("Response body: %s", w.Body.String()) t.Logf("Response body: %s", w.Body.String())
t.Errorf("Expected status 303 (redirect), got %d", w.Code) t.Errorf("Expected status 303 (redirect), got %d", w.Code)
} }
} }
// TestConfigServeHTTPPostInvalidPort tests validation of invalid port numbers // TestConfigServeHTTPPostInvalidPort tests validation of invalid port numbers
func TestConfigServeHTTPPostInvalidPort(t *testing.T) { func TestConfigServeHTTPPostInvalidPort(t *testing.T) {
configFile := createTestConfig(t, "test-tcp-client", "tcpclient", "example.i2p", 8080) configFile := createTestConfig(t, "test-tcp-client", "tcpclient", "example.i2p", 8080)
cfg, err := NewConfig(configFile) cfg, err := NewConfig(configFile)
if err != nil { if err != nil {
t.Fatalf("Failed to create config: %v", err) t.Fatalf("Failed to create config: %v", err)
} }
testCases := []struct { testCases := []struct {
name string name string
port string port string
wantCode int wantCode int
}{ }{
{"invalid port text", "abc", http.StatusBadRequest}, {"invalid port text", "abc", http.StatusBadRequest},
{"port too low", "0", http.StatusBadRequest}, {"port too low", "0", http.StatusBadRequest},
{"port too high", "99999", http.StatusBadRequest}, {"port too high", "99999", http.StatusBadRequest},
} }
for _, tc := range testCases { for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
formData := url.Values{} formData := url.Values{}
formData.Set("port", tc.port) formData.Set("port", tc.port)
req := httptest.NewRequest(http.MethodPost, "/test-tcp-client/config", strings.NewReader(formData.Encode())) req := httptest.NewRequest(http.MethodPost, "/test-tcp-client/config", strings.NewReader(formData.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
w := httptest.NewRecorder() w := httptest.NewRecorder()
cfg.ServeHTTP(w, req) cfg.ServeHTTP(w, req)
if w.Code != tc.wantCode { if w.Code != tc.wantCode {
t.Errorf("Expected status %d, got %d", tc.wantCode, w.Code) t.Errorf("Expected status %d, got %d", tc.wantCode, w.Code)
} }
}) })
} }
} }
// TestConfigServeHTTPPostWhileRunning tests that config cannot be changed while tunnel is running // TestConfigServeHTTPPostWhileRunning tests that config cannot be changed while tunnel is running
@@ -161,31 +161,31 @@ func TestConfigServeHTTPPostWhileRunning(t *testing.T) {
if !strings.Contains(body, "running") { if !strings.Contains(body, "running") {
t.Errorf("Error message should mention tunnel is running") t.Errorf("Error message should mention tunnel is running")
} }
}// TestNewConfig tests config creation from file } // TestNewConfig tests config creation from file
func TestNewConfig(t *testing.T) { func TestNewConfig(t *testing.T) {
configFile := createTestConfig(t, "test-tcp-client", "tcpclient", "example.i2p", 8080) configFile := createTestConfig(t, "test-tcp-client", "tcpclient", "example.i2p", 8080)
cfg, err := NewConfig(configFile) cfg, err := NewConfig(configFile)
if err != nil { if err != nil {
t.Fatalf("Failed to create config: %v", err) t.Fatalf("Failed to create config: %v", err)
} }
if cfg == nil { if cfg == nil {
t.Fatal("Expected non-nil config") t.Fatal("Expected non-nil config")
} }
if cfg.configPath != configFile { if cfg.configPath != configFile {
t.Errorf("Expected configPath %s, got %s", configFile, cfg.configPath) t.Errorf("Expected configPath %s, got %s", configFile, cfg.configPath)
} }
} }
// TestNewConfigInvalidFile tests handling of invalid config files // TestNewConfigInvalidFile tests handling of invalid config files
func TestNewConfigInvalidFile(t *testing.T) { func TestNewConfigInvalidFile(t *testing.T) {
cfg, err := NewConfig("/nonexistent/path/config.yaml") cfg, err := NewConfig("/nonexistent/path/config.yaml")
if err == nil { if err == nil {
t.Error("Expected error for non-existent file") t.Error("Expected error for non-existent file")
} }
if cfg != nil { if cfg != nil {
t.Error("Expected nil config for non-existent file") t.Error("Expected nil config for non-existent file")
} }
} }

View File

@@ -1,38 +1,38 @@
package controller package controller
import ( import (
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
"strings" "strings"
"testing" "testing"
) )
// TestControllerServeHTTPGet tests the GET request for control page // TestControllerServeHTTPGet tests the GET request for control page
func TestControllerServeHTTPGet(t *testing.T) { func TestControllerServeHTTPGet(t *testing.T) {
configFile := createTestConfig(t, "test-tcp-client", "tcpclient", "example.i2p", 8080) configFile := createTestConfig(t, "test-tcp-client", "tcpclient", "example.i2p", 8080)
controller, err := NewController(configFile) controller, err := NewController(configFile)
if err != nil { if err != nil {
t.Fatalf("Failed to create controller: %v", err) t.Fatalf("Failed to create controller: %v", err)
} }
req := httptest.NewRequest(http.MethodGet, "/test-tcp-client/control", nil) req := httptest.NewRequest(http.MethodGet, "/test-tcp-client/control", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
controller.ServeHTTP(w, req) controller.ServeHTTP(w, req)
if w.Code != http.StatusOK { if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code) t.Errorf("Expected status 200, got %d", w.Code)
} }
body := w.Body.String() body := w.Body.String()
if !strings.Contains(body, "test-tcp-client") { if !strings.Contains(body, "test-tcp-client") {
t.Errorf("Response should contain tunnel name") t.Errorf("Response should contain tunnel name")
} }
if !strings.Contains(body, "stopped") { if !strings.Contains(body, "stopped") {
t.Errorf("Response should show tunnel status") t.Errorf("Response should show tunnel status")
} }
} }
// TestControllerStart tests starting a tunnel via POST // TestControllerStart tests starting a tunnel via POST
@@ -109,86 +109,88 @@ func TestControllerStop(t *testing.T) {
func TestControllerRestart(t *testing.T) { func TestControllerRestart(t *testing.T) {
t.Skip("Skipping test that requires I2P router connection - known i2cp.leaseSetEncType duplicate parameter issue") t.Skip("Skipping test that requires I2P router connection - known i2cp.leaseSetEncType duplicate parameter issue")
configFile := createTestConfig(t, "test-tcp-client", "tcpclient", "example.i2p", 8080)controller, err := NewController(configFile) configFile := createTestConfig(t, "test-tcp-client", "tcpclient", "example.i2p", 8080)
if err != nil {
t.Fatalf("Failed to create controller: %v", err)
}
defer controller.Stop()
// Start tunnel first controller, err := NewController(configFile)
if err := controller.Start(); err != nil { if err != nil {
t.Fatalf("Failed to start tunnel: %v", err) t.Fatalf("Failed to create controller: %v", err)
} }
defer controller.Stop()
formData := url.Values{} // Start tunnel first
formData.Set("action", "Restart") if err := controller.Start(); err != nil {
t.Fatalf("Failed to start tunnel: %v", err)
}
req := httptest.NewRequest(http.MethodPost, "/test-tcp-client/control", strings.NewReader(formData.Encode())) formData := url.Values{}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded") formData.Set("action", "Restart")
w := httptest.NewRecorder()
controller.ServeHTTP(w, req) req := httptest.NewRequest(http.MethodPost, "/test-tcp-client/control", strings.NewReader(formData.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
w := httptest.NewRecorder()
// Should redirect on success controller.ServeHTTP(w, req)
if w.Code != http.StatusSeeOther {
t.Errorf("Expected status 303 (redirect), got %d", w.Code)
}
// Verify tunnel is running after restart // Should redirect on success
status := controller.Status() if w.Code != http.StatusSeeOther {
if status != "running" { t.Errorf("Expected status 303 (redirect), got %d", w.Code)
t.Errorf("Expected tunnel to be running after restart, got status: %s", status) }
}
// Verify tunnel is running after restart
status := controller.Status()
if status != "running" {
t.Errorf("Expected tunnel to be running after restart, got status: %s", status)
}
} }
// TestControllerInvalidAction tests handling of invalid actions // TestControllerInvalidAction tests handling of invalid actions
func TestControllerInvalidAction(t *testing.T) { func TestControllerInvalidAction(t *testing.T) {
configFile := createTestConfig(t, "test-tcp-client", "tcpclient", "example.i2p", 8080) configFile := createTestConfig(t, "test-tcp-client", "tcpclient", "example.i2p", 8080)
controller, err := NewController(configFile) controller, err := NewController(configFile)
if err != nil { if err != nil {
t.Fatalf("Failed to create controller: %v", err) t.Fatalf("Failed to create controller: %v", err)
} }
formData := url.Values{} formData := url.Values{}
formData.Set("action", "InvalidAction") formData.Set("action", "InvalidAction")
req := httptest.NewRequest(http.MethodPost, "/test-tcp-client/control", strings.NewReader(formData.Encode())) req := httptest.NewRequest(http.MethodPost, "/test-tcp-client/control", strings.NewReader(formData.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
w := httptest.NewRecorder() w := httptest.NewRecorder()
controller.ServeHTTP(w, req) controller.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest { if w.Code != http.StatusBadRequest {
t.Errorf("Expected status 400, got %d", w.Code) t.Errorf("Expected status 400, got %d", w.Code)
} }
body := w.Body.String() body := w.Body.String()
if !strings.Contains(body, "Unknown action") { if !strings.Contains(body, "Unknown action") {
t.Errorf("Error message should mention unknown action") t.Errorf("Error message should mention unknown action")
} }
} }
// TestMiniServeHTTP tests the mini control widget rendering // TestMiniServeHTTP tests the mini control widget rendering
func TestMiniServeHTTP(t *testing.T) { func TestMiniServeHTTP(t *testing.T) {
configFile := createTestConfig(t, "test-tcp-client", "tcpclient", "example.i2p", 8080) configFile := createTestConfig(t, "test-tcp-client", "tcpclient", "example.i2p", 8080)
controller, err := NewController(configFile) controller, err := NewController(configFile)
if err != nil { if err != nil {
t.Fatalf("Failed to create controller: %v", err) t.Fatalf("Failed to create controller: %v", err)
} }
req := httptest.NewRequest(http.MethodGet, "/home", nil) req := httptest.NewRequest(http.MethodGet, "/home", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
controller.MiniServeHTTP(w, req) controller.MiniServeHTTP(w, req)
if w.Code != http.StatusOK { if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code) t.Errorf("Expected status 200, got %d", w.Code)
} }
body := w.Body.String() body := w.Body.String()
if !strings.Contains(body, "test-tcp-client") { if !strings.Contains(body, "test-tcp-client") {
t.Errorf("Response should contain tunnel name") t.Errorf("Response should contain tunnel name")
} }
} }