tracker/http/http_test.go

91 lines
1.9 KiB
Go
Raw Normal View History

2015-01-01 18:02:25 +01:00
// Copyright 2015 The Chihaya Authors. All rights reserved.
2014-07-16 03:07:33 +02:00
// Use of this source code is governed by the BSD 2-Clause license,
// which can be found in the LICENSE file.
package http
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"sort"
2014-07-16 03:07:33 +02:00
"github.com/chihaya/bencode"
2014-07-16 03:07:33 +02:00
"github.com/chihaya/chihaya/config"
2014-07-23 23:30:38 +02:00
"github.com/chihaya/chihaya/stats"
2014-07-17 06:41:59 +02:00
"github.com/chihaya/chihaya/tracker"
2014-07-16 03:07:33 +02:00
)
type params map[string]string
2014-07-16 04:19:44 +02:00
var infoHash = string([]byte{0x89, 0xd4, 0xbc, 0x52, 0x11, 0x16, 0xca, 0x1d, 0x42, 0xa2, 0xf3, 0x0d, 0x1f, 0x27, 0x4d, 0x94, 0xe4, 0x68, 0x1d, 0xaf})
2014-07-16 03:07:33 +02:00
2014-07-23 23:30:38 +02:00
func init() {
stats.DefaultStats = stats.New(config.StatsConfig{})
}
2015-10-11 08:33:05 +02:00
func setupTracker(cfg *config.Config, tkr *tracker.Tracker) (*httptest.Server, error) {
if cfg == nil {
cfg = &config.DefaultConfig
}
if tkr == nil {
var err error
tkr, err = tracker.New(cfg)
if err != nil {
return nil, err
}
2014-07-16 03:07:33 +02:00
}
2014-07-16 04:19:44 +02:00
return createServer(tkr, cfg)
}
2014-07-17 06:41:59 +02:00
func createServer(tkr *tracker.Tracker, cfg *config.Config) (*httptest.Server, error) {
srv := &Server{
config: cfg,
tracker: tkr,
}
return httptest.NewServer(newRouter(srv)), nil
2014-07-16 03:07:33 +02:00
}
func announce(p params, srv *httptest.Server) ([]byte, error) {
values := &url.Values{}
for k, v := range p {
values.Add(k, v)
}
2014-07-16 19:53:42 +02:00
body, _, err := fetchPath(srv.URL + "/announce?" + values.Encode())
return body, err
}
func fetchPath(path string) ([]byte, int, error) {
response, err := http.Get(path)
2014-07-16 03:07:33 +02:00
if err != nil {
2014-07-16 19:53:42 +02:00
return nil, 0, err
2014-07-16 03:07:33 +02:00
}
body, err := ioutil.ReadAll(response.Body)
response.Body.Close()
2014-07-16 19:53:42 +02:00
return body, response.StatusCode, err
2014-07-16 03:07:33 +02:00
}
type peerList bencode.List
func (p peerList) Len() int {
return len(p)
}
func (p peerList) Less(i, j int) bool {
2014-07-16 04:48:04 +02:00
return p[i].(bencode.Dict)["peer id"].(string) < p[j].(bencode.Dict)["peer id"].(string)
}
func (p peerList) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
func sortPeersInResponse(dict bencode.Dict) {
if peers, ok := dict["peers"].(bencode.List); ok {
sort.Stable(peerList(peers))
}
}