rclone/cmd/serve/restic/restic_test.go
Nick Craig-Wood 9df322e889 tests: make test servers choose a random port to make more reliable
Tests have been randomly failing with messages like

    listen tcp 127.0.0.1:51778: bind: address already in use

Rework all the test servers so they choose a random free port on
startup and use that for the tests to avoid.
2019-05-01 16:09:50 +01:00

101 lines
2.2 KiB
Go

// Serve restic tests set up a server and run the integration tests
// for restic against it.
// +build go1.9
package restic
import (
"os"
"os/exec"
"testing"
_ "github.com/ncw/rclone/backend/all"
"github.com/ncw/rclone/cmd/serve/httplib"
"github.com/ncw/rclone/fstest"
"github.com/stretchr/testify/assert"
)
const (
testBindAddress = "localhost:0"
resticSource = "../../../../../restic/restic"
)
// TestRestic runs the restic server then runs the unit tests for the
// restic remote against it.
func TestRestic(t *testing.T) {
_, err := os.Stat(resticSource)
if err != nil {
t.Skipf("Skipping test as restic source not found: %v", err)
}
opt := httplib.DefaultOpt
opt.ListenAddr = testBindAddress
fstest.Initialise()
fremote, _, clean, err := fstest.RandomRemote(*fstest.RemoteName, *fstest.SubDir)
assert.NoError(t, err)
defer clean()
err = fremote.Mkdir("")
assert.NoError(t, err)
// Start the server
w := newServer(fremote, &opt)
assert.NoError(t, w.Serve())
defer func() {
w.Close()
w.Wait()
}()
// Change directory to run the tests
err = os.Chdir(resticSource)
assert.NoError(t, err, "failed to cd to restic source code")
// Run the restic tests
runTests := func(path string) {
args := []string{"test", "./internal/backend/rest", "-run", "TestBackendRESTExternalServer", "-count=1"}
if testing.Verbose() {
args = append(args, "-v")
}
cmd := exec.Command("go", args...)
cmd.Env = append(os.Environ(),
"RESTIC_TEST_REST_REPOSITORY=rest:"+w.Server.URL()+path,
)
out, err := cmd.CombinedOutput()
if len(out) != 0 {
t.Logf("\n----------\n%s----------\n", string(out))
}
assert.NoError(t, err, "Running restic integration tests")
}
// Run the tests with no path
runTests("")
//... and again with a path
runTests("potato/sausage/")
}
func TestMakeRemote(t *testing.T) {
for _, test := range []struct {
in, want string
}{
{"", ""},
{"/", ""},
{"/data", "data"},
{"/data/", "data"},
{"/data/1", "data/1"},
{"/data/12", "data/12/12"},
{"/data/123", "data/12/123"},
{"/data/123/", "data/12/123"},
{"/keys", "keys"},
{"/keys/1", "keys/1"},
{"/keys/12", "keys/12"},
{"/keys/123", "keys/123"},
} {
got := makeRemote(test.in)
assert.Equal(t, test.want, got, test.in)
}
}