Skip to content

Commit

Permalink
Add tests
Browse files Browse the repository at this point in the history
Signed-off-by: Rob Best <[email protected]>
  • Loading branch information
ribbybibby committed Mar 16, 2022
1 parent 26bd24f commit d994025
Show file tree
Hide file tree
Showing 9 changed files with 397 additions and 3 deletions.
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ Exports Prometheus metrics for [Dependency Track](https://dependencytrack.org/).

## TODO

- Tests for the client.
- Github Actions workflows for tests and release

## Usage
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ go 1.17

require (
github.com/go-kit/log v0.2.0
github.com/google/go-cmp v0.5.6
github.com/prometheus/client_golang v1.12.1
github.com/prometheus/common v0.32.1
gopkg.in/alecthomas/kingpin.v2 v2.2.6
Expand All @@ -16,7 +17,6 @@ require (
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/go-logfmt/logfmt v0.5.1 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/google/go-cmp v0.5.6 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
Expand Down
61 changes: 61 additions & 0 deletions internal/dependencytrack/client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package dependencytrack

import (
"encoding/json"
"net/http"
"testing"

"github.com/google/go-cmp/cmp"
)

func TestClientRequest(t *testing.T) {
type testSchema struct {
Name string
Parameters []string
}
expectedReqBody := &testSchema{
Name: "foo",
Parameters: []string{"one", "two", "three"},
}
expectedRespBody := &testSchema{
Name: "bar",
Parameters: []string{"apple", "orange", "banana"},
}

client, mux, teardown := setup()
defer teardown()

client.opts.APIKey = "FAKEAPIKEY"

mux.HandleFunc("/foobar", func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("X-Api-Key"); !cmp.Equal(got, "FAKEAPIKEY") {
t.Errorf("Got X-Api-Key header %v, wanted %v", got, "FAKEAPIKEY")
}

if got := r.Header.Get("Content-type"); !cmp.Equal(got, "application/json") {
t.Errorf("Got Content-type header %v, wanted %v", got, "application/json")
}

got := &testSchema{}
if err := json.NewDecoder(r.Body).Decode(got); err != nil {
t.Errorf("Unexpected error decoding request body: %v", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if !cmp.Equal(got, expectedReqBody) {
t.Errorf("Expected request body %v, got %v", expectedReqBody, got)
}

w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(expectedRespBody)
})

req, err := client.newRequest(http.MethodPost, "/foobar", expectedReqBody)
if err != nil {
t.Fatal(err)
}
data := &testSchema{}
if err := client.do(req, data); err != nil {
t.Fatal(err)
}
}
17 changes: 17 additions & 0 deletions internal/dependencytrack/dependency_track_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package dependencytrack

import (
"net/http"
"net/http/httptest"
)

// setup sets up a test HTTP server and a client configured to talk to it
func setup() (client *Client, mux *http.ServeMux, teardown func()) {
mux = http.NewServeMux()

server := httptest.NewServer(mux)

client = New(WithAddress(server.URL))

return client, mux, server.Close
}
1 change: 0 additions & 1 deletion internal/dependencytrack/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ type PortfolioMetrics struct {
// GetCurrentPortfolioMetrics returns the current metrics for the whole
// portfolio
func (c *Client) GetCurrentPortfolioMetrics() (*PortfolioMetrics, error) {

req, err := c.newRequest(http.MethodGet, "/api/v1/metrics/portfolio/current", nil)
if err != nil {
return nil, err
Expand Down
41 changes: 41 additions & 0 deletions internal/dependencytrack/metrics_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package dependencytrack

import (
"fmt"
"net/http"
"testing"

"github.com/google/go-cmp/cmp"
)

// TestGetCurrentPortfolioMetrics tests getting current portfolio metrics
func TestGetCurrentPortfolioMetrics(t *testing.T) {
client, mux, teardown := setup()
defer teardown()

mux.HandleFunc("/api/v1/metrics/portfolio/current", func(w http.ResponseWriter, r *http.Request) {
if got := r.Method; got != http.MethodGet {
t.Errorf("Got request method %v, want %v", got, http.MethodGet)
}
fmt.Fprintf(w,
`
{
"inheritedRiskScore": 2500.42
}
`,
)
})

got, err := client.GetCurrentPortfolioMetrics()
if err != nil {
t.Errorf("GetCurrentPortfolioMetrics returned error: %v", err)
}

want := &PortfolioMetrics{
InheritedRiskScore: 2500.42,
}

if !cmp.Equal(got, want) {
t.Errorf("Got portfolio metrics %v, want %v", got, want)
}
}
148 changes: 148 additions & 0 deletions internal/dependencytrack/policy_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
package dependencytrack

import (
"fmt"
"net/http"
"net/url"
"testing"
"time"

"github.com/google/go-cmp/cmp"
)

// TestGetViolations tests listing policy violations
func TestGetViolations(t *testing.T) {
client, mux, teardown := setup()
defer teardown()

now := time.Now().Truncate(time.Second)

mux.HandleFunc("/api/v1/violation", func(w http.ResponseWriter, r *http.Request) {
if got := r.Method; got != http.MethodGet {
t.Errorf("Got request method %v, want %v", got, http.MethodGet)
}
want := url.Values{}
want.Set("suppressed", "true")
if got := r.URL.Query(); !cmp.Equal(got, want) {
t.Errorf("Got query parameters: %v, want %v", got, want)
}
fmt.Fprintf(w,
`
[
{
"analysis": {
"analysisState": "APPROVED",
"isSuppressed": true
},
"policyCondition": {
"policy": {
"violationState": "WARN"
}
},
"project": {
"name": "foo",
"version": "bar",
"active": true,
"lastBomImport": %d,
"metrics": {
"critical": 0,
"high": 1,
"low": 2,
"medium": 3,
"unassigned": 4,
"inheritedRiskScore": 1240
},
"uuid": "fd1b10b9-678d-4af9-ad8e-877d1f357b03"
},
"type": "SECURITY"
},
{
"policyCondition": {
"policy": {
"violationState": "WARN"
}
},
"project": {
"name": "bar",
"version": "foo",
"active": false,
"metrics": {
"critical": 50,
"high": 25,
"low": 12,
"medium": 6,
"unassigned": 3,
"inheritedRiskScore": 2560.26
},
"uuid": "9b9a702a-a8b4-49fb-bb99-c05c1a8c8d49"
},
"type": "LICENSE"
}
]
`,
now.Unix(),
)
})

got, err := client.GetViolations(true)
if err != nil {
t.Errorf("GetViolations returned error: %v", err)
}

want := []*PolicyViolation{
{
Analysis: &ViolationAnalysis{
AnalysisState: "APPROVED",
IsSuppressed: true,
},
PolicyCondition: PolicyCondition{
Policy: Policy{
ViolationState: "WARN",
},
},
Project: Project{
Name: "foo",
Version: "bar",
Active: true,
LastBomImport: Time{now},
Metrics: ProjectMetrics{
Critical: 0,
High: 1,
Low: 2,
Medium: 3,
Unassigned: 4,
InheritedRiskScore: 1240,
},
UUID: "fd1b10b9-678d-4af9-ad8e-877d1f357b03",
},
Type: "SECURITY",
},
{
PolicyCondition: PolicyCondition{
Policy: Policy{
ViolationState: "WARN",
},
},
Project: Project{
Name: "bar",
Version: "foo",
Active: false,
LastBomImport: Time{},
Metrics: ProjectMetrics{
Critical: 50,
High: 25,
Low: 12,
Medium: 6,
Unassigned: 3,
InheritedRiskScore: 2560.26,
},
UUID: "9b9a702a-a8b4-49fb-bb99-c05c1a8c8d49",
},
Type: "LICENSE",
},
}

if !cmp.Equal(got, want) {
t.Errorf("Got violations %v, want %v", got, want)
}
}
Loading

0 comments on commit d994025

Please sign in to comment.