vendor: switch to using go1.11 modules

This commit is contained in:
Nick Craig-Wood 2018-08-28 15:27:07 +01:00
parent 5c75453aba
commit da1682a30e
6142 changed files with 390 additions and 5155875 deletions

View file

@ -1,28 +0,0 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
*.prof
vendor
coverage

View file

@ -1,37 +0,0 @@
language: go
go:
- master
- 1.9
- 1.8
- 1.7
- 1.6
cache:
directories:
- ${HOME}/source
before_install:
- pushd ${HOME}/source
- if [[ ! -d "./make-4.0" ]]; then
wget http://ftp.gnu.org/gnu/make/make-4.0.tar.gz &&
tar -vxzf make-4.0.tar.gz &&
pushd make-4.0 && ./configure --prefix=/usr/local && make && popd;
fi
- pushd make-4.0 && sudo make install && popd
- if [[ ! -d "./glide-v0.12.3" ]]; then
wget https://github.com/Masterminds/glide/releases/download/v0.12.3/glide-v0.12.3-linux-amd64.tar.gz &&
tar -vxzf glide-v0.12.3-linux-amd64.tar.gz &&
mv linux-amd64 glide-v0.12.3;
fi
- pushd glide-v0.12.3 && sudo cp glide /usr/local/bin && popd
- popd
- /usr/local/bin/make --version
- /usr/local/bin/glide --version
install:
- go get -u github.com/golang/lint/golint
- glide install
script:
- /usr/local/bin/make check
- /usr/local/bin/make test-coverage

View file

@ -1,61 +0,0 @@
SHELL := /bin/bash
PACKAGE_NAME="github.com/pengsrc/go-shared"
DIRS_TO_CHECK=$(shell ls -d */ | grep -v "vendor")
PKGS_TO_CHECK=$(shell go list ./... | grep -vE "/vendor")
ifneq (${PKG},)
DIRS_TO_CHECK="./${PKG}"
PKGS_TO_CHECK="${PACKAGE_NAME}/${PKG}"
endif
.PHONY: help
help:
@echo "Please use \`make <target>\` where <target> is one of"
@echo " check to vet and lint"
@echo " test to run test"
@echo " test-coverage to run test with coverage"
.PHONY: check
check: format vet lint
.PHONY: format
format:
@gofmt -w .
@echo "Done"
.PHONY: vet
vet:
@echo "Go tool vet, skipping vendor packages"
@go tool vet -all ${DIRS_TO_CHECK}
@echo "Done"
.PHONY: lint
lint:
@echo "Golint, skipping vendor packages"
@lint=$$(for pkg in ${PKGS_TO_CHECK}; do golint $${pkg}; done); \
lint=$$(echo "$${lint}"); \
if [[ -n $${lint} ]]; then echo "$${lint}"; exit 1; fi
@echo "Done"
.PHONY: update
.PHONY: test
test:
@echo "Run test"
@go test -v ${PKGS_TO_CHECK}
@echo "Done"
.PHONY: test-coverage
test-coverage:
@echo "Run test with coverage"
@for pkg in ${PKGS_TO_CHECK}; do \
output="coverage$${pkg#${PACKAGE_NAME}}"; \
mkdir -p $${output}; \
go test -v -cover -coverprofile="$${output}/profile.out" $${pkg}; \
if [[ -e "$${output}/profile.out" ]]; then \
go tool cover -html="$${output}/profile.out" \
-o "$${output}/profile.html"; \
fi; \
done
@echo "Done"

View file

@ -1,19 +0,0 @@
# go-shared
[![Build Status](https://travis-ci.org/pengsrc/go-shared.svg?branch=master)](https://travis-ci.org/pengsrc/go-shared)
[![Go Report Card](https://goreportcard.com/badge/github.com/pengsrc/go-shared)](https://goreportcard.com/report/github.com/pengsrc/go-shared)
[![License](http://img.shields.io/badge/license-apache%20v2-blue.svg)](https://github.com/pengsrc/go-shared/blob/master/LICENSE)
Useful packages for the Go programming language.
## Contributing
1. Fork it ( https://github.com/pengsrc/go-shared/fork )
2. Create your feature branch (`git checkout -b new-feature`)
3. Commit your changes (`git commit -asm 'Add some feature'`)
4. Push to the branch (`git push origin new-feature`)
5. Create a new Pull Request
## License
The Apache License (Version 2.0, January 2004).

View file

@ -1,36 +0,0 @@
package buffer
import (
"sync"
"testing"
"github.com/stretchr/testify/assert"
)
func TestBuffers(t *testing.T) {
const dummyData = "dummy data"
p := NewBytesPool()
var wg sync.WaitGroup
for g := 0; g < 10; g++ {
wg.Add(1)
go func() {
for i := 0; i < 100; i++ {
buf := p.Get()
assert.Zero(t, buf.Len(), "Expected truncated buffer")
assert.NotZero(t, buf.Cap(), "Expected non-zero capacity")
buf.AppendString(dummyData)
assert.Equal(t, buf.Len(), len(dummyData), "Expected buffer to contain dummy data")
buf.Free()
}
wg.Done()
}()
}
wg.Wait()
}
func TestGlobalBytesPool(t *testing.T) {
assert.NotNil(t, GlobalBytesPool())
}

View file

@ -1,76 +0,0 @@
package buffer
import (
"bytes"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/pengsrc/go-shared/convert"
)
func TestBufferWrites(t *testing.T) {
buf := NewBytesPool().Get()
tests := []struct {
desc string
f func()
want string
}{
{"AppendByte", func() { buf.AppendByte('v') }, "v"},
{"AppendBytes", func() { buf.AppendBytes([]byte{'a', 'b', 'c'}) }, "abc"},
{"AppendString", func() { buf.AppendString("foo") }, "foo"},
{"AppendIntPositive", func() { buf.AppendInt(42) }, "42"},
{"AppendIntNegative", func() { buf.AppendInt(-42) }, "-42"},
{"AppendUint", func() { buf.AppendUint(42) }, "42"},
{"AppendBool", func() { buf.AppendBool(true) }, "true"},
{"AppendFloat64", func() { buf.AppendFloat(3.14, 64) }, "3.14"},
// Intentionally introduce some floating-point error.
{"AppendFloat32", func() { buf.AppendFloat(float64(float32(3.14)), 32) }, "3.14"},
{"AppendTime", func() { buf.AppendTime(time.Time{}, convert.ISO8601Milli) }, "0001-01-01T00:00:00.000Z"},
{"AppendWrite", func() { buf.Write([]byte("foo")) }, "foo"},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
buf.Reset()
tt.f()
assert.Equal(t, tt.want, buf.String(), "Unexpected buffer.String().")
assert.Equal(t, tt.want, string(buf.Bytes()), "Unexpected string(buffer.Bytes()).")
assert.Equal(t, len(tt.want), buf.Len(), "Unexpected buffer length.")
// We're not writing more than a kilobyte in tests.
assert.Equal(t, defaultSize, buf.Cap(), "Expected buffer capacity to remain constant.")
})
}
}
func BenchmarkBuffers(b *testing.B) {
// Because we use the strconv.AppendFoo functions so liberally, we can't
// use the standard library's bytes.Buffer anyways (without incurring a
// bunch of extra allocations). Nevertheless, let's make sure that we're
// not losing any precious nanoseconds.
str := strings.Repeat("a", 1024)
slice := make([]byte, 1024)
buf := bytes.NewBuffer(slice)
custom := NewBytesPool().Get()
b.Run("ByteSlice", func(b *testing.B) {
for i := 0; i < b.N; i++ {
slice = append(slice, str...)
slice = slice[:0]
}
})
b.Run("BytesBuffer", func(b *testing.B) {
for i := 0; i < b.N; i++ {
buf.WriteString(str)
buf.Reset()
}
})
b.Run("CustomBuffer", func(b *testing.B) {
for i := 0; i < b.N; i++ {
custom.AppendString(str)
custom.Reset()
}
})
}

View file

@ -1,23 +0,0 @@
package check
import (
"io/ioutil"
"os"
"testing"
"github.com/stretchr/testify/assert"
)
func TestCheckDir(t *testing.T) {
// Path not exist.
assert.Error(t, Dir("/not-exist-dir"))
// Path is not directory.
f, err := ioutil.TempFile(os.TempDir(), "test-check-dir-")
assert.NoError(t, err)
f.Close()
os.Remove(f.Name())
// OK.
assert.NoError(t, Dir(os.TempDir()))
}

View file

@ -1,12 +0,0 @@
package check
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestCheckErrorForExit(t *testing.T) {
ErrorForExit("name", nil)
assert.True(t, true)
}

View file

@ -1,16 +0,0 @@
package check
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestCheckHostAndPort(t *testing.T) {
assert.False(t, HostAndPort("127.0.0.1:80:90"))
assert.False(t, HostAndPort("127.0.0.1"))
assert.False(t, HostAndPort("mysql"))
assert.False(t, HostAndPort("mysql:mysql"))
assert.True(t, HostAndPort("mysql:3306"))
assert.True(t, HostAndPort("172.16.70.50:6379"))
}

View file

@ -1,27 +0,0 @@
package check
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestStringSliceContains(t *testing.T) {
assert.True(t, StringSliceContains([]string{"1", "2", "3"}, "2"))
assert.False(t, StringSliceContains([]string{"1", "2", "3"}, "4"))
}
func TestIntSliceContains(t *testing.T) {
assert.True(t, IntSliceContains([]int{1, 2, 3, 4, 5, 6}, 4))
assert.False(t, IntSliceContains([]int{1, 2, 3, 4, 5, 6}, 7))
}
func TestInt32SliceContains(t *testing.T) {
assert.True(t, Int32SliceContains([]int32{1, 2, 3, 4, 5, 6}, 4))
assert.False(t, Int32SliceContains([]int32{1, 2, 3, 4, 5, 6}, 7))
}
func TestInt64SliceContains(t *testing.T) {
assert.True(t, Int64SliceContains([]int64{1, 2, 3, 4, 5, 6}, 4))
assert.False(t, Int64SliceContains([]int64{1, 2, 3, 4, 5, 6}, 7))
}

View file

@ -1,14 +0,0 @@
package convert
import (
"strings"
"testing"
)
func TestStringSliceWithConverter(t *testing.T) {
s := StringSliceWithConverter([]string{"A", "b", "C"}, strings.ToLower)
e := []string{"a", "b", "c"}
if s[0] != e[0] || s[1] != e[1] || s[2] != e[2] {
t.Errorf("%v != %v", s, e)
}
}

View file

@ -1,107 +0,0 @@
package convert
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestTimeToString(t *testing.T) {
tz, err := time.LoadLocation("Asia/Shanghai")
assert.NoError(t, err)
someTime := time.Date(2016, 9, 1, 15, 30, 0, 500000000, tz)
assert.Equal(t, "Thu, 01 Sep 2016 07:30:00 GMT", TimeToString(someTime, RFC822))
assert.Equal(t, "2016-09-01T07:30:00Z", TimeToString(someTime, ISO8601))
assert.Equal(t, "2016-09-01T07:30:00.500Z", TimeToString(someTime, ISO8601Milli))
assert.Equal(t, "01/Sep/2016:15:30:00 +0800", TimeToString(someTime, NGINXTime))
assert.Equal(t, "01/Sep/2016:07:30:00 +0000", TimeToString(someTime.UTC(), NGINXTime))
}
func TestStringToTime(t *testing.T) {
tz, err := time.LoadLocation("Asia/Shanghai")
assert.NoError(t, err)
someTime := time.Date(2016, 9, 1, 15, 30, 0, 0, tz)
parsedTime, err := StringToTime("Thu, 01 Sep 2016 07:30:00 GMT", RFC822)
assert.NoError(t, err)
assert.Equal(t, someTime.UTC(), parsedTime)
parsedTime, err = StringToTime("2016-09-01T07:30:00Z", ISO8601)
assert.NoError(t, err)
assert.Equal(t, someTime.UTC(), parsedTime)
parsedTime, err = StringToTime("1472715000", ISO8601)
assert.Error(t, err)
assert.Equal(t, time.Time{}, parsedTime)
someTime = time.Date(2016, 9, 1, 15, 30, 0, 500000000, tz)
parsedTime, err = StringToTime("2016-09-01T07:30:00.500Z", ISO8601Milli)
assert.NoError(t, err)
assert.Equal(t, someTime.UTC(), parsedTime)
someTime = time.Date(2016, 9, 1, 15, 30, 0, 0, tz)
parsedTime, err = StringToTime("01/Sep/2016:15:30:00 +0800", NGINXTime)
assert.NoError(t, err)
assert.Equal(t, someTime.UTC(), parsedTime.UTC())
parsedTime, err = StringToTime("01/Sep/2016:07:30:00 +0000", NGINXTime)
assert.NoError(t, err)
assert.Equal(t, someTime.UTC(), parsedTime.UTC())
}
func TestTimeToTimestamp(t *testing.T) {
tz, err := time.LoadLocation("Asia/Shanghai")
assert.NoError(t, err)
someTime := time.Date(2016, 9, 1, 15, 30, 0, 0, tz)
assert.Equal(t, int64(1472715000), TimeToTimestamp(someTime))
}
func TestTimestampToTime(t *testing.T) {
tz, err := time.LoadLocation("Asia/Shanghai")
assert.NoError(t, err)
someTime := time.Date(2016, 9, 1, 15, 30, 0, 0, tz)
assert.Equal(t, someTime.UTC(), TimestampToTime(1472715000))
}
func TestTimestampToTimePointer(t *testing.T) {
tz, err := time.LoadLocation("Asia/Shanghai")
assert.NoError(t, err)
someTime := time.Date(2016, 9, 1, 15, 30, 0, 0, tz).UTC()
assert.Equal(t, &someTime, TimestampToTimePointer(1472715000))
assert.Nil(t, TimestampToTimePointer(0))
}
func TestTimePointerToTimestamp(t *testing.T) {
tz, err := time.LoadLocation("Asia/Shanghai")
assert.NoError(t, err)
unixTime := int64(1472715000)
someTime := time.Date(2016, 9, 1, 15, 30, 0, 0, tz)
assert.Equal(t, unixTime, TimePointerToTimestamp(&someTime))
assert.Equal(t, int64(0), TimePointerToTimestamp(nil))
}
func TestStringToTimestamp(t *testing.T) {
assert.Equal(t, int64(1472715000), StringToTimestamp("Thu, 01 Sep 2016 07:30:00 GMT", RFC822))
assert.Equal(t, int64(-1), StringToTimestamp("2016-09-01T07:30:00.000Z", RFC822))
assert.Equal(t, int64(1472715000), StringToTimestamp("2016-09-01T07:30:00Z", ISO8601))
assert.Equal(t, int64(1472715000), StringToTimestamp("2016-09-01T07:30:00.000Z", ISO8601Milli))
assert.Equal(t, int64(1472715000), StringToTimestamp("2016-09-01T07:30:00.500Z", ISO8601Milli))
assert.Equal(t, int64(1472715000), StringToTimestamp("01/Sep/2016:15:30:00 +0800", NGINXTime))
assert.Equal(t, int64(1472715000), StringToTimestamp("01/Sep/2016:07:30:00 +0000", NGINXTime))
}
func TestTimestampToString(t *testing.T) {
assert.Equal(t, StringToTimestamp("Thu, 01 Sep 2016 07:30:00 GMT", RFC822), int64(1472715000))
assert.Equal(t, StringToTimestamp("2016-09-01T07:30:00.000Z", RFC822), int64(-1))
assert.Equal(t, StringToTimestamp("2016-09-01T07:30:00Z", ISO8601), int64(1472715000))
assert.Equal(t, StringToTimestamp("2016-09-01T07:30:00.000Z", ISO8601Milli), int64(1472715000))
assert.Equal(t, StringToTimestamp("2016-09-01T07:30:00.500Z", ISO8601Milli), int64(1472715000))
assert.Equal(t, StringToTimestamp("01/Sep/2016:15:30:00 +0800", NGINXTime), int64(1472715000))
assert.Equal(t, StringToTimestamp("01/Sep/2016:07:30:00 +0000", NGINXTime), int64(1472715000))
}

View file

@ -1,677 +0,0 @@
package convert
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestStringValue(t *testing.T) {
s := "string"
assert.Equal(t, s, StringValue(String(s)))
assert.Equal(t, "", StringValue(nil))
}
var testCasesStringSlice = [][]string{
{"a", "b", "c", "d", "e"},
{"a", "b", "", "", "e"},
}
func TestStringSlice(t *testing.T) {
for idx, in := range testCasesStringSlice {
if in == nil {
continue
}
out := StringSlice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := StringValueSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
var testCasesStringValueSlice = [][]*string{
{String("a"), String("b"), nil, String("c")},
}
func TestStringValueSlice(t *testing.T) {
for idx, in := range testCasesStringValueSlice {
if in == nil {
continue
}
out := StringValueSlice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
if in[i] == nil {
assert.Empty(t, out[i], "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx)
}
}
out2 := StringSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
for i := range out2 {
if in[i] == nil {
assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx)
}
}
}
}
var testCasesStringMap = []map[string]string{
{"a": "1", "b": "2", "c": "3"},
}
func TestStringMap(t *testing.T) {
for idx, in := range testCasesStringMap {
if in == nil {
continue
}
out := StringMap(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := StringValueMap(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
func TestBoolValue(t *testing.T) {
b := true
assert.Equal(t, b, BoolValue(Bool(b)))
assert.Equal(t, false, BoolValue(nil))
}
var testCasesBoolSlice = [][]bool{
{true, true, false, false},
}
func TestBoolSlice(t *testing.T) {
for idx, in := range testCasesBoolSlice {
if in == nil {
continue
}
out := BoolSlice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := BoolValueSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
var testCasesBoolValueSlice = [][]*bool{}
func TestBoolValueSlice(t *testing.T) {
for idx, in := range testCasesBoolValueSlice {
if in == nil {
continue
}
out := BoolValueSlice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
if in[i] == nil {
assert.Empty(t, out[i], "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx)
}
}
out2 := BoolSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
for i := range out2 {
if in[i] == nil {
assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx)
}
}
}
}
var testCasesBoolMap = []map[string]bool{
{"a": true, "b": false, "c": true},
}
func TestBoolMap(t *testing.T) {
for idx, in := range testCasesBoolMap {
if in == nil {
continue
}
out := BoolMap(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := BoolValueMap(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
func TestIntValue(t *testing.T) {
i := 1024
assert.Equal(t, i, IntValue(Int(i)))
assert.Equal(t, 0, IntValue(nil))
}
var testCasesIntSlice = [][]int{
{1, 2, 3, 4},
}
func TestIntSlice(t *testing.T) {
for idx, in := range testCasesIntSlice {
if in == nil {
continue
}
out := IntSlice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := IntValueSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
var testCasesIntValueSlice = [][]*int{}
func TestIntValueSlice(t *testing.T) {
for idx, in := range testCasesIntValueSlice {
if in == nil {
continue
}
out := IntValueSlice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
if in[i] == nil {
assert.Empty(t, out[i], "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx)
}
}
out2 := IntSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
for i := range out2 {
if in[i] == nil {
assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx)
}
}
}
}
var testCasesIntMap = []map[string]int{
{"a": 3, "b": 2, "c": 1},
}
func TestIntMap(t *testing.T) {
for idx, in := range testCasesIntMap {
if in == nil {
continue
}
out := IntMap(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := IntValueMap(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
func TestInt32Value(t *testing.T) {
i := int32(1024)
assert.Equal(t, i, Int32Value(Int32(i)))
assert.Equal(t, int32(0), Int32Value(nil))
}
var testCasesInt32Slice = [][]int32{
{1, 2, 3, 4},
}
func TestInt32Slice(t *testing.T) {
for idx, in := range testCasesInt32Slice {
if in == nil {
continue
}
out := Int32Slice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := Int32ValueSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
var testCasesInt32ValueSlice = [][]*int32{}
func TestInt32ValueSlice(t *testing.T) {
for idx, in := range testCasesInt32ValueSlice {
if in == nil {
continue
}
out := Int32ValueSlice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
if in[i] == nil {
assert.Empty(t, out[i], "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx)
}
}
out2 := Int32Slice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
for i := range out2 {
if in[i] == nil {
assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx)
}
}
}
}
var testCasesInt32Map = []map[string]int32{
{"a": 3, "b": 2, "c": 1},
}
func TestInt32Map(t *testing.T) {
for idx, in := range testCasesInt32Map {
if in == nil {
continue
}
out := Int32Map(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := Int32ValueMap(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
func TestInt64Value(t *testing.T) {
i := int64(1024)
assert.Equal(t, i, Int64Value(Int64(i)))
assert.Equal(t, int64(0), Int64Value(nil))
}
var testCasesInt64Slice = [][]int64{
{1, 2, 3, 4},
}
func TestInt64Slice(t *testing.T) {
for idx, in := range testCasesInt64Slice {
if in == nil {
continue
}
out := Int64Slice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := Int64ValueSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
var testCasesInt64ValueSlice = [][]*int64{}
func TestInt64ValueSlice(t *testing.T) {
for idx, in := range testCasesInt64ValueSlice {
if in == nil {
continue
}
out := Int64ValueSlice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
if in[i] == nil {
assert.Empty(t, out[i], "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx)
}
}
out2 := Int64Slice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
for i := range out2 {
if in[i] == nil {
assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx)
}
}
}
}
var testCasesInt64Map = []map[string]int64{
{"a": 3, "b": 2, "c": 1},
}
func TestInt64Map(t *testing.T) {
for idx, in := range testCasesInt64Map {
if in == nil {
continue
}
out := Int64Map(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := Int64ValueMap(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
func TestUint8Value(t *testing.T) {
i := uint8(128)
assert.Equal(t, i, Uint8Value(Uint8(i)))
assert.Equal(t, uint8(0), Uint8Value(nil))
}
func TestUint32Value(t *testing.T) {
i := uint32(1024)
assert.Equal(t, i, Uint32Value(Uint32(i)))
assert.Equal(t, uint32(0), Uint32Value(nil))
}
func TestUint64Value(t *testing.T) {
i := uint64(1024)
assert.Equal(t, i, Uint64Value(Uint64(i)))
assert.Equal(t, uint64(0), Uint64Value(nil))
}
var testCasesUint64Slice = [][]uint64{
{1, 2, 3, 4},
}
func TestUint64Slice(t *testing.T) {
for idx, in := range testCasesUint64Slice {
if in == nil {
continue
}
out := Uint64Slice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := Uint64ValueSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
func TestFloat32Value(t *testing.T) {
i := float32(1024)
assert.Equal(t, i, Float32Value(Float32(i)))
assert.Equal(t, float32(0), Float32Value(nil))
}
var testCasesFloat32Slice = [][]float32{
{1, 2, 3, 4},
}
func TestFloat32Slice(t *testing.T) {
for idx, in := range testCasesFloat32Slice {
if in == nil {
continue
}
out := Float32Slice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := Float32ValueSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
var testCasesFloat32ValueSlice = [][]*float32{}
func TestFloat32ValueSlice(t *testing.T) {
for idx, in := range testCasesFloat32ValueSlice {
if in == nil {
continue
}
out := Float32ValueSlice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
if in[i] == nil {
assert.Empty(t, out[i], "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx)
}
}
out2 := Float32Slice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
for i := range out2 {
if in[i] == nil {
assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx)
}
}
}
}
var testCasesFloat32Map = []map[string]float32{
{"a": 3, "b": 2, "c": 1},
}
func TestFloat32Map(t *testing.T) {
for idx, in := range testCasesFloat32Map {
if in == nil {
continue
}
out := Float32Map(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := Float32ValueMap(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
func TestFloat64Value(t *testing.T) {
i := float64(1024)
assert.Equal(t, i, Float64Value(Float64(i)))
assert.Equal(t, float64(0), Float64Value(nil))
}
var testCasesFloat64Slice = [][]float64{
{1, 2, 3, 4},
}
func TestFloat64Slice(t *testing.T) {
for idx, in := range testCasesFloat64Slice {
if in == nil {
continue
}
out := Float64Slice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := Float64ValueSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
var testCasesFloat64ValueSlice = [][]*float64{}
func TestFloat64ValueSlice(t *testing.T) {
for idx, in := range testCasesFloat64ValueSlice {
if in == nil {
continue
}
out := Float64ValueSlice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
if in[i] == nil {
assert.Empty(t, out[i], "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx)
}
}
out2 := Float64Slice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
for i := range out2 {
if in[i] == nil {
assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx)
}
}
}
}
var testCasesFloat64Map = []map[string]float64{
{"a": 3, "b": 2, "c": 1},
}
func TestFloat64Map(t *testing.T) {
for idx, in := range testCasesFloat64Map {
if in == nil {
continue
}
out := Float64Map(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := Float64ValueMap(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
func TestTimeValue(t *testing.T) {
tm := time.Time{}
assert.Equal(t, tm, TimeValue(Time(tm)))
assert.Equal(t, time.Time{}, TimeValue(nil))
}
var testCasesTimeSlice = [][]time.Time{
{time.Now(), time.Now().AddDate(100, 0, 0)},
}
func TestTimeSlice(t *testing.T) {
for idx, in := range testCasesTimeSlice {
if in == nil {
continue
}
out := TimeSlice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := TimeValueSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
var testCasesTimeValueSlice = [][]*time.Time{}
func TestTimeValueSlice(t *testing.T) {
for idx, in := range testCasesTimeValueSlice {
if in == nil {
continue
}
out := TimeValueSlice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
if in[i] == nil {
assert.Empty(t, out[i], "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx)
}
}
out2 := TimeSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
for i := range out2 {
if in[i] == nil {
assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx)
}
}
}
}
var testCasesTimeMap = []map[string]time.Time{
{"a": time.Now().AddDate(-100, 0, 0), "b": time.Now()},
}
func TestTimeMap(t *testing.T) {
for idx, in := range testCasesTimeMap {
if in == nil {
continue
}
out := TimeMap(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := TimeValueMap(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}

View file

@ -1,18 +0,0 @@
hash: 2943a8fbc1720796d8d0a1ba8b1372e04a2bdaa6a4bd9829182a6d29aa330f42
updated: 2017-11-25T10:26:15.990096+08:00
imports:
- name: github.com/Jeffail/gabs
version: 2a3aa15961d5fee6047b8151b67ac2f08ba2c48c
testImports:
- name: github.com/davecgh/go-spew
version: 346938d642f2ec3594ed81d874461961cd0faa76
subpackages:
- spew
- name: github.com/pmezard/go-difflib
version: 792786c7400a136282c1664665ae0a8db921c6c2
subpackages:
- difflib
- name: github.com/stretchr/testify
version: 69483b4bd14f5845b5a1e55bca19e954e827f1d0
subpackages:
- assert

View file

@ -1,11 +0,0 @@
package: github.com/pengsrc/go-shared
testImport:
# Test
- package: github.com/stretchr/testify
version: v1.1.4
- package: github.com/davecgh/go-spew
version: v1.1.0
- package: github.com/pmezard/go-difflib
version: v1.0.0

View file

@ -1,145 +0,0 @@
package log
import (
"context"
"errors"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/pengsrc/go-shared/buffer"
"github.com/pengsrc/go-shared/convert"
)
func TestEventCallerPool(t *testing.T) {
p := NewEventCallerPool()
var wg sync.WaitGroup
for g := 0; g < 10; g++ {
wg.Add(1)
go func() {
for i := 0; i < 100; i++ {
eventCaller := p.Get()
assert.NotNil(t, eventCaller)
eventCaller.Free()
}
wg.Done()
}()
}
wg.Wait()
}
func TestEntryCaller(t *testing.T) {
tests := []struct {
caller *EventCaller
full string
short string
}{
{
caller: newEventCaller(100, "/path/to/foo.go", 42, false),
full: "undefined",
short: "undefined",
},
{
caller: newEventCaller(100, "/path/to/foo.go", 42, true),
full: "/path/to/foo.go:42",
short: "to/foo.go:42",
},
{
caller: newEventCaller(100, "to/foo.go", 42, true),
full: "to/foo.go:42",
short: "to/foo.go:42",
},
}
for _, tt := range tests {
assert.Equal(t, tt.full, tt.caller.String(), "Unexpected string from EntryCaller.")
assert.Equal(t, tt.full, tt.caller.FullPath(), "Unexpected FullPath from EntryCaller.")
assert.Equal(t, tt.short, tt.caller.TrimmedPath(), "Unexpected TrimmedPath from EntryCaller.")
}
}
func TestEventPool(t *testing.T) {
p := NewEventPool()
var wg sync.WaitGroup
for g := 0; g < 10; g++ {
wg.Add(1)
go func() {
for i := 0; i < 100; i++ {
event := p.Get()
assert.NotNil(t, event)
event.Free()
}
wg.Done()
}()
}
wg.Wait()
}
func TestEvent(t *testing.T) {
buf := buffer.GlobalBytesPool().Get()
defer buf.Free()
l, err := NewLogger(buf, "DEBUG")
assert.NoError(t, err)
l.DebugEvent(context.TODO()).Byte("b", 'b').Message("DEBUG b")
assert.Contains(t, buf.String(), "DEBUG b b=b")
t.Log(buf.String())
buf.Reset()
l.DebugEvent(context.TODO()).Bytes("bs", []byte("bs")).Message("DEBUG bs")
l.DebugEvent(context.TODO()).Bytes("bs", []byte("bs bs")).Messagef("DEBUG %s", "bs")
assert.Contains(t, buf.String(), "DEBUG bs bs=bs")
assert.Contains(t, buf.String(), `DEBUG bs bs="bs bs"`)
buf.Reset()
l.DebugEvent(context.TODO()).String("s", "s").Message("DEBUG s")
l.DebugEvent(context.TODO()).String("s", "s s").Messagef("DEBUG %d", 1024)
assert.Contains(t, buf.String(), "DEBUG s s=s")
assert.Contains(t, buf.String(), `DEBUG 1024 s="s s"`)
buf.Reset()
l.InfoEvent(context.TODO()).
Int("i", 1).Int32("i32", int32(2)).Int64("i64", int64(3)).
Messagef("INFO %d", 123)
assert.Contains(t, buf.String(), "INFO 123 i=1 i32=2 i64=3")
buf.Reset()
l.InfoEvent(context.TODO()).
Uint("i", 1).Uint32("i32", uint32(2)).Uint64("i64", uint64(3)).
Messagef("INFO %d", 123)
assert.Contains(t, buf.String(), "INFO 123 i=1 i32=2 i64=3")
buf.Reset()
l.WarnEvent(context.TODO()).
Float32("f32", float32(32.2333)).Float64("f64", float64(64.6444)).
Messagef("WARN %s %d.", "hello", 1024)
assert.Contains(t, buf.String(), "WARN hello 1024. f32=32.2333 f64=64.6444")
buf.Reset()
l.WarnEvent(context.TODO()).
Bool("true", true).Bool("false", false).
Message("WARN bool.")
assert.Contains(t, buf.String(), "WARN bool. true=true false=false")
buf.Reset()
l.ErrorEvent(context.TODO()).
Time("time", time.Time{}, convert.RFC822).Error("error", errors.New("error message")).
Message("Error.")
assert.Contains(t, buf.String(), `Error. time="Mon, 01 Jan 0001 00:00:00 GMT" error="error message"`)
buf.Reset()
l.DebugEvent(context.TODO()).
String("a", "a a").
String("b", "b'b").
String("c", `c"c`).
Message("yes")
assert.Contains(t, buf.String(), `a="a a"`)
assert.Contains(t, buf.String(), `b=b'b`)
assert.Contains(t, buf.String(), `c="c\"c"`)
buf.Reset()
}

View file

@ -1,21 +0,0 @@
package log
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
)
func TestExported(t *testing.T) {
l, err := NewTerminalLogger("DEBUG")
assert.NoError(t, err)
SetGlobalLogger(l)
c := context.Background()
l.Debug(c, "Singleton logger")
assert.NotNil(t, InfoEvent(context.Background()))
Debugf(c, "Debug message test, hi %s", "Apple")
}

View file

@ -1,45 +0,0 @@
package log
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestParseLevel(t *testing.T) {
var l Level
var err error
assert.Equal(t, l, MuteLevel)
assert.NoError(t, err)
l, err = ParseLevel("FATAL")
assert.Equal(t, l, FatalLevel)
assert.NoError(t, err)
l, err = ParseLevel("PANIC")
assert.Equal(t, l, PanicLevel)
assert.NoError(t, err)
l, err = ParseLevel("ERROR")
assert.Equal(t, l, ErrorLevel)
assert.NoError(t, err)
l, err = ParseLevel("WARN")
assert.Equal(t, l, WarnLevel)
assert.NoError(t, err)
l, err = ParseLevel("INFO")
assert.Equal(t, l, InfoLevel)
assert.NoError(t, err)
l, err = ParseLevel("DEBUG")
assert.Equal(t, l, DebugLevel)
assert.NoError(t, err)
l, err = ParseLevel("invalid")
assert.Error(t, err)
}
func TestLevelString(t *testing.T) {
assert.Equal(t, "FATAL", FatalLevel.String())
assert.Equal(t, "PANIC", PanicLevel.String())
assert.Equal(t, "ERROR", ErrorLevel.String())
assert.Equal(t, "WARN", WarnLevel.String())
assert.Equal(t, "INFO", InfoLevel.String())
assert.Equal(t, "DEBUG", DebugLevel.String())
}

View file

@ -1,331 +0,0 @@
package log
import (
"context"
"fmt"
"io/ioutil"
"os"
"path"
"strings"
"syscall"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/pengsrc/go-shared/buffer"
)
func TestSetAndGetLevel(t *testing.T) {
l, err := NewTerminalLogger()
assert.NoError(t, err)
l.SetLevel("ERROR")
assert.Equal(t, "ERROR", l.GetLevel())
}
func TestNewLogger(t *testing.T) {
buf := buffer.GlobalBytesPool().Get()
defer buf.Free()
l, err := NewLogger(buf, "INFO")
assert.NoError(t, err)
l.Debug(context.Background(), "DEBUG message")
l.Info(context.Background(), "INFO message")
assert.NotContains(t, buf.String(), "DEBUG message")
assert.Contains(t, buf.String(), "INFO message")
buf.Reset()
// Test logging for context.
type contextKey string
const traceID contextKey = "trace_id"
ctx := context.WithValue(nil, traceID, "60b725f10c9c85c70d97880dfe8191b3")
l.SetInterestContextKeys([]interface{}{traceID})
l.Info(ctx, "Hello World!")
assert.Contains(t, buf.String(), "trace_id=60b725f10c9c85c70d97880dfe8191b3")
t.Log(buf.String())
buf.Reset()
l.SetCallerFlag(true)
l.Info(ctx, "Hello World!")
assert.Contains(t, buf.String(), "source=log/logger_test.go")
t.Log(buf.String())
buf.Reset()
l.Infof(ctx, "Hello %s!", "World")
assert.Contains(t, buf.String(), "source=log/logger_test.go")
t.Log(buf.String())
buf.Reset()
l.InfoEvent(ctx).Messagef("Hello %s!", "World")
assert.Contains(t, buf.String(), "source=log/logger_test.go")
t.Log(buf.String())
buf.Reset()
l.InfoEvent(ctx).Int("count", 1024).Messagef("Hello %s!", "World")
assert.Contains(t, buf.String(), "source=log/logger_test.go")
t.Log(buf.String())
buf.Reset()
}
func TestNewLoggerWithError(t *testing.T) {
buf := buffer.GlobalBytesPool().Get()
errBuf := buffer.GlobalBytesPool().Get()
defer buf.Free()
defer errBuf.Free()
l, err := NewLoggerWithError(buf, errBuf, "INFO")
assert.NoError(t, err)
l.Debug(context.Background(), "DEBUG message")
l.Info(context.Background(), "INFO message")
l.Error(context.Background(), "ERROR message")
assert.NotContains(t, buf.String(), "DEBUG message")
assert.Contains(t, buf.String(), "INFO message")
assert.Contains(t, buf.String(), "ERROR message")
assert.NotContains(t, errBuf.String(), "DEBUG message")
assert.NotContains(t, errBuf.String(), "INFO message")
assert.Contains(t, errBuf.String(), "ERROR message")
}
func TestNewFileLogger(t *testing.T) {
t.Skip()
lFile := path.Join(os.TempDir(), "test.log")
defer os.Remove(lFile)
// Create logger failed.
_, err := NewLoggerWithError(nil, nil, "DEBUG")
assert.Error(t, err)
_, err = NewLoggerWithError(ioutil.Discard, ioutil.Discard, "INVALID")
assert.Error(t, err)
// Create logger success.
l, err := NewFileLogger(lFile, "INFO")
assert.NoError(t, err)
l.Debug(context.Background(), "file - DEBUG message")
l.Info(context.Background(), "file - INFO message")
l.Warn(context.Background(), "file - WARN message")
l.Error(context.Background(), "file - ERROR message")
data, err := ioutil.ReadFile(lFile)
assert.NoError(t, err)
assert.Equal(t, 4, len(strings.Split(string(data), "\n")))
// Move log file.
movedLFile := fmt.Sprintf(`%s.move`, lFile)
err = os.Rename(lFile, movedLFile)
assert.NoError(t, err)
defer os.Remove(movedLFile)
l.Error(context.Background(), "file - ERROR message")
data, err = ioutil.ReadFile(movedLFile)
assert.NoError(t, err)
assert.Equal(t, 5, len(strings.Split(string(data), "\n")))
// Reopen.
syscall.Kill(syscall.Getpid(), syscall.SIGHUP)
time.Sleep(1 * time.Second)
l.Warn(context.Background(), "file - WARN message")
l.Error(context.Background(), "file - ERROR message")
data, err = ioutil.ReadFile(lFile)
assert.NoError(t, err)
assert.Equal(t, 3, len(strings.Split(string(data), "\n")))
}
func TestNewFileLoggerWithError(t *testing.T) {
t.Skip()
lFile := path.Join(os.TempDir(), "test.log")
errLFile := path.Join(os.TempDir(), "test.log.wf")
defer os.Remove(lFile)
defer os.Remove(errLFile)
// Create logger failed.
_, err := NewFileLoggerWithError("/not/exists/dir", "/not/exists/dir", "DEBUG")
assert.Error(t, err)
_, err = NewFileLoggerWithError(lFile, "/not/exists/dir", "DEBUG")
assert.Error(t, err)
_, err = NewFileLoggerWithError(os.TempDir(), os.TempDir(), "DEBUG")
assert.Error(t, err)
_, err = NewFileLoggerWithError(lFile, os.TempDir(), "DEBUG")
assert.Error(t, err)
// Create logger success.
l, err := NewFileLoggerWithError(lFile, errLFile, "DEBUG")
assert.NoError(t, err)
l.Debug(context.Background(), "file - DEBUG message")
l.Info(context.Background(), "file - INFO message")
l.Warn(context.Background(), "file - WARN message")
l.Error(context.Background(), "file - ERROR message")
data, err := ioutil.ReadFile(lFile)
assert.NoError(t, err)
assert.Equal(t, 5, len(strings.Split(string(data), "\n")))
errLog, err := ioutil.ReadFile(errLFile)
assert.NoError(t, err)
assert.Equal(t, 3, len(strings.Split(string(errLog), "\n")))
// Move data file.
movedLogFile := fmt.Sprintf(`%s.move`, lFile)
err = os.Rename(lFile, movedLogFile)
assert.NoError(t, err)
defer os.Remove(movedLogFile)
movedErrLogFile := fmt.Sprintf(`%s.move`, errLFile)
err = os.Rename(errLFile, movedErrLogFile)
assert.NoError(t, err)
defer os.Remove(movedErrLogFile)
l.Error(context.Background(), "file - ERROR message")
data, err = ioutil.ReadFile(movedLogFile)
assert.NoError(t, err)
assert.Equal(t, 6, len(strings.Split(string(data), "\n")))
errLog, err = ioutil.ReadFile(movedErrLogFile)
assert.NoError(t, err)
assert.Equal(t, 4, len(strings.Split(string(errLog), "\n")))
// Reopen.
syscall.Kill(syscall.Getpid(), syscall.SIGHUP)
time.Sleep(1 * time.Second)
l.Warn(context.Background(), "file - WARN message")
l.Error(context.Background(), "file - ERROR message")
data, err = ioutil.ReadFile(lFile)
assert.NoError(t, err)
assert.Equal(t, 3, len(strings.Split(string(data), "\n")))
errLog, err = ioutil.ReadFile(errLFile)
assert.NoError(t, err)
assert.Equal(t, 3, len(strings.Split(string(errLog), "\n")))
}
func TestBufferedFileLogger(t *testing.T) {
lFile := path.Join(os.TempDir(), "test.log")
defer os.Remove(lFile)
l, err := NewBufferedFileLogger(lFile, 1, "DEBUG")
assert.NoError(t, err)
l.Debug(context.Background(), "file - DEBUG message")
l.Info(context.Background(), "file - INFO message")
l.Warn(context.Background(), "file - WARN message")
l.Error(context.Background(), "file - ERROR message")
data, err := ioutil.ReadFile(lFile)
assert.NoError(t, err)
assert.Equal(t, 1, len(strings.Split(string(data), "\n")))
// Wait timeout.
time.Sleep(2 * time.Second)
data, err = ioutil.ReadFile(lFile)
assert.NoError(t, err)
assert.Equal(t, 5, len(strings.Split(string(data), "\n")))
}
func TestBufferedFileLoggerWithError(t *testing.T) {
lFile := path.Join(os.TempDir(), "test.log")
errLFile := path.Join(os.TempDir(), "test.log.wf")
defer os.Remove(lFile)
defer os.Remove(errLFile)
// Create logger failed.
_, err := NewBufferedFileLoggerWithError("/not/exists/dir", "/not/exists/dir", 0, "DEBUG")
assert.Error(t, err)
_, err = NewBufferedFileLoggerWithError(lFile, "/not/exists/dir", 0, "DEBUG")
assert.Error(t, err)
_, err = NewBufferedFileLoggerWithError(os.TempDir(), os.TempDir(), 0, "DEBUG")
assert.Error(t, err)
_, err = NewBufferedFileLoggerWithError(lFile, os.TempDir(), 0, "DEBUG")
assert.Error(t, err)
// Create logger success.
errL, err := NewBufferedFileLoggerWithError(lFile, errLFile, 1, "DEBUG")
assert.NoError(t, err)
errL.Debug(context.Background(), "file - DEBUG message")
errL.Info(context.Background(), "file - INFO message")
errL.Warn(context.Background(), "file - WARN message")
errL.Error(context.Background(), "file - ERROR message")
data, err := ioutil.ReadFile(lFile)
assert.NoError(t, err)
assert.Equal(t, 1, len(strings.Split(string(data), "\n")))
errData, err := ioutil.ReadFile(errLFile)
assert.NoError(t, err)
assert.Equal(t, 1, len(strings.Split(string(errData), "\n")))
// Flush log.
errL.Flush()
data, err = ioutil.ReadFile(lFile)
assert.NoError(t, err)
assert.Equal(t, 5, len(strings.Split(string(data), "\n")))
errData, err = ioutil.ReadFile(errLFile)
assert.NoError(t, err)
assert.Equal(t, 3, len(strings.Split(string(errData), "\n")))
// Wait timeout to improve test coverage.
time.Sleep(2 * time.Second)
// Reopen using signal to improve test coverage.
syscall.Kill(syscall.Getpid(), syscall.SIGHUP)
}
func TestTerminalLogger(t *testing.T) {
l, err := NewTerminalLogger("DEBUG")
assert.NoError(t, err)
l.Debug(context.Background(), "terminal - DEBUG message")
l.Info(context.Background(), "terminal - INFO message")
l.Warn(context.Background(), "terminal - WARN message")
l.Error(context.Background(), "terminal - ERROR message")
l.Debugf(context.Background(), "terminal - DEBUG message - %d", time.Now().Unix())
l.Infof(context.Background(), "terminal - INFO message - %d", time.Now().Unix())
l.Warnf(context.Background(), "terminal - WARN message - %d", time.Now().Unix())
l.Errorf(context.Background(), "terminal - ERROR message - %d", time.Now().Unix())
}
func TestBufferedTerminalLogger(t *testing.T) {
l, err := NewBufferedTerminalLogger("DEBUG")
assert.NoError(t, err)
l.Debug(context.Background(), "terminal - DEBUG message")
l.Info(context.Background(), "terminal - INFO message")
l.Warn(context.Background(), "terminal - WARN message")
l.Error(context.Background(), "terminal - ERROR message")
l.Flush()
}
func BenchmarkLogger(b *testing.B) {
l, err := NewLogger(ioutil.Discard, "DEBUG")
assert.NoError(b, err)
ctx := context.Background()
b.ResetTimer()
for i := 0; i < b.N; i++ {
l.DebugEvent(ctx).String("key", "value").Messagef("Hello %s!", "World")
}
}

View file

@ -1,36 +0,0 @@
package log
import (
"io"
"io/ioutil"
"os"
"testing"
"github.com/stretchr/testify/assert"
)
func TestStandardWriter(t *testing.T) {
var w io.Writer
w = &StandardWriter{
w: os.Stdout, ew: os.Stderr,
dl: MuteLevel, pid: os.Getpid(),
}
lw, ok := w.(LevelWriter)
assert.True(t, ok)
_, ok = w.(Flusher)
assert.True(t, ok)
_, err := lw.Write([]byte("Hello World!"))
assert.NoError(t, err)
}
func BenchmarkStandardWriter(b *testing.B) {
lw := &StandardWriter{w: ioutil.Discard, ew: ioutil.Discard}
b.ResetTimer()
for i := 0; i < b.N; i++ {
lw.Write([]byte("Hello World!"))
}
}

View file

@ -1,46 +0,0 @@
// Package pid provides structure and helper functions to create and remove
// PID file. A PID file is usually a file used to store the process ID of a
// running process.
package pid
import (
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
)
// File is a file used to store the process ID of a running process.
type File struct {
path string
}
func checkPIDFileAlreadyExists(path string) error {
if pidByte, err := ioutil.ReadFile(path); err == nil {
pidString := strings.TrimSpace(string(pidByte))
if pid, err := strconv.Atoi(pidString); err == nil {
if processExists(pid) {
return fmt.Errorf("pid file found, ensure server is not running or delete %s", path)
}
}
}
return nil
}
// New creates a PID file using the specified path.
func New(path string) (*File, error) {
if err := checkPIDFileAlreadyExists(path); err != nil {
return nil, err
}
if err := ioutil.WriteFile(path, []byte(fmt.Sprintf("%d", os.Getpid())), 0644); err != nil {
return nil, err
}
return &File{path: path}, nil
}
// Remove removes the File.
func (file File) Remove() error {
return os.Remove(file.path)
}

View file

@ -1,14 +0,0 @@
// +build darwin
package pid
import (
"syscall"
)
func processExists(pid int) bool {
// OS X does not have a proc filesystem.
// Use kill -0 pid to judge if the process exists.
err := syscall.Kill(pid, 0)
return err == nil
}

View file

@ -1,42 +0,0 @@
package pid
import (
"io/ioutil"
"os"
"path/filepath"
"testing"
)
func TestNewAndRemove(t *testing.T) {
dir, err := ioutil.TempDir(os.TempDir(), "test-pidfile")
if err != nil {
t.Fatal("Could not create test directory")
}
path := filepath.Join(dir, "testfile")
file, err := New(path)
if err != nil {
t.Fatal("Could not create test file", err)
}
_, err = New(path)
if err == nil {
t.Fatal("Test file creation not blocked")
}
if err := file.Remove(); err != nil {
t.Fatal("Could not delete created test file")
}
if err := os.Remove(dir); err != nil {
t.Fatal("Could not delete test dir")
}
}
func TestRemoveInvalidPath(t *testing.T) {
file := File{path: filepath.Join("foo", "bar")}
if err := file.Remove(); err == nil {
t.Fatal("Non-existing file doesn't give an error on delete")
}
}

View file

@ -1,16 +0,0 @@
// +build !windows,!darwin
package pid
import (
"os"
"path/filepath"
"strconv"
)
func processExists(pid int) bool {
if _, err := os.Stat(filepath.Join("/proc", strconv.Itoa(pid))); err == nil {
return true
}
return false
}

View file

@ -1,23 +0,0 @@
package pid
import "syscall"
const (
processQueryLimitedInformation = 0x1000
stillActive = 259
)
func processExists(pid int) bool {
h, err := syscall.OpenProcess(processQueryLimitedInformation, false, uint32(pid))
if err != nil {
return false
}
var c uint32
err = syscall.GetExitCodeProcess(h, &c)
syscall.Close(h)
if err != nil {
return c == stillActive
}
return true
}

View file

@ -1,124 +0,0 @@
package reopen
import (
"io/ioutil"
"os"
"testing"
)
// TestReopenAppend tests that we always append to an existing file
func TestReopenAppend(t *testing.T) {
filename := "/tmp/reopen_test_foo"
defer os.Remove(filename)
// Create a sample file using normal means.
orig, err := os.Create(filename)
if err != nil {
t.Fatalf("Unable to create initial file %s: %s", filename, err)
}
_, err = orig.Write([]byte("line0\n"))
if err != nil {
t.Fatalf("Unable to write initial line %s: %s", filename, err)
}
err = orig.Close()
if err != nil {
t.Fatalf("Unable to close initial file: %s", err)
}
// Test that making a new File appends.
f, err := NewFileWriter(filename)
if err != nil {
t.Fatalf("Unable to create %s", filename)
}
_, err = f.Write([]byte("line1\n"))
if err != nil {
t.Errorf("Got write error1: %s", err)
}
// Test that reopen always appends.
err = f.Reopen()
if err != nil {
t.Errorf("Got reopen error %s: %s", filename, err)
}
_, err = f.Write([]byte("line2\n"))
if err != nil {
t.Errorf("Got write error2 on %s: %s", filename, err)
}
// Close file.
err = f.Close()
if err != nil {
t.Errorf("Got closing error for %s: %s", filename, err)
}
// Read file, make sure it contains line0, line1, line2.
out, err := ioutil.ReadFile(filename)
if err != nil {
t.Fatalf("Unable read in final file %s: %s", filename, err)
}
outStr := string(out)
if outStr != "line0\nline1\nline2\n" {
t.Errorf("Result was %s", outStr)
}
}
// TestChangeINode tests that reopen works when inode is swapped out.
func TestChangeINODE(t *testing.T) {
filename := "/tmp/reopen_test_foo"
moveFilename := "/tmp/reopen_test_foo.orig"
defer os.Remove(filename)
defer os.Remove(moveFilename)
// Step 1 -- Create a sample file using normal means.
orig, err := os.Create(filename)
if err != nil {
t.Fatalf("Unable to create initial file %s: %s", filename, err)
}
err = orig.Close()
if err != nil {
t.Fatalf("Unable to close initial file: %s", err)
}
// Step 2 -- Test that making a new File appends.
f, err := NewFileWriter(filename)
if err != nil {
t.Fatalf("Unable to create %s", filename)
}
_, err = f.Write([]byte("line1\n"))
if err != nil {
t.Errorf("Got write error1: %s", err)
}
// Step 3 -- Now move file.
err = os.Rename(filename, moveFilename)
if err != nil {
t.Errorf("Renaming error: %s", err)
}
f.Write([]byte("after1\n"))
// Step Test that reopen always appends.
err = f.Reopen()
if err != nil {
t.Errorf("Got reopen error %s: %s", filename, err)
}
_, err = f.Write([]byte("line2\n"))
if err != nil {
t.Errorf("Got write error2 on %s: %s", filename, err)
}
// Close file.
err = f.Close()
if err != nil {
t.Errorf("Got closing error for %s: %s", filename, err)
}
// Read file, make sure it contains line0, line1, line2.
out, err := ioutil.ReadFile(filename)
if err != nil {
t.Fatalf("Unable read in final file %s: %s", filename, err)
}
outStr := string(out)
if outStr != "line2\n" {
t.Errorf("Result was %s", outStr)
}
}

View file

@ -1,151 +0,0 @@
package rest
import (
"bytes"
"errors"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/Jeffail/gabs"
)
// Method contains the supported HTTP verbs.
type Method string
// Supported HTTP verbs.
const (
Get Method = "GET"
Post Method = "POST"
Put Method = "PUT"
Patch Method = "PATCH"
Delete Method = "DELETE"
)
// Request holds the request to an API Call.
type Request struct {
Method Method
BaseURL string // e.g. https://api.service.com
Headers map[string]string
QueryParams map[string]string
Body []byte
}
// Response holds the response from an API call.
type Response struct {
StatusCode int // e.g. 200
Headers http.Header // e.g. map[X-Rate-Limit:[600]]
Body string // e.g. {"result: success"}
JSON *gabs.Container
}
// ParseJSON parses the response body to JSON container.
func (r *Response) ParseJSON() error {
if strings.Contains(r.Headers.Get("Content-Type"), "application/json") {
json, err := gabs.ParseJSON([]byte(r.Body))
if err != nil {
return err
}
r.JSON = json
return nil
}
return errors.New("response body is not JSON")
}
// DefaultClient is used if no custom HTTP client is defined
var DefaultClient = &Client{HTTPClient: http.DefaultClient}
// Client allows modification of client headers, redirect policy
// and other settings
// See https://golang.org/pkg/net/http
type Client struct {
HTTPClient *http.Client
}
// The following functions enable the ability to define a
// custom HTTP Client
// MakeRequest makes the API call.
func (c *Client) MakeRequest(req *http.Request) (*http.Response, error) {
return c.HTTPClient.Do(req)
}
// API is the main interface to the API.
func (c *Client) API(r *Request) (*Response, error) {
// Build the HTTP request object.
req, err := BuildRequestObject(r)
if err != nil {
return nil, err
}
// Build the HTTP client and make the request.
res, err := c.MakeRequest(req)
if err != nil {
return nil, err
}
// Build Response object.
response, err := BuildResponse(res)
if err != nil {
return nil, err
}
return response, nil
}
// AddQueryParameters adds query parameters to the URL.
func AddQueryParameters(baseURL string, queryParams map[string]string) string {
baseURL += "?"
params := url.Values{}
for key, value := range queryParams {
params.Add(key, value)
}
return baseURL + params.Encode()
}
// BuildRequestObject creates the HTTP request object.
func BuildRequestObject(r *Request) (*http.Request, error) {
// Add any query parameters to the URL.
if len(r.QueryParams) != 0 {
r.BaseURL = AddQueryParameters(r.BaseURL, r.QueryParams)
}
req, err := http.NewRequest(string(r.Method), r.BaseURL, bytes.NewBuffer(r.Body))
for key, value := range r.Headers {
req.Header.Set(key, value)
}
_, exists := req.Header["Content-Type"]
if len(r.Body) > 0 && !exists {
req.Header.Set("Content-Type", "application/json")
}
return req, err
}
// BuildResponse builds the response struct.
func BuildResponse(r *http.Response) (*Response, error) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
defer r.Body.Close()
response := Response{
StatusCode: r.StatusCode,
Body: string(body),
Headers: r.Header,
}
return &response, nil
}
// MakeRequest makes the API call.
func MakeRequest(r *http.Request) (*http.Response, error) {
return DefaultClient.HTTPClient.Do(r)
}
// API is the main interface to the API.
func API(request *Request) (*Response, error) {
return DefaultClient.API(request)
}

View file

@ -1,138 +0,0 @@
package rest
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestBuildURL(t *testing.T) {
testURL := AddQueryParameters(
"http://api.test.com",
map[string]string{
"test": "1",
"test2": "2",
},
)
assert.Equal(t, "http://api.test.com?test=1&test2=2", testURL)
}
func TestBuildRequest(t *testing.T) {
request := Request{
Method: Get,
BaseURL: "http://api.test.com",
Headers: map[string]string{
"Content-Type": "application/json",
"Authorization": "Bearer APK_KEY",
},
QueryParams: map[string]string{
"test": "1",
"test2": "2",
},
}
req, err := BuildRequestObject(&request)
assert.NoError(t, err)
assert.NotNil(t, req)
}
func TestBuildResponse(t *testing.T) {
fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/not+json")
fmt.Fprintln(w, "{\"message\": \"success\"}")
}))
defer fakeServer.Close()
request := Request{
Method: Get,
BaseURL: fakeServer.URL,
}
req, err := BuildRequestObject(&request)
assert.NoError(t, err)
res, err := MakeRequest(req)
assert.NoError(t, err)
response, err := BuildResponse(res)
assert.NoError(t, err)
err = response.ParseJSON()
assert.Error(t, err)
assert.Equal(t, 200, response.StatusCode)
assert.NotEqual(t, 0, len(response.Body))
assert.NotEqual(t, 0, len(response.Headers))
assert.Nil(t, response.JSON)
}
func TestRest(t *testing.T) {
fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprintln(w, "{\"message\": \"success\"}")
}))
defer fakeServer.Close()
request := Request{
Method: Get,
BaseURL: fakeServer.URL + "/test_endpoint",
Headers: map[string]string{
"Content-Type": "application/json",
"Authorization": "Bearer APK_KEY",
},
QueryParams: map[string]string{
"test": "1",
"test2": "2",
},
}
response, err := API(&request)
assert.NoError(t, err)
err = response.ParseJSON()
assert.NoError(t, err)
assert.Equal(t, 200, response.StatusCode)
assert.NotEqual(t, 0, len(response.Body))
assert.NotEqual(t, 0, len(response.Headers))
assert.Equal(t, "success", response.JSON.Path("message").Data().(string))
}
func TestDefaultContentType(t *testing.T) {
request := Request{
Method: Get,
BaseURL: "http://localhost",
Body: []byte(`{"hello": "world"}`),
}
req, err := BuildRequestObject(&request)
assert.NoError(t, err)
assert.Equal(t, "application/json", req.Header.Get("Content-Type"))
}
func TestCustomContentType(t *testing.T) {
request := Request{
Method: Get,
BaseURL: "http://localhost",
Headers: map[string]string{"Content-Type": "custom"},
Body: []byte("Hello World"),
}
res, err := BuildRequestObject(&request)
assert.NoError(t, err)
assert.Equal(t, "custom", res.Header.Get("Content-Type"))
}
func TestCustomHTTPClient(t *testing.T) {
fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(time.Millisecond * 20)
fmt.Fprintln(w, "{\"message\": \"success\"}")
}))
defer fakeServer.Close()
request := Request{
Method: Get,
BaseURL: fakeServer.URL + "/test_endpoint",
}
customClient := &Client{&http.Client{Timeout: time.Millisecond * 10}}
_, err := customClient.API(&request)
assert.True(t, strings.Contains(err.Error(), "Client.Timeout exceeded while awaiting headers"))
}

View file

@ -1,4 +0,0 @@
package utils
// ContextKey is the type that used for saving and restoring value in context.
type ContextKey string

View file

@ -1,13 +0,0 @@
package utils
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestContextKey(t *testing.T) {
var value ContextKey = "Hello world."
assert.Equal(t, "Hello world.", string(value))
}

View file

@ -1,17 +0,0 @@
package utils
import (
"os"
"runtime"
)
// GetHome returns the home directory.
func GetHome() string {
if runtime.GOOS == "windows" {
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
}
return os.Getenv("HOME")
}

View file

@ -1,15 +0,0 @@
package utils
import (
"os/user"
"testing"
"github.com/stretchr/testify/assert"
)
func TestGetHome(t *testing.T) {
usr, err := user.Current()
assert.NoError(t, err)
assert.Equal(t, usr.HomeDir, GetHome())
}

View file

@ -1,16 +0,0 @@
package utils
import (
"context"
"runtime/debug"
"github.com/pengsrc/go-shared/log"
)
// Recover is a utils that recovers from panics, logs the panic (and a
// backtrace) for functions in goroutine.
func Recover(ctx context.Context) {
if x := recover(); x != nil {
log.Errorf(ctx, "Caught panic: %v, Trace: %s", x, debug.Stack())
}
}

View file

@ -1,31 +0,0 @@
package utils
import (
"context"
"io/ioutil"
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/pengsrc/go-shared/log"
)
func TestRecover(t *testing.T) {
discardLogger, err := log.NewLogger(ioutil.Discard)
assert.NoError(t, err)
log.SetGlobalLogger(discardLogger)
defer log.SetGlobalLogger(nil)
ctx := context.Background()
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer Recover(ctx)
wg.Done()
panic("fear")
}()
wg.Wait()
}