79 lines
2.3 KiB
Go
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
|
|
}
|