Skip to content

feat: add new command to send test data to Observe #113

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Nov 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module github.com/observeinc/observe-agent
go 1.22.7

require (
github.com/jarcoal/httpmock v1.3.1
github.com/observeinc/observe-agent/observecol v0.0.0-00010101000000-000000000000
github.com/prometheus/client_model v0.6.1
github.com/prometheus/common v0.59.1
Expand Down
48 changes: 48 additions & 0 deletions internal/commands/sendtestdata/postdata.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package sendtestdata

import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"

"github.com/spf13/viper"
)

func PostTestData(data any, URL string, headers map[string]string) (string, error) {
postBody, err := json.Marshal(data)
if err != nil {
return "", err
}
client := &http.Client{}
req, err := http.NewRequest("POST", URL, bytes.NewBuffer(postBody))
if err != nil {
return "", err
}
headers["Content-Type"] = "application/json"
for key, value := range headers {
req.Header.Add(key, value)
}
resp, err := client.Do(req)
if err != nil {
return "", err
}
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
bodyString := string(bodyBytes)
if resp.StatusCode != 200 {
return "", fmt.Errorf("sending test data to %s failed with response: %s", URL, bodyString)
}
return bodyString, nil
}

func PostDataToObserve(data any, extraPath string, v *viper.Viper) (string, error) {
collector_url := v.GetString("observe_url")
endpoint := fmt.Sprintf("%s/v1/http%s", strings.TrimRight(collector_url, "/"), extraPath)
authToken := fmt.Sprintf("Bearer %s", v.GetString("token"))
return PostTestData(data, endpoint, map[string]string{"Authorization": authToken})
}
54 changes: 54 additions & 0 deletions internal/commands/sendtestdata/postdata_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package sendtestdata

import (
"testing"

"github.com/jarcoal/httpmock"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah httpmock is the best way to do this!

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

func TestPostTestData(t *testing.T) {
httpmock.Activate()
t.Cleanup(httpmock.DeactivateAndReset)

testURL := "https://example.com/test"
expectedResponse := `{"ok":true}`
// Verify that the data is sent to the expected endpoint along with the bearer and json headers.
httpmock.RegisterMatcherResponder("POST", testURL,
httpmock.BodyContainsString(`"hello":"world"`).And(
httpmock.HeaderIs("Content-Type", "application/json"),
httpmock.HeaderIs("SomeHeader", "some value"),
),
httpmock.NewStringResponder(200, expectedResponse),
)

testData := map[string]string{"hello": "world"}
testHeaders := map[string]string{"SomeHeader": "some value"}
resp, err := PostTestData(testData, testURL, testHeaders)
assert.NoError(t, err)
assert.Equal(t, expectedResponse, resp)
}

func TestPostDataToObserve(t *testing.T) {
httpmock.Activate()
t.Cleanup(httpmock.DeactivateAndReset)

expectedResponse := `{"ok":true}`
// Verify that the data is sent to the expected endpoint along with the bearer and json headers.
httpmock.RegisterMatcherResponder("POST", "https://123456.collect.observe-eng.com/v1/http/test",
httpmock.BodyContainsString(`"hello":"world"`).And(
httpmock.HeaderIs("Content-Type", "application/json"),
httpmock.HeaderIs("Authorization", "Bearer test-token"),
),
httpmock.NewStringResponder(200, expectedResponse),
)

v := viper.New()
v.Set("observe_url", "https://123456.collect.observe-eng.com/")
v.Set("token", "test-token")
testData := map[string]string{"hello": "world"}
resp, err := PostDataToObserve(testData, "/test", v)
assert.NoError(t, err)
assert.Equal(t, expectedResponse, resp)
}
55 changes: 55 additions & 0 deletions internal/commands/sendtestdata/sendtestdata.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
Copyright © 2024 NAME HERE <EMAIL ADDRESS>
*/
package sendtestdata

import (
"encoding/json"
"fmt"

"github.com/observeinc/observe-agent/internal/root"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

const TestDataExtraPath = "/observe-agent/test"

var defaultTestData = map[string]any{
"hello": "world",
}

func NewSendTestDataCmd() *cobra.Command {
return &cobra.Command{
Use: "send-test-data",
Short: "Sends test data to Observe",
Long: "Sends test data to Observe",
RunE: func(cmd *cobra.Command, args []string) error {
var testData map[string]any
dataFlag, _ := cmd.Flags().GetString("data")
if dataFlag != "" {
err := json.Unmarshal([]byte(dataFlag), &testData)
if err != nil {
return err
}
} else {
testData = defaultTestData
}
respBody, err := PostDataToObserve(testData, TestDataExtraPath, viper.GetViper())
if err != nil {
return err
}
fmt.Printf("Successfully sent test data. Saw response: %s\n", respBody)
return nil
},
}
}

func init() {
sendTestDataCmd := NewSendTestDataCmd()
RegisterTestDataFlags(sendTestDataCmd)
root.RootCmd.AddCommand(sendTestDataCmd)
}

func RegisterTestDataFlags(cmd *cobra.Command) {
cmd.Flags().String("data", "", "specify a given json object to send")
}
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
_ "github.com/observeinc/observe-agent/internal/commands/config"
_ "github.com/observeinc/observe-agent/internal/commands/diagnose"
_ "github.com/observeinc/observe-agent/internal/commands/initconfig"
_ "github.com/observeinc/observe-agent/internal/commands/sendtestdata"
_ "github.com/observeinc/observe-agent/internal/commands/start"
_ "github.com/observeinc/observe-agent/internal/commands/status"
_ "github.com/observeinc/observe-agent/internal/commands/version"
Expand Down
22 changes: 22 additions & 0 deletions vendor/github.com/jarcoal/httpmock/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 20 additions & 0 deletions vendor/github.com/jarcoal/httpmock/LICENSE

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading