tracker/http/http_test.go

77 lines
1.7 KiB
Go
Raw Normal View History

2014-07-16 03:07:33 +02:00
// Copyright 2014 The Chihaya Authors. All rights reserved.
// 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"
_ "github.com/chihaya/chihaya/drivers/backend/noop"
_ "github.com/chihaya/chihaya/drivers/tracker/memory"
)
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
func setupTracker(cfg *config.Config) (*httptest.Server, error) {
tkr, err := NewTracker(cfg)
if err != nil {
return nil, err
}
2014-07-16 04:19:44 +02:00
return createServer(tkr, cfg)
}
func createServer(tkr *Tracker, cfg *config.Config) (*httptest.Server, error) {
2014-07-16 10:40:51 +02:00
return httptest.NewServer(NewRouter(tkr, cfg)), 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))
}
}