ooni-probe-cli/internal/fakefill/fakefill_test.go
Simone Basso 93f084598e
feat(httpx): improve testing using the fakefiller (#649)
This diff extracts the fakefiller inside of internal/ooapi (a
currently unused package) into its own package.

The fakefiller knows how to fill many fields that are typically
shared as data structures across processes.

It is not perfect in that it cannot fill logger or http client
fields, but still helps with better filling and testing.

So, here we're using the fakefiller to improve testing of httpx
and, nicely enough, we've already catched a bug in the way in
which APIClientTemplate.Build misses to forward Authorization from
the original template. Yay!

Work part of https://github.com/ooni/probe/issues/1951
2022-01-05 14:49:31 +01:00

92 lines
1.8 KiB
Go

package fakefill
import (
"testing"
"time"
)
// exampleStructure is an example structure we fill.
type exampleStructure struct {
CategoryCodes string
CountryCode string
Enabled bool
MaxResults int64
Now time.Time
}
func TestFakeFillWorksWithCustomTime(t *testing.T) {
var req *exampleStructure
ff := &Filler{
Now: func() time.Time {
return time.Date(1992, time.January, 24, 17, 53, 0, 0, time.UTC)
},
}
ff.Fill(&req)
if req == nil {
t.Fatal("we expected non nil here")
}
}
func TestFakeFillAllocatesIntoAPointerToPointer(t *testing.T) {
var req *exampleStructure
ff := &Filler{}
ff.Fill(&req)
if req == nil {
t.Fatal("we expected non nil here")
}
}
func TestFakeFillAllocatesIntoAMapLikeWithStringKeys(t *testing.T) {
var resp map[string]*exampleStructure
ff := &Filler{}
ff.Fill(&resp)
if resp == nil {
t.Fatal("we expected non nil here")
}
if len(resp) < 1 {
t.Fatal("we expected some data here")
}
for _, value := range resp {
if value == nil {
t.Fatal("expected non-nil here")
}
}
}
func TestFakeFillAllocatesIntoAMapLikeWithNonStringKeys(t *testing.T) {
var panicmsg string
func() {
defer func() {
if v := recover(); v != nil {
panicmsg = v.(string)
}
}()
var resp map[int64]*exampleStructure
ff := &Filler{}
ff.Fill(&resp)
if resp != nil {
t.Fatal("we expected nil here")
}
}()
if panicmsg != "fakefill: we only support string key types" {
t.Fatal("unexpected panic message", panicmsg)
}
}
func TestFakeFillAllocatesIntoASlice(t *testing.T) {
var resp *[]*exampleStructure
ff := &Filler{}
ff.Fill(&resp)
if resp == nil {
t.Fatal("we expected non nil here")
}
if len(*resp) < 1 {
t.Fatal("we expected some data here")
}
for _, entry := range *resp {
if entry == nil {
t.Fatal("expected non-nil here")
}
}
}