Skip to content

Commit

Permalink
use cobra to make subcommands
Browse files Browse the repository at this point in the history
  • Loading branch information
finn-tbd committed Oct 31, 2023
1 parent d2e7dc7 commit fbbd955
Show file tree
Hide file tree
Showing 4 changed files with 157 additions and 124 deletions.
129 changes: 6 additions & 123 deletions cmd/web5-spec-test/main.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,17 @@
package main

import (
"context"
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
"time"

"github.com/TBD54566975/web5-spec/openapi"
"github.com/TBD54566975/web5-spec/tests"
"github.com/spf13/cobra"
"golang.org/x/exp/slog"
)

var (
nostart = flag.Bool("no-start", false, "when set, the server is not built and is expected to be already running")
nostop = flag.Bool("no-stop", false, "when set, the server is not asked to shut down")
server = flag.String("server", "http://localhost:8080", "url of the server to connect to")

dir string
root = cobra.Command{
Use: "web5-spec",
}

dockerfiles = []string{
".web5-component/test.Dockerfile",
Expand All @@ -29,119 +21,10 @@ var (
)

func main() {
os.Exit(runTests()) // without this weird wrapper thing, the defers wont get called
}

func runTests() int {
flag.Parse()

dir, _ = os.Getwd()
if len(flag.Args()) > 0 {
dir = flag.Arg(0)
}

logger := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug})
slog.SetDefault(slog.New(logger))

if !*nostart {
var dockerfile string
for _, d := range dockerfiles {
candidate := filepath.Join(dir, d)
if _, err := os.Stat(candidate); !os.IsNotExist(err) {
dockerfile = d
}
}

if dockerfile == "" {
slog.Error("no dockerfile found", "paths", dockerfiles)
return 1
}

cmd := docker("build", "-t", "web5-spec:latest", "-f", dockerfile, ".")
if err := cmd.Run(); err != nil {
slog.Error("error building server", "error", err)
return 1
}

cmd = docker("run", "-p", "8080:8080", "--name", "web5-spec", "--rm", "web5-spec:latest")
if err := cmd.Start(); err != nil {
slog.Error("error running server", "error", err)
return 1
}

if !*nostop {
defer func() {
cmd := docker("stop", "web5-spec")
if err := cmd.Run(); err != nil {
slog.Error("error stopping server container", "error", err)
}
}()
}
}

ctx := context.Background()

client, err := openapi.NewClientWithResponses(*server)
if err != nil {
panic(err)
}

var serverID openapi.TestServerID
for {
serverIDResponse, err := client.IdentifySelfWithResponse(ctx)
if err != nil {
slog.Debug("server ID check failed, retrying in 1 second", "err", err)
time.Sleep(time.Second)
continue
}

if serverIDResponse.JSON200 == nil {
slog.Debug("server ID check failed, retrying in 1 second", "status", serverIDResponse.Status(), "body", string(serverIDResponse.Body))
time.Sleep(time.Second)
continue
}

serverID = *serverIDResponse.JSON200
break
}

defer func() {
_, err := client.ServerShutdown(context.Background())
if err != nil {
slog.Error("error shutting down server", "error", err)
}
}()

slog.Debug("server running", "sdk", serverID.Name, "url", serverID.Url)

report := Report{
TestServerID: serverID,
Results: tests.RunTests(*server),
}

fmt.Println()
if txt, err := report.Text(); err != nil {
slog.Error("error generating text report", "error", err)
} else {
fmt.Println(txt)
}
fmt.Println()

stepSummaryFile := os.Getenv("GITHUB_STEP_SUMMARY")
if stepSummaryFile != "" {
if err := report.WriteMarkdown(stepSummaryFile); err != nil {
slog.Error("error writing github step summary", "file", stepSummaryFile, "error", err)
}
}

if !report.IsPassing() {
return 1
}

return 0
root.Execute()
}

func docker(args ...string) *exec.Cmd {
func docker(dir string, args ...string) *exec.Cmd {
cmd := exec.Command("docker", args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
Expand Down
130 changes: 130 additions & 0 deletions cmd/web5-spec-test/test-one.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
package main

import (
"context"
"fmt"
"os"
"path/filepath"
"time"

"github.com/TBD54566975/web5-spec/openapi"
"github.com/TBD54566975/web5-spec/tests"
"github.com/spf13/cobra"
"golang.org/x/exp/slog"
)

var (
testOneCmd = cobra.Command{
Use: "one [dir]",
Run: func(cmd *cobra.Command, args []string) {
dir, _ := os.Getwd()
if len(args) > 0 {
dir = args[0]
}

os.Exit(testOne(dir))
},
}
)

func testOne(dir string) int {
logger := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug})
slog.SetDefault(slog.New(logger))

var dockerfile string
for _, d := range dockerfiles {
candidate := filepath.Join(dir, d)
if _, err := os.Stat(candidate); !os.IsNotExist(err) {
dockerfile = d
}
}

if dockerfile == "" {
slog.Error("no dockerfile found", "paths", dockerfiles)
return 1
}

cmd := docker(dir, "build", "-t", "web5-spec:latest", "-f", dockerfile, ".")
if err := cmd.Run(); err != nil {
slog.Error("error building server", "error", err)
return 1
}

cmd = docker(dir, "run", "-p", "8080:8080", "--name", "web5-spec", "--rm", "web5-spec:latest")
if err := cmd.Start(); err != nil {
slog.Error("error running server", "error", err)
return 1
}

defer func() {
cmd := docker(dir, "stop", "web5-spec")
if err := cmd.Run(); err != nil {
slog.Error("error stopping server container", "error", err)
}
}()

ctx := context.Background()

client, err := openapi.NewClientWithResponses("http://localhost:8080")
if err != nil {
panic(err)
}

var serverID openapi.TestServerID
for {
serverIDResponse, err := client.IdentifySelfWithResponse(ctx)
if err != nil {
slog.Debug("server ID check failed, retrying in 1 second", "err", err)
time.Sleep(time.Second)
continue
}

if serverIDResponse.JSON200 == nil {
slog.Debug("server ID check failed, retrying in 1 second", "status", serverIDResponse.Status(), "body", string(serverIDResponse.Body))
time.Sleep(time.Second)
continue
}

serverID = *serverIDResponse.JSON200
break
}

defer func() {
_, err := client.ServerShutdown(context.Background())
if err != nil {
slog.Error("error shutting down server", "error", err)
}
}()

slog.Debug("server running", "sdk", serverID.Name, "url", serverID.Url)

report := Report{
TestServerID: serverID,
Results: tests.RunTests("http://localhost:8080"),
}

fmt.Println()
if txt, err := report.Text(); err != nil {
slog.Error("error generating text report", "error", err)
} else {
fmt.Println(txt)
}
fmt.Println()

stepSummaryFile := os.Getenv("GITHUB_STEP_SUMMARY")
if stepSummaryFile != "" {
if err := report.WriteMarkdown(stepSummaryFile); err != nil {
slog.Error("error writing github step summary", "file", stepSummaryFile, "error", err)
}
}

if !report.IsPassing() {
return 1
}

return 0
}

func init() {
root.AddCommand(&testOneCmd)
}
6 changes: 5 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,14 @@ go 1.20

require (
github.com/mr-tron/base58 v1.2.0
github.com/spf13/cobra v1.7.0
golang.org/x/exp v0.0.0-20230905200255-921286631fa9
gopkg.in/square/go-jose.v2 v2.6.0
)

require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/stretchr/testify v1.8.4 // indirect
golang.org/x/crypto v0.14.0 // indirect
gopkg.in/square/go-jose.v2 v2.6.0 // indirect
)
16 changes: 16 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,8 +1,24 @@
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/mr-tron/base58 v1.2.0 h1:T/HDJBh4ZCPbU39/+c3rRvE0uKBQlU27+QI8LJ4t64o=
github.com/mr-tron/base58 v1.2.0/go.mod h1:BinMc/sQntlIE1frQmRFPUoPA1Zkr8VRgBdjWI2mNwc=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I=
github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/square/go-jose.v2 v2.6.0 h1:NGk74WTnPKBNUhNzQX7PYcTLUjoq7mzKk2OKbvwk2iI=
gopkg.in/square/go-jose.v2 v2.6.0/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

0 comments on commit fbbd955

Please sign in to comment.