File: tor_dialer_test.go

package info (click to toggle)
golang-github-cretz-bine 0.2.0%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bookworm-backports, sid, trixie
  • size: 652 kB
  • sloc: makefile: 3
file content (45 lines) | stat: -rw-r--r-- 1,237 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package tests

import (
	"context"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"testing"
	"time"

	"github.com/cretz/bine/tor"
	"golang.org/x/net/context/ctxhttp"
)

func TestDialerSimpleHTTP(t *testing.T) {
	ctx := GlobalEnabledNetworkContext(t)
	httpClient := httpClient(ctx, nil)
	// IsTor check
	byts := httpGet(ctx, httpClient, "https://check.torproject.org/api/ip")
	jsn := map[string]interface{}{}
	ctx.Require.NoError(json.Unmarshal(byts, &jsn))
	ctx.Require.True(jsn["IsTor"].(bool))
}

func httpClient(ctx *TestContext, conf *tor.DialConf) *http.Client {
	// 15 seconds max to dial
	dialCtx, dialCancel := context.WithTimeout(ctx, 15*time.Second)
	defer dialCancel()
	// Make connection
	dialer, err := ctx.Dialer(dialCtx, conf)
	ctx.Require.NoError(err)
	return &http.Client{Transport: &http.Transport{DialContext: dialer.DialContext}}
}

func httpGet(ctx *TestContext, client *http.Client, url string) []byte {
	// We'll give it 30 seconds to respond
	callCtx, callCancel := context.WithTimeout(ctx, 30*time.Second)
	defer callCancel()
	resp, err := ctxhttp.Get(callCtx, client, url)
	ctx.Require.NoError(err)
	defer resp.Body.Close()
	respBytes, err := ioutil.ReadAll(resp.Body)
	ctx.Require.NoError(err)
	return respBytes
}