Fix tests for Windows - part 1 (#8414)

This commit is contained in:
Paweł Żak 2020-11-23 16:40:32 +01:00 committed by GitHub
parent d64c72294a
commit 0fcfee0caf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
51 changed files with 416 additions and 253 deletions

1
.gitattributes vendored
View File

@ -3,3 +3,4 @@ README.md merge=union
go.sum merge=union go.sum merge=union
plugins/inputs/all/all.go merge=union plugins/inputs/all/all.go merge=union
plugins/outputs/all/all.go merge=union plugins/outputs/all/all.go merge=union
**/testdata/** test eol=lf

View File

@ -114,12 +114,7 @@ fmtcheck:
.PHONY: test-windows .PHONY: test-windows
test-windows: test-windows:
go test -short $(race_detector) ./plugins/inputs/ping/... go test -short ./...
go test -short $(race_detector) ./plugins/inputs/win_perf_counters/...
go test -short $(race_detector) ./plugins/inputs/win_services/...
go test -short $(race_detector) ./plugins/inputs/procstat/...
go test -short $(race_detector) ./plugins/inputs/ntpq/...
go test -short $(race_detector) ./plugins/processors/port_name/...
.PHONY: vet .PHONY: vet
vet: vet:

View File

@ -12,7 +12,7 @@ clone_folder: C:\gopath\src\github.com\influxdata\telegraf
environment: environment:
GOPATH: C:\gopath GOPATH: C:\gopath
stack: go 1.14 stack: go 1.15
platform: x64 platform: x64

View File

@ -2,6 +2,7 @@ package config
import ( import (
"os" "os"
"strings"
"testing" "testing"
"time" "time"
@ -201,7 +202,7 @@ func TestConfig_LoadSpecialTypes(t *testing.T) {
// Tests telegraf size parsing. // Tests telegraf size parsing.
assert.Equal(t, internal.Size{Size: 1024 * 1024}, inputHTTPListener.MaxBodySize) assert.Equal(t, internal.Size{Size: 1024 * 1024}, inputHTTPListener.MaxBodySize)
// Tests toml multiline basic strings. // Tests toml multiline basic strings.
assert.Equal(t, "/path/to/my/cert\n", inputHTTPListener.TLSCert) assert.Equal(t, "/path/to/my/cert", strings.TrimRight(inputHTTPListener.TLSCert, "\r\n"))
} }
func TestConfig_FieldNotDefined(t *testing.T) { func TestConfig_FieldNotDefined(t *testing.T) {

View File

@ -176,14 +176,6 @@
# If no servers are specified, then 127.0.0.1 is used as the host and 4020 as the port. # If no servers are specified, then 127.0.0.1 is used as the host and 4020 as the port.
servers = ["127.0.0.1:4021"] servers = ["127.0.0.1:4021"]
# Read metrics from local Lustre service on OST, MDS
[[inputs.lustre2]]
# An array of /proc globs to search for Lustre stats
# If not specified, the default will work on Lustre 2.5.x
#
# ost_procfiles = ["/proc/fs/lustre/obdfilter/*/stats", "/proc/fs/lustre/osd-ldiskfs/*/stats"]
# mds_procfiles = ["/proc/fs/lustre/mdt/*/md_stats"]
# Read metrics about memory usage # Read metrics about memory usage
[[inputs.mem]] [[inputs.mem]]
# no configuration # no configuration

View File

@ -1,29 +1,38 @@
// +build !windows
// TODO: Windows - should be enabled for Windows when super asterisk is fixed on Windows
// https://github.com/influxdata/telegraf/issues/6248
package globpath package globpath
import ( import (
"os"
"path/filepath"
"runtime" "runtime"
"strings"
"testing" "testing"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
var (
testdataDir = getTestdataDir()
)
func TestCompileAndMatch(t *testing.T) { func TestCompileAndMatch(t *testing.T) {
dir := getTestdataDir()
// test super asterisk // test super asterisk
g1, err := Compile(dir + "/**") g1, err := Compile(filepath.Join(testdataDir, "**"))
require.NoError(t, err) require.NoError(t, err)
// test single asterisk // test single asterisk
g2, err := Compile(dir + "/*.log") g2, err := Compile(filepath.Join(testdataDir, "*.log"))
require.NoError(t, err) require.NoError(t, err)
// test no meta characters (file exists) // test no meta characters (file exists)
g3, err := Compile(dir + "/log1.log") g3, err := Compile(filepath.Join(testdataDir, "log1.log"))
require.NoError(t, err) require.NoError(t, err)
// test file that doesn't exist // test file that doesn't exist
g4, err := Compile(dir + "/i_dont_exist.log") g4, err := Compile(filepath.Join(testdataDir, "i_dont_exist.log"))
require.NoError(t, err) require.NoError(t, err)
// test super asterisk that doesn't exist // test super asterisk that doesn't exist
g5, err := Compile(dir + "/dir_doesnt_exist/**") g5, err := Compile(filepath.Join(testdataDir, "dir_doesnt_exist", "**"))
require.NoError(t, err) require.NoError(t, err)
matches := g1.Match() matches := g1.Match()
@ -39,15 +48,14 @@ func TestCompileAndMatch(t *testing.T) {
} }
func TestRootGlob(t *testing.T) { func TestRootGlob(t *testing.T) {
dir := getTestdataDir()
tests := []struct { tests := []struct {
input string input string
output string output string
}{ }{
{dir + "/**", dir + "/*"}, {filepath.Join(testdataDir, "**"), filepath.Join(testdataDir, "*")},
{dir + "/nested?/**", dir + "/nested?/*"}, {filepath.Join(testdataDir, "nested?", "**"), filepath.Join(testdataDir, "nested?", "*")},
{dir + "/ne**/nest*", dir + "/ne*"}, {filepath.Join(testdataDir, "ne**", "nest*"), filepath.Join(testdataDir, "ne*")},
{dir + "/nested?/*", ""}, {filepath.Join(testdataDir, "nested?", "*"), ""},
} }
for _, test := range tests { for _, test := range tests {
@ -57,21 +65,19 @@ func TestRootGlob(t *testing.T) {
} }
func TestFindNestedTextFile(t *testing.T) { func TestFindNestedTextFile(t *testing.T) {
dir := getTestdataDir()
// test super asterisk // test super asterisk
g1, err := Compile(dir + "/**.txt") g1, err := Compile(filepath.Join(testdataDir, "**.txt"))
require.NoError(t, err) require.NoError(t, err)
matches := g1.Match() matches := g1.Match()
require.Len(t, matches, 1) require.Len(t, matches, 1)
} }
func getTestdataDir() string {
_, filename, _, _ := runtime.Caller(1)
return strings.Replace(filename, "globpath_test.go", "testdata", 1)
}
func TestMatch_ErrPermission(t *testing.T) { func TestMatch_ErrPermission(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Skipping Unix only test")
}
tests := []struct { tests := []struct {
input string input string
expected []string expected []string
@ -98,3 +104,13 @@ func TestWindowsSeparator(t *testing.T) {
ok := glob.MatchString("testdata\\nested1") ok := glob.MatchString("testdata\\nested1")
require.True(t, ok) require.True(t, ok)
} }
func getTestdataDir() string {
dir, err := os.Getwd()
if err != nil {
// if we cannot even establish the test directory, further progress is meaningless
panic(err)
}
return filepath.Join(dir, "testdata")
}

View File

@ -56,15 +56,15 @@ cache_readaheads
Using this configuration: Using this configuration:
```toml ```toml
[bcache] [[inputs.bcache]]
# Bcache sets path ## Bcache sets path
# If not specified, then default is: ## If not specified, then default is:
# bcachePath = "/sys/fs/bcache" bcachePath = "/sys/fs/bcache"
#
# By default, telegraf gather stats for all bcache devices ## By default, Telegraf gather stats for all bcache devices
# Setting devices will restrict the stats to the specified ## Setting devices will restrict the stats to the specified
# bcache devices. ## bcache devices.
# bcacheDevs = ["bcache0", ...] bcacheDevs = ["bcache0"]
``` ```
When run with: When run with:

View File

@ -1,3 +1,7 @@
// +build !windows
// bcache doesn't aim for Windows
package bcache package bcache
import ( import (
@ -22,7 +26,7 @@ var sampleConfig = `
## If not specified, then default is: ## If not specified, then default is:
bcachePath = "/sys/fs/bcache" bcachePath = "/sys/fs/bcache"
## By default, telegraf gather stats for all bcache devices ## By default, Telegraf gather stats for all bcache devices
## Setting devices will restrict the stats to the specified ## Setting devices will restrict the stats to the specified
## bcache devices. ## bcache devices.
bcacheDevs = ["bcache0"] bcacheDevs = ["bcache0"]

View File

@ -1,3 +1,5 @@
// +build !windows
package bcache package bcache
import ( import (

View File

@ -0,0 +1,3 @@
// +build windows
package bcache

View File

@ -4,7 +4,7 @@ import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"os" "os"
"path" "path/filepath"
"strconv" "strconv"
"strings" "strings"
"testing" "testing"
@ -163,7 +163,7 @@ func assertFoundSocket(t *testing.T, dir, sockType string, i int, sockets []*soc
} else { } else {
prefix = monPrefix prefix = monPrefix
} }
expected := path.Join(dir, sockFile(prefix, i)) expected := filepath.Join(dir, sockFile(prefix, i))
found := false found := false
for _, s := range sockets { for _, s := range sockets {
fmt.Printf("Checking %s\n", s.socket) fmt.Printf("Checking %s\n", s.socket)
@ -183,7 +183,7 @@ func sockFile(prefix string, i int) string {
func createTestFiles(dir string, st *SockTest) { func createTestFiles(dir string, st *SockTest) {
writeFile := func(prefix string, i int) { writeFile := func(prefix string, i int) {
f := sockFile(prefix, i) f := sockFile(prefix, i)
fpath := path.Join(dir, f) fpath := filepath.Join(dir, f)
ioutil.WriteFile(fpath, []byte(""), 0777) ioutil.WriteFile(fpath, []byte(""), 0777)
} }
tstFileApply(st, writeFile) tstFileApply(st, writeFile)
@ -192,7 +192,7 @@ func createTestFiles(dir string, st *SockTest) {
func cleanupTestFiles(dir string, st *SockTest) { func cleanupTestFiles(dir string, st *SockTest) {
rmFile := func(prefix string, i int) { rmFile := func(prefix string, i int) {
f := sockFile(prefix, i) f := sockFile(prefix, i)
fpath := path.Join(dir, f) fpath := filepath.Join(dir, f)
err := os.Remove(fpath) err := os.Remove(fpath)
if err != nil { if err != nil {
fmt.Printf("Error removing test file %s: %v\n", fpath, err) fmt.Printf("Error removing test file %s: %v\n", fpath, err)

View File

@ -1,6 +1,7 @@
package disk package disk
import ( import (
"fmt"
"os" "os"
"testing" "testing"
@ -74,13 +75,13 @@ func TestDiskUsage(t *testing.T) {
assert.Equal(t, expectedAllDiskMetrics, numDiskMetrics) assert.Equal(t, expectedAllDiskMetrics, numDiskMetrics)
tags1 := map[string]string{ tags1 := map[string]string{
"path": "/", "path": string(os.PathSeparator),
"fstype": "ext4", "fstype": "ext4",
"device": "sda", "device": "sda",
"mode": "ro", "mode": "ro",
} }
tags2 := map[string]string{ tags2 := map[string]string{
"path": "/home", "path": fmt.Sprintf("%chome", os.PathSeparator),
"fstype": "ext4", "fstype": "ext4",
"device": "sdb", "device": "sdb",
"mode": "rw", "mode": "rw",
@ -144,7 +145,7 @@ func TestDiskUsageHostMountPrefix(t *testing.T) {
}, },
}, },
expectedTags: map[string]string{ expectedTags: map[string]string{
"path": "/", "path": string(os.PathSeparator),
"device": "sda", "device": "sda",
"fstype": "ext4", "fstype": "ext4",
"mode": "ro", "mode": "ro",
@ -177,7 +178,7 @@ func TestDiskUsageHostMountPrefix(t *testing.T) {
}, },
hostMountPrefix: "/hostfs", hostMountPrefix: "/hostfs",
expectedTags: map[string]string{ expectedTags: map[string]string{
"path": "/var", "path": fmt.Sprintf("%cvar", os.PathSeparator),
"device": "sda", "device": "sda",
"fstype": "ext4", "fstype": "ext4",
"mode": "ro", "mode": "ro",
@ -210,7 +211,7 @@ func TestDiskUsageHostMountPrefix(t *testing.T) {
}, },
hostMountPrefix: "/hostfs", hostMountPrefix: "/hostfs",
expectedTags: map[string]string{ expectedTags: map[string]string{
"path": "/", "path": string(os.PathSeparator),
"device": "sda", "device": "sda",
"fstype": "ext4", "fstype": "ext4",
"mode": "ro", "mode": "ro",

View File

@ -1,3 +1,8 @@
// +build !windows
// TODO: Windows - should be enabled for Windows when super asterisk is fixed on Windows
// https://github.com/influxdata/telegraf/issues/6248
package exec package exec
import ( import (

View File

@ -1,5 +1,3 @@
// +build !windows
package execd package execd
import ( import (
@ -11,17 +9,16 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/agent" "github.com/influxdata/telegraf/agent"
"github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/metric"
"github.com/influxdata/telegraf/models" "github.com/influxdata/telegraf/models"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf/plugins/parsers" "github.com/influxdata/telegraf/plugins/parsers"
"github.com/influxdata/telegraf/plugins/serializers" "github.com/influxdata/telegraf/plugins/serializers"
"github.com/influxdata/telegraf/testutil"
"github.com/influxdata/telegraf"
) )
func TestSettingConfigWorks(t *testing.T) { func TestSettingConfigWorks(t *testing.T) {

View File

@ -7,7 +7,6 @@ import (
"context" "context"
"io" "io"
"os" "os"
"runtime"
"syscall" "syscall"
"testing" "testing"
"time" "time"
@ -16,10 +15,6 @@ import (
) )
func TestShimUSR1SignalingWorks(t *testing.T) { func TestShimUSR1SignalingWorks(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip()
return
}
stdinReader, stdinWriter := io.Pipe() stdinReader, stdinWriter := io.Pipe()
stdoutReader, stdoutWriter := io.Pipe() stdoutReader, stdoutWriter := io.Pipe()

View File

@ -1,3 +1,8 @@
// +build !windows
// TODO: Windows - should be enabled for Windows when super asterisk is fixed on Windows
// https://github.com/influxdata/telegraf/issues/6248
package file package file
import ( import (

View File

@ -1,3 +1,8 @@
// +build !windows
// TODO: Windows - should be enabled for Windows when super asterisk is fixed on Windows
// https://github.com/influxdata/telegraf/issues/6248
package filecount package filecount
import ( import (

View File

@ -1,3 +1,8 @@
// +build !windows
// TODO: Windows - should be enabled for Windows when super asterisk is fixed on Windows
// https://github.com/influxdata/telegraf/issues/6248
package filecount package filecount
import ( import (

View File

@ -1,102 +1,108 @@
// +build !windows
// TODO: Windows - should be enabled for Windows when super asterisk is fixed on Windows
// https://github.com/influxdata/telegraf/issues/6248
package filestat package filestat
import ( import (
"runtime" "os"
"strings" "path/filepath"
"testing" "testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/assert" )
var (
testdataDir = getTestdataDir()
) )
func TestGatherNoMd5(t *testing.T) { func TestGatherNoMd5(t *testing.T) {
dir := getTestdataDir()
fs := NewFileStat() fs := NewFileStat()
fs.Log = testutil.Logger{} fs.Log = testutil.Logger{}
fs.Files = []string{ fs.Files = []string{
dir + "log1.log", filepath.Join(testdataDir, "log1.log"),
dir + "log2.log", filepath.Join(testdataDir, "log2.log"),
"/non/existant/file", filepath.Join(testdataDir, "non_existent_file"),
} }
acc := testutil.Accumulator{} acc := testutil.Accumulator{}
acc.GatherError(fs.Gather) acc.GatherError(fs.Gather)
tags1 := map[string]string{ tags1 := map[string]string{
"file": dir + "log1.log", "file": filepath.Join(testdataDir, "log1.log"),
} }
require.True(t, acc.HasPoint("filestat", tags1, "size_bytes", int64(0))) require.True(t, acc.HasPoint("filestat", tags1, "size_bytes", int64(0)))
require.True(t, acc.HasPoint("filestat", tags1, "exists", int64(1))) require.True(t, acc.HasPoint("filestat", tags1, "exists", int64(1)))
tags2 := map[string]string{ tags2 := map[string]string{
"file": dir + "log2.log", "file": filepath.Join(testdataDir, "log2.log"),
} }
require.True(t, acc.HasPoint("filestat", tags2, "size_bytes", int64(0))) require.True(t, acc.HasPoint("filestat", tags2, "size_bytes", int64(0)))
require.True(t, acc.HasPoint("filestat", tags2, "exists", int64(1))) require.True(t, acc.HasPoint("filestat", tags2, "exists", int64(1)))
tags3 := map[string]string{ tags3 := map[string]string{
"file": "/non/existant/file", "file": filepath.Join(testdataDir, "non_existent_file"),
} }
require.True(t, acc.HasPoint("filestat", tags3, "exists", int64(0))) require.True(t, acc.HasPoint("filestat", tags3, "exists", int64(0)))
} }
func TestGatherExplicitFiles(t *testing.T) { func TestGatherExplicitFiles(t *testing.T) {
dir := getTestdataDir()
fs := NewFileStat() fs := NewFileStat()
fs.Log = testutil.Logger{} fs.Log = testutil.Logger{}
fs.Md5 = true fs.Md5 = true
fs.Files = []string{ fs.Files = []string{
dir + "log1.log", filepath.Join(testdataDir, "log1.log"),
dir + "log2.log", filepath.Join(testdataDir, "log2.log"),
"/non/existant/file", filepath.Join(testdataDir, "non_existent_file"),
} }
acc := testutil.Accumulator{} acc := testutil.Accumulator{}
acc.GatherError(fs.Gather) acc.GatherError(fs.Gather)
tags1 := map[string]string{ tags1 := map[string]string{
"file": dir + "log1.log", "file": filepath.Join(testdataDir, "log1.log"),
} }
require.True(t, acc.HasPoint("filestat", tags1, "size_bytes", int64(0))) require.True(t, acc.HasPoint("filestat", tags1, "size_bytes", int64(0)))
require.True(t, acc.HasPoint("filestat", tags1, "exists", int64(1))) require.True(t, acc.HasPoint("filestat", tags1, "exists", int64(1)))
require.True(t, acc.HasPoint("filestat", tags1, "md5_sum", "d41d8cd98f00b204e9800998ecf8427e")) require.True(t, acc.HasPoint("filestat", tags1, "md5_sum", "d41d8cd98f00b204e9800998ecf8427e"))
tags2 := map[string]string{ tags2 := map[string]string{
"file": dir + "log2.log", "file": filepath.Join(testdataDir, "log2.log"),
} }
require.True(t, acc.HasPoint("filestat", tags2, "size_bytes", int64(0))) require.True(t, acc.HasPoint("filestat", tags2, "size_bytes", int64(0)))
require.True(t, acc.HasPoint("filestat", tags2, "exists", int64(1))) require.True(t, acc.HasPoint("filestat", tags2, "exists", int64(1)))
require.True(t, acc.HasPoint("filestat", tags2, "md5_sum", "d41d8cd98f00b204e9800998ecf8427e")) require.True(t, acc.HasPoint("filestat", tags2, "md5_sum", "d41d8cd98f00b204e9800998ecf8427e"))
tags3 := map[string]string{ tags3 := map[string]string{
"file": "/non/existant/file", "file": filepath.Join(testdataDir, "non_existent_file"),
} }
require.True(t, acc.HasPoint("filestat", tags3, "exists", int64(0))) require.True(t, acc.HasPoint("filestat", tags3, "exists", int64(0)))
} }
func TestGatherGlob(t *testing.T) { func TestGatherGlob(t *testing.T) {
dir := getTestdataDir()
fs := NewFileStat() fs := NewFileStat()
fs.Log = testutil.Logger{} fs.Log = testutil.Logger{}
fs.Md5 = true fs.Md5 = true
fs.Files = []string{ fs.Files = []string{
dir + "*.log", filepath.Join(testdataDir, "*.log"),
} }
acc := testutil.Accumulator{} acc := testutil.Accumulator{}
acc.GatherError(fs.Gather) acc.GatherError(fs.Gather)
tags1 := map[string]string{ tags1 := map[string]string{
"file": dir + "log1.log", "file": filepath.Join(testdataDir, "log1.log"),
} }
require.True(t, acc.HasPoint("filestat", tags1, "size_bytes", int64(0))) require.True(t, acc.HasPoint("filestat", tags1, "size_bytes", int64(0)))
require.True(t, acc.HasPoint("filestat", tags1, "exists", int64(1))) require.True(t, acc.HasPoint("filestat", tags1, "exists", int64(1)))
require.True(t, acc.HasPoint("filestat", tags1, "md5_sum", "d41d8cd98f00b204e9800998ecf8427e")) require.True(t, acc.HasPoint("filestat", tags1, "md5_sum", "d41d8cd98f00b204e9800998ecf8427e"))
tags2 := map[string]string{ tags2 := map[string]string{
"file": dir + "log2.log", "file": filepath.Join(testdataDir, "log2.log"),
} }
require.True(t, acc.HasPoint("filestat", tags2, "size_bytes", int64(0))) require.True(t, acc.HasPoint("filestat", tags2, "size_bytes", int64(0)))
require.True(t, acc.HasPoint("filestat", tags2, "exists", int64(1))) require.True(t, acc.HasPoint("filestat", tags2, "exists", int64(1)))
@ -104,33 +110,32 @@ func TestGatherGlob(t *testing.T) {
} }
func TestGatherSuperAsterisk(t *testing.T) { func TestGatherSuperAsterisk(t *testing.T) {
dir := getTestdataDir()
fs := NewFileStat() fs := NewFileStat()
fs.Log = testutil.Logger{} fs.Log = testutil.Logger{}
fs.Md5 = true fs.Md5 = true
fs.Files = []string{ fs.Files = []string{
dir + "**", filepath.Join(testdataDir, "**"),
} }
acc := testutil.Accumulator{} acc := testutil.Accumulator{}
acc.GatherError(fs.Gather) acc.GatherError(fs.Gather)
tags1 := map[string]string{ tags1 := map[string]string{
"file": dir + "log1.log", "file": filepath.Join(testdataDir, "log1.log"),
} }
require.True(t, acc.HasPoint("filestat", tags1, "size_bytes", int64(0))) require.True(t, acc.HasPoint("filestat", tags1, "size_bytes", int64(0)))
require.True(t, acc.HasPoint("filestat", tags1, "exists", int64(1))) require.True(t, acc.HasPoint("filestat", tags1, "exists", int64(1)))
require.True(t, acc.HasPoint("filestat", tags1, "md5_sum", "d41d8cd98f00b204e9800998ecf8427e")) require.True(t, acc.HasPoint("filestat", tags1, "md5_sum", "d41d8cd98f00b204e9800998ecf8427e"))
tags2 := map[string]string{ tags2 := map[string]string{
"file": dir + "log2.log", "file": filepath.Join(testdataDir, "log2.log"),
} }
require.True(t, acc.HasPoint("filestat", tags2, "size_bytes", int64(0))) require.True(t, acc.HasPoint("filestat", tags2, "size_bytes", int64(0)))
require.True(t, acc.HasPoint("filestat", tags2, "exists", int64(1))) require.True(t, acc.HasPoint("filestat", tags2, "exists", int64(1)))
require.True(t, acc.HasPoint("filestat", tags2, "md5_sum", "d41d8cd98f00b204e9800998ecf8427e")) require.True(t, acc.HasPoint("filestat", tags2, "md5_sum", "d41d8cd98f00b204e9800998ecf8427e"))
tags3 := map[string]string{ tags3 := map[string]string{
"file": dir + "test.conf", "file": filepath.Join(testdataDir, "test.conf"),
} }
require.True(t, acc.HasPoint("filestat", tags3, "size_bytes", int64(104))) require.True(t, acc.HasPoint("filestat", tags3, "size_bytes", int64(104)))
require.True(t, acc.HasPoint("filestat", tags3, "exists", int64(1))) require.True(t, acc.HasPoint("filestat", tags3, "exists", int64(1)))
@ -138,18 +143,17 @@ func TestGatherSuperAsterisk(t *testing.T) {
} }
func TestModificationTime(t *testing.T) { func TestModificationTime(t *testing.T) {
dir := getTestdataDir()
fs := NewFileStat() fs := NewFileStat()
fs.Log = testutil.Logger{} fs.Log = testutil.Logger{}
fs.Files = []string{ fs.Files = []string{
dir + "log1.log", filepath.Join(testdataDir, "log1.log"),
} }
acc := testutil.Accumulator{} acc := testutil.Accumulator{}
acc.GatherError(fs.Gather) acc.GatherError(fs.Gather)
tags1 := map[string]string{ tags1 := map[string]string{
"file": dir + "log1.log", "file": filepath.Join(testdataDir, "log1.log"),
} }
require.True(t, acc.HasPoint("filestat", tags1, "size_bytes", int64(0))) require.True(t, acc.HasPoint("filestat", tags1, "size_bytes", int64(0)))
require.True(t, acc.HasPoint("filestat", tags1, "exists", int64(1))) require.True(t, acc.HasPoint("filestat", tags1, "exists", int64(1)))
@ -160,22 +164,21 @@ func TestNoModificationTime(t *testing.T) {
fs := NewFileStat() fs := NewFileStat()
fs.Log = testutil.Logger{} fs.Log = testutil.Logger{}
fs.Files = []string{ fs.Files = []string{
"/non/existant/file", filepath.Join(testdataDir, "non_existent_file"),
} }
acc := testutil.Accumulator{} acc := testutil.Accumulator{}
acc.GatherError(fs.Gather) acc.GatherError(fs.Gather)
tags1 := map[string]string{ tags1 := map[string]string{
"file": "/non/existant/file", "file": filepath.Join(testdataDir, "non_existent_file"),
} }
require.True(t, acc.HasPoint("filestat", tags1, "exists", int64(0))) require.True(t, acc.HasPoint("filestat", tags1, "exists", int64(0)))
require.False(t, acc.HasInt64Field("filestat", "modification_time")) require.False(t, acc.HasInt64Field("filestat", "modification_time"))
} }
func TestGetMd5(t *testing.T) { func TestGetMd5(t *testing.T) {
dir := getTestdataDir() md5, err := getMd5(filepath.Join(testdataDir, "test.conf"))
md5, err := getMd5(dir + "test.conf")
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, "5a7e9b77fa25e7bb411dbd17cf403c1f", md5) assert.Equal(t, "5a7e9b77fa25e7bb411dbd17cf403c1f", md5)
@ -184,6 +187,11 @@ func TestGetMd5(t *testing.T) {
} }
func getTestdataDir() string { func getTestdataDir() string {
_, filename, _, _ := runtime.Caller(1) dir, err := os.Getwd()
return strings.Replace(filename, "filestat_test.go", "testdata/", 1) if err != nil {
// if we cannot even establish the test directory, further progress is meaningless
panic(err)
}
return filepath.Join(dir, "testdata")
} }

View File

@ -7,6 +7,8 @@ import (
"net" "net"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os"
"path/filepath"
"strings" "strings"
"testing" "testing"
@ -114,12 +116,13 @@ func TestHaproxyGeneratesMetricsWithoutAuthentication(t *testing.T) {
func TestHaproxyGeneratesMetricsUsingSocket(t *testing.T) { func TestHaproxyGeneratesMetricsUsingSocket(t *testing.T) {
var randomNumber int64 var randomNumber int64
var sockets [5]net.Listener var sockets [5]net.Listener
_globmask := "/tmp/test-haproxy*.sock"
_badmask := "/tmp/test-fail-haproxy*.sock" _globmask := filepath.Join(os.TempDir(), "test-haproxy*.sock")
_badmask := filepath.Join(os.TempDir(), "test-fail-haproxy*.sock")
for i := 0; i < 5; i++ { for i := 0; i < 5; i++ {
binary.Read(rand.Reader, binary.LittleEndian, &randomNumber) binary.Read(rand.Reader, binary.LittleEndian, &randomNumber)
sockname := fmt.Sprintf("/tmp/test-haproxy%d.sock", randomNumber) sockname := filepath.Join(os.TempDir(), fmt.Sprintf("test-haproxy%d.sock", randomNumber))
sock, err := net.Listen("unix", sockname) sock, err := net.Listen("unix", sockname)
if err != nil { if err != nil {
@ -146,7 +149,7 @@ func TestHaproxyGeneratesMetricsUsingSocket(t *testing.T) {
for _, sock := range sockets { for _, sock := range sockets {
tags := map[string]string{ tags := map[string]string{
"server": sock.Addr().String(), "server": getSocketAddr(sock.Addr().String()),
"proxy": "git", "proxy": "git",
"sv": "www", "sv": "www",
"type": "server", "type": "server",

View File

@ -1,3 +1,7 @@
// +build !windows
// TODO: Windows - should be enabled for Windows when https://github.com/influxdata/telegraf/issues/8451 is fixed
package http_response package http_response
import ( import (
@ -162,7 +166,7 @@ func TestHeaders(t *testing.T) {
h := &HTTPResponse{ h := &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL, URLs: []string{ts.URL},
Method: "GET", Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 2}, ResponseTimeout: internal.Duration{Duration: time.Second * 2},
Headers: map[string]string{ Headers: map[string]string{
@ -198,7 +202,7 @@ func TestFields(t *testing.T) {
h := &HTTPResponse{ h := &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/good", URLs: []string{ts.URL + "/good"},
Body: "{ 'test': 'data'}", Body: "{ 'test': 'data'}",
Method: "GET", Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20}, ResponseTimeout: internal.Duration{Duration: time.Second * 20},
@ -236,7 +240,7 @@ func TestResponseBodyField(t *testing.T) {
h := &HTTPResponse{ h := &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/good", URLs: []string{ts.URL + "/good"},
Body: "{ 'test': 'data'}", Body: "{ 'test': 'data'}",
Method: "GET", Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20}, ResponseTimeout: internal.Duration{Duration: time.Second * 20},
@ -271,7 +275,7 @@ func TestResponseBodyField(t *testing.T) {
// Invalid UTF-8 String // Invalid UTF-8 String
h = &HTTPResponse{ h = &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/invalidUTF8", URLs: []string{ts.URL + "/invalidUTF8"},
Body: "{ 'test': 'data'}", Body: "{ 'test': 'data'}",
Method: "GET", Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20}, ResponseTimeout: internal.Duration{Duration: time.Second * 20},
@ -305,7 +309,7 @@ func TestResponseBodyMaxSize(t *testing.T) {
h := &HTTPResponse{ h := &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/good", URLs: []string{ts.URL + "/good"},
Body: "{ 'test': 'data'}", Body: "{ 'test': 'data'}",
Method: "GET", Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20}, ResponseTimeout: internal.Duration{Duration: time.Second * 20},
@ -339,7 +343,7 @@ func TestHTTPHeaderTags(t *testing.T) {
h := &HTTPResponse{ h := &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/good", URLs: []string{ts.URL + "/good"},
Body: "{ 'test': 'data'}", Body: "{ 'test': 'data'}",
Method: "GET", Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20}, ResponseTimeout: internal.Duration{Duration: time.Second * 20},
@ -374,7 +378,7 @@ func TestHTTPHeaderTags(t *testing.T) {
h = &HTTPResponse{ h = &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/noheader", URLs: []string{ts.URL + "/noheader"},
Body: "{ 'test': 'data'}", Body: "{ 'test': 'data'}",
Method: "GET", Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20}, ResponseTimeout: internal.Duration{Duration: time.Second * 20},
@ -400,7 +404,7 @@ func TestHTTPHeaderTags(t *testing.T) {
// Connection failed // Connection failed
h = &HTTPResponse{ h = &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: "https:/nonexistent.nonexistent", // Any non-routable IP works here URLs: []string{"https:/nonexistent.nonexistent"}, // Any non-routable IP works here
Body: "", Body: "",
Method: "GET", Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 5}, ResponseTimeout: internal.Duration{Duration: time.Second * 5},
@ -456,7 +460,7 @@ func TestInterface(t *testing.T) {
h := &HTTPResponse{ h := &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/good", URLs: []string{ts.URL + "/good"},
Body: "{ 'test': 'data'}", Body: "{ 'test': 'data'}",
Method: "GET", Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20}, ResponseTimeout: internal.Duration{Duration: time.Second * 20},
@ -495,7 +499,7 @@ func TestRedirects(t *testing.T) {
h := &HTTPResponse{ h := &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/redirect", URLs: []string{ts.URL + "/redirect"},
Body: "{ 'test': 'data'}", Body: "{ 'test': 'data'}",
Method: "GET", Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20}, ResponseTimeout: internal.Duration{Duration: time.Second * 20},
@ -526,7 +530,7 @@ func TestRedirects(t *testing.T) {
h = &HTTPResponse{ h = &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/badredirect", URLs: []string{ts.URL + "/badredirect"},
Body: "{ 'test': 'data'}", Body: "{ 'test': 'data'}",
Method: "GET", Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20}, ResponseTimeout: internal.Duration{Duration: time.Second * 20},
@ -563,7 +567,7 @@ func TestMethod(t *testing.T) {
h := &HTTPResponse{ h := &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/mustbepostmethod", URLs: []string{ts.URL + "/mustbepostmethod"},
Body: "{ 'test': 'data'}", Body: "{ 'test': 'data'}",
Method: "POST", Method: "POST",
ResponseTimeout: internal.Duration{Duration: time.Second * 20}, ResponseTimeout: internal.Duration{Duration: time.Second * 20},
@ -594,7 +598,7 @@ func TestMethod(t *testing.T) {
h = &HTTPResponse{ h = &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/mustbepostmethod", URLs: []string{ts.URL + "/mustbepostmethod"},
Body: "{ 'test': 'data'}", Body: "{ 'test': 'data'}",
Method: "GET", Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20}, ResponseTimeout: internal.Duration{Duration: time.Second * 20},
@ -626,7 +630,7 @@ func TestMethod(t *testing.T) {
//check that lowercase methods work correctly //check that lowercase methods work correctly
h = &HTTPResponse{ h = &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/mustbepostmethod", URLs: []string{ts.URL + "/mustbepostmethod"},
Body: "{ 'test': 'data'}", Body: "{ 'test': 'data'}",
Method: "head", Method: "head",
ResponseTimeout: internal.Duration{Duration: time.Second * 20}, ResponseTimeout: internal.Duration{Duration: time.Second * 20},
@ -663,7 +667,7 @@ func TestBody(t *testing.T) {
h := &HTTPResponse{ h := &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/musthaveabody", URLs: []string{ts.URL + "/musthaveabody"},
Body: "{ 'test': 'data'}", Body: "{ 'test': 'data'}",
Method: "GET", Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20}, ResponseTimeout: internal.Duration{Duration: time.Second * 20},
@ -694,7 +698,7 @@ func TestBody(t *testing.T) {
h = &HTTPResponse{ h = &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/musthaveabody", URLs: []string{ts.URL + "/musthaveabody"},
Method: "GET", Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20}, ResponseTimeout: internal.Duration{Duration: time.Second * 20},
Headers: map[string]string{ Headers: map[string]string{
@ -728,7 +732,7 @@ func TestStringMatch(t *testing.T) {
h := &HTTPResponse{ h := &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/good", URLs: []string{ts.URL + "/good"},
Body: "{ 'test': 'data'}", Body: "{ 'test': 'data'}",
Method: "GET", Method: "GET",
ResponseStringMatch: "hit the good page", ResponseStringMatch: "hit the good page",
@ -766,7 +770,7 @@ func TestStringMatchJson(t *testing.T) {
h := &HTTPResponse{ h := &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/jsonresponse", URLs: []string{ts.URL + "/jsonresponse"},
Body: "{ 'test': 'data'}", Body: "{ 'test': 'data'}",
Method: "GET", Method: "GET",
ResponseStringMatch: "\"service_status\": \"up\"", ResponseStringMatch: "\"service_status\": \"up\"",
@ -804,7 +808,7 @@ func TestStringMatchFail(t *testing.T) {
h := &HTTPResponse{ h := &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/good", URLs: []string{ts.URL + "/good"},
Body: "{ 'test': 'data'}", Body: "{ 'test': 'data'}",
Method: "GET", Method: "GET",
ResponseStringMatch: "hit the bad page", ResponseStringMatch: "hit the bad page",
@ -847,7 +851,7 @@ func TestTimeout(t *testing.T) {
h := &HTTPResponse{ h := &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/twosecondnap", URLs: []string{ts.URL + "/twosecondnap"},
Body: "{ 'test': 'data'}", Body: "{ 'test': 'data'}",
Method: "GET", Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second}, ResponseTimeout: internal.Duration{Duration: time.Second},
@ -881,7 +885,7 @@ func TestBadRegex(t *testing.T) {
h := &HTTPResponse{ h := &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/good", URLs: []string{ts.URL + "/good"},
Body: "{ 'test': 'data'}", Body: "{ 'test': 'data'}",
Method: "GET", Method: "GET",
ResponseStringMatch: "bad regex:[[", ResponseStringMatch: "bad regex:[[",
@ -905,7 +909,7 @@ func TestNetworkErrors(t *testing.T) {
// DNS error // DNS error
h := &HTTPResponse{ h := &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: "https://nonexistent.nonexistent", // Any non-resolvable URL works here URLs: []string{"https://nonexistent.nonexistent"}, // Any non-resolvable URL works here
Body: "", Body: "",
Method: "GET", Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20}, ResponseTimeout: internal.Duration{Duration: time.Second * 20},
@ -932,7 +936,7 @@ func TestNetworkErrors(t *testing.T) {
// Connection failed // Connection failed
h = &HTTPResponse{ h = &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: "https:/nonexistent.nonexistent", // Any non-routable IP works here URLs: []string{"https:/nonexistent.nonexistent"}, // Any non-routable IP works here
Body: "", Body: "",
Method: "GET", Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 5}, ResponseTimeout: internal.Duration{Duration: time.Second * 5},
@ -1082,7 +1086,7 @@ func TestBasicAuth(t *testing.T) {
h := &HTTPResponse{ h := &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/good", URLs: []string{ts.URL + "/good"},
Body: "{ 'test': 'data'}", Body: "{ 'test': 'data'}",
Method: "GET", Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20}, ResponseTimeout: internal.Duration{Duration: time.Second * 20},
@ -1121,7 +1125,7 @@ func TestStatusCodeMatchFail(t *testing.T) {
h := &HTTPResponse{ h := &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/nocontent", URLs: []string{ts.URL + "/nocontent"},
ResponseStatusCode: http.StatusOK, ResponseStatusCode: http.StatusOK,
ResponseTimeout: internal.Duration{Duration: time.Second * 20}, ResponseTimeout: internal.Duration{Duration: time.Second * 20},
} }
@ -1154,7 +1158,7 @@ func TestStatusCodeMatch(t *testing.T) {
h := &HTTPResponse{ h := &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/nocontent", URLs: []string{ts.URL + "/nocontent"},
ResponseStatusCode: http.StatusNoContent, ResponseStatusCode: http.StatusNoContent,
ResponseTimeout: internal.Duration{Duration: time.Second * 20}, ResponseTimeout: internal.Duration{Duration: time.Second * 20},
} }
@ -1187,7 +1191,7 @@ func TestStatusCodeAndStringMatch(t *testing.T) {
h := &HTTPResponse{ h := &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/good", URLs: []string{ts.URL + "/good"},
ResponseStatusCode: http.StatusOK, ResponseStatusCode: http.StatusOK,
ResponseStringMatch: "hit the good page", ResponseStringMatch: "hit the good page",
ResponseTimeout: internal.Duration{Duration: time.Second * 20}, ResponseTimeout: internal.Duration{Duration: time.Second * 20},
@ -1222,7 +1226,7 @@ func TestStatusCodeAndStringMatchFail(t *testing.T) {
h := &HTTPResponse{ h := &HTTPResponse{
Log: testutil.Logger{}, Log: testutil.Logger{},
Address: ts.URL + "/nocontent", URLs: []string{ts.URL + "/nocontent"},
ResponseStatusCode: http.StatusOK, ResponseStatusCode: http.StatusOK,
ResponseStringMatch: "hit the good page", ResponseStringMatch: "hit the good page",
ResponseTimeout: internal.Duration{Duration: time.Second * 20}, ResponseTimeout: internal.Duration{Duration: time.Second * 20},

View File

@ -8,6 +8,7 @@ import (
"log" "log"
"os" "os"
"os/exec" "os/exec"
"runtime"
"testing" "testing"
) )
@ -133,19 +134,25 @@ func makeFakeSNMPSrc(code string) string {
return path return path
} }
func buildFakeSNMPCmd(src string) { func buildFakeSNMPCmd(src string, executable string) {
err := exec.Command("go", "build", "-o", "snmpwalk", src).Run() err := exec.Command("go", "build", "-o", executable, src).Run()
if err != nil { if err != nil {
log.Fatalln(err) log.Fatalln(err)
} }
} }
func testMain(t *testing.T, code string, endpoint string, serverType ServerType) { func testMain(t *testing.T, code string, endpoint string, serverType ServerType) {
executable := "snmpwalk"
if runtime.GOOS == "windows" {
executable = "snmpwalk.exe"
}
// Build the fake snmpwalk for test // Build the fake snmpwalk for test
src := makeFakeSNMPSrc(code) src := makeFakeSNMPSrc(code)
defer os.Remove(src) defer os.Remove(src)
buildFakeSNMPCmd(src) buildFakeSNMPCmd(src, executable)
defer os.Remove("./snmpwalk") defer os.Remove("./" + executable)
envPathOrigin := os.Getenv("PATH") envPathOrigin := os.Getenv("PATH")
// Refer to the fake snmpwalk // Refer to the fake snmpwalk
os.Setenv("PATH", ".") os.Setenv("PATH", ".")

View File

@ -3,22 +3,26 @@ package logparser
import ( import (
"io/ioutil" "io/ioutil"
"os" "os"
"runtime" "path/filepath"
"strings"
"testing" "testing"
"time" "time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/testutil"
)
var (
testdataDir = getTestdataDir()
) )
func TestStartNoParsers(t *testing.T) { func TestStartNoParsers(t *testing.T) {
logparser := &LogParserPlugin{ logparser := &LogParserPlugin{
Log: testutil.Logger{}, Log: testutil.Logger{},
FromBeginning: true, FromBeginning: true,
Files: []string{"testdata/*.log"}, Files: []string{filepath.Join(testdataDir, "*.log")},
} }
acc := testutil.Accumulator{} acc := testutil.Accumulator{}
@ -26,15 +30,13 @@ func TestStartNoParsers(t *testing.T) {
} }
func TestGrokParseLogFilesNonExistPattern(t *testing.T) { func TestGrokParseLogFilesNonExistPattern(t *testing.T) {
thisdir := getCurrentDir()
logparser := &LogParserPlugin{ logparser := &LogParserPlugin{
Log: testutil.Logger{}, Log: testutil.Logger{},
FromBeginning: true, FromBeginning: true,
Files: []string{thisdir + "testdata/*.log"}, Files: []string{filepath.Join(testdataDir, "*.log")},
GrokConfig: GrokConfig{ GrokConfig: GrokConfig{
Patterns: []string{"%{FOOBAR}"}, Patterns: []string{"%{FOOBAR}"},
CustomPatternFiles: []string{thisdir + "testdata/test-patterns"}, CustomPatternFiles: []string{filepath.Join(testdataDir, "test-patterns")},
}, },
} }
@ -44,17 +46,15 @@ func TestGrokParseLogFilesNonExistPattern(t *testing.T) {
} }
func TestGrokParseLogFiles(t *testing.T) { func TestGrokParseLogFiles(t *testing.T) {
thisdir := getCurrentDir()
logparser := &LogParserPlugin{ logparser := &LogParserPlugin{
Log: testutil.Logger{}, Log: testutil.Logger{},
GrokConfig: GrokConfig{ GrokConfig: GrokConfig{
MeasurementName: "logparser_grok", MeasurementName: "logparser_grok",
Patterns: []string{"%{TEST_LOG_A}", "%{TEST_LOG_B}", "%{TEST_LOG_C}"}, Patterns: []string{"%{TEST_LOG_A}", "%{TEST_LOG_B}", "%{TEST_LOG_C}"},
CustomPatternFiles: []string{thisdir + "testdata/test-patterns"}, CustomPatternFiles: []string{filepath.Join(testdataDir, "test-patterns")},
}, },
FromBeginning: true, FromBeginning: true,
Files: []string{thisdir + "testdata/*.log"}, Files: []string{filepath.Join(testdataDir, "*.log")},
} }
acc := testutil.Accumulator{} acc := testutil.Accumulator{}
@ -68,7 +68,7 @@ func TestGrokParseLogFiles(t *testing.T) {
"logparser_grok", "logparser_grok",
map[string]string{ map[string]string{
"response_code": "200", "response_code": "200",
"path": thisdir + "testdata/test_a.log", "path": filepath.Join(testdataDir, "test_a.log"),
}, },
map[string]interface{}{ map[string]interface{}{
"clientip": "192.168.1.1", "clientip": "192.168.1.1",
@ -81,7 +81,7 @@ func TestGrokParseLogFiles(t *testing.T) {
testutil.MustMetric( testutil.MustMetric(
"logparser_grok", "logparser_grok",
map[string]string{ map[string]string{
"path": thisdir + "testdata/test_b.log", "path": filepath.Join(testdataDir, "test_b.log"),
}, },
map[string]interface{}{ map[string]interface{}{
"myfloat": 1.25, "myfloat": 1.25,
@ -93,7 +93,7 @@ func TestGrokParseLogFiles(t *testing.T) {
testutil.MustMetric( testutil.MustMetric(
"logparser_grok", "logparser_grok",
map[string]string{ map[string]string{
"path": thisdir + "testdata/test_c.log", "path": filepath.Join(testdataDir, "test_c.log"),
"response_code": "200", "response_code": "200",
}, },
map[string]interface{}{ map[string]interface{}{
@ -115,16 +115,14 @@ func TestGrokParseLogFilesAppearLater(t *testing.T) {
defer os.RemoveAll(emptydir) defer os.RemoveAll(emptydir)
assert.NoError(t, err) assert.NoError(t, err)
thisdir := getCurrentDir()
logparser := &LogParserPlugin{ logparser := &LogParserPlugin{
Log: testutil.Logger{}, Log: testutil.Logger{},
FromBeginning: true, FromBeginning: true,
Files: []string{emptydir + "/*.log"}, Files: []string{filepath.Join(emptydir, "*.log")},
GrokConfig: GrokConfig{ GrokConfig: GrokConfig{
MeasurementName: "logparser_grok", MeasurementName: "logparser_grok",
Patterns: []string{"%{TEST_LOG_A}", "%{TEST_LOG_B}"}, Patterns: []string{"%{TEST_LOG_A}", "%{TEST_LOG_B}"},
CustomPatternFiles: []string{thisdir + "testdata/test-patterns"}, CustomPatternFiles: []string{filepath.Join(testdataDir, "test-patterns")},
}, },
} }
@ -133,7 +131,12 @@ func TestGrokParseLogFilesAppearLater(t *testing.T) {
assert.Equal(t, acc.NFields(), 0) assert.Equal(t, acc.NFields(), 0)
_ = os.Symlink(thisdir+"testdata/test_a.log", emptydir+"/test_a.log") input, err := ioutil.ReadFile(filepath.Join(testdataDir, "test_a.log"))
assert.NoError(t, err)
err = ioutil.WriteFile(filepath.Join(emptydir, "test_a.log"), input, 0644)
assert.NoError(t, err)
assert.NoError(t, acc.GatherError(logparser.Gather)) assert.NoError(t, acc.GatherError(logparser.Gather))
acc.Wait(1) acc.Wait(1)
@ -148,23 +151,21 @@ func TestGrokParseLogFilesAppearLater(t *testing.T) {
}, },
map[string]string{ map[string]string{
"response_code": "200", "response_code": "200",
"path": emptydir + "/test_a.log", "path": filepath.Join(emptydir, "test_a.log"),
}) })
} }
// Test that test_a.log line gets parsed even though we don't have the correct // Test that test_a.log line gets parsed even though we don't have the correct
// pattern available for test_b.log // pattern available for test_b.log
func TestGrokParseLogFilesOneBad(t *testing.T) { func TestGrokParseLogFilesOneBad(t *testing.T) {
thisdir := getCurrentDir()
logparser := &LogParserPlugin{ logparser := &LogParserPlugin{
Log: testutil.Logger{}, Log: testutil.Logger{},
FromBeginning: true, FromBeginning: true,
Files: []string{thisdir + "testdata/test_a.log"}, Files: []string{filepath.Join(testdataDir, "test_a.log")},
GrokConfig: GrokConfig{ GrokConfig: GrokConfig{
MeasurementName: "logparser_grok", MeasurementName: "logparser_grok",
Patterns: []string{"%{TEST_LOG_A}", "%{TEST_LOG_BAD}"}, Patterns: []string{"%{TEST_LOG_A}", "%{TEST_LOG_BAD}"},
CustomPatternFiles: []string{thisdir + "testdata/test-patterns"}, CustomPatternFiles: []string{filepath.Join(testdataDir, "test-patterns")},
}, },
} }
@ -184,22 +185,20 @@ func TestGrokParseLogFilesOneBad(t *testing.T) {
}, },
map[string]string{ map[string]string{
"response_code": "200", "response_code": "200",
"path": thisdir + "testdata/test_a.log", "path": filepath.Join(testdataDir, "test_a.log"),
}) })
} }
func TestGrokParseLogFiles_TimestampInEpochMilli(t *testing.T) { func TestGrokParseLogFiles_TimestampInEpochMilli(t *testing.T) {
thisdir := getCurrentDir()
logparser := &LogParserPlugin{ logparser := &LogParserPlugin{
Log: testutil.Logger{}, Log: testutil.Logger{},
GrokConfig: GrokConfig{ GrokConfig: GrokConfig{
MeasurementName: "logparser_grok", MeasurementName: "logparser_grok",
Patterns: []string{"%{TEST_LOG_C}"}, Patterns: []string{"%{TEST_LOG_C}"},
CustomPatternFiles: []string{thisdir + "testdata/test-patterns"}, CustomPatternFiles: []string{filepath.Join(testdataDir, "test-patterns")},
}, },
FromBeginning: true, FromBeginning: true,
Files: []string{thisdir + "testdata/test_c.log"}, Files: []string{filepath.Join(testdataDir, "test_c.log")},
} }
acc := testutil.Accumulator{} acc := testutil.Accumulator{}
@ -218,11 +217,16 @@ func TestGrokParseLogFiles_TimestampInEpochMilli(t *testing.T) {
}, },
map[string]string{ map[string]string{
"response_code": "200", "response_code": "200",
"path": thisdir + "testdata/test_c.log", "path": filepath.Join(testdataDir, "test_c.log"),
}) })
} }
func getCurrentDir() string { func getTestdataDir() string {
_, filename, _, _ := runtime.Caller(1) dir, err := os.Getwd()
return strings.Replace(filename, "logparser_test.go", "", 1) if err != nil {
// if we cannot even establish the test directory, further progress is meaningless
panic(err)
}
return filepath.Join(dir, "testdata")
} }

View File

@ -1,5 +1,9 @@
// +build !windows
// lustre2 doesn't aim for Windows
/* /*
Lustre 2.x telegraf plugin Lustre 2.x Telegraf plugin
Lustre (http://lustre.org/) is an open-source, parallel file system Lustre (http://lustre.org/) is an open-source, parallel file system
for HPC environments. It stores statistics about its activity in for HPC environments. It stores statistics about its activity in

View File

@ -1,3 +1,5 @@
// +build !windows
package lustre2 package lustre2
import ( import (

View File

@ -0,0 +1,3 @@
// +build windows
package lustre2

View File

@ -4,6 +4,7 @@ import (
"errors" "errors"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url"
"testing" "testing"
"time" "time"
@ -573,21 +574,19 @@ func TestAllowHosts(t *testing.T) {
} }
func TestConnection(t *testing.T) { func TestConnection(t *testing.T) {
r := &Monit{ r := &Monit{
Address: "http://127.0.0.1:2812", Address: "http://127.0.0.1:2812",
Username: "test", Username: "test",
Password: "test", Password: "test",
} }
var acc testutil.Accumulator
r.Init() r.Init()
var acc testutil.Accumulator
err := r.Gather(&acc) err := r.Gather(&acc)
if assert.Error(t, err) { if assert.Error(t, err) {
assert.Contains(t, err.Error(), "connect: connection refused") _, ok := err.(*url.Error)
assert.True(t, ok)
} }
} }

View File

@ -91,6 +91,7 @@ func TestTCPError(t *testing.T) {
c := NetResponse{ c := NetResponse{
Protocol: "tcp", Protocol: "tcp",
Address: ":9999", Address: ":9999",
Timeout: internal.Duration{Duration: time.Second * 30},
} }
// Error // Error
err1 := c.Gather(&acc) err1 := c.Gather(&acc)

View File

@ -4,20 +4,37 @@ import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath"
"runtime"
"strings"
"testing" "testing"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/influxdata/telegraf/testutil"
) )
func fakePassengerStatus(stat string) { func fakePassengerStatus(stat string) string {
content := fmt.Sprintf("#!/bin/sh\ncat << EOF\n%s\nEOF", stat) var fileExtension, content string
ioutil.WriteFile("/tmp/passenger-status", []byte(content), 0700) if runtime.GOOS == "windows" {
fileExtension = ".bat"
content = "@echo off\n"
for _, line := range strings.Split(strings.TrimSuffix(stat, "\n"), "\n") {
content += "for /f \"delims=\" %%A in (\"" + line + "\") do echo %%~A\n" //my eyes are bleeding
}
} else {
content = fmt.Sprintf("#!/bin/sh\ncat << EOF\n%s\nEOF", stat)
}
tempFilePath := filepath.Join(os.TempDir(), "passenger-status"+fileExtension)
ioutil.WriteFile(tempFilePath, []byte(content), 0700)
return tempFilePath
} }
func teardown() { func teardown(tempFilePath string) {
os.Remove("/tmp/passenger-status") os.Remove(tempFilePath)
} }
func Test_Invalid_Passenger_Status_Cli(t *testing.T) { func Test_Invalid_Passenger_Status_Cli(t *testing.T) {
@ -29,28 +46,28 @@ func Test_Invalid_Passenger_Status_Cli(t *testing.T) {
err := r.Gather(&acc) err := r.Gather(&acc)
require.Error(t, err) require.Error(t, err)
assert.Equal(t, err.Error(), `exec: "an-invalid-command": executable file not found in $PATH`) assert.Contains(t, err.Error(), `exec: "an-invalid-command": executable file not found in `)
} }
func Test_Invalid_Xml(t *testing.T) { func Test_Invalid_Xml(t *testing.T) {
fakePassengerStatus("invalid xml") tempFilePath := fakePassengerStatus("invalid xml")
defer teardown() defer teardown(tempFilePath)
r := &passenger{ r := &passenger{
Command: "/tmp/passenger-status", Command: tempFilePath,
} }
var acc testutil.Accumulator var acc testutil.Accumulator
err := r.Gather(&acc) err := r.Gather(&acc)
require.Error(t, err) require.Error(t, err)
assert.Equal(t, err.Error(), "Cannot parse input with error: EOF\n") assert.Equal(t, "Cannot parse input with error: EOF\n", err.Error())
} }
// We test this by ensure that the error message match the path of default cli // We test this by ensure that the error message match the path of default cli
func Test_Default_Config_Load_Default_Command(t *testing.T) { func Test_Default_Config_Load_Default_Command(t *testing.T) {
fakePassengerStatus("invalid xml") tempFilePath := fakePassengerStatus("invalid xml")
defer teardown() defer teardown(tempFilePath)
r := &passenger{} r := &passenger{}
@ -58,16 +75,16 @@ func Test_Default_Config_Load_Default_Command(t *testing.T) {
err := r.Gather(&acc) err := r.Gather(&acc)
require.Error(t, err) require.Error(t, err)
assert.Equal(t, err.Error(), "exec: \"passenger-status\": executable file not found in $PATH") assert.Contains(t, err.Error(), "exec: \"passenger-status\": executable file not found in ")
} }
func TestPassengerGenerateMetric(t *testing.T) { func TestPassengerGenerateMetric(t *testing.T) {
fakePassengerStatus(sampleStat) tempFilePath := fakePassengerStatus(sampleStat)
defer teardown() defer teardown(tempFilePath)
//Now we tested again above server, with our authentication data //Now we tested again above server, with our authentication data
r := &passenger{ r := &passenger{
Command: "/tmp/passenger-status", Command: tempFilePath,
} }
var acc testutil.Accumulator var acc testutil.Accumulator

View File

@ -1,3 +1,8 @@
// +build !windows
// TODO: Windows - should be enabled for Windows when super asterisk is fixed on Windows
// https://github.com/influxdata/telegraf/issues/6248
package phpfpm package phpfpm
import ( import (

View File

@ -1,3 +1,7 @@
// +build !windows
// postfix doesn't aim for Windows
package postfix package postfix
import ( import (

View File

@ -1,3 +1,5 @@
// +build !windows
package postfix package postfix
import ( import (

View File

@ -0,0 +1,3 @@
// +build windows
package postfix

View File

@ -3,11 +3,14 @@ package powerdns
import ( import (
"fmt" "fmt"
"net" "net"
"os"
"path/filepath"
"testing" "testing"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/influxdata/telegraf/testutil"
) )
type statServer struct{} type statServer struct{}
@ -71,7 +74,8 @@ func (s statServer) serverSocket(l net.Listener) {
func TestPowerdnsGeneratesMetrics(t *testing.T) { func TestPowerdnsGeneratesMetrics(t *testing.T) {
// We create a fake server to return test data // We create a fake server to return test data
randomNumber := int64(5239846799706671610) randomNumber := int64(5239846799706671610)
socket, err := net.Listen("unix", fmt.Sprintf("/tmp/pdns%d.controlsocket", randomNumber)) sockname := filepath.Join(os.TempDir(), fmt.Sprintf("pdns%d.controlsocket", randomNumber))
socket, err := net.Listen("unix", sockname)
if err != nil { if err != nil {
t.Fatal("Cannot initialize server on port ") t.Fatal("Cannot initialize server on port ")
} }
@ -82,11 +86,10 @@ func TestPowerdnsGeneratesMetrics(t *testing.T) {
go s.serverSocket(socket) go s.serverSocket(socket)
p := &Powerdns{ p := &Powerdns{
UnixSockets: []string{fmt.Sprintf("/tmp/pdns%d.controlsocket", randomNumber)}, UnixSockets: []string{sockname},
} }
var acc testutil.Accumulator var acc testutil.Accumulator
err = acc.GatherError(p.Gather) err = acc.GatherError(p.Gather)
require.NoError(t, err) require.NoError(t, err)

View File

@ -99,8 +99,8 @@ var intOverflowMetrics = "all-outqueries\t18446744073709550195\nanswers-slow\t36
"x-ourtime2-4\t302\nx-ourtime4-8\t194\nx-ourtime8-16\t24\n" "x-ourtime2-4\t302\nx-ourtime4-8\t194\nx-ourtime8-16\t24\n"
func TestPowerdnsRecursorGeneratesMetrics(t *testing.T) { func TestPowerdnsRecursorGeneratesMetrics(t *testing.T) {
if runtime.GOOS == "darwin" { if runtime.GOOS == "darwin" || runtime.GOOS == "windows" {
t.Skip("Skipping test on darwin") t.Skip("Skipping on windows and darwin, as unixgram sockets are not supported")
} }
// We create a fake server to return test data // We create a fake server to return test data
controlSocket := "/tmp/pdns5724354148158589552.controlsocket" controlSocket := "/tmp/pdns5724354148158589552.controlsocket"

View File

@ -8,9 +8,11 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
) )
func TestDellApis(t *testing.T) { func TestDellApis(t *testing.T) {
@ -643,7 +645,6 @@ func checkAuth(r *http.Request, username, password string) bool {
} }
func TestConnection(t *testing.T) { func TestConnection(t *testing.T) {
r := &Redfish{ r := &Redfish{
Address: "http://127.0.0.1", Address: "http://127.0.0.1",
Username: "test", Username: "test",
@ -654,8 +655,10 @@ func TestConnection(t *testing.T) {
var acc testutil.Accumulator var acc testutil.Accumulator
r.Init() r.Init()
err := r.Gather(&acc) err := r.Gather(&acc)
require.Error(t, err) if assert.Error(t, err) {
require.Contains(t, err.Error(), "connect: connection refused") _, ok := err.(*url.Error)
assert.True(t, ok)
}
} }
func TestInvalidUsernameorPassword(t *testing.T) { func TestInvalidUsernameorPassword(t *testing.T) {

View File

@ -640,8 +640,8 @@ func TestGather(t *testing.T) {
assert.Len(t, m.Fields, 2) assert.Len(t, m.Fields, 2)
assert.Equal(t, 234, m.Fields["myfield2"]) assert.Equal(t, 234, m.Fields["myfield2"])
assert.Equal(t, "baz", m.Fields["myfield3"]) assert.Equal(t, "baz", m.Fields["myfield3"])
assert.True(t, tstart.Before(m.Time)) assert.True(t, !tstart.After(m.Time))
assert.True(t, tstop.After(m.Time)) assert.True(t, !tstop.Before(m.Time))
m2 := acc.Metrics[1] m2 := acc.Metrics[1]
assert.Equal(t, "myOtherTable", m2.Measurement) assert.Equal(t, "myOtherTable", m2.Measurement)

View File

@ -9,6 +9,7 @@ import (
"net" "net"
"os" "os"
"path/filepath" "path/filepath"
"runtime"
"testing" "testing"
"time" "time"
@ -138,7 +139,8 @@ func TestSocketListener_unix(t *testing.T) {
defer testEmptyLog(t)() defer testEmptyLog(t)()
os.Create(sock) f, _ := os.Create(sock)
f.Close()
sl := newSocketListener() sl := newSocketListener()
sl.Log = testutil.Logger{} sl.Log = testutil.Logger{}
sl.ServiceAddress = "unix://" + sock sl.ServiceAddress = "unix://" + sock
@ -156,6 +158,10 @@ func TestSocketListener_unix(t *testing.T) {
} }
func TestSocketListener_unixgram(t *testing.T) { func TestSocketListener_unixgram(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Skipping on Windows, as unixgram sockets are not supported")
}
tmpdir, err := ioutil.TempDir("", "telegraf") tmpdir, err := ioutil.TempDir("", "telegraf")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(tmpdir) defer os.RemoveAll(tmpdir)

View File

@ -9,11 +9,12 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal" "github.com/influxdata/telegraf/internal"
framing "github.com/influxdata/telegraf/internal/syslog" framing "github.com/influxdata/telegraf/internal/syslog"
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
) )
func getTestCasesForNonTransparent() []testCaseStream { func getTestCasesForNonTransparent() []testCaseStream {

View File

@ -10,11 +10,12 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal" "github.com/influxdata/telegraf/internal"
framing "github.com/influxdata/telegraf/internal/syslog" framing "github.com/influxdata/telegraf/internal/syslog"
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
) )
func getTestCasesForOctetCounting() []testCaseStream { func getTestCasesForOctetCounting() []testCaseStream {

View File

@ -6,13 +6,15 @@ import (
"net" "net"
"os" "os"
"path/filepath" "path/filepath"
"runtime"
"sync/atomic" "sync/atomic"
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
) )
func getTestCasesForRFC5426() []testCasePacket { func getTestCasesForRFC5426() []testCasePacket {
@ -284,6 +286,10 @@ func TestStrict_udp(t *testing.T) {
} }
func TestBestEffort_unixgram(t *testing.T) { func TestBestEffort_unixgram(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Skipping on Windows, as unixgram sockets are not supported")
}
tmpdir, err := ioutil.TempDir("", "telegraf") tmpdir, err := ioutil.TempDir("", "telegraf")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(tmpdir) defer os.RemoveAll(tmpdir)
@ -293,6 +299,10 @@ func TestBestEffort_unixgram(t *testing.T) {
} }
func TestStrict_unixgram(t *testing.T) { func TestStrict_unixgram(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Skipping on Windows, as unixgram sockets are not supported")
}
tmpdir, err := ioutil.TempDir("", "telegraf") tmpdir, err := ioutil.TempDir("", "telegraf")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(tmpdir) defer os.RemoveAll(tmpdir)

View File

@ -7,6 +7,7 @@ import (
"net" "net"
"net/url" "net/url"
"os" "os"
"path/filepath"
"strings" "strings"
"sync" "sync"
"time" "time"
@ -16,6 +17,7 @@ import (
"github.com/influxdata/go-syslog/v2/nontransparent" "github.com/influxdata/go-syslog/v2/nontransparent"
"github.com/influxdata/go-syslog/v2/octetcounting" "github.com/influxdata/go-syslog/v2/octetcounting"
"github.com/influxdata/go-syslog/v2/rfc5424" "github.com/influxdata/go-syslog/v2/rfc5424"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal" "github.com/influxdata/telegraf/internal"
framing "github.com/influxdata/telegraf/internal/syslog" framing "github.com/influxdata/telegraf/internal/syslog"
@ -195,7 +197,10 @@ func getAddressParts(a string) (string, string, error) {
return "", "", fmt.Errorf("missing protocol within address '%s'", a) return "", "", fmt.Errorf("missing protocol within address '%s'", a)
} }
u, _ := url.Parse(a) u, err := url.Parse(filepath.ToSlash(a)) //convert backslashes to slashes (to make Windows path a valid URL)
if err != nil {
return "", "", fmt.Errorf("could not parse address '%s': %v", a, err)
}
switch u.Scheme { switch u.Scheme {
case "unix", "unixpacket", "unixgram": case "unix", "unixpacket", "unixgram":
return parts[0], parts[1], nil return parts[0], parts[1], nil

View File

@ -4,12 +4,14 @@ import (
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"runtime"
"strings" "strings"
"testing" "testing"
"time" "time"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/influxdata/telegraf/testutil"
) )
const ( const (
@ -49,13 +51,16 @@ func TestAddress(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
sock := filepath.Join(tmpdir, "syslog.TestAddress.sock") sock := filepath.Join(tmpdir, "syslog.TestAddress.sock")
rec = &Syslog{ if runtime.GOOS != "windows" {
Address: "unixgram://" + sock, // Skipping on Windows, as unixgram sockets are not supported
rec = &Syslog{
Address: "unixgram://" + sock,
}
err = rec.Start(&testutil.Accumulator{})
require.NoError(t, err)
require.Equal(t, sock, rec.Address)
rec.Stop()
} }
err = rec.Start(&testutil.Accumulator{})
require.NoError(t, err)
require.Equal(t, sock, rec.Address)
rec.Stop()
// Default port is 6514 // Default port is 6514
rec = &Syslog{ rec = &Syslog{

View File

@ -5,11 +5,13 @@ import (
"io/ioutil" "io/ioutil"
"log" "log"
"os" "os"
"runtime" "path/filepath"
"strings"
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal" "github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/parsers" "github.com/influxdata/telegraf/plugins/parsers"
@ -17,8 +19,10 @@ import (
"github.com/influxdata/telegraf/plugins/parsers/influx" "github.com/influxdata/telegraf/plugins/parsers/influx"
"github.com/influxdata/telegraf/plugins/parsers/json" "github.com/influxdata/telegraf/plugins/parsers/json"
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/assert" )
"github.com/stretchr/testify/require"
var (
testdataDir = getTestdataDir()
) )
func TestTailBadLine(t *testing.T) { func TestTailBadLine(t *testing.T) {
@ -58,7 +62,7 @@ func TestTailBadLine(t *testing.T) {
assert.Contains(t, buf.String(), "Malformed log line") assert.Contains(t, buf.String(), "Malformed log line")
} }
func TestTailDosLineendings(t *testing.T) { func TestTailDosLineEndings(t *testing.T) {
tmpfile, err := ioutil.TempFile("", "") tmpfile, err := ioutil.TempFile("", "")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tmpfile.Name()) defer os.Remove(tmpfile.Name())
@ -92,14 +96,13 @@ func TestTailDosLineendings(t *testing.T) {
} }
func TestGrokParseLogFilesWithMultiline(t *testing.T) { func TestGrokParseLogFilesWithMultiline(t *testing.T) {
thisdir := getCurrentDir()
//we make sure the timeout won't kick in //we make sure the timeout won't kick in
duration, _ := time.ParseDuration("100s") duration, _ := time.ParseDuration("100s")
tt := NewTail() tt := NewTail()
tt.Log = testutil.Logger{} tt.Log = testutil.Logger{}
tt.FromBeginning = true tt.FromBeginning = true
tt.Files = []string{thisdir + "testdata/test_multiline.log"} tt.Files = []string{filepath.Join(testdataDir, "test_multiline.log")}
tt.MultilineConfig = MultilineConfig{ tt.MultilineConfig = MultilineConfig{
Pattern: `^[^\[]`, Pattern: `^[^\[]`,
MatchWhichLine: Previous, MatchWhichLine: Previous,
@ -117,7 +120,7 @@ func TestGrokParseLogFilesWithMultiline(t *testing.T) {
acc.Wait(3) acc.Wait(3)
expectedPath := thisdir + "testdata/test_multiline.log" expectedPath := filepath.Join(testdataDir, "test_multiline.log")
acc.AssertContainsTaggedFields(t, "tail_grok", acc.AssertContainsTaggedFields(t, "tail_grok",
map[string]interface{}{ map[string]interface{}{
"message": "HelloExample: This is debug", "message": "HelloExample: This is debug",
@ -151,7 +154,7 @@ func TestGrokParseLogFilesWithMultilineTimeout(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tmpfile.Name()) defer os.Remove(tmpfile.Name())
// This seems neccessary in order to get the test to read the following lines. // This seems necessary in order to get the test to read the following lines.
_, err = tmpfile.WriteString("[04/Jun/2016:12:41:48 +0100] INFO HelloExample: This is fluff\r\n") _, err = tmpfile.WriteString("[04/Jun/2016:12:41:48 +0100] INFO HelloExample: This is fluff\r\n")
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, tmpfile.Sync()) require.NoError(t, tmpfile.Sync())
@ -209,14 +212,13 @@ func TestGrokParseLogFilesWithMultilineTimeout(t *testing.T) {
} }
func TestGrokParseLogFilesWithMultilineTailerCloseFlushesMultilineBuffer(t *testing.T) { func TestGrokParseLogFilesWithMultilineTailerCloseFlushesMultilineBuffer(t *testing.T) {
thisdir := getCurrentDir()
//we make sure the timeout won't kick in //we make sure the timeout won't kick in
duration := 100 * time.Second duration := 100 * time.Second
tt := NewTail() tt := NewTail()
tt.Log = testutil.Logger{} tt.Log = testutil.Logger{}
tt.FromBeginning = true tt.FromBeginning = true
tt.Files = []string{thisdir + "testdata/test_multiline.log"} tt.Files = []string{filepath.Join(testdataDir, "test_multiline.log")}
tt.MultilineConfig = MultilineConfig{ tt.MultilineConfig = MultilineConfig{
Pattern: `^[^\[]`, Pattern: `^[^\[]`,
MatchWhichLine: Previous, MatchWhichLine: Previous,
@ -236,7 +238,7 @@ func TestGrokParseLogFilesWithMultilineTailerCloseFlushesMultilineBuffer(t *test
tt.Stop() tt.Stop()
acc.Wait(4) acc.Wait(4)
expectedPath := thisdir + "testdata/test_multiline.log" expectedPath := filepath.Join(testdataDir, "test_multiline.log")
acc.AssertContainsTaggedFields(t, "tail_grok", acc.AssertContainsTaggedFields(t, "tail_grok",
map[string]interface{}{ map[string]interface{}{
"message": "HelloExample: This is warn", "message": "HelloExample: This is warn",
@ -251,7 +253,7 @@ func createGrokParser() (parsers.Parser, error) {
grokConfig := &parsers.Config{ grokConfig := &parsers.Config{
MetricName: "tail_grok", MetricName: "tail_grok",
GrokPatterns: []string{"%{TEST_LOG_MULTILINE}"}, GrokPatterns: []string{"%{TEST_LOG_MULTILINE}"},
GrokCustomPatternFiles: []string{getCurrentDir() + "testdata/test-patterns"}, GrokCustomPatternFiles: []string{filepath.Join(testdataDir, "test-patterns")},
DataFormat: "grok", DataFormat: "grok",
} }
parser, err := parsers.NewParser(grokConfig) parser, err := parsers.NewParser(grokConfig)
@ -374,11 +376,6 @@ func TestMultipleMetricsOnFirstLine(t *testing.T) {
testutil.IgnoreTime()) testutil.IgnoreTime())
} }
func getCurrentDir() string {
_, filename, _, _ := runtime.Caller(1)
return strings.Replace(filename, "tail_test.go", "", 1)
}
func TestCharacterEncoding(t *testing.T) { func TestCharacterEncoding(t *testing.T) {
full := []telegraf.Metric{ full := []telegraf.Metric{
testutil.MustMetric("cpu", testutil.MustMetric("cpu",
@ -437,7 +434,7 @@ func TestCharacterEncoding(t *testing.T) {
{ {
name: "utf-8", name: "utf-8",
plugin: &Tail{ plugin: &Tail{
Files: []string{"testdata/cpu-utf-8.influx"}, Files: []string{filepath.Join(testdataDir, "cpu-utf-8.influx")},
FromBeginning: true, FromBeginning: true,
MaxUndeliveredLines: 1000, MaxUndeliveredLines: 1000,
Log: testutil.Logger{}, Log: testutil.Logger{},
@ -448,7 +445,7 @@ func TestCharacterEncoding(t *testing.T) {
{ {
name: "utf-8 seek", name: "utf-8 seek",
plugin: &Tail{ plugin: &Tail{
Files: []string{"testdata/cpu-utf-8.influx"}, Files: []string{filepath.Join(testdataDir, "cpu-utf-8.influx")},
MaxUndeliveredLines: 1000, MaxUndeliveredLines: 1000,
Log: testutil.Logger{}, Log: testutil.Logger{},
CharacterEncoding: "utf-8", CharacterEncoding: "utf-8",
@ -459,7 +456,7 @@ func TestCharacterEncoding(t *testing.T) {
{ {
name: "utf-16le", name: "utf-16le",
plugin: &Tail{ plugin: &Tail{
Files: []string{"testdata/cpu-utf-16le.influx"}, Files: []string{filepath.Join(testdataDir, "cpu-utf-16le.influx")},
FromBeginning: true, FromBeginning: true,
MaxUndeliveredLines: 1000, MaxUndeliveredLines: 1000,
Log: testutil.Logger{}, Log: testutil.Logger{},
@ -470,7 +467,7 @@ func TestCharacterEncoding(t *testing.T) {
{ {
name: "utf-16le seek", name: "utf-16le seek",
plugin: &Tail{ plugin: &Tail{
Files: []string{"testdata/cpu-utf-16le.influx"}, Files: []string{filepath.Join(testdataDir, "cpu-utf-16le.influx")},
MaxUndeliveredLines: 1000, MaxUndeliveredLines: 1000,
Log: testutil.Logger{}, Log: testutil.Logger{},
CharacterEncoding: "utf-16le", CharacterEncoding: "utf-16le",
@ -481,7 +478,7 @@ func TestCharacterEncoding(t *testing.T) {
{ {
name: "utf-16be", name: "utf-16be",
plugin: &Tail{ plugin: &Tail{
Files: []string{"testdata/cpu-utf-16be.influx"}, Files: []string{filepath.Join(testdataDir, "cpu-utf-16be.influx")},
FromBeginning: true, FromBeginning: true,
MaxUndeliveredLines: 1000, MaxUndeliveredLines: 1000,
Log: testutil.Logger{}, Log: testutil.Logger{},
@ -565,3 +562,13 @@ func TestTailEOF(t *testing.T) {
err = tmpfile.Close() err = tmpfile.Close()
require.NoError(t, err) require.NoError(t, err)
} }
func getTestdataDir() string {
dir, err := os.Getwd()
if err != nil {
// if we cannot even establish the test directory, further progress is meaningless
panic(err)
}
return filepath.Join(dir, "testdata")
}

View File

@ -10,6 +10,7 @@ import (
"io/ioutil" "io/ioutil"
"net" "net"
"net/url" "net/url"
"path/filepath"
"strings" "strings"
"time" "time"
@ -60,6 +61,9 @@ func (c *X509Cert) locationToURL(location string) (*url.URL, error) {
if strings.HasPrefix(location, "/") { if strings.HasPrefix(location, "/") {
location = "file://" + location location = "file://" + location
} }
if strings.Index(location, ":\\") == 1 {
location = "file://" + filepath.ToSlash(location)
}
u, err := url.Parse(location) u, err := url.Parse(location)
if err != nil { if err != nil {

View File

@ -7,6 +7,8 @@ import (
"io/ioutil" "io/ioutil"
"math/big" "math/big"
"os" "os"
"path/filepath"
"runtime"
"testing" "testing"
"time" "time"
@ -51,7 +53,7 @@ func TestGatherRemote(t *testing.T) {
{name: "wrong port", server: ":99999", error: true}, {name: "wrong port", server: ":99999", error: true},
{name: "no server", timeout: 5}, {name: "no server", timeout: 5},
{name: "successful https", server: "https://example.org:443", timeout: 5}, {name: "successful https", server: "https://example.org:443", timeout: 5},
{name: "successful file", server: "file://" + tmpfile.Name(), timeout: 5}, {name: "successful file", server: "file://" + filepath.ToSlash(tmpfile.Name()), timeout: 5},
{name: "unsupported scheme", server: "foo://", timeout: 5, error: true}, {name: "unsupported scheme", server: "foo://", timeout: 5, error: true},
{name: "no certificate", timeout: 5, unset: true, error: true}, {name: "no certificate", timeout: 5, unset: true, error: true},
{name: "closed connection", close: true, error: true}, {name: "closed connection", close: true, error: true},
@ -166,9 +168,11 @@ func TestGatherLocal(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
err = f.Chmod(test.mode) if runtime.GOOS != "windows" {
if err != nil { err = f.Chmod(test.mode)
t.Fatal(err) if err != nil {
t.Fatal(err)
}
} }
err = f.Close() err = f.Close()

View File

@ -6,6 +6,7 @@ import (
"net" "net"
"os" "os"
"path/filepath" "path/filepath"
"runtime"
"sync" "sync"
"testing" "testing"
@ -66,6 +67,10 @@ func TestSocketWriter_unix(t *testing.T) {
} }
func TestSocketWriter_unixgram(t *testing.T) { func TestSocketWriter_unixgram(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Skipping on Windows, as unixgram sockets are not supported")
}
tmpdir, err := ioutil.TempDir("", "telegraf") tmpdir, err := ioutil.TempDir("", "telegraf")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(tmpdir) defer os.RemoveAll(tmpdir)

View File

@ -6,12 +6,13 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal" "github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/internal/snmp" "github.com/influxdata/telegraf/internal/snmp"
si "github.com/influxdata/telegraf/plugins/inputs/snmp" si "github.com/influxdata/telegraf/plugins/inputs/snmp"
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
) )
func TestTable(t *testing.T) { func TestTable(t *testing.T) {

View File

@ -1,6 +1,7 @@
package ifname package ifname
import ( import (
"runtime"
"time" "time"
) )
@ -30,6 +31,15 @@ func (c *TTLCache) Get(key keyType) (valType, bool, time.Duration) {
if !ok { if !ok {
return valType{}, false, 0 return valType{}, false, 0
} }
if runtime.GOOS == "windows" {
// Sometimes on Windows `c.now().Sub(v.time) == 0` due to clock resolution issues:
// https://github.com/golang/go/issues/17696
// https://github.com/golang/go/issues/29485
// Force clock to refresh:
time.Sleep(time.Nanosecond)
}
age := c.now().Sub(v.time) age := c.now().Sub(v.time)
if age < c.validDuration { if age < c.validDuration {
return v.val, ok, age return v.val, ok, age

View File

@ -111,7 +111,7 @@ func (d *ReverseDNSCache) lookup(ip string) ([]string, error) {
// check if the value is cached // check if the value is cached
d.rwLock.RLock() d.rwLock.RLock()
result, found := d.lockedGetFromCache(ip) result, found := d.lockedGetFromCache(ip)
if found && result.completed && result.expiresAt.After(time.Now()) { if found && result.completed && !result.expiresAt.Before(time.Now()) {
defer d.rwLock.RUnlock() defer d.rwLock.RUnlock()
atomic.AddUint64(&d.stats.CacheHit, 1) atomic.AddUint64(&d.stats.CacheHit, 1)
// cache is valid // cache is valid
@ -176,7 +176,7 @@ func (d *ReverseDNSCache) subscribeTo(ip string) callbackChannelType {
// the dnslookup that is returned until you clone it. // the dnslookup that is returned until you clone it.
func (d *ReverseDNSCache) lockedGetFromCache(ip string) (lookup *dnslookup, found bool) { func (d *ReverseDNSCache) lockedGetFromCache(ip string) (lookup *dnslookup, found bool) {
lookup, found = d.cache[ip] lookup, found = d.cache[ip]
if found && lookup.expiresAt.Before(time.Now()) { if found && !lookup.expiresAt.After(time.Now()) {
return nil, false return nil, false
} }
return lookup, found return lookup, found
@ -185,7 +185,7 @@ func (d *ReverseDNSCache) lockedGetFromCache(ip string) (lookup *dnslookup, foun
// lockedSaveToCache stores a lookup in the correct internal ip cache. // lockedSaveToCache stores a lookup in the correct internal ip cache.
// you MUST first do a write lock before calling it. // you MUST first do a write lock before calling it.
func (d *ReverseDNSCache) lockedSaveToCache(lookup *dnslookup) { func (d *ReverseDNSCache) lockedSaveToCache(lookup *dnslookup) {
if lookup.expiresAt.Before(time.Now()) { if !lookup.expiresAt.After(time.Now()) {
return // don't cache. return // don't cache.
} }
d.cache[lookup.ip] = lookup d.cache[lookup.ip] = lookup
@ -277,7 +277,7 @@ func (d *ReverseDNSCache) cleanup() {
} }
ipsToDelete := []string{} ipsToDelete := []string{}
for i := 0; i < len(d.expireList); i++ { for i := 0; i < len(d.expireList); i++ {
if d.expireList[i].expiresAt.After(now) { if !d.expireList[i].expiresAt.Before(now) {
break // done. Nothing after this point is expired. break // done. Nothing after this point is expired.
} }
ipsToDelete = append(ipsToDelete, d.expireList[i].ip) ipsToDelete = append(ipsToDelete, d.expireList[i].ip)

View File

@ -1,13 +1,15 @@
package reverse_dns package reverse_dns
import ( import (
"runtime"
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/metric"
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
) )
func TestSimpleReverseLookup(t *testing.T) { func TestSimpleReverseLookup(t *testing.T) {
@ -40,7 +42,10 @@ func TestSimpleReverseLookup(t *testing.T) {
processedMetric := acc.GetTelegrafMetrics()[0] processedMetric := acc.GetTelegrafMetrics()[0]
f, ok := processedMetric.GetField("source_name") f, ok := processedMetric.GetField("source_name")
require.True(t, ok) require.True(t, ok)
require.EqualValues(t, "localhost", f) if runtime.GOOS != "windows" {
// lookupAddr on Windows works differently than on Linux so `source_name` won't be "localhost" on every environment
require.EqualValues(t, "localhost", f)
}
tag, ok := processedMetric.GetTag("dest_name") tag, ok := processedMetric.GetTag("dest_name")
require.True(t, ok) require.True(t, ok)