first commit

This commit is contained in:
libroot 2026-11-19 04:40:59 +02:00
commit 8c4dcae475
Signed by: libroot
GPG key ID: 2AC68C029EBE9ACE
89 changed files with 24623 additions and 0 deletions

74
tests/main_test.go Normal file
View file

@ -0,0 +1,74 @@
package main
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"
)
// TestFileWriteBudget: a download slower than the server's WriteTimeout still
// completes, because handleFiles replaces that page-sized budget with
// fileWriteBudget. The control - the same slow download with the budget cut
// short - must be truncated, or the test would not be exercising the deadline
// at all.
func TestFileWriteBudget(t *testing.T) {
const size = 64 << 20 // well past the loopback socket buffers
path := filepath.Join(t.TempDir(), "big.pdf")
if err := os.WriteFile(path, bytes.Repeat([]byte("snowchive"), size/9+1)[:size], 0o644); err != nil {
t.Fatal(err)
}
old := fileWriteBudget
defer func() { fileWriteBudget = old }()
// The same two lines handleFiles uses, over a server whose page budget is
// far shorter than the download takes.
ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(fileWriteBudget))
http.ServeFile(w, r, path)
}))
ts.Config.WriteTimeout = 300 * time.Millisecond
ts.Start()
defer ts.Close()
// fetch reads 1 MB at a time with a pause after each chunk, returning the
// bytes received before the body ended.
fetch := func(pause time.Duration) (int64, time.Duration) {
start := time.Now()
resp, err := http.Get(ts.URL)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
var got int64
buf := make([]byte, 1<<20)
for {
n, err := io.ReadFull(resp.Body, buf)
got += int64(n)
if err != nil {
return got, time.Since(start)
}
time.Sleep(pause)
}
}
fileWriteBudget = 30 * time.Second
got, elapsed := fetch(40 * time.Millisecond)
if got != size {
t.Errorf("slow download got %d of %d bytes", got, size)
}
if elapsed < 2*ts.Config.WriteTimeout {
t.Errorf("download took %v: too fast to prove it outlasted the %v WriteTimeout",
elapsed, ts.Config.WriteTimeout)
}
fileWriteBudget = 200 * time.Millisecond
if got, _ := fetch(40 * time.Millisecond); got >= size {
t.Errorf("control: a %v budget did not cut the download (got all %d bytes)",
fileWriteBudget, got)
}
}