test_server.go 2.56 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Copyright 2017 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

17
package http
18 19 20

import (
	"io/ioutil"
21
	"net/http"
22 23 24 25 26 27
	"net/http/httptest"
	"os"
	"testing"

	"github.com/ethereum/go-ethereum/swarm/api"
	"github.com/ethereum/go-ethereum/swarm/storage"
28
	"github.com/ethereum/go-ethereum/swarm/storage/feed"
29 30
)

31 32 33 34
type TestServer interface {
	ServeHTTP(http.ResponseWriter, *http.Request)
}

35
func NewTestSwarmServer(t *testing.T, serverFunc func(*api.API) TestServer, resolver api.Resolver) *TestSwarmServer {
36 37 38 39
	dir, err := ioutil.TempDir("", "swarm-storage-test")
	if err != nil {
		t.Fatal(err)
	}
40 41 42 43 44
	storeparams := storage.NewDefaultLocalStoreParams()
	storeparams.DbCapacity = 5000000
	storeparams.CacheCapacity = 5000
	storeparams.Init(dir)
	localStore, err := storage.NewLocalStore(storeparams, nil)
45 46 47 48
	if err != nil {
		os.RemoveAll(dir)
		t.Fatal(err)
	}
49 50
	fileStore := storage.NewFileStore(localStore, storage.NewFileStoreParams())

51
	// Swarm feeds test setup
52
	feedsDir, err := ioutil.TempDir("", "swarm-feeds-test")
53 54 55
	if err != nil {
		t.Fatal(err)
	}
56

57 58
	rhparams := &feed.HandlerParams{}
	rh, err := feed.NewTestHandler(feedsDir, rhparams)
59 60
	if err != nil {
		t.Fatal(err)
61
	}
62

63
	a := api.NewAPI(fileStore, resolver, rh.Handler, nil)
64
	srv := httptest.NewServer(serverFunc(a))
65 66 67 68 69
	tss := &TestSwarmServer{
		Server:    srv,
		FileStore: fileStore,
		dir:       dir,
		Hasher:    storage.MakeHashFunc(storage.DefaultHash)(),
70 71 72 73
		cleanup: func() {
			srv.Close()
			rh.Close()
			os.RemoveAll(dir)
74
			os.RemoveAll(feedsDir)
75
		},
76
		CurrentTime: 42,
77
	}
78
	feed.TimestampProvider = tss
79
	return tss
80 81 82 83
}

type TestSwarmServer struct {
	*httptest.Server
84 85 86 87 88
	Hasher      storage.SwarmHash
	FileStore   *storage.FileStore
	dir         string
	cleanup     func()
	CurrentTime uint64
89 90 91
}

func (t *TestSwarmServer) Close() {
92
	t.cleanup()
93
}
94

95 96
func (t *TestSwarmServer) Now() feed.Timestamp {
	return feed.Timestamp{Time: t.CurrentTime}
97
}