Skip to content

Commit 28f79cf

Browse files
Merge pull request #24 from DataDog/darcy.rayner/improve-testability
Improve ability to run package code in tests
2 parents be5520c + 3599d53 commit 28f79cf

File tree

3 files changed

+76
-2
lines changed

3 files changed

+76
-2
lines changed

ddlambda.go

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ package ddlambda
1010

1111
import (
1212
"context"
13+
"encoding/json"
1314
"fmt"
1415
"net/http"
1516
"os"
@@ -111,14 +112,33 @@ func Metric(metric string, value float64, tags ...string) {
111112

112113
// MetricWithTimestamp sends a distribution metric to DataDog with a custom timestamp
113114
func MetricWithTimestamp(metric string, value float64, timestamp time.Time, tags ...string) {
114-
listener := metrics.GetListener(GetContext())
115+
ctx := GetContext()
116+
117+
if ctx == nil {
118+
logger.Debug("no context available, did you wrap your handler?")
119+
return
120+
}
121+
122+
listener := metrics.GetListener(ctx)
123+
115124
if listener == nil {
116125
logger.Error(fmt.Errorf("couldn't get metrics listener from current context"))
117126
return
118127
}
119128
listener.AddDistributionMetric(metric, value, timestamp, tags...)
120129
}
121130

131+
// InvokeDryRun is a utility to easily run your lambda for testing
132+
func InvokeDryRun(callback func(ctx context.Context), cfg *Config) (interface{}, error) {
133+
wrapped := WrapHandler(callback, cfg)
134+
// Convert the wrapped handler to it's underlying raw handler type
135+
handler, ok := wrapped.(func(ctx context.Context, msg json.RawMessage) (interface{}, error))
136+
if !ok {
137+
logger.Debug("Could not unwrap lambda during dry run")
138+
}
139+
return handler(context.Background(), json.RawMessage("{}"))
140+
}
141+
122142
func (cfg *Config) toMetricsConfig() metrics.Config {
123143

124144
mc := metrics.Config{
@@ -130,6 +150,7 @@ func (cfg *Config) toMetricsConfig() metrics.Config {
130150
mc.ShouldRetryOnFailure = cfg.ShouldRetryOnFailure
131151
mc.APIKey = cfg.APIKey
132152
mc.KMSAPIKey = cfg.KMSAPIKey
153+
mc.Site = cfg.Site
133154
mc.ShouldUseLogForwarder = cfg.ShouldUseLogForwarder
134155
}
135156

@@ -139,7 +160,11 @@ func (cfg *Config) toMetricsConfig() metrics.Config {
139160
if mc.Site == "" {
140161
mc.Site = DefaultSite
141162
}
142-
mc.Site = fmt.Sprintf("https://api.%s/api/v1", mc.Site)
163+
if strings.HasPrefix(mc.Site, "https://") || strings.HasPrefix(mc.Site, "http://") {
164+
mc.Site = fmt.Sprintf("%s/api/v1", mc.Site)
165+
} else {
166+
mc.Site = fmt.Sprintf("https://api.%s/api/v1", mc.Site)
167+
}
143168

144169
if !mc.ShouldUseLogForwarder {
145170
shouldUseLogForwarder := os.Getenv(DatadogShouldUseLogForwarderEnvVar)

ddlambda_test.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
* Unless explicitly stated otherwise all files in this repository are licensed
3+
* under the Apache License Version 2.0.
4+
*
5+
* This product includes software developed at Datadog (https://www.datadoghq.com/).
6+
* Copyright 2019 Datadog, Inc.
7+
*/
8+
package ddlambda
9+
10+
import (
11+
"context"
12+
"net/http"
13+
"net/http/httptest"
14+
"testing"
15+
16+
"github.com/stretchr/testify/assert"
17+
)
18+
19+
func TestInvokeDryRun(t *testing.T) {
20+
called := false
21+
InvokeDryRun(func(ctx context.Context) {
22+
called = true
23+
globalCtx := GetContext()
24+
assert.Equal(t, globalCtx, ctx)
25+
}, nil)
26+
assert.True(t, called)
27+
}
28+
29+
func TestMetricsSilentFailWithoutWrapper(t *testing.T) {
30+
Metric("my-metric", 100, "my:tag")
31+
}
32+
33+
func TestMetricsSubmitWithWrapper(t *testing.T) {
34+
called := false
35+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
36+
called = true
37+
w.WriteHeader(http.StatusCreated)
38+
}))
39+
defer server.Close()
40+
41+
InvokeDryRun(func(ctx context.Context) {
42+
Metric("my-metric", 100, "my:tag")
43+
}, &Config{
44+
APIKey: "abc-123",
45+
Site: server.URL,
46+
})
47+
assert.True(t, called)
48+
}

internal/wrapper/wrap_handler.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ func WrapHandlerWithListeners(handler interface{}, listeners ...HandlerListener)
5151
for _, listener := range listeners {
5252
listener.HandlerFinished(ctx)
5353
}
54+
CurrentContext = nil
5455
return result, err
5556
}
5657
}

0 commit comments

Comments
 (0)