Skip to content
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
6 changes: 6 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,14 @@ gofmt-api:
gofmt-cli:
gofmt $(GOFMT_ARGS) ./$(CLI_CODE)

# Run tests for modules
modules-test:
cd utils && go test -i . -v
cd utils && go test . -v

# Run all tests
test:
make modules-test
# Install dependencies for TLS
cd $(TLS_DIR) && go test -i . -v
# Run TLS tests
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7
github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
github.com/crewjam/saml v0.0.0-20190508002657-ca21de9dd5b9 h1:fkoDz41YaEsWQOfxO16AsId5KEhxFIniiaJmR7dYBYE=
github.com/crewjam/saml v0.0.0-20190508002657-ca21de9dd5b9/go.mod h1:w5eu+HNtubx+kRpQL6QFT2F3yIFfYVe6+EzOFVU7Hko=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/denisenkom/go-mssqldb v0.0.0-20190423183735-731ef375ac02/go.mod h1:zAg7JM8CkOJ43xKXIj7eRO9kmWm/TW578qo+oDO6tuM=
Expand Down Expand Up @@ -171,9 +172,12 @@ github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnIn
github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE=
github.com/spf13/viper v1.6.2 h1:7aKfF+e8/k68gda3LOjo5RxiUqddoFxVq4BKBPrxk5E=
github.com/spf13/viper v1.6.2/go.mod h1:t3iDnF5Jlj76alVNuyFBk5oUMCvsrkbvZK0WQdfDi5k=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s=
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
Expand Down
2 changes: 2 additions & 0 deletions utils/go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
module github.com/jmpsec/osctrl/utils

go 1.12

require github.com/stretchr/testify v1.5.1
10 changes: 10 additions & 0 deletions utils/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
20 changes: 14 additions & 6 deletions utils/http-utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package utils
import (
"crypto/tls"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
Expand Down Expand Up @@ -74,20 +75,27 @@ func SendRequest(reqType, url string, params io.Reader, headers map[string]strin
return resp.StatusCode, bodyBytes, nil
}

// DebugHTTPDump - Helper for debugging purposes and dump a full HTTP request
func DebugHTTPDump(r *http.Request, debugCheck bool, showBody bool) {
// DebugHTTP - Helper for debugging purposes and dump a full HTTP request
func DebugHTTP(r *http.Request, debugCheck bool, showBody bool) string {
var debug string
if debugCheck {
log.Println("-------------------------------------------------- request")
debug = fmt.Sprintf("%s\n", "---------------- request")
requestDump, err := httputil.DumpRequest(r, showBody)
if err != nil {
log.Printf("error while dumprequest %v", err)
}
log.Println(string(requestDump))
debug += fmt.Sprintf("%s\n", string(requestDump))
if !showBody {
log.Println("---------------- Skipping Request Body -------------------")
debug += fmt.Sprintf("%s\n", "---------------- No Body")
}
log.Println("-------------------------------------------------------end")
debug += fmt.Sprintf("%s\n", "---------------- end")
}
return debug
}

// DebugHTTPDump - Helper for debugging purposes and dump a full HTTP request
func DebugHTTPDump(r *http.Request, debugCheck bool, showBody bool) {
log.Println(DebugHTTP(r, debugCheck, showBody))
}

// HTTPResponse - Helper to send HTTP response
Expand Down
103 changes: 103 additions & 0 deletions utils/http-utils_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package utils

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

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

func TestHTTPResponse(t *testing.T) {
t.Run("json content-type", func(t *testing.T) {
rr := httptest.NewRecorder()
HTTPResponse(rr, JSONApplicationUTF8, http.StatusOK, []byte("JSON Content-Type"))
assert.Equal(t, JSONApplicationUTF8, rr.Header().Get(ContentType))
assert.Equal(t, "JSON Content-Type", rr.Body.String())
})

t.Run("empty content-type", func(t *testing.T) {
rr := httptest.NewRecorder()
HTTPResponse(rr, "", http.StatusOK, []byte("Empty Content-Type"))
assert.Equal(t, "", rr.Header().Get(ContentType))
assert.Equal(t, "Empty Content-Type", rr.Body.String())
})

t.Run("json body", func(t *testing.T) {
rr := httptest.NewRecorder()
type DataJSON struct {
Key1 string `json:"key1"`
Key2 string `json:"key2"`
}
data := DataJSON{
Key1: "value1",
Key2: "value2",
}
HTTPResponse(rr, JSONApplication, http.StatusOK, data)
assert.Equal(t, JSONApplication, rr.Header().Get(ContentType))
assert.Equal(t, `{"key1":"value1","key2":"value2"}`, rr.Body.String())
})
}

func serverMock() *httptest.Server {
handler := http.NewServeMux()
handler.HandleFunc("/server/testing", testingMock)
srv := httptest.NewServer(handler)
return srv
}

func testingMock(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("the test works"))
}

func TestSendRequest(t *testing.T) {
server := serverMock()
defer server.Close()

t.Run("invalid url", func(t *testing.T) {
_, _, err := SendRequest(http.MethodPost, "http://whatever/notfound", nil, map[string]string{})
assert.Error(t, err)
})
t.Run("url not found", func(t *testing.T) {
code, _, err := SendRequest(http.MethodPost, server.URL+"/notfound", nil, map[string]string{})
assert.NoError(t, err)
assert.Equal(t, http.StatusNotFound, code)
})
t.Run("url not found", func(t *testing.T) {
code, body, err := SendRequest(http.MethodPost, server.URL+"/server/testing", nil, map[string]string{})
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, code)
assert.Equal(t, []byte("the test works"), body)
})
}

func TestDebugHTTPDump(t *testing.T) {
t.Run("no debug", func(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, "https://whatever/server/path", nil)
output := DebugHTTP(req, false, false)
assert.Equal(t, ``, output)
})

t.Run("debug no body", func(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, "https://whatever/server/path", nil)
output := DebugHTTP(req, true, false)
expected := fmt.Sprintf("%s\n", "---------------- request")
expected += fmt.Sprintf("%s\r\n", "GET /server/path HTTP/1.1")
expected += fmt.Sprintf("%s\r\n\r\n\n", "Host: whatever")
expected += fmt.Sprintf("%s\n", "---------------- No Body")
expected += fmt.Sprintf("%s\n","---------------- end")
assert.Equal(t, expected, output)
})

t.Run("debug with body", func(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, "https://whatever/server/path", nil)
output := DebugHTTP(req, true, false)
expected := fmt.Sprintf("%s\n", "---------------- request")
expected += fmt.Sprintf("%s\r\n", "GET /server/path HTTP/1.1")
expected += fmt.Sprintf("%s\r\n\r\n\n", "Host: whatever")
expected += fmt.Sprintf("%s\n", "---------------- No Body")
expected += fmt.Sprintf("%s\n","---------------- end")
assert.Equal(t, expected, output)
})
}
11 changes: 7 additions & 4 deletions utils/time-utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ var (
OneMinute = 60 * time.Second
// OneHour - 3600 seconds
OneHour = 60 * time.Minute
// SixHours -
// SixHours - 21600 seconds
SixHours = 6 * time.Hour
// OneDay -
// OneDay - 86400 seconds
OneDay = 24 * time.Hour
// FifteenDays -
// FifteenDays - 1296000 seconds
FifteenDays = 15 * OneDay
)

Expand Down Expand Up @@ -85,8 +85,11 @@ func InFutureTime(t time.Time) string {
}
now := time.Now()
seconds := int(t.Sub(now).Seconds())
if seconds <= 0 {
if seconds <= 2 {
return "Expired"
}
if seconds < DurationSeconds(OneMinute) {
return "Expires in " + strconv.Itoa(seconds) + " seconds"
}
return "Expires in " + StringifyTime(seconds)
}
119 changes: 119 additions & 0 deletions utils/time-utils_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
package utils

import (
"testing"
"time"

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

func TestStringifyTime(t *testing.T) {
assert := assert.New(t)
var tests = []struct {
input int
expected string
}{
{17, ""},
{77, "1 minute"},
{287, "4 minutes"},
{34117, "9 hours"},
{456435277, "5282 days"},
}
for _, test := range tests {
assert.Equal(test.expected, StringifyTime(test.input))
}
}

func TestDurationSeconds(t *testing.T) {
assert := assert.New(t)
var tests = []struct {
input time.Duration
expected int
}{
{60 * time.Second, 60},
{60 * time.Minute, 3600},
{6 * time.Hour, 21600},
{24 * time.Hour, 86400},
{15 * OneDay, 1296000},
}
for _, test := range tests {
assert.Equal(test.expected, DurationSeconds(test.input))
}
}

func TestTimeTimestamp(t *testing.T) {
assert := assert.New(t)
var tests = []struct {
input time.Time
expected string
}{
{time.Date(1999, time.November, 10, 11, 12, 13, 1234, time.UTC), "942232333"},
{time.Date(2009, time.December, 11, 12, 13, 14, 12345, time.UTC), "1260533594"},
{time.Date(2015, time.January, 12, 13, 14, 15, 123456, time.UTC), "1421068455"},
{time.Date(2019, time.September, 17, 17, 17, 17, 17, time.UTC), "1568740637"},
{time.Date(2020, time.February, 29, 23, 59, 0, 0, time.UTC), "1583020740"},
}
for _, test := range tests {
assert.Equal(test.expected, TimeTimestamp(test.input))
}
}

func TestPastFutureTimes(t *testing.T) {
now := time.Now()
assert := assert.New(t)
var tests = []struct {
input time.Time
expected string
}{
{now.Add(-1 * time.Second), "Just Now"},
{now.Add(-57 * time.Second), "57 seconds ago"},
{now.Add(-10 * time.Minute), "10 minutes ago"},
{now.Add(-200 * time.Hour), "8 days ago"},
{time.Date(1999, time.November, 10, 11, 12, 13, 1234, time.UTC), "Since Wed Nov 10 11:12:13 UTC 1999"},
{now.Add(1 * time.Second), "Expired"},
{now.Add(37 * time.Second), "Expires in 36 seconds"},
{now.Add(400 * time.Second), "Expires in 6 minutes"},
{now.Add(77 * time.Hour), "Expires in 3 days"},
{time.Time{}, "Never"},
}
for _, test := range tests {
assert.Equal(test.expected, PastFutureTimes(test.input))
}
}

func TestPastTimeAgo(t *testing.T) {
now := time.Now()
assert := assert.New(t)
var tests = []struct {
input time.Time
expected string
}{
{now.Add(-1 * time.Second), "Just Now"},
{now.Add(-57 * time.Second), "57 seconds ago"},
{now.Add(-10 * time.Minute), "10 minutes ago"},
{now.Add(-200 * time.Hour), "8 days ago"},
{time.Date(1999, time.November, 10, 11, 12, 13, 1234, time.UTC), "Since Wed Nov 10 11:12:13 UTC 1999"},
{time.Time{}, "Never"},
}
for _, test := range tests {
assert.Equal(test.expected, PastTimeAgo(test.input))
}
}

func TestInFutureTime(t *testing.T) {
now := time.Now()
assert := assert.New(t)
var tests = []struct {
input time.Time
expected string
}{
{now.Add(1 * time.Second), "Expired"},
{now.Add(57 * time.Second), "Expires in 56 seconds"},
{now.Add(400 * time.Second), "Expires in 6 minutes"},
{now.Add(77 * time.Hour), "Expires in 3 days"},
{time.Time{}, "Never"},
}
for _, test := range tests {
assert.Equal(test.expected, InFutureTime(test.input))
}
}