ooni-probe-cli/internal/cmd/jafar/uncensored/uncensored_test.go
Simone Basso 0fdc9cafb5
fix(all): introduce and use iox.ReadAllContext (#379)
* fix(all): introduce and use iox.ReadAllContext

This improvement over the ioutil.ReadAll utility returns early
if the context expires. This enables us to unblock stuck code in
case there's censorship confounding the TCP stack.

See https://github.com/ooni/probe/issues/1417.

Compared to the functionality postulated in the above mentioned
issue, I choose to be more generic and separate limiting the
maximum body size (not implemented here) from using the context
to return early when reading a body (or any other reader).

After implementing iox.ReadAllContext, I made sure we always
use it everywhere in the tree instead of ioutil.ReadAll.

This includes many parts of the codebase where in theory we don't
need iox.ReadAllContext. Though, changing all the places makes
checking whether we're not using ioutil.ReadAll where we should
not be using it easy: `git grep` should return no lines.

* Update internal/iox/iox_test.go

* fix(ndt7): treat context errors as non-errors

The rationale is explained by the comment documenting reduceErr.

* Update internal/engine/experiment/ndt7/download.go
2021-06-15 11:57:40 +02:00

77 lines
1.6 KiB
Go

package uncensored
import (
"bytes"
"context"
"net/http"
"net/url"
"testing"
"github.com/ooni/probe-cli/v3/internal/iox"
)
func TestGood(t *testing.T) {
client, err := NewClient("dot://1.1.1.1:853")
if err != nil {
t.Fatal(err)
}
defer client.CloseIdleConnections()
if client.Address() != "1.1.1.1:853" {
t.Fatal("invalid address")
}
if client.Network() != "dot" {
t.Fatal("invalid network")
}
ctx := context.Background()
addrs, err := client.LookupHost(ctx, "dns.google")
if err != nil {
t.Fatal(err)
}
var quad8, two8two4 bool
for _, addr := range addrs {
quad8 = quad8 || (addr == "8.8.8.8")
two8two4 = two8two4 || (addr == "8.8.4.4")
}
if quad8 != true && two8two4 != true {
t.Fatal("invalid response")
}
conn, err := client.DialContext(ctx, "tcp", "8.8.8.8:853")
if err != nil {
t.Fatal(err)
}
defer conn.Close()
resp, err := client.RoundTrip(&http.Request{
Method: "GET",
URL: &url.URL{
Scheme: "https",
Host: "www.google.com",
Path: "/humans.txt",
},
Header: http.Header{},
})
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatal("invalid status-code")
}
data, err := iox.ReadAllContext(context.Background(), resp.Body)
if err != nil {
t.Fatal(err)
}
if !bytes.HasPrefix(data, []byte("Google is built by a large team")) {
t.Fatal("not the expected body")
}
}
func TestNewClientFailure(t *testing.T) {
clnt, err := NewClient("antani:///")
if err == nil {
t.Fatal("expected an error here")
}
if clnt != nil {
t.Fatal("expected nil client here")
}
}