|
| 1 | +// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 2 | +// or more contributor license agreements. Licensed under the Elastic License; |
| 3 | +// you may not use this file except in compliance with the Elastic License. |
| 4 | + |
| 5 | +package util |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "errors" |
| 10 | + "testing" |
| 11 | + |
| 12 | + "github.com/elastic/elastic-agent-libs/logp" |
| 13 | + |
| 14 | + "github.com/stretchr/testify/require" |
| 15 | + |
| 16 | + "github.com/elastic/go-sysinfo/types" |
| 17 | +) |
| 18 | + |
| 19 | +func TestGetHostName(t *testing.T) { |
| 20 | + cases := map[string]struct { |
| 21 | + fqdnFeatureEnabled bool |
| 22 | + hostInfo types.HostInfo |
| 23 | + host types.Host |
| 24 | + log *logp.Logger |
| 25 | + |
| 26 | + expected string |
| 27 | + }{ |
| 28 | + "fqdn_feature_disabled": { |
| 29 | + fqdnFeatureEnabled: false, |
| 30 | + hostInfo: types.HostInfo{Hostname: "foobar"}, |
| 31 | + expected: "foobar", |
| 32 | + }, |
| 33 | + "fqdn_lookup_fails": { |
| 34 | + fqdnFeatureEnabled: true, |
| 35 | + hostInfo: types.HostInfo{Hostname: "foobar"}, |
| 36 | + host: &mockHost{ |
| 37 | + fqdn: "", |
| 38 | + fqdnErr: errors.New("fqdn lookup failed while testing"), |
| 39 | + }, |
| 40 | + log: logp.NewLogger("testing"), |
| 41 | + expected: "foobar", |
| 42 | + }, |
| 43 | + "fqdn_lookup_succeeds": { |
| 44 | + fqdnFeatureEnabled: true, |
| 45 | + hostInfo: types.HostInfo{Hostname: "foobar"}, |
| 46 | + host: &mockHost{ |
| 47 | + fqdn: "qux", |
| 48 | + fqdnErr: nil, |
| 49 | + }, |
| 50 | + expected: "qux", |
| 51 | + }, |
| 52 | + } |
| 53 | + |
| 54 | + for name, test := range cases { |
| 55 | + t.Run(name, func(t *testing.T) { |
| 56 | + hostname := GetHostName(test.fqdnFeatureEnabled, test.hostInfo, test.host, test.log) |
| 57 | + require.Equal(t, test.expected, hostname) |
| 58 | + }) |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +type mockHost struct { |
| 63 | + fqdn string |
| 64 | + fqdnErr error |
| 65 | +} |
| 66 | + |
| 67 | +func (m *mockHost) CPUTime() (types.CPUTimes, error) { return types.CPUTimes{}, nil } |
| 68 | +func (m *mockHost) Info() types.HostInfo { return types.HostInfo{} } |
| 69 | +func (m *mockHost) Memory() (*types.HostMemoryInfo, error) { return nil, nil } |
| 70 | +func (m *mockHost) FQDNWithContext(ctx context.Context) (string, error) { |
| 71 | + return m.fqdn, m.fqdnErr |
| 72 | +} |
| 73 | +func (m *mockHost) FQDN() (string, error) { return m.FQDNWithContext(context.Background()) } |
0 commit comments