From 0fcfee0caf908adc6c2ff4711d791b6cef181de9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20=C5=BBak?= Date: Mon, 23 Nov 2020 16:40:32 +0100 Subject: [PATCH] Fix tests for Windows - part 1 (#8414) --- .gitattributes | 1 + Makefile | 7 +- appveyor.yml | 2 +- config/config_test.go | 3 +- config/testdata/telegraf-agent.toml | 8 -- internal/globpath/globpath_test.go | 54 ++++++++----- plugins/inputs/bcache/README.md | 18 ++--- plugins/inputs/bcache/bcache.go | 6 +- plugins/inputs/bcache/bcache_test.go | 2 + plugins/inputs/bcache/bcache_windows.go | 3 + plugins/inputs/ceph/ceph_test.go | 8 +- plugins/inputs/disk/disk_test.go | 11 +-- plugins/inputs/exec/exec_test.go | 5 ++ plugins/inputs/execd/execd_test.go | 11 +-- plugins/inputs/execd/shim/shim_posix_test.go | 5 -- plugins/inputs/file/file_test.go | 5 ++ plugins/inputs/filecount/filecount_test.go | 5 ++ .../filecount/filesystem_helpers_test.go | 5 ++ plugins/inputs/filestat/filestat_test.go | 78 ++++++++++--------- plugins/inputs/haproxy/haproxy_test.go | 11 ++- .../http_response/http_response_test.go | 60 +++++++------- plugins/inputs/leofs/leofs_test.go | 15 +++- plugins/inputs/logparser/logparser_test.go | 74 +++++++++--------- plugins/inputs/lustre2/lustre2.go | 6 +- plugins/inputs/lustre2/lustre2_test.go | 2 + plugins/inputs/lustre2/lustre2_windows.go | 3 + plugins/inputs/monit/monit_test.go | 9 +-- .../inputs/net_response/net_response_test.go | 1 + plugins/inputs/passenger/passenger_test.go | 51 ++++++++---- plugins/inputs/phpfpm/phpfpm_test.go | 5 ++ plugins/inputs/postfix/postfix.go | 4 + plugins/inputs/postfix/postfix_test.go | 2 + plugins/inputs/postfix/postfix_windows.go | 3 + plugins/inputs/powerdns/powerdns_test.go | 11 ++- .../powerdns_recursor_test.go | 4 +- plugins/inputs/redfish/redfish_test.go | 11 ++- plugins/inputs/snmp/snmp_test.go | 4 +- .../socket_listener/socket_listener_test.go | 8 +- plugins/inputs/syslog/nontransparent_test.go | 3 +- plugins/inputs/syslog/octetcounting_test.go | 3 +- plugins/inputs/syslog/rfc5426_test.go | 12 ++- plugins/inputs/syslog/syslog.go | 7 +- plugins/inputs/syslog/syslog_test.go | 19 +++-- plugins/inputs/tail/tail_test.go | 53 +++++++------ plugins/inputs/x509_cert/x509_cert.go | 4 + plugins/inputs/x509_cert/x509_cert_test.go | 12 ++- .../socket_writer/socket_writer_test.go | 5 ++ plugins/processors/ifname/ifname_test.go | 3 +- plugins/processors/ifname/ttl_cache.go | 10 +++ plugins/processors/reverse_dns/rdnscache.go | 8 +- .../processors/reverse_dns/reversedns_test.go | 9 ++- 51 files changed, 416 insertions(+), 253 deletions(-) create mode 100644 plugins/inputs/bcache/bcache_windows.go create mode 100644 plugins/inputs/lustre2/lustre2_windows.go create mode 100644 plugins/inputs/postfix/postfix_windows.go diff --git a/.gitattributes b/.gitattributes index 21bc439bf..7769daa83 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,3 +3,4 @@ README.md merge=union go.sum merge=union plugins/inputs/all/all.go merge=union plugins/outputs/all/all.go merge=union +**/testdata/** test eol=lf diff --git a/Makefile b/Makefile index 44375dbcc..92e947725 100644 --- a/Makefile +++ b/Makefile @@ -114,12 +114,7 @@ fmtcheck: .PHONY: test-windows test-windows: - go test -short $(race_detector) ./plugins/inputs/ping/... - 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/... + go test -short ./... .PHONY: vet vet: diff --git a/appveyor.yml b/appveyor.yml index b454c8dc8..6f5f6e948 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -12,7 +12,7 @@ clone_folder: C:\gopath\src\github.com\influxdata\telegraf environment: GOPATH: C:\gopath -stack: go 1.14 +stack: go 1.15 platform: x64 diff --git a/config/config_test.go b/config/config_test.go index 5543c60e7..79d74e83b 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -2,6 +2,7 @@ package config import ( "os" + "strings" "testing" "time" @@ -201,7 +202,7 @@ func TestConfig_LoadSpecialTypes(t *testing.T) { // Tests telegraf size parsing. assert.Equal(t, internal.Size{Size: 1024 * 1024}, inputHTTPListener.MaxBodySize) // 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) { diff --git a/config/testdata/telegraf-agent.toml b/config/testdata/telegraf-agent.toml index f71b98206..6967d6e86 100644 --- a/config/testdata/telegraf-agent.toml +++ b/config/testdata/telegraf-agent.toml @@ -176,14 +176,6 @@ # 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"] -# 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 [[inputs.mem]] # no configuration diff --git a/internal/globpath/globpath_test.go b/internal/globpath/globpath_test.go index 60562d8f8..92af2d20b 100644 --- a/internal/globpath/globpath_test.go +++ b/internal/globpath/globpath_test.go @@ -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 import ( + "os" + "path/filepath" "runtime" - "strings" "testing" "github.com/stretchr/testify/require" ) +var ( + testdataDir = getTestdataDir() +) + func TestCompileAndMatch(t *testing.T) { - dir := getTestdataDir() // test super asterisk - g1, err := Compile(dir + "/**") + g1, err := Compile(filepath.Join(testdataDir, "**")) require.NoError(t, err) // test single asterisk - g2, err := Compile(dir + "/*.log") + g2, err := Compile(filepath.Join(testdataDir, "*.log")) require.NoError(t, err) // test no meta characters (file exists) - g3, err := Compile(dir + "/log1.log") + g3, err := Compile(filepath.Join(testdataDir, "log1.log")) require.NoError(t, err) // 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) // 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) matches := g1.Match() @@ -39,15 +48,14 @@ func TestCompileAndMatch(t *testing.T) { } func TestRootGlob(t *testing.T) { - dir := getTestdataDir() tests := []struct { input string output string }{ - {dir + "/**", dir + "/*"}, - {dir + "/nested?/**", dir + "/nested?/*"}, - {dir + "/ne**/nest*", dir + "/ne*"}, - {dir + "/nested?/*", ""}, + {filepath.Join(testdataDir, "**"), filepath.Join(testdataDir, "*")}, + {filepath.Join(testdataDir, "nested?", "**"), filepath.Join(testdataDir, "nested?", "*")}, + {filepath.Join(testdataDir, "ne**", "nest*"), filepath.Join(testdataDir, "ne*")}, + {filepath.Join(testdataDir, "nested?", "*"), ""}, } for _, test := range tests { @@ -57,21 +65,19 @@ func TestRootGlob(t *testing.T) { } func TestFindNestedTextFile(t *testing.T) { - dir := getTestdataDir() // test super asterisk - g1, err := Compile(dir + "/**.txt") + g1, err := Compile(filepath.Join(testdataDir, "**.txt")) require.NoError(t, err) matches := g1.Match() 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) { + if runtime.GOOS == "windows" { + t.Skip("Skipping Unix only test") + } + tests := []struct { input string expected []string @@ -98,3 +104,13 @@ func TestWindowsSeparator(t *testing.T) { ok := glob.MatchString("testdata\\nested1") 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") +} diff --git a/plugins/inputs/bcache/README.md b/plugins/inputs/bcache/README.md index 11d567ec5..88c9f14f9 100644 --- a/plugins/inputs/bcache/README.md +++ b/plugins/inputs/bcache/README.md @@ -56,15 +56,15 @@ cache_readaheads Using this configuration: ```toml -[bcache] - # Bcache sets path - # If not specified, then default is: - # bcachePath = "/sys/fs/bcache" - # - # By default, telegraf gather stats for all bcache devices - # Setting devices will restrict the stats to the specified - # bcache devices. - # bcacheDevs = ["bcache0", ...] +[[inputs.bcache]] + ## Bcache sets path + ## If not specified, then default is: + bcachePath = "/sys/fs/bcache" + + ## By default, Telegraf gather stats for all bcache devices + ## Setting devices will restrict the stats to the specified + ## bcache devices. + bcacheDevs = ["bcache0"] ``` When run with: diff --git a/plugins/inputs/bcache/bcache.go b/plugins/inputs/bcache/bcache.go index 849e6dd37..c94af73f9 100644 --- a/plugins/inputs/bcache/bcache.go +++ b/plugins/inputs/bcache/bcache.go @@ -1,3 +1,7 @@ +// +build !windows + +// bcache doesn't aim for Windows + package bcache import ( @@ -22,7 +26,7 @@ var sampleConfig = ` ## If not specified, then default is: 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 ## bcache devices. bcacheDevs = ["bcache0"] diff --git a/plugins/inputs/bcache/bcache_test.go b/plugins/inputs/bcache/bcache_test.go index bd191528f..4646963c4 100644 --- a/plugins/inputs/bcache/bcache_test.go +++ b/plugins/inputs/bcache/bcache_test.go @@ -1,3 +1,5 @@ +// +build !windows + package bcache import ( diff --git a/plugins/inputs/bcache/bcache_windows.go b/plugins/inputs/bcache/bcache_windows.go new file mode 100644 index 000000000..9a580cc94 --- /dev/null +++ b/plugins/inputs/bcache/bcache_windows.go @@ -0,0 +1,3 @@ +// +build windows + +package bcache diff --git a/plugins/inputs/ceph/ceph_test.go b/plugins/inputs/ceph/ceph_test.go index 78da3438d..f57cda467 100644 --- a/plugins/inputs/ceph/ceph_test.go +++ b/plugins/inputs/ceph/ceph_test.go @@ -4,7 +4,7 @@ import ( "fmt" "io/ioutil" "os" - "path" + "path/filepath" "strconv" "strings" "testing" @@ -163,7 +163,7 @@ func assertFoundSocket(t *testing.T, dir, sockType string, i int, sockets []*soc } else { prefix = monPrefix } - expected := path.Join(dir, sockFile(prefix, i)) + expected := filepath.Join(dir, sockFile(prefix, i)) found := false for _, s := range sockets { fmt.Printf("Checking %s\n", s.socket) @@ -183,7 +183,7 @@ func sockFile(prefix string, i int) string { func createTestFiles(dir string, st *SockTest) { writeFile := func(prefix string, i int) { f := sockFile(prefix, i) - fpath := path.Join(dir, f) + fpath := filepath.Join(dir, f) ioutil.WriteFile(fpath, []byte(""), 0777) } tstFileApply(st, writeFile) @@ -192,7 +192,7 @@ func createTestFiles(dir string, st *SockTest) { func cleanupTestFiles(dir string, st *SockTest) { rmFile := func(prefix string, i int) { f := sockFile(prefix, i) - fpath := path.Join(dir, f) + fpath := filepath.Join(dir, f) err := os.Remove(fpath) if err != nil { fmt.Printf("Error removing test file %s: %v\n", fpath, err) diff --git a/plugins/inputs/disk/disk_test.go b/plugins/inputs/disk/disk_test.go index aeb2ae92b..13180fffb 100644 --- a/plugins/inputs/disk/disk_test.go +++ b/plugins/inputs/disk/disk_test.go @@ -1,6 +1,7 @@ package disk import ( + "fmt" "os" "testing" @@ -74,13 +75,13 @@ func TestDiskUsage(t *testing.T) { assert.Equal(t, expectedAllDiskMetrics, numDiskMetrics) tags1 := map[string]string{ - "path": "/", + "path": string(os.PathSeparator), "fstype": "ext4", "device": "sda", "mode": "ro", } tags2 := map[string]string{ - "path": "/home", + "path": fmt.Sprintf("%chome", os.PathSeparator), "fstype": "ext4", "device": "sdb", "mode": "rw", @@ -144,7 +145,7 @@ func TestDiskUsageHostMountPrefix(t *testing.T) { }, }, expectedTags: map[string]string{ - "path": "/", + "path": string(os.PathSeparator), "device": "sda", "fstype": "ext4", "mode": "ro", @@ -177,7 +178,7 @@ func TestDiskUsageHostMountPrefix(t *testing.T) { }, hostMountPrefix: "/hostfs", expectedTags: map[string]string{ - "path": "/var", + "path": fmt.Sprintf("%cvar", os.PathSeparator), "device": "sda", "fstype": "ext4", "mode": "ro", @@ -210,7 +211,7 @@ func TestDiskUsageHostMountPrefix(t *testing.T) { }, hostMountPrefix: "/hostfs", expectedTags: map[string]string{ - "path": "/", + "path": string(os.PathSeparator), "device": "sda", "fstype": "ext4", "mode": "ro", diff --git a/plugins/inputs/exec/exec_test.go b/plugins/inputs/exec/exec_test.go index d0fcc71f6..38503a7c0 100644 --- a/plugins/inputs/exec/exec_test.go +++ b/plugins/inputs/exec/exec_test.go @@ -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 import ( diff --git a/plugins/inputs/execd/execd_test.go b/plugins/inputs/execd/execd_test.go index a7be617da..6cb254eb5 100644 --- a/plugins/inputs/execd/execd_test.go +++ b/plugins/inputs/execd/execd_test.go @@ -1,5 +1,3 @@ -// +build !windows - package execd import ( @@ -11,17 +9,16 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/agent" "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/metric" "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/serializers" - - "github.com/influxdata/telegraf" + "github.com/influxdata/telegraf/testutil" ) func TestSettingConfigWorks(t *testing.T) { diff --git a/plugins/inputs/execd/shim/shim_posix_test.go b/plugins/inputs/execd/shim/shim_posix_test.go index 873ef89bf..594985d23 100644 --- a/plugins/inputs/execd/shim/shim_posix_test.go +++ b/plugins/inputs/execd/shim/shim_posix_test.go @@ -7,7 +7,6 @@ import ( "context" "io" "os" - "runtime" "syscall" "testing" "time" @@ -16,10 +15,6 @@ import ( ) func TestShimUSR1SignalingWorks(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip() - return - } stdinReader, stdinWriter := io.Pipe() stdoutReader, stdoutWriter := io.Pipe() diff --git a/plugins/inputs/file/file_test.go b/plugins/inputs/file/file_test.go index 427ff25d8..a5cacec21 100644 --- a/plugins/inputs/file/file_test.go +++ b/plugins/inputs/file/file_test.go @@ -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 import ( diff --git a/plugins/inputs/filecount/filecount_test.go b/plugins/inputs/filecount/filecount_test.go index 568ee07b5..39bbafb36 100644 --- a/plugins/inputs/filecount/filecount_test.go +++ b/plugins/inputs/filecount/filecount_test.go @@ -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 import ( diff --git a/plugins/inputs/filecount/filesystem_helpers_test.go b/plugins/inputs/filecount/filesystem_helpers_test.go index 08bb15a2e..62e7e2f81 100644 --- a/plugins/inputs/filecount/filesystem_helpers_test.go +++ b/plugins/inputs/filecount/filesystem_helpers_test.go @@ -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 import ( diff --git a/plugins/inputs/filestat/filestat_test.go b/plugins/inputs/filestat/filestat_test.go index a38d3b0aa..79a111ffb 100644 --- a/plugins/inputs/filestat/filestat_test.go +++ b/plugins/inputs/filestat/filestat_test.go @@ -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 import ( - "runtime" - "strings" + "os" + "path/filepath" "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/influxdata/telegraf/testutil" - "github.com/stretchr/testify/assert" +) + +var ( + testdataDir = getTestdataDir() ) func TestGatherNoMd5(t *testing.T) { - dir := getTestdataDir() fs := NewFileStat() fs.Log = testutil.Logger{} fs.Files = []string{ - dir + "log1.log", - dir + "log2.log", - "/non/existant/file", + filepath.Join(testdataDir, "log1.log"), + filepath.Join(testdataDir, "log2.log"), + filepath.Join(testdataDir, "non_existent_file"), } acc := testutil.Accumulator{} acc.GatherError(fs.Gather) 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, "exists", int64(1))) 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, "exists", int64(1))) 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))) } func TestGatherExplicitFiles(t *testing.T) { - dir := getTestdataDir() fs := NewFileStat() fs.Log = testutil.Logger{} fs.Md5 = true fs.Files = []string{ - dir + "log1.log", - dir + "log2.log", - "/non/existant/file", + filepath.Join(testdataDir, "log1.log"), + filepath.Join(testdataDir, "log2.log"), + filepath.Join(testdataDir, "non_existent_file"), } acc := testutil.Accumulator{} acc.GatherError(fs.Gather) 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, "exists", int64(1))) require.True(t, acc.HasPoint("filestat", tags1, "md5_sum", "d41d8cd98f00b204e9800998ecf8427e")) 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, "exists", int64(1))) require.True(t, acc.HasPoint("filestat", tags2, "md5_sum", "d41d8cd98f00b204e9800998ecf8427e")) 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))) } func TestGatherGlob(t *testing.T) { - dir := getTestdataDir() fs := NewFileStat() fs.Log = testutil.Logger{} fs.Md5 = true fs.Files = []string{ - dir + "*.log", + filepath.Join(testdataDir, "*.log"), } acc := testutil.Accumulator{} acc.GatherError(fs.Gather) 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, "exists", int64(1))) require.True(t, acc.HasPoint("filestat", tags1, "md5_sum", "d41d8cd98f00b204e9800998ecf8427e")) 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, "exists", int64(1))) @@ -104,33 +110,32 @@ func TestGatherGlob(t *testing.T) { } func TestGatherSuperAsterisk(t *testing.T) { - dir := getTestdataDir() fs := NewFileStat() fs.Log = testutil.Logger{} fs.Md5 = true fs.Files = []string{ - dir + "**", + filepath.Join(testdataDir, "**"), } acc := testutil.Accumulator{} acc.GatherError(fs.Gather) 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, "exists", int64(1))) require.True(t, acc.HasPoint("filestat", tags1, "md5_sum", "d41d8cd98f00b204e9800998ecf8427e")) 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, "exists", int64(1))) require.True(t, acc.HasPoint("filestat", tags2, "md5_sum", "d41d8cd98f00b204e9800998ecf8427e")) 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, "exists", int64(1))) @@ -138,18 +143,17 @@ func TestGatherSuperAsterisk(t *testing.T) { } func TestModificationTime(t *testing.T) { - dir := getTestdataDir() fs := NewFileStat() fs.Log = testutil.Logger{} fs.Files = []string{ - dir + "log1.log", + filepath.Join(testdataDir, "log1.log"), } acc := testutil.Accumulator{} acc.GatherError(fs.Gather) 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, "exists", int64(1))) @@ -160,22 +164,21 @@ func TestNoModificationTime(t *testing.T) { fs := NewFileStat() fs.Log = testutil.Logger{} fs.Files = []string{ - "/non/existant/file", + filepath.Join(testdataDir, "non_existent_file"), } acc := testutil.Accumulator{} acc.GatherError(fs.Gather) 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.False(t, acc.HasInt64Field("filestat", "modification_time")) } func TestGetMd5(t *testing.T) { - dir := getTestdataDir() - md5, err := getMd5(dir + "test.conf") + md5, err := getMd5(filepath.Join(testdataDir, "test.conf")) assert.NoError(t, err) assert.Equal(t, "5a7e9b77fa25e7bb411dbd17cf403c1f", md5) @@ -184,6 +187,11 @@ func TestGetMd5(t *testing.T) { } func getTestdataDir() string { - _, filename, _, _ := runtime.Caller(1) - return strings.Replace(filename, "filestat_test.go", "testdata/", 1) + 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") } diff --git a/plugins/inputs/haproxy/haproxy_test.go b/plugins/inputs/haproxy/haproxy_test.go index e05031f19..0a360c351 100644 --- a/plugins/inputs/haproxy/haproxy_test.go +++ b/plugins/inputs/haproxy/haproxy_test.go @@ -7,6 +7,8 @@ import ( "net" "net/http" "net/http/httptest" + "os" + "path/filepath" "strings" "testing" @@ -114,12 +116,13 @@ func TestHaproxyGeneratesMetricsWithoutAuthentication(t *testing.T) { func TestHaproxyGeneratesMetricsUsingSocket(t *testing.T) { var randomNumber int64 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++ { 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) if err != nil { @@ -146,7 +149,7 @@ func TestHaproxyGeneratesMetricsUsingSocket(t *testing.T) { for _, sock := range sockets { tags := map[string]string{ - "server": sock.Addr().String(), + "server": getSocketAddr(sock.Addr().String()), "proxy": "git", "sv": "www", "type": "server", diff --git a/plugins/inputs/http_response/http_response_test.go b/plugins/inputs/http_response/http_response_test.go index adf4e7999..3c290c153 100644 --- a/plugins/inputs/http_response/http_response_test.go +++ b/plugins/inputs/http_response/http_response_test.go @@ -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 import ( @@ -162,7 +166,7 @@ func TestHeaders(t *testing.T) { h := &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL, + URLs: []string{ts.URL}, Method: "GET", ResponseTimeout: internal.Duration{Duration: time.Second * 2}, Headers: map[string]string{ @@ -198,7 +202,7 @@ func TestFields(t *testing.T) { h := &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/good", + URLs: []string{ts.URL + "/good"}, Body: "{ 'test': 'data'}", Method: "GET", ResponseTimeout: internal.Duration{Duration: time.Second * 20}, @@ -236,7 +240,7 @@ func TestResponseBodyField(t *testing.T) { h := &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/good", + URLs: []string{ts.URL + "/good"}, Body: "{ 'test': 'data'}", Method: "GET", ResponseTimeout: internal.Duration{Duration: time.Second * 20}, @@ -271,7 +275,7 @@ func TestResponseBodyField(t *testing.T) { // Invalid UTF-8 String h = &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/invalidUTF8", + URLs: []string{ts.URL + "/invalidUTF8"}, Body: "{ 'test': 'data'}", Method: "GET", ResponseTimeout: internal.Duration{Duration: time.Second * 20}, @@ -305,7 +309,7 @@ func TestResponseBodyMaxSize(t *testing.T) { h := &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/good", + URLs: []string{ts.URL + "/good"}, Body: "{ 'test': 'data'}", Method: "GET", ResponseTimeout: internal.Duration{Duration: time.Second * 20}, @@ -339,7 +343,7 @@ func TestHTTPHeaderTags(t *testing.T) { h := &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/good", + URLs: []string{ts.URL + "/good"}, Body: "{ 'test': 'data'}", Method: "GET", ResponseTimeout: internal.Duration{Duration: time.Second * 20}, @@ -374,7 +378,7 @@ func TestHTTPHeaderTags(t *testing.T) { h = &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/noheader", + URLs: []string{ts.URL + "/noheader"}, Body: "{ 'test': 'data'}", Method: "GET", ResponseTimeout: internal.Duration{Duration: time.Second * 20}, @@ -400,7 +404,7 @@ func TestHTTPHeaderTags(t *testing.T) { // Connection failed h = &HTTPResponse{ 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: "", Method: "GET", ResponseTimeout: internal.Duration{Duration: time.Second * 5}, @@ -456,7 +460,7 @@ func TestInterface(t *testing.T) { h := &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/good", + URLs: []string{ts.URL + "/good"}, Body: "{ 'test': 'data'}", Method: "GET", ResponseTimeout: internal.Duration{Duration: time.Second * 20}, @@ -495,7 +499,7 @@ func TestRedirects(t *testing.T) { h := &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/redirect", + URLs: []string{ts.URL + "/redirect"}, Body: "{ 'test': 'data'}", Method: "GET", ResponseTimeout: internal.Duration{Duration: time.Second * 20}, @@ -526,7 +530,7 @@ func TestRedirects(t *testing.T) { h = &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/badredirect", + URLs: []string{ts.URL + "/badredirect"}, Body: "{ 'test': 'data'}", Method: "GET", ResponseTimeout: internal.Duration{Duration: time.Second * 20}, @@ -563,7 +567,7 @@ func TestMethod(t *testing.T) { h := &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/mustbepostmethod", + URLs: []string{ts.URL + "/mustbepostmethod"}, Body: "{ 'test': 'data'}", Method: "POST", ResponseTimeout: internal.Duration{Duration: time.Second * 20}, @@ -594,7 +598,7 @@ func TestMethod(t *testing.T) { h = &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/mustbepostmethod", + URLs: []string{ts.URL + "/mustbepostmethod"}, Body: "{ 'test': 'data'}", Method: "GET", ResponseTimeout: internal.Duration{Duration: time.Second * 20}, @@ -626,7 +630,7 @@ func TestMethod(t *testing.T) { //check that lowercase methods work correctly h = &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/mustbepostmethod", + URLs: []string{ts.URL + "/mustbepostmethod"}, Body: "{ 'test': 'data'}", Method: "head", ResponseTimeout: internal.Duration{Duration: time.Second * 20}, @@ -663,7 +667,7 @@ func TestBody(t *testing.T) { h := &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/musthaveabody", + URLs: []string{ts.URL + "/musthaveabody"}, Body: "{ 'test': 'data'}", Method: "GET", ResponseTimeout: internal.Duration{Duration: time.Second * 20}, @@ -694,7 +698,7 @@ func TestBody(t *testing.T) { h = &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/musthaveabody", + URLs: []string{ts.URL + "/musthaveabody"}, Method: "GET", ResponseTimeout: internal.Duration{Duration: time.Second * 20}, Headers: map[string]string{ @@ -728,7 +732,7 @@ func TestStringMatch(t *testing.T) { h := &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/good", + URLs: []string{ts.URL + "/good"}, Body: "{ 'test': 'data'}", Method: "GET", ResponseStringMatch: "hit the good page", @@ -766,7 +770,7 @@ func TestStringMatchJson(t *testing.T) { h := &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/jsonresponse", + URLs: []string{ts.URL + "/jsonresponse"}, Body: "{ 'test': 'data'}", Method: "GET", ResponseStringMatch: "\"service_status\": \"up\"", @@ -804,7 +808,7 @@ func TestStringMatchFail(t *testing.T) { h := &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/good", + URLs: []string{ts.URL + "/good"}, Body: "{ 'test': 'data'}", Method: "GET", ResponseStringMatch: "hit the bad page", @@ -847,7 +851,7 @@ func TestTimeout(t *testing.T) { h := &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/twosecondnap", + URLs: []string{ts.URL + "/twosecondnap"}, Body: "{ 'test': 'data'}", Method: "GET", ResponseTimeout: internal.Duration{Duration: time.Second}, @@ -881,7 +885,7 @@ func TestBadRegex(t *testing.T) { h := &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/good", + URLs: []string{ts.URL + "/good"}, Body: "{ 'test': 'data'}", Method: "GET", ResponseStringMatch: "bad regex:[[", @@ -905,7 +909,7 @@ func TestNetworkErrors(t *testing.T) { // DNS error h := &HTTPResponse{ 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: "", Method: "GET", ResponseTimeout: internal.Duration{Duration: time.Second * 20}, @@ -932,7 +936,7 @@ func TestNetworkErrors(t *testing.T) { // Connection failed h = &HTTPResponse{ 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: "", Method: "GET", ResponseTimeout: internal.Duration{Duration: time.Second * 5}, @@ -1082,7 +1086,7 @@ func TestBasicAuth(t *testing.T) { h := &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/good", + URLs: []string{ts.URL + "/good"}, Body: "{ 'test': 'data'}", Method: "GET", ResponseTimeout: internal.Duration{Duration: time.Second * 20}, @@ -1121,7 +1125,7 @@ func TestStatusCodeMatchFail(t *testing.T) { h := &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/nocontent", + URLs: []string{ts.URL + "/nocontent"}, ResponseStatusCode: http.StatusOK, ResponseTimeout: internal.Duration{Duration: time.Second * 20}, } @@ -1154,7 +1158,7 @@ func TestStatusCodeMatch(t *testing.T) { h := &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/nocontent", + URLs: []string{ts.URL + "/nocontent"}, ResponseStatusCode: http.StatusNoContent, ResponseTimeout: internal.Duration{Duration: time.Second * 20}, } @@ -1187,7 +1191,7 @@ func TestStatusCodeAndStringMatch(t *testing.T) { h := &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/good", + URLs: []string{ts.URL + "/good"}, ResponseStatusCode: http.StatusOK, ResponseStringMatch: "hit the good page", ResponseTimeout: internal.Duration{Duration: time.Second * 20}, @@ -1222,7 +1226,7 @@ func TestStatusCodeAndStringMatchFail(t *testing.T) { h := &HTTPResponse{ Log: testutil.Logger{}, - Address: ts.URL + "/nocontent", + URLs: []string{ts.URL + "/nocontent"}, ResponseStatusCode: http.StatusOK, ResponseStringMatch: "hit the good page", ResponseTimeout: internal.Duration{Duration: time.Second * 20}, diff --git a/plugins/inputs/leofs/leofs_test.go b/plugins/inputs/leofs/leofs_test.go index f456a998e..6d7799d0b 100644 --- a/plugins/inputs/leofs/leofs_test.go +++ b/plugins/inputs/leofs/leofs_test.go @@ -8,6 +8,7 @@ import ( "log" "os" "os/exec" + "runtime" "testing" ) @@ -133,19 +134,25 @@ func makeFakeSNMPSrc(code string) string { return path } -func buildFakeSNMPCmd(src string) { - err := exec.Command("go", "build", "-o", "snmpwalk", src).Run() +func buildFakeSNMPCmd(src string, executable string) { + err := exec.Command("go", "build", "-o", executable, src).Run() if err != nil { log.Fatalln(err) } } 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 src := makeFakeSNMPSrc(code) defer os.Remove(src) - buildFakeSNMPCmd(src) - defer os.Remove("./snmpwalk") + buildFakeSNMPCmd(src, executable) + defer os.Remove("./" + executable) + envPathOrigin := os.Getenv("PATH") // Refer to the fake snmpwalk os.Setenv("PATH", ".") diff --git a/plugins/inputs/logparser/logparser_test.go b/plugins/inputs/logparser/logparser_test.go index 142f78d46..9bf4f125a 100644 --- a/plugins/inputs/logparser/logparser_test.go +++ b/plugins/inputs/logparser/logparser_test.go @@ -3,22 +3,26 @@ package logparser import ( "io/ioutil" "os" - "runtime" - "strings" + "path/filepath" "testing" "time" - "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/testutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/influxdata/telegraf" + "github.com/influxdata/telegraf/testutil" +) + +var ( + testdataDir = getTestdataDir() ) func TestStartNoParsers(t *testing.T) { logparser := &LogParserPlugin{ Log: testutil.Logger{}, FromBeginning: true, - Files: []string{"testdata/*.log"}, + Files: []string{filepath.Join(testdataDir, "*.log")}, } acc := testutil.Accumulator{} @@ -26,15 +30,13 @@ func TestStartNoParsers(t *testing.T) { } func TestGrokParseLogFilesNonExistPattern(t *testing.T) { - thisdir := getCurrentDir() - logparser := &LogParserPlugin{ Log: testutil.Logger{}, FromBeginning: true, - Files: []string{thisdir + "testdata/*.log"}, + Files: []string{filepath.Join(testdataDir, "*.log")}, GrokConfig: GrokConfig{ 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) { - thisdir := getCurrentDir() - logparser := &LogParserPlugin{ Log: testutil.Logger{}, GrokConfig: GrokConfig{ MeasurementName: "logparser_grok", 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, - Files: []string{thisdir + "testdata/*.log"}, + Files: []string{filepath.Join(testdataDir, "*.log")}, } acc := testutil.Accumulator{} @@ -68,7 +68,7 @@ func TestGrokParseLogFiles(t *testing.T) { "logparser_grok", map[string]string{ "response_code": "200", - "path": thisdir + "testdata/test_a.log", + "path": filepath.Join(testdataDir, "test_a.log"), }, map[string]interface{}{ "clientip": "192.168.1.1", @@ -81,7 +81,7 @@ func TestGrokParseLogFiles(t *testing.T) { testutil.MustMetric( "logparser_grok", map[string]string{ - "path": thisdir + "testdata/test_b.log", + "path": filepath.Join(testdataDir, "test_b.log"), }, map[string]interface{}{ "myfloat": 1.25, @@ -93,7 +93,7 @@ func TestGrokParseLogFiles(t *testing.T) { testutil.MustMetric( "logparser_grok", map[string]string{ - "path": thisdir + "testdata/test_c.log", + "path": filepath.Join(testdataDir, "test_c.log"), "response_code": "200", }, map[string]interface{}{ @@ -115,16 +115,14 @@ func TestGrokParseLogFilesAppearLater(t *testing.T) { defer os.RemoveAll(emptydir) assert.NoError(t, err) - thisdir := getCurrentDir() - logparser := &LogParserPlugin{ Log: testutil.Logger{}, FromBeginning: true, - Files: []string{emptydir + "/*.log"}, + Files: []string{filepath.Join(emptydir, "*.log")}, GrokConfig: GrokConfig{ MeasurementName: "logparser_grok", 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) - _ = 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)) acc.Wait(1) @@ -148,23 +151,21 @@ func TestGrokParseLogFilesAppearLater(t *testing.T) { }, map[string]string{ "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 // pattern available for test_b.log func TestGrokParseLogFilesOneBad(t *testing.T) { - thisdir := getCurrentDir() - logparser := &LogParserPlugin{ Log: testutil.Logger{}, FromBeginning: true, - Files: []string{thisdir + "testdata/test_a.log"}, + Files: []string{filepath.Join(testdataDir, "test_a.log")}, GrokConfig: GrokConfig{ MeasurementName: "logparser_grok", 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{ "response_code": "200", - "path": thisdir + "testdata/test_a.log", + "path": filepath.Join(testdataDir, "test_a.log"), }) } func TestGrokParseLogFiles_TimestampInEpochMilli(t *testing.T) { - thisdir := getCurrentDir() - logparser := &LogParserPlugin{ Log: testutil.Logger{}, GrokConfig: GrokConfig{ MeasurementName: "logparser_grok", Patterns: []string{"%{TEST_LOG_C}"}, - CustomPatternFiles: []string{thisdir + "testdata/test-patterns"}, + CustomPatternFiles: []string{filepath.Join(testdataDir, "test-patterns")}, }, FromBeginning: true, - Files: []string{thisdir + "testdata/test_c.log"}, + Files: []string{filepath.Join(testdataDir, "test_c.log")}, } acc := testutil.Accumulator{} @@ -218,11 +217,16 @@ func TestGrokParseLogFiles_TimestampInEpochMilli(t *testing.T) { }, map[string]string{ "response_code": "200", - "path": thisdir + "testdata/test_c.log", + "path": filepath.Join(testdataDir, "test_c.log"), }) } -func getCurrentDir() string { - _, filename, _, _ := runtime.Caller(1) - return strings.Replace(filename, "logparser_test.go", "", 1) +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") } diff --git a/plugins/inputs/lustre2/lustre2.go b/plugins/inputs/lustre2/lustre2.go index 611ba294d..44e046c73 100644 --- a/plugins/inputs/lustre2/lustre2.go +++ b/plugins/inputs/lustre2/lustre2.go @@ -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 for HPC environments. It stores statistics about its activity in diff --git a/plugins/inputs/lustre2/lustre2_test.go b/plugins/inputs/lustre2/lustre2_test.go index 8e93da8e8..1fb55d304 100644 --- a/plugins/inputs/lustre2/lustre2_test.go +++ b/plugins/inputs/lustre2/lustre2_test.go @@ -1,3 +1,5 @@ +// +build !windows + package lustre2 import ( diff --git a/plugins/inputs/lustre2/lustre2_windows.go b/plugins/inputs/lustre2/lustre2_windows.go new file mode 100644 index 000000000..0c4d97060 --- /dev/null +++ b/plugins/inputs/lustre2/lustre2_windows.go @@ -0,0 +1,3 @@ +// +build windows + +package lustre2 diff --git a/plugins/inputs/monit/monit_test.go b/plugins/inputs/monit/monit_test.go index 2739240f1..d17db8d2a 100644 --- a/plugins/inputs/monit/monit_test.go +++ b/plugins/inputs/monit/monit_test.go @@ -4,6 +4,7 @@ import ( "errors" "net/http" "net/http/httptest" + "net/url" "testing" "time" @@ -573,21 +574,19 @@ func TestAllowHosts(t *testing.T) { } func TestConnection(t *testing.T) { - r := &Monit{ Address: "http://127.0.0.1:2812", Username: "test", Password: "test", } - var acc testutil.Accumulator - r.Init() + var acc testutil.Accumulator err := r.Gather(&acc) - if assert.Error(t, err) { - assert.Contains(t, err.Error(), "connect: connection refused") + _, ok := err.(*url.Error) + assert.True(t, ok) } } diff --git a/plugins/inputs/net_response/net_response_test.go b/plugins/inputs/net_response/net_response_test.go index ef4d0714a..8f01d6879 100644 --- a/plugins/inputs/net_response/net_response_test.go +++ b/plugins/inputs/net_response/net_response_test.go @@ -91,6 +91,7 @@ func TestTCPError(t *testing.T) { c := NetResponse{ Protocol: "tcp", Address: ":9999", + Timeout: internal.Duration{Duration: time.Second * 30}, } // Error err1 := c.Gather(&acc) diff --git a/plugins/inputs/passenger/passenger_test.go b/plugins/inputs/passenger/passenger_test.go index c54239d39..ce1ebe462 100644 --- a/plugins/inputs/passenger/passenger_test.go +++ b/plugins/inputs/passenger/passenger_test.go @@ -4,20 +4,37 @@ import ( "fmt" "io/ioutil" "os" + "path/filepath" + "runtime" + "strings" "testing" - "github.com/influxdata/telegraf/testutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/influxdata/telegraf/testutil" ) -func fakePassengerStatus(stat string) { - content := fmt.Sprintf("#!/bin/sh\ncat << EOF\n%s\nEOF", stat) - ioutil.WriteFile("/tmp/passenger-status", []byte(content), 0700) +func fakePassengerStatus(stat string) string { + var fileExtension, content string + 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() { - os.Remove("/tmp/passenger-status") +func teardown(tempFilePath string) { + os.Remove(tempFilePath) } 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) 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) { - fakePassengerStatus("invalid xml") - defer teardown() + tempFilePath := fakePassengerStatus("invalid xml") + defer teardown(tempFilePath) r := &passenger{ - Command: "/tmp/passenger-status", + Command: tempFilePath, } var acc testutil.Accumulator err := r.Gather(&acc) 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 func Test_Default_Config_Load_Default_Command(t *testing.T) { - fakePassengerStatus("invalid xml") - defer teardown() + tempFilePath := fakePassengerStatus("invalid xml") + defer teardown(tempFilePath) r := &passenger{} @@ -58,16 +75,16 @@ func Test_Default_Config_Load_Default_Command(t *testing.T) { err := r.Gather(&acc) 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) { - fakePassengerStatus(sampleStat) - defer teardown() + tempFilePath := fakePassengerStatus(sampleStat) + defer teardown(tempFilePath) //Now we tested again above server, with our authentication data r := &passenger{ - Command: "/tmp/passenger-status", + Command: tempFilePath, } var acc testutil.Accumulator diff --git a/plugins/inputs/phpfpm/phpfpm_test.go b/plugins/inputs/phpfpm/phpfpm_test.go index 7be2e6a27..6db740df4 100644 --- a/plugins/inputs/phpfpm/phpfpm_test.go +++ b/plugins/inputs/phpfpm/phpfpm_test.go @@ -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 import ( diff --git a/plugins/inputs/postfix/postfix.go b/plugins/inputs/postfix/postfix.go index 8700362d0..87e11a195 100644 --- a/plugins/inputs/postfix/postfix.go +++ b/plugins/inputs/postfix/postfix.go @@ -1,3 +1,7 @@ +// +build !windows + +// postfix doesn't aim for Windows + package postfix import ( diff --git a/plugins/inputs/postfix/postfix_test.go b/plugins/inputs/postfix/postfix_test.go index 5dbc91d13..ad997eebd 100644 --- a/plugins/inputs/postfix/postfix_test.go +++ b/plugins/inputs/postfix/postfix_test.go @@ -1,3 +1,5 @@ +// +build !windows + package postfix import ( diff --git a/plugins/inputs/postfix/postfix_windows.go b/plugins/inputs/postfix/postfix_windows.go new file mode 100644 index 000000000..122c1543d --- /dev/null +++ b/plugins/inputs/postfix/postfix_windows.go @@ -0,0 +1,3 @@ +// +build windows + +package postfix diff --git a/plugins/inputs/powerdns/powerdns_test.go b/plugins/inputs/powerdns/powerdns_test.go index fe64be5db..0fe3e3105 100644 --- a/plugins/inputs/powerdns/powerdns_test.go +++ b/plugins/inputs/powerdns/powerdns_test.go @@ -3,11 +3,14 @@ package powerdns import ( "fmt" "net" + "os" + "path/filepath" "testing" - "github.com/influxdata/telegraf/testutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/influxdata/telegraf/testutil" ) type statServer struct{} @@ -71,7 +74,8 @@ func (s statServer) serverSocket(l net.Listener) { func TestPowerdnsGeneratesMetrics(t *testing.T) { // We create a fake server to return test data 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 { t.Fatal("Cannot initialize server on port ") } @@ -82,11 +86,10 @@ func TestPowerdnsGeneratesMetrics(t *testing.T) { go s.serverSocket(socket) p := &Powerdns{ - UnixSockets: []string{fmt.Sprintf("/tmp/pdns%d.controlsocket", randomNumber)}, + UnixSockets: []string{sockname}, } var acc testutil.Accumulator - err = acc.GatherError(p.Gather) require.NoError(t, err) diff --git a/plugins/inputs/powerdns_recursor/powerdns_recursor_test.go b/plugins/inputs/powerdns_recursor/powerdns_recursor_test.go index d0f5690cc..25d39dcd4 100644 --- a/plugins/inputs/powerdns_recursor/powerdns_recursor_test.go +++ b/plugins/inputs/powerdns_recursor/powerdns_recursor_test.go @@ -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" func TestPowerdnsRecursorGeneratesMetrics(t *testing.T) { - if runtime.GOOS == "darwin" { - t.Skip("Skipping test on darwin") + if runtime.GOOS == "darwin" || runtime.GOOS == "windows" { + t.Skip("Skipping on windows and darwin, as unixgram sockets are not supported") } // We create a fake server to return test data controlSocket := "/tmp/pdns5724354148158589552.controlsocket" diff --git a/plugins/inputs/redfish/redfish_test.go b/plugins/inputs/redfish/redfish_test.go index 8821b3d97..c3c6f0d10 100644 --- a/plugins/inputs/redfish/redfish_test.go +++ b/plugins/inputs/redfish/redfish_test.go @@ -8,9 +8,11 @@ import ( "testing" "time" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/testutil" - "github.com/stretchr/testify/require" ) func TestDellApis(t *testing.T) { @@ -643,7 +645,6 @@ func checkAuth(r *http.Request, username, password string) bool { } func TestConnection(t *testing.T) { - r := &Redfish{ Address: "http://127.0.0.1", Username: "test", @@ -654,8 +655,10 @@ func TestConnection(t *testing.T) { var acc testutil.Accumulator r.Init() err := r.Gather(&acc) - require.Error(t, err) - require.Contains(t, err.Error(), "connect: connection refused") + if assert.Error(t, err) { + _, ok := err.(*url.Error) + assert.True(t, ok) + } } func TestInvalidUsernameorPassword(t *testing.T) { diff --git a/plugins/inputs/snmp/snmp_test.go b/plugins/inputs/snmp/snmp_test.go index 583b2dc84..9d9d7df23 100644 --- a/plugins/inputs/snmp/snmp_test.go +++ b/plugins/inputs/snmp/snmp_test.go @@ -640,8 +640,8 @@ func TestGather(t *testing.T) { assert.Len(t, m.Fields, 2) assert.Equal(t, 234, m.Fields["myfield2"]) assert.Equal(t, "baz", m.Fields["myfield3"]) - assert.True(t, tstart.Before(m.Time)) - assert.True(t, tstop.After(m.Time)) + assert.True(t, !tstart.After(m.Time)) + assert.True(t, !tstop.Before(m.Time)) m2 := acc.Metrics[1] assert.Equal(t, "myOtherTable", m2.Measurement) diff --git a/plugins/inputs/socket_listener/socket_listener_test.go b/plugins/inputs/socket_listener/socket_listener_test.go index a46add15c..03d0c0453 100644 --- a/plugins/inputs/socket_listener/socket_listener_test.go +++ b/plugins/inputs/socket_listener/socket_listener_test.go @@ -9,6 +9,7 @@ import ( "net" "os" "path/filepath" + "runtime" "testing" "time" @@ -138,7 +139,8 @@ func TestSocketListener_unix(t *testing.T) { defer testEmptyLog(t)() - os.Create(sock) + f, _ := os.Create(sock) + f.Close() sl := newSocketListener() sl.Log = testutil.Logger{} sl.ServiceAddress = "unix://" + sock @@ -156,6 +158,10 @@ func TestSocketListener_unix(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") require.NoError(t, err) defer os.RemoveAll(tmpdir) diff --git a/plugins/inputs/syslog/nontransparent_test.go b/plugins/inputs/syslog/nontransparent_test.go index d0352c6ae..544b31929 100644 --- a/plugins/inputs/syslog/nontransparent_test.go +++ b/plugins/inputs/syslog/nontransparent_test.go @@ -9,11 +9,12 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/internal" framing "github.com/influxdata/telegraf/internal/syslog" "github.com/influxdata/telegraf/testutil" - "github.com/stretchr/testify/require" ) func getTestCasesForNonTransparent() []testCaseStream { diff --git a/plugins/inputs/syslog/octetcounting_test.go b/plugins/inputs/syslog/octetcounting_test.go index 210b64dbe..87909fcec 100644 --- a/plugins/inputs/syslog/octetcounting_test.go +++ b/plugins/inputs/syslog/octetcounting_test.go @@ -10,11 +10,12 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/internal" framing "github.com/influxdata/telegraf/internal/syslog" "github.com/influxdata/telegraf/testutil" - "github.com/stretchr/testify/require" ) func getTestCasesForOctetCounting() []testCaseStream { diff --git a/plugins/inputs/syslog/rfc5426_test.go b/plugins/inputs/syslog/rfc5426_test.go index 31007bad9..2a6d937fb 100644 --- a/plugins/inputs/syslog/rfc5426_test.go +++ b/plugins/inputs/syslog/rfc5426_test.go @@ -6,13 +6,15 @@ import ( "net" "os" "path/filepath" + "runtime" "sync/atomic" "testing" "time" + "github.com/stretchr/testify/require" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/testutil" - "github.com/stretchr/testify/require" ) func getTestCasesForRFC5426() []testCasePacket { @@ -284,6 +286,10 @@ func TestStrict_udp(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") require.NoError(t, err) defer os.RemoveAll(tmpdir) @@ -293,6 +299,10 @@ func TestBestEffort_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") require.NoError(t, err) defer os.RemoveAll(tmpdir) diff --git a/plugins/inputs/syslog/syslog.go b/plugins/inputs/syslog/syslog.go index 6b3615a3e..17b9b77a5 100644 --- a/plugins/inputs/syslog/syslog.go +++ b/plugins/inputs/syslog/syslog.go @@ -7,6 +7,7 @@ import ( "net" "net/url" "os" + "path/filepath" "strings" "sync" "time" @@ -16,6 +17,7 @@ import ( "github.com/influxdata/go-syslog/v2/nontransparent" "github.com/influxdata/go-syslog/v2/octetcounting" "github.com/influxdata/go-syslog/v2/rfc5424" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/internal" 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) } - 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 { case "unix", "unixpacket", "unixgram": return parts[0], parts[1], nil diff --git a/plugins/inputs/syslog/syslog_test.go b/plugins/inputs/syslog/syslog_test.go index 66568380e..ac0539d30 100644 --- a/plugins/inputs/syslog/syslog_test.go +++ b/plugins/inputs/syslog/syslog_test.go @@ -4,12 +4,14 @@ import ( "io/ioutil" "os" "path/filepath" + "runtime" "strings" "testing" "time" - "github.com/influxdata/telegraf/testutil" "github.com/stretchr/testify/require" + + "github.com/influxdata/telegraf/testutil" ) const ( @@ -49,13 +51,16 @@ func TestAddress(t *testing.T) { require.NoError(t, err) sock := filepath.Join(tmpdir, "syslog.TestAddress.sock") - rec = &Syslog{ - Address: "unixgram://" + sock, + if runtime.GOOS != "windows" { + // 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 rec = &Syslog{ diff --git a/plugins/inputs/tail/tail_test.go b/plugins/inputs/tail/tail_test.go index 5669fbf2e..83f6c9e78 100644 --- a/plugins/inputs/tail/tail_test.go +++ b/plugins/inputs/tail/tail_test.go @@ -5,11 +5,13 @@ import ( "io/ioutil" "log" "os" - "runtime" - "strings" + "path/filepath" "testing" "time" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/internal" "github.com/influxdata/telegraf/plugins/parsers" @@ -17,8 +19,10 @@ import ( "github.com/influxdata/telegraf/plugins/parsers/influx" "github.com/influxdata/telegraf/plugins/parsers/json" "github.com/influxdata/telegraf/testutil" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" +) + +var ( + testdataDir = getTestdataDir() ) func TestTailBadLine(t *testing.T) { @@ -58,7 +62,7 @@ func TestTailBadLine(t *testing.T) { assert.Contains(t, buf.String(), "Malformed log line") } -func TestTailDosLineendings(t *testing.T) { +func TestTailDosLineEndings(t *testing.T) { tmpfile, err := ioutil.TempFile("", "") require.NoError(t, err) defer os.Remove(tmpfile.Name()) @@ -92,14 +96,13 @@ func TestTailDosLineendings(t *testing.T) { } func TestGrokParseLogFilesWithMultiline(t *testing.T) { - thisdir := getCurrentDir() //we make sure the timeout won't kick in duration, _ := time.ParseDuration("100s") tt := NewTail() tt.Log = testutil.Logger{} tt.FromBeginning = true - tt.Files = []string{thisdir + "testdata/test_multiline.log"} + tt.Files = []string{filepath.Join(testdataDir, "test_multiline.log")} tt.MultilineConfig = MultilineConfig{ Pattern: `^[^\[]`, MatchWhichLine: Previous, @@ -117,7 +120,7 @@ func TestGrokParseLogFilesWithMultiline(t *testing.T) { acc.Wait(3) - expectedPath := thisdir + "testdata/test_multiline.log" + expectedPath := filepath.Join(testdataDir, "test_multiline.log") acc.AssertContainsTaggedFields(t, "tail_grok", map[string]interface{}{ "message": "HelloExample: This is debug", @@ -151,7 +154,7 @@ func TestGrokParseLogFilesWithMultilineTimeout(t *testing.T) { require.NoError(t, err) 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") require.NoError(t, err) require.NoError(t, tmpfile.Sync()) @@ -209,14 +212,13 @@ func TestGrokParseLogFilesWithMultilineTimeout(t *testing.T) { } func TestGrokParseLogFilesWithMultilineTailerCloseFlushesMultilineBuffer(t *testing.T) { - thisdir := getCurrentDir() //we make sure the timeout won't kick in duration := 100 * time.Second tt := NewTail() tt.Log = testutil.Logger{} tt.FromBeginning = true - tt.Files = []string{thisdir + "testdata/test_multiline.log"} + tt.Files = []string{filepath.Join(testdataDir, "test_multiline.log")} tt.MultilineConfig = MultilineConfig{ Pattern: `^[^\[]`, MatchWhichLine: Previous, @@ -236,7 +238,7 @@ func TestGrokParseLogFilesWithMultilineTailerCloseFlushesMultilineBuffer(t *test tt.Stop() acc.Wait(4) - expectedPath := thisdir + "testdata/test_multiline.log" + expectedPath := filepath.Join(testdataDir, "test_multiline.log") acc.AssertContainsTaggedFields(t, "tail_grok", map[string]interface{}{ "message": "HelloExample: This is warn", @@ -251,7 +253,7 @@ func createGrokParser() (parsers.Parser, error) { grokConfig := &parsers.Config{ MetricName: "tail_grok", GrokPatterns: []string{"%{TEST_LOG_MULTILINE}"}, - GrokCustomPatternFiles: []string{getCurrentDir() + "testdata/test-patterns"}, + GrokCustomPatternFiles: []string{filepath.Join(testdataDir, "test-patterns")}, DataFormat: "grok", } parser, err := parsers.NewParser(grokConfig) @@ -374,11 +376,6 @@ func TestMultipleMetricsOnFirstLine(t *testing.T) { testutil.IgnoreTime()) } -func getCurrentDir() string { - _, filename, _, _ := runtime.Caller(1) - return strings.Replace(filename, "tail_test.go", "", 1) -} - func TestCharacterEncoding(t *testing.T) { full := []telegraf.Metric{ testutil.MustMetric("cpu", @@ -437,7 +434,7 @@ func TestCharacterEncoding(t *testing.T) { { name: "utf-8", plugin: &Tail{ - Files: []string{"testdata/cpu-utf-8.influx"}, + Files: []string{filepath.Join(testdataDir, "cpu-utf-8.influx")}, FromBeginning: true, MaxUndeliveredLines: 1000, Log: testutil.Logger{}, @@ -448,7 +445,7 @@ func TestCharacterEncoding(t *testing.T) { { name: "utf-8 seek", plugin: &Tail{ - Files: []string{"testdata/cpu-utf-8.influx"}, + Files: []string{filepath.Join(testdataDir, "cpu-utf-8.influx")}, MaxUndeliveredLines: 1000, Log: testutil.Logger{}, CharacterEncoding: "utf-8", @@ -459,7 +456,7 @@ func TestCharacterEncoding(t *testing.T) { { name: "utf-16le", plugin: &Tail{ - Files: []string{"testdata/cpu-utf-16le.influx"}, + Files: []string{filepath.Join(testdataDir, "cpu-utf-16le.influx")}, FromBeginning: true, MaxUndeliveredLines: 1000, Log: testutil.Logger{}, @@ -470,7 +467,7 @@ func TestCharacterEncoding(t *testing.T) { { name: "utf-16le seek", plugin: &Tail{ - Files: []string{"testdata/cpu-utf-16le.influx"}, + Files: []string{filepath.Join(testdataDir, "cpu-utf-16le.influx")}, MaxUndeliveredLines: 1000, Log: testutil.Logger{}, CharacterEncoding: "utf-16le", @@ -481,7 +478,7 @@ func TestCharacterEncoding(t *testing.T) { { name: "utf-16be", plugin: &Tail{ - Files: []string{"testdata/cpu-utf-16be.influx"}, + Files: []string{filepath.Join(testdataDir, "cpu-utf-16be.influx")}, FromBeginning: true, MaxUndeliveredLines: 1000, Log: testutil.Logger{}, @@ -565,3 +562,13 @@ func TestTailEOF(t *testing.T) { err = tmpfile.Close() 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") +} diff --git a/plugins/inputs/x509_cert/x509_cert.go b/plugins/inputs/x509_cert/x509_cert.go index 983926af1..e5c2f835b 100644 --- a/plugins/inputs/x509_cert/x509_cert.go +++ b/plugins/inputs/x509_cert/x509_cert.go @@ -10,6 +10,7 @@ import ( "io/ioutil" "net" "net/url" + "path/filepath" "strings" "time" @@ -60,6 +61,9 @@ func (c *X509Cert) locationToURL(location string) (*url.URL, error) { if strings.HasPrefix(location, "/") { location = "file://" + location } + if strings.Index(location, ":\\") == 1 { + location = "file://" + filepath.ToSlash(location) + } u, err := url.Parse(location) if err != nil { diff --git a/plugins/inputs/x509_cert/x509_cert_test.go b/plugins/inputs/x509_cert/x509_cert_test.go index c34524457..041d20db7 100644 --- a/plugins/inputs/x509_cert/x509_cert_test.go +++ b/plugins/inputs/x509_cert/x509_cert_test.go @@ -7,6 +7,8 @@ import ( "io/ioutil" "math/big" "os" + "path/filepath" + "runtime" "testing" "time" @@ -51,7 +53,7 @@ func TestGatherRemote(t *testing.T) { {name: "wrong port", server: ":99999", error: true}, {name: "no server", 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: "no certificate", timeout: 5, unset: true, error: true}, {name: "closed connection", close: true, error: true}, @@ -166,9 +168,11 @@ func TestGatherLocal(t *testing.T) { t.Fatal(err) } - err = f.Chmod(test.mode) - if err != nil { - t.Fatal(err) + if runtime.GOOS != "windows" { + err = f.Chmod(test.mode) + if err != nil { + t.Fatal(err) + } } err = f.Close() diff --git a/plugins/outputs/socket_writer/socket_writer_test.go b/plugins/outputs/socket_writer/socket_writer_test.go index 14b25e6c5..98ae51b8d 100644 --- a/plugins/outputs/socket_writer/socket_writer_test.go +++ b/plugins/outputs/socket_writer/socket_writer_test.go @@ -6,6 +6,7 @@ import ( "net" "os" "path/filepath" + "runtime" "sync" "testing" @@ -66,6 +67,10 @@ func TestSocketWriter_unix(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") require.NoError(t, err) defer os.RemoveAll(tmpdir) diff --git a/plugins/processors/ifname/ifname_test.go b/plugins/processors/ifname/ifname_test.go index 85ddc7674..25e130e3a 100644 --- a/plugins/processors/ifname/ifname_test.go +++ b/plugins/processors/ifname/ifname_test.go @@ -6,12 +6,13 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/internal" "github.com/influxdata/telegraf/internal/snmp" si "github.com/influxdata/telegraf/plugins/inputs/snmp" "github.com/influxdata/telegraf/testutil" - "github.com/stretchr/testify/require" ) func TestTable(t *testing.T) { diff --git a/plugins/processors/ifname/ttl_cache.go b/plugins/processors/ifname/ttl_cache.go index 8f9c4ae65..99cbab1d5 100644 --- a/plugins/processors/ifname/ttl_cache.go +++ b/plugins/processors/ifname/ttl_cache.go @@ -1,6 +1,7 @@ package ifname import ( + "runtime" "time" ) @@ -30,6 +31,15 @@ func (c *TTLCache) Get(key keyType) (valType, bool, time.Duration) { if !ok { 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) if age < c.validDuration { return v.val, ok, age diff --git a/plugins/processors/reverse_dns/rdnscache.go b/plugins/processors/reverse_dns/rdnscache.go index 1d86b5385..cc9574552 100644 --- a/plugins/processors/reverse_dns/rdnscache.go +++ b/plugins/processors/reverse_dns/rdnscache.go @@ -111,7 +111,7 @@ func (d *ReverseDNSCache) lookup(ip string) ([]string, error) { // check if the value is cached d.rwLock.RLock() 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() atomic.AddUint64(&d.stats.CacheHit, 1) // cache is valid @@ -176,7 +176,7 @@ func (d *ReverseDNSCache) subscribeTo(ip string) callbackChannelType { // the dnslookup that is returned until you clone it. func (d *ReverseDNSCache) lockedGetFromCache(ip string) (lookup *dnslookup, found bool) { lookup, found = d.cache[ip] - if found && lookup.expiresAt.Before(time.Now()) { + if found && !lookup.expiresAt.After(time.Now()) { return nil, false } 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. // you MUST first do a write lock before calling it. func (d *ReverseDNSCache) lockedSaveToCache(lookup *dnslookup) { - if lookup.expiresAt.Before(time.Now()) { + if !lookup.expiresAt.After(time.Now()) { return // don't cache. } d.cache[lookup.ip] = lookup @@ -277,7 +277,7 @@ func (d *ReverseDNSCache) cleanup() { } ipsToDelete := []string{} 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. } ipsToDelete = append(ipsToDelete, d.expireList[i].ip) diff --git a/plugins/processors/reverse_dns/reversedns_test.go b/plugins/processors/reverse_dns/reversedns_test.go index 499dffb77..660c25e30 100644 --- a/plugins/processors/reverse_dns/reversedns_test.go +++ b/plugins/processors/reverse_dns/reversedns_test.go @@ -1,13 +1,15 @@ package reverse_dns import ( + "runtime" "testing" "time" + "github.com/stretchr/testify/require" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/testutil" - "github.com/stretchr/testify/require" ) func TestSimpleReverseLookup(t *testing.T) { @@ -40,7 +42,10 @@ func TestSimpleReverseLookup(t *testing.T) { processedMetric := acc.GetTelegrafMetrics()[0] f, ok := processedMetric.GetField("source_name") 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") require.True(t, ok)