2023-01-27 21:37:20 +00:00
|
|
|
// Copyright (c) Tailscale Inc & AUTHORS
|
|
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
2021-07-15 19:43:13 +01:00
|
|
|
|
|
|
|
package speedtest
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"testing"
|
2022-09-15 01:52:47 +01:00
|
|
|
"time"
|
2021-07-15 19:43:13 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestDownload(t *testing.T) {
|
|
|
|
// start a listener and find the port where the server will be listening.
|
|
|
|
l, err := net.Listen("tcp", ":0")
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
t.Cleanup(func() { l.Close() })
|
|
|
|
|
|
|
|
serverIP := l.Addr().String()
|
|
|
|
t.Log("server IP found:", serverIP)
|
|
|
|
|
|
|
|
type state struct {
|
|
|
|
err error
|
|
|
|
}
|
2022-09-15 01:52:47 +01:00
|
|
|
displayResult := func(t *testing.T, r Result, start time.Time) {
|
2021-07-15 19:43:13 +01:00
|
|
|
t.Helper()
|
2022-09-15 01:52:47 +01:00
|
|
|
t.Logf("{ Megabytes: %.2f, Start: %.1f, End: %.1f, Total: %t }", r.MegaBytes(), r.IntervalStart.Sub(start).Seconds(), r.IntervalEnd.Sub(start).Seconds(), r.Total)
|
2021-07-15 19:43:13 +01:00
|
|
|
}
|
|
|
|
stateChan := make(chan state, 1)
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
err := Serve(l)
|
|
|
|
stateChan <- state{err: err}
|
|
|
|
}()
|
|
|
|
|
|
|
|
// ensure that the test returns an appropriate number of Result structs
|
|
|
|
expectedLen := int(DefaultDuration.Seconds()) + 1
|
|
|
|
|
|
|
|
t.Run("download test", func(t *testing.T) {
|
|
|
|
// conduct a download test
|
|
|
|
results, err := RunClient(Download, DefaultDuration, serverIP)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal("download test failed:", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(results) < expectedLen {
|
|
|
|
t.Fatalf("download results: expected length: %d, actual length: %d", expectedLen, len(results))
|
|
|
|
}
|
|
|
|
|
2022-09-15 01:52:47 +01:00
|
|
|
start := results[0].IntervalStart
|
2021-07-15 19:43:13 +01:00
|
|
|
for _, result := range results {
|
2022-09-15 01:52:47 +01:00
|
|
|
displayResult(t, result, start)
|
2021-07-15 19:43:13 +01:00
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("upload test", func(t *testing.T) {
|
|
|
|
// conduct an upload test
|
|
|
|
results, err := RunClient(Upload, DefaultDuration, serverIP)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal("upload test failed:", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(results) < expectedLen {
|
|
|
|
t.Fatalf("upload results: expected length: %d, actual length: %d", expectedLen, len(results))
|
|
|
|
}
|
|
|
|
|
2022-09-15 01:52:47 +01:00
|
|
|
start := results[0].IntervalStart
|
2021-07-15 19:43:13 +01:00
|
|
|
for _, result := range results {
|
2022-09-15 01:52:47 +01:00
|
|
|
displayResult(t, result, start)
|
2021-07-15 19:43:13 +01:00
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
// causes the server goroutine to finish
|
|
|
|
l.Close()
|
|
|
|
|
|
|
|
testState := <-stateChan
|
|
|
|
if testState.err != nil {
|
|
|
|
t.Error("server error:", err)
|
|
|
|
}
|
|
|
|
}
|