ooni-probe-cli/internal/httpapi/descriptor_test.go
Simone Basso c2ea0b4704
feat(webconnectivity): try all the available THs (#980)
We introduce a fork of internal/httpx, named internal/httpapi, where there is a clear split between the concept of an API endpoint (such as https://0.th.ooni.org/) and of an API descriptor (such as using `GET` to access /api/v1/test-list/url).

Additionally, httpapi allows to create a SequenceCaller that tries to call a given API descriptor using multiple API endpoints. The SequenceCaller will stop once an endpoint works or when all the available endpoints have been tried unsuccessfully.

The definition of "success" is the following: we consider "failure" any error that occurs during the HTTP round trip or when reading the response body. We DO NOT consider "failure" errors (1) when parsing the input URL; (2) when the server returns >= 400; (3) when the server returns a string that does not parse as valid JSON. The idea of this classification of failures is that we ONLY want to retry when we see what looks like a network error that may be caused by (collateral or targeted) censorship.

We take advantage of the availability of this new package and we refactor web_connectivity@v0.4 and web_connectivity@v0.5 to use a SequenceCaller for calling the web connectivity TH API. This means that we will now try all the available THs advertised by the backend rather than just selecting and using the first one provided by the backend.

Because this diff is designed to be backported to the `release/3.16` branch, we have omitted additional changes to always use httpapi where we are currently using httpx. Yet, to remind ourselves about the need to do that, we have deprecated the httpx package. We will rewrite all the code currently using httpx to use httpapi as part of future work.

It is also worth noting that httpapi will allow us to refactor the backend code such that (1) we remove code to select a backend URL endpoint at the beginning and (2) we try several endpoints. The design of the code is such that we can add to the mix some endpoints using as `http.Client` a special client using a tunnel. This will allow us to automatically fallback backend queries.

Closes https://github.com/ooni/probe/issues/2353.

Related to https://github.com/ooni/probe/issues/1519.
2022-11-21 16:28:53 +01:00

249 lines
6.0 KiB
Go

package httpapi
import (
"log"
"net/http"
"net/url"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/ooni/probe-cli/v3/internal/model"
)
func TestDescriptor_WithBodyLogging(t *testing.T) {
type fields struct {
Accept string
Authorization string
ContentType string
LogBody bool
Logger model.Logger
MaxBodySize int64
Method string
RequestBody []byte
Timeout time.Duration
URLPath string
URLQuery url.Values
}
tests := []struct {
name string
fields fields
want *Descriptor
}{{
name: "with empty fields",
fields: fields{}, // LogBody defaults to false
want: &Descriptor{
LogBody: true,
},
}, {
name: "with nonempty fields",
fields: fields{
Accept: "xx",
Authorization: "y",
ContentType: "zzz",
LogBody: false, // obviously must be false
Logger: model.DiscardLogger,
MaxBodySize: 123,
Method: "POST",
RequestBody: []byte("123"),
Timeout: 15555,
URLPath: "/",
URLQuery: map[string][]string{
"a": {"b"},
},
},
want: &Descriptor{
Accept: "xx",
Authorization: "y",
ContentType: "zzz",
LogBody: true,
Logger: model.DiscardLogger,
MaxBodySize: 123,
Method: "POST",
RequestBody: []byte("123"),
Timeout: 15555,
URLPath: "/",
URLQuery: map[string][]string{
"a": {"b"},
},
},
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
desc := &Descriptor{
Accept: tt.fields.Accept,
Authorization: tt.fields.Authorization,
ContentType: tt.fields.ContentType,
LogBody: tt.fields.LogBody,
Logger: tt.fields.Logger,
MaxBodySize: tt.fields.MaxBodySize,
Method: tt.fields.Method,
RequestBody: tt.fields.RequestBody,
Timeout: tt.fields.Timeout,
URLPath: tt.fields.URLPath,
URLQuery: tt.fields.URLQuery,
}
got := desc.WithBodyLogging(true)
if diff := cmp.Diff(tt.want, got); diff != "" {
t.Fatal(diff)
}
})
}
}
func TestNewGetJSONDescriptor(t *testing.T) {
expected := &Descriptor{
Accept: "application/json",
Authorization: "",
ContentType: "",
LogBody: false,
Logger: model.DiscardLogger,
MaxBodySize: DefaultMaxBodySize,
Method: http.MethodGet,
RequestBody: nil,
Timeout: DefaultCallTimeout,
URLPath: "/robots.txt",
URLQuery: url.Values{},
}
got := NewGETJSONDescriptor(model.DiscardLogger, "/robots.txt")
if diff := cmp.Diff(expected, got); diff != "" {
t.Fatal(diff)
}
}
func TestNewGetJSONWithQueryDescriptor(t *testing.T) {
query := url.Values{
"a": {"b"},
"c": {"d"},
}
expected := &Descriptor{
Accept: "application/json",
Authorization: "",
ContentType: "",
LogBody: false,
Logger: model.DiscardLogger,
MaxBodySize: DefaultMaxBodySize,
Method: http.MethodGet,
RequestBody: nil,
Timeout: DefaultCallTimeout,
URLPath: "/robots.txt",
URLQuery: query,
}
got := NewGETJSONWithQueryDescriptor(model.DiscardLogger, "/robots.txt", query)
if diff := cmp.Diff(expected, got); diff != "" {
t.Fatal(diff)
}
}
func TestNewPOSTJSONWithJSONResponseDescriptor(t *testing.T) {
type request struct {
Name string
Age int64
}
t.Run("with failure", func(t *testing.T) {
request := make(chan int64)
got, err := NewPOSTJSONWithJSONResponseDescriptor(model.DiscardLogger, "/robots.txt", request)
if err == nil || err.Error() != "json: unsupported type: chan int64" {
log.Fatal("unexpected err", err)
}
if got != nil {
log.Fatal("expected to get a nil Descriptor")
}
})
t.Run("with success", func(t *testing.T) {
request := request{
Name: "sbs",
Age: 99,
}
expected := &Descriptor{
Accept: "application/json",
Authorization: "",
ContentType: "application/json",
LogBody: false,
Logger: model.DiscardLogger,
MaxBodySize: DefaultMaxBodySize,
Method: http.MethodPost,
RequestBody: []byte(`{"Name":"sbs","Age":99}`),
Timeout: DefaultCallTimeout,
URLPath: "/robots.txt",
URLQuery: nil,
}
got, err := NewPOSTJSONWithJSONResponseDescriptor(model.DiscardLogger, "/robots.txt", request)
if err != nil {
log.Fatal(err)
}
if diff := cmp.Diff(expected, got); diff != "" {
t.Fatal(diff)
}
})
}
func TestMustNewPOSTJSONWithJSONResponseDescriptor(t *testing.T) {
type request struct {
Name string
Age int64
}
t.Run("with failure", func(t *testing.T) {
var panicked bool
func() {
defer func() {
if r := recover(); r != nil {
panicked = true
}
}()
request := make(chan int64)
_ = MustNewPOSTJSONWithJSONResponseDescriptor(model.DiscardLogger, "/robots.txt", request)
}()
if !panicked {
t.Fatal("did not panic")
}
})
t.Run("with success", func(t *testing.T) {
request := request{
Name: "sbs",
Age: 99,
}
expected := &Descriptor{
Accept: "application/json",
Authorization: "",
ContentType: "application/json",
LogBody: false,
Logger: model.DiscardLogger,
MaxBodySize: DefaultMaxBodySize,
Method: http.MethodPost,
RequestBody: []byte(`{"Name":"sbs","Age":99}`),
Timeout: DefaultCallTimeout,
URLPath: "/robots.txt",
URLQuery: nil,
}
got := MustNewPOSTJSONWithJSONResponseDescriptor(model.DiscardLogger, "/robots.txt", request)
if diff := cmp.Diff(expected, got); diff != "" {
t.Fatal(diff)
}
})
}
func TestNewGetResourceDescriptor(t *testing.T) {
expected := &Descriptor{
Accept: "",
Authorization: "",
ContentType: "",
LogBody: false,
Logger: model.DiscardLogger,
MaxBodySize: DefaultMaxBodySize,
Method: http.MethodGet,
RequestBody: nil,
Timeout: DefaultCallTimeout,
URLPath: "/robots.txt",
URLQuery: url.Values{},
}
got := NewGETResourceDescriptor(model.DiscardLogger, "/robots.txt")
if diff := cmp.Diff(expected, got); diff != "" {
t.Fatal(diff)
}
}