dharma/pkg/testutil/testserver.go
Felipe M. 0ef15167d5
All checks were successful
ci/woodpecker/tag/release Pipeline was successful
initial release
2025-05-04 10:49:50 +02:00

79 lines
2.3 KiB
Go

package testutil
import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
)
// StartTestsiteServer starts an HTTP server for the testsite directory
// and returns the server URL and a cleanup function
func StartTestsiteServer() (string, func(), error) {
// Determine the absolute path to the testsite directory
wd, err := os.Getwd()
if err != nil {
return "", nil, fmt.Errorf("failed to get working directory: %v", err)
}
// Navigate up to find the project root
// This assumes the function is called from somewhere within the project
projectRoot := wd
for {
if _, err := os.Stat(filepath.Join(projectRoot, "testsite")); err == nil {
break // Found the testsite directory
}
parent := filepath.Dir(projectRoot)
if parent == projectRoot {
return "", nil, fmt.Errorf("testsite directory not found")
}
projectRoot = parent
}
testsitePath := filepath.Join(projectRoot, "testsite")
if _, err := os.Stat(testsitePath); err != nil {
return "", nil, fmt.Errorf("testsite directory not found: %v", err)
}
// Create a file server for the testsite directory
fileServer := http.FileServer(http.Dir(testsitePath))
// Create a test server to serve the testsite files
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fileServer.ServeHTTP(w, r)
}))
// Return the server URL and a cleanup function
return server.URL, server.Close, nil
}
// GetTestsitePath returns the absolute path to the testsite directory
func GetTestsitePath() (string, error) {
// Determine the absolute path to the testsite directory
wd, err := os.Getwd()
if err != nil {
return "", fmt.Errorf("failed to get working directory: %v", err)
}
// Navigate up to find the project root
// This assumes the function is called from somewhere within the project
projectRoot := wd
for {
if _, err := os.Stat(filepath.Join(projectRoot, "testsite")); err == nil {
break // Found the testsite directory
}
parent := filepath.Dir(projectRoot)
if parent == projectRoot {
return "", fmt.Errorf("testsite directory not found")
}
projectRoot = parent
}
testsitePath := filepath.Join(projectRoot, "testsite")
if _, err := os.Stat(testsitePath); err != nil {
return "", fmt.Errorf("testsite directory not found: %v", err)
}
return testsitePath, nil
}