ooni-probe-cli/internal/engine/ooapi/internal/generator/fakeapitest.go
Simone Basso 28ce79eff1
feat(ooapi): add toplevel client and simplify API (#248)
* feat(ooapi): add toplevel client and simplify API

This diff should simplify using ooapi from other packages by
adding more abstraction that wraps the existing code.

Part of https://github.com/ooni/probe/issues/1355.

* fix(ooapi): use correct comment for cloners

See https://github.com/ooni/probe-cli/pull/248#discussion_r590663843

* fix(ooapi): make sure the documentation is current

See https://github.com/ooni/probe-cli/pull/248#discussion_r590665773

* fix(ooapi): automate copying APIs

See https://github.com/ooni/probe-cli/pull/248#discussion_r590665837

* feat(ooapi): add unit tests for clientcall.go

See https://github.com/ooni/probe-cli/pull/248#discussion_r590666297

* fix(ooapi): rewrite integration tests to use toplevel API

See https://github.com/ooni/probe-cli/pull/248#discussion_r590665084
2021-03-19 09:30:42 +01:00

59 lines
1.8 KiB
Go

package main
import (
"fmt"
"strings"
"time"
)
func (d *Descriptor) genNewFakeAPI(sb *strings.Builder) {
fmt.Fprintf(sb, "type %s struct {\n", d.FakeAPIStructName())
if d.RequiresLogin {
fmt.Fprintf(sb, "\tWithResult %s\n", d.CallerInterfaceName())
}
fmt.Fprint(sb, "\tErr error\n")
fmt.Fprintf(sb, "\tResponse %s\n", d.ResponseTypeName())
fmt.Fprint(sb, "\tCountCall int32\n")
fmt.Fprint(sb, "}\n\n")
fmt.Fprintf(sb, "func (fapi *%s) Call(ctx context.Context, req %s) (%s, error) {\n",
d.FakeAPIStructName(), d.RequestTypeName(), d.ResponseTypeName())
fmt.Fprint(sb, "\tatomic.AddInt32(&fapi.CountCall, 1)\n")
fmt.Fprint(sb, "\treturn fapi.Response, fapi.Err\n")
fmt.Fprint(sb, "}\n\n")
if d.RequiresLogin {
fmt.Fprintf(sb, "func (fapi *%s) WithToken(token string) %s {\n",
d.FakeAPIStructName(), d.CallerInterfaceName())
fmt.Fprint(sb, "\treturn fapi.WithResult\n")
fmt.Fprint(sb, "}\n\n")
}
fmt.Fprint(sb, "var (\n")
fmt.Fprintf(sb, "\t_ %s = &%s{}\n", d.CallerInterfaceName(),
d.FakeAPIStructName())
if d.RequiresLogin {
fmt.Fprintf(sb, "\t_ %s = &%s{}\n", d.ClonerInterfaceName(),
d.FakeAPIStructName())
}
fmt.Fprint(sb, ")\n\n")
}
// GenFakeAPITestGo generates fakeapi_test.go.
func GenFakeAPITestGo(file string) {
var sb strings.Builder
fmt.Fprint(&sb, "// Code generated by go generate; DO NOT EDIT.\n")
fmt.Fprintf(&sb, "// %s\n\n", time.Now())
fmt.Fprint(&sb, "package ooapi\n\n")
fmt.Fprintf(&sb, "//go:generate go run ./internal/generator -file %s\n\n", file)
fmt.Fprint(&sb, "import (\n")
fmt.Fprint(&sb, "\t\"context\"\n")
fmt.Fprint(&sb, "\t\"sync/atomic\"\n")
fmt.Fprint(&sb, "\n")
fmt.Fprint(&sb, "\t\"github.com/ooni/probe-cli/v3/internal/engine/ooapi/apimodel\"\n")
fmt.Fprint(&sb, ")\n")
for _, desc := range Descriptors {
desc.genNewFakeAPI(&sb)
}
writefile(file, &sb)
}