Skip to content

Commit

Permalink
tests and slog
Browse files Browse the repository at this point in the history
  • Loading branch information
otherview committed Dec 30, 2024
1 parent c43af61 commit 0d9199c
Show file tree
Hide file tree
Showing 10 changed files with 63 additions and 27 deletions.
4 changes: 3 additions & 1 deletion .github/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,13 +143,15 @@ The `thorbuilder` package is a key component of the networkHub framework. It sim
### Example Usage:

#### Building the Thor Binary:

```go
package main

import (
"fmt"
"log"
"github.com/vechain/networkhub/thorbuilder"
"log/slog"
)

func main() {
Expand All @@ -165,6 +167,6 @@ func main() {
log.Fatalf("Failed to build binary: %v", err)
}

fmt.Printf("Thor binary built successfully at: %s\n", thorBinaryPath)
slog.Info("Thor binary built successfully at: %s", thorBinaryPath)
}
```
8 changes: 4 additions & 4 deletions cmd/cmd/api.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package cmd

import (
"fmt"
"log/slog"

"github.com/spf13/cobra"
"github.com/vechain/networkhub/entrypoint/api"
Expand All @@ -15,7 +15,7 @@ var apiCmd = &cobra.Command{
Use: "api",
Short: "Starts NetworkHub as an HTTP API server",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("api called")
slog.Info("api called")

envManager := hub.NewNetworkHub()
envManager.RegisterEnvironment("local", local.NewLocalEnv)
Expand All @@ -28,10 +28,10 @@ var apiCmd = &cobra.Command{
httpAPI := api.New(envManager, presets)

if err := httpAPI.Start(); err != nil {
fmt.Println("Shutting down.. Unexpected error in api - %w", err)
slog.Error("Shutting down.. Unexpected error in api - %w", err)
return
}
fmt.Println("Shutting down..")
slog.Info("Shutting down..")
},
}

Expand Down
3 changes: 2 additions & 1 deletion cmd/cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ var startCmd = &cobra.Command{
err := cmdManager.Start(networkID)
if err != nil {
slog.Error("unable to start network", "err", err)
close(sigChan)
return
}
slog.Info("network started successfully...")
Expand Down Expand Up @@ -89,7 +90,7 @@ var configureCmd = &cobra.Command{
// Read from the specified file
data, err := os.ReadFile(args[0])
if err != nil {
fmt.Printf("Error reading config file: %v\n", err)
slog.Error("Error reading config file: %v\n", err)
os.Exit(1)
}

Expand Down
33 changes: 33 additions & 0 deletions cmd/cmd/cmd_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package cmd

import (
"bytes"
"log/slog"
"testing"

"github.com/stretchr/testify/assert"
)

func TestStartCmd(t *testing.T) {
actual := new(bytes.Buffer)

// Override rootCmd's output to the test buffer
rootCmd.SetOut(actual)
rootCmd.SetErr(actual)

// Reconfigure slog to write to the same buffer
logger := slog.New(slog.NewTextHandler(actual, nil))
slog.SetDefault(logger)

// Set the command arguments
rootCmd.SetArgs([]string{"cmd", "start", "testnetwork"})

// Execute the command
err := rootCmd.Execute()

// Assert no error occurred
assert.NoError(t, err)

// Check that the expected message is in the buffer
assert.Contains(t, actual.String(), "network testnetwork is not configured", "Expected output is not found")
}
5 changes: 2 additions & 3 deletions cmd/cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
package cmd

import (
"os"

"github.com/spf13/cobra"
"os"
)

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "netowrkHub",
Use: "networkhub",
Short: "Vechain network launcher",
// Uncomment the following line if your bare application
// has an action associated with it:
Expand Down
5 changes: 3 additions & 2 deletions entrypoint/api/http_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package api
import (
"encoding/json"
"fmt"
"log/slog"
"net/http"
"strings"

Expand All @@ -29,10 +30,10 @@ func (s *Server) Start() error {
http.HandleFunc("/start/", s.startHandler)
http.HandleFunc("/stop/", s.stopHandler)

fmt.Println("Server started on :8080")
slog.Info("Server started on :8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Println("Error starting server:", err)
slog.Error("Error starting server:", err)
}
return nil
}
Expand Down
11 changes: 6 additions & 5 deletions environments/local/local_node.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"log/slog"
"os"
"os/exec"
"path/filepath"
Expand Down Expand Up @@ -93,9 +94,9 @@ func (n *Node) Start() error {
cmd.Args = append(cmd.Args, "--verbosity", strconv.Itoa(n.nodeCfg.GetVerbosity()))
}

fmt.Println(cmd)
slog.Info(cmd.String())
if n.nodeCfg.GetFakeExecution() {
fmt.Println("FakeExecution enabled - Not starting node: ", n.nodeCfg.GetID())
slog.Info("FakeExecution enabled - Not starting node: ", "id", n.nodeCfg.GetID())
return nil
}
// Start the command and check for errors
Expand All @@ -105,7 +106,7 @@ func (n *Node) Start() error {

n.cmdExec = cmd

fmt.Println("Thor command executed successfully")
slog.Info("Thor command executed successfully")
return nil
}

Expand All @@ -130,12 +131,12 @@ func (n *Node) Stop() error {
if err := n.cmdExec.Process.Kill(); err != nil {
return fmt.Errorf("failed to kill process - %w", err)
}
fmt.Println("Process killed as timeout reached")
slog.Error("Process killed as timeout reached")
case err := <-done:
if err != nil {
return fmt.Errorf("process exited with error - %w", err)
}
fmt.Println("Process stopped gracefully")
slog.Info("Process stopped gracefully")
}
return nil
}
7 changes: 4 additions & 3 deletions environments/local/local_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"github.com/vechain/networkhub/thorbuilder"

Check failure on line 6 in environments/local/local_test.go

View workflow job for this annotation

GitHub Actions / Lint / golangci-lint

File is not `goimports`-ed (goimports)
"log/slog"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -145,7 +146,7 @@ func TestLocal(t *testing.T) {
)
require.NoError(t, err)

fmt.Println(networkJSON)
slog.Info(networkJSON)
localEnv := NewLocalEnv()
_, err = localEnv.LoadConfig(networkCfg)
require.NoError(t, err)
Expand All @@ -158,7 +159,7 @@ func TestLocal(t *testing.T) {
account, err := c.GetAccount(datagen.RandAccount().Address)
require.NoError(t, err)

fmt.Println(account)
slog.Info("Account", "acc", account)

time.Sleep(time.Minute)
err = localEnv.StopNetwork()
Expand Down Expand Up @@ -191,7 +192,7 @@ func TestThreeNodes(t *testing.T) {
account, err := c.GetAccount(datagen.RandAccount().Address)
require.NoError(t, err)

fmt.Println(account)
slog.Info("account:", "acc", account)

time.Sleep(30 * time.Second)
err = localEnv.StopNetwork()
Expand Down
9 changes: 3 additions & 6 deletions preset/genesis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package preset

import (
"encoding/json"
"fmt"
"math/big"
"testing"

Expand All @@ -16,15 +15,13 @@ func TestGenesisUnmarshal(t *testing.T) {
}

ble := genesis.HexOrDecimal256(*big.NewInt(123))

bwoop := derp{Hex: &ble}
fmt.Println(bwoop)
t.Log(derp{Hex: &ble})

marshalJSON, err := ble.MarshalJSON()
require.NoError(t, err)
fmt.Println(string(marshalJSON))
t.Log(string(marshalJSON))

marshal, err := json.Marshal(ble)
require.NoError(t, err)
fmt.Println(marshal)
t.Log(marshal)
}
5 changes: 3 additions & 2 deletions thorbuilder/thorbuilder.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package thorbuilder

import (
"fmt"
"log/slog"
"os"
"os/exec"
"path/filepath"
Expand Down Expand Up @@ -32,7 +33,7 @@ func (b *Builder) Download() error {
if b.reusable {
// Check if the folder exists and ensure it contains a cloned repository
if _, err := os.Stat(filepath.Join(b.downloadPath, ".git")); err == nil {
fmt.Printf("Reusable directory with repository exists: %s\n", b.downloadPath)
slog.Info("Reusable directory with repository exists: ", "path", b.downloadPath)
return nil
}
}
Expand All @@ -59,7 +60,7 @@ func (b *Builder) Build() (string, error) {
// Check if the binary exists and if it does return the path
thorBinaryPath := filepath.Join(b.downloadPath, "bin", "thor")
if _, err := os.Stat(thorBinaryPath); err == nil {
fmt.Printf("Reusable binary exists: %s\n", thorBinaryPath)
slog.Info("Reusable binary exists: ", "path", thorBinaryPath)
return thorBinaryPath, nil
}
}
Expand Down

0 comments on commit 0d9199c

Please sign in to comment.