diff --git a/README.md b/README.md index aac78f3..96d5db2 100644 --- a/README.md +++ b/README.md @@ -134,8 +134,8 @@ If you've never contributed to a Go project before, here is an example workflow. 1. `git push -u origin development` (setup where you push to, check it works) Before opening a pull request, run `make test` and `make lint` (which needs -[golangci-lint](https://golangci-lint.run/)). If you change an enum or -`interface.go`, run `make generate` and commit the regenerated files. +[golangci-lint](https://golangci-lint.run/)). If you change an enum, run +`make generate` and commit the regenerated files. # Packet Captures @@ -201,8 +201,8 @@ protocol pair). By default it replays the recordings in `netsnmp/testdata`. With installed (`libsnmp-dev`), `make -C netsnmp test_netsnmp` compares with the library directly, and `go test -tags netsnmp -rec ./...` in `netsnmp/` re-records them. -The `*_string.go` files and the `go.uber.org/mock` mocks in `mocks/` are generated by -`go generate ./...`, which runs the `stringer` and `mockgen` versions pinned in `tools/go.mod`. +The `*_string.go` files are generated by `go generate ./...`, which runs the `stringer` +version pinned in `tools/go.mod`. To profile cpu usage: diff --git a/doc.go b/doc.go index 1c8baea..0ad45bf 100644 --- a/doc.go +++ b/doc.go @@ -13,8 +13,9 @@ // // # Lifecycle // -// A client is a [Client] whose exported fields configure it: a literal, or -// [NewHandler] for code that takes the [Handler] interface. [Client.Connect] +// A client is a [Client] whose exported fields configure it. The package +// declares no interface of the client for tests to mock: code that mocks it +// declares one of its own with the methods it calls. [Client.Connect] // fills in defaults ([MaxOids], a background Context), checks the SNMPv3 // configuration and opens the connection, a UDP socket connected to Target and // Port, which replaces the client's (a failed Connect keeps it); a client may diff --git a/engine_walk_test.go b/engine_walk_test.go index 8e8955f..f13e556 100644 --- a/engine_walk_test.go +++ b/engine_walk_test.go @@ -7,6 +7,7 @@ package gosnmp import ( "fmt" "maps" + "math" "reflect" "slices" "strings" @@ -213,7 +214,11 @@ func walkScenarios() map[string]walkScenario { "empty-subtree/bulk": {root: ".1.3.6.1.2.1.1.4", bulk: true}, "max-repetitions/two": {root: walkIfDescr, bulk: true, setup: func(x *Client) { x.MaxRepetitions = 2 }}, "max-repetitions/one": {root: walkSystem, bulk: true, setup: func(x *Client) { x.MaxRepetitions = 1 }}, - "v1-bulk": {root: walkSystem, bulk: true, v1: true}, + // The request carries max-repetitions with its top bit cleared; the + // default replaces only a zero field, so the top bit alone sends 0. + "max-repetitions/max-uint32": {root: walkIfDescr, bulk: true, setup: func(x *Client) { x.MaxRepetitions = math.MaxUint32 }}, + "max-repetitions/top-bit": {root: walkIfDescr, bulk: true, setup: func(x *Client) { x.MaxRepetitions = 1 << 31 }}, + "v1-bulk": {root: walkSystem, bulk: true, v1: true}, // A root the codec cannot encode fails the walk before any request, // naming the root as given. "root-invalid": {root: "1.3.6.x"}, diff --git a/go.mod b/go.mod index 884908c..705247e 100644 --- a/go.mod +++ b/go.mod @@ -2,9 +2,6 @@ module github.com/netdata/gosnmp go 1.27.0 -require ( - github.com/stretchr/testify v1.12.1 - go.uber.org/mock v0.6.0 -) +require github.com/stretchr/testify v1.12.1 require go.yaml.in/yaml/v3 v3.0.5 // indirect diff --git a/go.sum b/go.sum index 09f0a53..c233683 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,4 @@ github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= -go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= -go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= diff --git a/interface.go b/interface.go deleted file mode 100644 index b99ed5e..0000000 --- a/interface.go +++ /dev/null @@ -1,217 +0,0 @@ -// Copyright 2012 The GoSNMP Authors. All rights reserved. Use of this -// source code is governed by a BSD-style license that can be found in the -// LICENSE file. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gosnmp - -import ( - "math" - "time" -) - -//go:generate go tool -modfile=tools/go.mod mockgen -source=interface.go -destination=mocks/gosnmp_mock.go -package=mocks - -// Handler is the interface of a Client, provided for mocks in tests; the -// methods that act are documented on Client, the others get or set its -// fields. Like a Client, a Handler is not safe for concurrent use, Close -// excepted. -type Handler interface { - // Connect: see Client.Connect. - Connect() error - - // Get: see Client.Get. - Get(oids []string) (result *Message, err error) - - // WalkAll: see Client.WalkAll. - WalkAll(rootOid string) (results []VarBind, err error) - - // BulkWalkAll: see Client.BulkWalkAll. - BulkWalkAll(rootOid string) (results []VarBind, err error) - - // Close: see Client.Close. - Close() error - - // Target gets the Target - Target() string - - // SetTarget sets the Target - SetTarget(target string) - - // Port gets the Port - Port() uint16 - - // SetPort sets the Port - SetPort(port uint16) - - // Community gets the Community - Community() string - - // SetCommunity sets the Community - SetCommunity(community string) - - // Version gets the Version - Version() Version - - // SetVersion sets the Version - SetVersion(version Version) - - // Timeout gets the Timeout - Timeout() time.Duration - - // SetTimeout sets the Timeout - SetTimeout(timeout time.Duration) - - // Retries gets the Retries - Retries() int - - // SetRetries sets the Retries - SetRetries(retries int) - - // MaxOids gets the MaxOids - MaxOids() int - - // SetMaxOids sets the MaxOids - SetMaxOids(maxOids int) - - // MaxRepetitions gets the MaxRepetitions - MaxRepetitions() uint32 - - // SetMaxRepetitions sets the MaxRepetitions, with its top bit cleared - SetMaxRepetitions(maxRepetitions uint32) - - // SecurityLevel gets the SecurityLevel - SecurityLevel() SecurityLevel - - // SetSecurityLevel sets the SecurityLevel - SetSecurityLevel(securityLevel SecurityLevel) - - // User gets the User - User() User - - // SetUser sets the User - SetUser(user User) - - // ForgetEngine: see Client.ForgetEngine. - ForgetEngine() - - // ContextName gets the ContextName - ContextName() string - - // SetContextName sets the ContextName - SetContextName(contextName string) -} - -// snmpHandler is a wrapper around gosnmp -type snmpHandler struct { - Client -} - -// NewHandler returns a Handler backed by a new Client with Port 161, -// Community "public", Version2c, a Timeout of 2 seconds, 3 Retries and -// MaxOids at the MaxOids constant. -func NewHandler() Handler { - return &snmpHandler{ - Client{ - Port: 161, - Community: "public", - Version: Version2c, - Timeout: 2 * time.Second, - Retries: 3, - MaxOids: MaxOids, - }, - } -} - -func (x *snmpHandler) Target() string { - // not x.Target because it would reference function Target - return x.Client.Target -} - -func (x *snmpHandler) SetTarget(target string) { - x.Client.Target = target -} - -func (x *snmpHandler) Port() uint16 { - return x.Client.Port -} - -func (x *snmpHandler) SetPort(port uint16) { - x.Client.Port = port -} - -func (x *snmpHandler) Community() string { - return x.Client.Community -} - -func (x *snmpHandler) SetCommunity(community string) { - x.Client.Community = community -} - -func (x *snmpHandler) Version() Version { - return x.Client.Version -} - -func (x *snmpHandler) SetVersion(version Version) { - x.Client.Version = version -} - -func (x *snmpHandler) Timeout() time.Duration { - return x.Client.Timeout -} - -func (x *snmpHandler) SetTimeout(timeout time.Duration) { - x.Client.Timeout = timeout -} - -func (x *snmpHandler) Retries() int { - return x.Client.Retries -} - -func (x *snmpHandler) SetRetries(retries int) { - x.Client.Retries = retries -} - -func (x *snmpHandler) MaxOids() int { - return x.Client.MaxOids -} - -func (x *snmpHandler) SetMaxOids(maxOids int) { - x.Client.MaxOids = maxOids -} - -func (x *snmpHandler) MaxRepetitions() uint32 { - return x.Client.MaxRepetitions -} - -// SetMaxRepetitions sets MaxRepetitions with its top bit cleared. -func (x *snmpHandler) SetMaxRepetitions(maxRepetitions uint32) { - x.Client.MaxRepetitions = maxRepetitions & math.MaxInt32 -} - -func (x *snmpHandler) SecurityLevel() SecurityLevel { - return x.Client.SecurityLevel -} - -func (x *snmpHandler) SetSecurityLevel(securityLevel SecurityLevel) { - x.Client.SecurityLevel = securityLevel -} - -func (x *snmpHandler) User() User { - return x.Client.User -} - -func (x *snmpHandler) SetUser(user User) { - x.Client.User = user -} - -func (x *snmpHandler) ContextName() string { - return x.Client.ContextName -} - -func (x *snmpHandler) SetContextName(contextName string) { - x.Client.ContextName = contextName -} diff --git a/mocks/gosnmp_mock.go b/mocks/gosnmp_mock.go deleted file mode 100644 index 7be1dfd..0000000 --- a/mocks/gosnmp_mock.go +++ /dev/null @@ -1,413 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: interface.go -// -// Generated by this command: -// -// mockgen -source=interface.go -destination=mocks/gosnmp_mock.go -package=mocks -// - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - time "time" - - gosnmp "github.com/netdata/gosnmp" - gomock "go.uber.org/mock/gomock" -) - -// MockHandler is a mock of Handler interface. -type MockHandler struct { - ctrl *gomock.Controller - recorder *MockHandlerMockRecorder - isgomock struct{} -} - -// MockHandlerMockRecorder is the mock recorder for MockHandler. -type MockHandlerMockRecorder struct { - mock *MockHandler -} - -// NewMockHandler creates a new mock instance. -func NewMockHandler(ctrl *gomock.Controller) *MockHandler { - mock := &MockHandler{ctrl: ctrl} - mock.recorder = &MockHandlerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockHandler) EXPECT() *MockHandlerMockRecorder { - return m.recorder -} - -// BulkWalkAll mocks base method. -func (m *MockHandler) BulkWalkAll(rootOid string) ([]gosnmp.VarBind, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BulkWalkAll", rootOid) - ret0, _ := ret[0].([]gosnmp.VarBind) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// BulkWalkAll indicates an expected call of BulkWalkAll. -func (mr *MockHandlerMockRecorder) BulkWalkAll(rootOid any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BulkWalkAll", reflect.TypeOf((*MockHandler)(nil).BulkWalkAll), rootOid) -} - -// Close mocks base method. -func (m *MockHandler) Close() error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Close") - ret0, _ := ret[0].(error) - return ret0 -} - -// Close indicates an expected call of Close. -func (mr *MockHandlerMockRecorder) Close() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockHandler)(nil).Close)) -} - -// Community mocks base method. -func (m *MockHandler) Community() string { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Community") - ret0, _ := ret[0].(string) - return ret0 -} - -// Community indicates an expected call of Community. -func (mr *MockHandlerMockRecorder) Community() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Community", reflect.TypeOf((*MockHandler)(nil).Community)) -} - -// Connect mocks base method. -func (m *MockHandler) Connect() error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Connect") - ret0, _ := ret[0].(error) - return ret0 -} - -// Connect indicates an expected call of Connect. -func (mr *MockHandlerMockRecorder) Connect() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Connect", reflect.TypeOf((*MockHandler)(nil).Connect)) -} - -// ContextName mocks base method. -func (m *MockHandler) ContextName() string { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ContextName") - ret0, _ := ret[0].(string) - return ret0 -} - -// ContextName indicates an expected call of ContextName. -func (mr *MockHandlerMockRecorder) ContextName() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContextName", reflect.TypeOf((*MockHandler)(nil).ContextName)) -} - -// ForgetEngine mocks base method. -func (m *MockHandler) ForgetEngine() { - m.ctrl.T.Helper() - m.ctrl.Call(m, "ForgetEngine") -} - -// ForgetEngine indicates an expected call of ForgetEngine. -func (mr *MockHandlerMockRecorder) ForgetEngine() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ForgetEngine", reflect.TypeOf((*MockHandler)(nil).ForgetEngine)) -} - -// Get mocks base method. -func (m *MockHandler) Get(oids []string) (*gosnmp.Message, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Get", oids) - ret0, _ := ret[0].(*gosnmp.Message) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Get indicates an expected call of Get. -func (mr *MockHandlerMockRecorder) Get(oids any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockHandler)(nil).Get), oids) -} - -// MaxOids mocks base method. -func (m *MockHandler) MaxOids() int { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "MaxOids") - ret0, _ := ret[0].(int) - return ret0 -} - -// MaxOids indicates an expected call of MaxOids. -func (mr *MockHandlerMockRecorder) MaxOids() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MaxOids", reflect.TypeOf((*MockHandler)(nil).MaxOids)) -} - -// MaxRepetitions mocks base method. -func (m *MockHandler) MaxRepetitions() uint32 { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "MaxRepetitions") - ret0, _ := ret[0].(uint32) - return ret0 -} - -// MaxRepetitions indicates an expected call of MaxRepetitions. -func (mr *MockHandlerMockRecorder) MaxRepetitions() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MaxRepetitions", reflect.TypeOf((*MockHandler)(nil).MaxRepetitions)) -} - -// Port mocks base method. -func (m *MockHandler) Port() uint16 { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Port") - ret0, _ := ret[0].(uint16) - return ret0 -} - -// Port indicates an expected call of Port. -func (mr *MockHandlerMockRecorder) Port() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Port", reflect.TypeOf((*MockHandler)(nil).Port)) -} - -// Retries mocks base method. -func (m *MockHandler) Retries() int { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Retries") - ret0, _ := ret[0].(int) - return ret0 -} - -// Retries indicates an expected call of Retries. -func (mr *MockHandlerMockRecorder) Retries() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Retries", reflect.TypeOf((*MockHandler)(nil).Retries)) -} - -// SecurityLevel mocks base method. -func (m *MockHandler) SecurityLevel() gosnmp.SecurityLevel { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SecurityLevel") - ret0, _ := ret[0].(gosnmp.SecurityLevel) - return ret0 -} - -// SecurityLevel indicates an expected call of SecurityLevel. -func (mr *MockHandlerMockRecorder) SecurityLevel() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SecurityLevel", reflect.TypeOf((*MockHandler)(nil).SecurityLevel)) -} - -// SetCommunity mocks base method. -func (m *MockHandler) SetCommunity(community string) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetCommunity", community) -} - -// SetCommunity indicates an expected call of SetCommunity. -func (mr *MockHandlerMockRecorder) SetCommunity(community any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetCommunity", reflect.TypeOf((*MockHandler)(nil).SetCommunity), community) -} - -// SetContextName mocks base method. -func (m *MockHandler) SetContextName(contextName string) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetContextName", contextName) -} - -// SetContextName indicates an expected call of SetContextName. -func (mr *MockHandlerMockRecorder) SetContextName(contextName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetContextName", reflect.TypeOf((*MockHandler)(nil).SetContextName), contextName) -} - -// SetMaxOids mocks base method. -func (m *MockHandler) SetMaxOids(maxOids int) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetMaxOids", maxOids) -} - -// SetMaxOids indicates an expected call of SetMaxOids. -func (mr *MockHandlerMockRecorder) SetMaxOids(maxOids any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetMaxOids", reflect.TypeOf((*MockHandler)(nil).SetMaxOids), maxOids) -} - -// SetMaxRepetitions mocks base method. -func (m *MockHandler) SetMaxRepetitions(maxRepetitions uint32) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetMaxRepetitions", maxRepetitions) -} - -// SetMaxRepetitions indicates an expected call of SetMaxRepetitions. -func (mr *MockHandlerMockRecorder) SetMaxRepetitions(maxRepetitions any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetMaxRepetitions", reflect.TypeOf((*MockHandler)(nil).SetMaxRepetitions), maxRepetitions) -} - -// SetPort mocks base method. -func (m *MockHandler) SetPort(port uint16) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetPort", port) -} - -// SetPort indicates an expected call of SetPort. -func (mr *MockHandlerMockRecorder) SetPort(port any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetPort", reflect.TypeOf((*MockHandler)(nil).SetPort), port) -} - -// SetRetries mocks base method. -func (m *MockHandler) SetRetries(retries int) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetRetries", retries) -} - -// SetRetries indicates an expected call of SetRetries. -func (mr *MockHandlerMockRecorder) SetRetries(retries any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetRetries", reflect.TypeOf((*MockHandler)(nil).SetRetries), retries) -} - -// SetSecurityLevel mocks base method. -func (m *MockHandler) SetSecurityLevel(securityLevel gosnmp.SecurityLevel) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetSecurityLevel", securityLevel) -} - -// SetSecurityLevel indicates an expected call of SetSecurityLevel. -func (mr *MockHandlerMockRecorder) SetSecurityLevel(securityLevel any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSecurityLevel", reflect.TypeOf((*MockHandler)(nil).SetSecurityLevel), securityLevel) -} - -// SetTarget mocks base method. -func (m *MockHandler) SetTarget(target string) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetTarget", target) -} - -// SetTarget indicates an expected call of SetTarget. -func (mr *MockHandlerMockRecorder) SetTarget(target any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetTarget", reflect.TypeOf((*MockHandler)(nil).SetTarget), target) -} - -// SetTimeout mocks base method. -func (m *MockHandler) SetTimeout(timeout time.Duration) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetTimeout", timeout) -} - -// SetTimeout indicates an expected call of SetTimeout. -func (mr *MockHandlerMockRecorder) SetTimeout(timeout any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetTimeout", reflect.TypeOf((*MockHandler)(nil).SetTimeout), timeout) -} - -// SetUser mocks base method. -func (m *MockHandler) SetUser(user gosnmp.User) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetUser", user) -} - -// SetUser indicates an expected call of SetUser. -func (mr *MockHandlerMockRecorder) SetUser(user any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetUser", reflect.TypeOf((*MockHandler)(nil).SetUser), user) -} - -// SetVersion mocks base method. -func (m *MockHandler) SetVersion(version gosnmp.Version) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetVersion", version) -} - -// SetVersion indicates an expected call of SetVersion. -func (mr *MockHandlerMockRecorder) SetVersion(version any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetVersion", reflect.TypeOf((*MockHandler)(nil).SetVersion), version) -} - -// Target mocks base method. -func (m *MockHandler) Target() string { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Target") - ret0, _ := ret[0].(string) - return ret0 -} - -// Target indicates an expected call of Target. -func (mr *MockHandlerMockRecorder) Target() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Target", reflect.TypeOf((*MockHandler)(nil).Target)) -} - -// Timeout mocks base method. -func (m *MockHandler) Timeout() time.Duration { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Timeout") - ret0, _ := ret[0].(time.Duration) - return ret0 -} - -// Timeout indicates an expected call of Timeout. -func (mr *MockHandlerMockRecorder) Timeout() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Timeout", reflect.TypeOf((*MockHandler)(nil).Timeout)) -} - -// User mocks base method. -func (m *MockHandler) User() gosnmp.User { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "User") - ret0, _ := ret[0].(gosnmp.User) - return ret0 -} - -// User indicates an expected call of User. -func (mr *MockHandlerMockRecorder) User() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "User", reflect.TypeOf((*MockHandler)(nil).User)) -} - -// Version mocks base method. -func (m *MockHandler) Version() gosnmp.Version { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Version") - ret0, _ := ret[0].(gosnmp.Version) - return ret0 -} - -// Version indicates an expected call of Version. -func (mr *MockHandlerMockRecorder) Version() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Version", reflect.TypeOf((*MockHandler)(nil).Version)) -} - -// WalkAll mocks base method. -func (m *MockHandler) WalkAll(rootOid string) ([]gosnmp.VarBind, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "WalkAll", rootOid) - ret0, _ := ret[0].([]gosnmp.VarBind) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// WalkAll indicates an expected call of WalkAll. -func (mr *MockHandlerMockRecorder) WalkAll(rootOid any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WalkAll", reflect.TypeOf((*MockHandler)(nil).WalkAll), rootOid) -} diff --git a/request_test.go b/request_test.go index 161df16..8fe550e 100644 --- a/request_test.go +++ b/request_test.go @@ -5,35 +5,14 @@ package gosnmp import ( - "math" "net" "strconv" "testing" - "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -// TestHandlerMaxRepetitions pins that a Handler keeps max-repetitions with -// its top bit cleared. -func TestHandlerMaxRepetitions(t *testing.T) { - h := NewHandler() - assert.Equal(t, uint32(0), h.MaxRepetitions(), "new") - h.SetMaxRepetitions(math.MaxUint32) - assert.Equal(t, uint32(math.MaxInt32), h.MaxRepetitions()) -} - -// TestNewHandler pins the client a new Handler is backed by: SNMPv2c to port -// 161 with the community "public", a Timeout of 2 seconds, 3 Retries and -// MaxOids at the MaxOids constant, nothing else set. -func TestNewHandler(t *testing.T) { - h, ok := NewHandler().(*snmpHandler) - require.True(t, ok) - want := &Client{Port: 161, Community: "public", Version: Version2c, Timeout: 2 * time.Second, Retries: 3, MaxOids: MaxOids} - assert.Equal(t, want, &h.Client) -} - // TestWalkRequestChecks pins the checks a walk makes before its first // request, in their order, on a client without Connect (MaxOids zero): the // root, then GetBulk on SNMPv1, then MaxOids against the one OID a request diff --git a/testdata/engine/walk.golden b/testdata/engine/walk.golden index 0a83341..cc66637 100644 --- a/testdata/engine/walk.golden +++ b/testdata/engine/walk.golden @@ -707,6 +707,15 @@ 0s values: [] 0s result: no error +== walk/max-repetitions/max-uint32 +0s client: 2c root=".1.3.6.1.2.1.2.2.1.2" bulk=true max-repetitions=4294967295 +0s deadline +1s +0s write #1: 2c "public" GetBulkRequest id=1001 nonRepeaters=0 maxRepetitions=2147483647 [.1.3.6.1.2.1.2.2.1.2] +0s agent answers #1 after 0s +0s read from 127.0.0.2:161: 2c "public" Response id=1001 [.1.3.6.1.2.1.2.2.1.2.1=OctetString:"lo" .1.3.6.1.2.1.2.2.1.2.2=OctetString:"eth0" .1.3.6.1.2.1.2.2.1.2.10=OctetString:"eth1" .1.3.6.1.4.1.99.1.0=Integer:7 .1.3.6.1.4.1.99.1.0=EndOfMibView:] +0s values: [.1.3.6.1.2.1.2.2.1.2.1=OctetString:"lo" .1.3.6.1.2.1.2.2.1.2.2=OctetString:"eth0" .1.3.6.1.2.1.2.2.1.2.10=OctetString:"eth1"] +0s result: no error + == walk/max-repetitions/one 0s client: 2c root=".1.3.6.1.2.1.1" bulk=true max-repetitions=1 0s deadline +1s @@ -728,6 +737,15 @@ 0s values: [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent" .1.3.6.1.2.1.1.3.0=TimeTicks:4200 .1.3.6.1.2.1.1.5.0=OctetString:"codec-host"] 0s result: no error +== walk/max-repetitions/top-bit +0s client: 2c root=".1.3.6.1.2.1.2.2.1.2" bulk=true max-repetitions=2147483648 +0s deadline +1s +0s write #1: 2c "public" GetBulkRequest id=1001 nonRepeaters=0 maxRepetitions=0 [.1.3.6.1.2.1.2.2.1.2] +0s agent answers #1 after 0s +0s read from 127.0.0.2:161: 2c "public" Response id=1001 [] +0s values: [] +0s result: no error + == walk/max-repetitions/two 0s client: 2c root=".1.3.6.1.2.1.2.2.1.2" bulk=true max-repetitions=2 0s deadline +1s diff --git a/tools/go.mod b/tools/go.mod index 434735f..6136533 100644 --- a/tools/go.mod +++ b/tools/go.mod @@ -5,13 +5,11 @@ module github.com/netdata/gosnmp/tools go 1.27.0 tool ( - go.uber.org/mock/mockgen golang.org/x/tools/cmd/stringer golang.org/x/vuln/cmd/govulncheck ) require ( - go.uber.org/mock v0.6.0 // indirect golang.org/x/mod v0.41.0 // indirect golang.org/x/sync v0.23.0 // indirect golang.org/x/sys v0.48.0 // indirect diff --git a/tools/go.sum b/tools/go.sum index 5444336..d374986 100644 --- a/tools/go.sum +++ b/tools/go.sum @@ -1,17 +1,9 @@ -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/google/go-cmdtest v0.4.1-0.20220921163831-55ab3332a786 h1:rcv+Ippz6RAtvaGgKxc+8FQIpxHgsF+HBzPyYL2cyVU= github.com/google/go-cmdtest v0.4.1-0.20220921163831-55ab3332a786/go.mod h1:apVn/GCasLZUVpAJ6oWAuyP7Ne7CEsQbTnc0plM3m+o= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/renameio v0.1.0 h1:GOZbcHa3HfsPKPlmyPyN2KEohoMXOhdMbHrvbpl2QaA= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= -github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= -go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= @@ -28,5 +20,3 @@ golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated h1:1h2MnaIAIXISqTF golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated/go.mod h1:RVAQXBGNv1ib0J382/DPCRS/BPnsGebyM1Gj5VSDpG8= golang.org/x/vuln v1.8.0 h1:clG4qBU6zH5VKjti8n5j8BBuYzoSha392xXMkXS351U= golang.org/x/vuln v1.8.0/go.mod h1:Fzm4XK3Hbl1ZvZ7JpNTEWb7CJWOZ7m2LX0GLu4Fsrwo= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/transport_test.go b/transport_test.go index 8ef2c99..a254c4a 100644 --- a/transport_test.go +++ b/transport_test.go @@ -425,8 +425,10 @@ func (c *closeErrConn) Close() error { } // TestCloseOnce pins that Close closes the connection once, returns its error -// and leaves no connection, and that a client without one closes cleanly. +// and leaves no connection, and that a client without one closes cleanly: +// one whose connection Close already closed, and one that never had any. func TestCloseOnce(t *testing.T) { + assert.NoError(t, (&Client{}).Close(), "a client that never had a connection") c := &closeErrConn{} x := &Client{Conn: c} assert.ErrorIs(t, x.Close(), errCloseConn) @@ -435,42 +437,6 @@ func TestCloseOnce(t *testing.T) { assert.Equal(t, 1, c.closes) } -// TestHandlerClose pins that the Handler's Close is the client's: on a client -// without a connection it returns nil, and it closes a connection once, leaving -// no connection. -func TestHandlerClose(t *testing.T) { - type outcome struct { - panics bool - first, second error - connSet bool // Conn is still set after the two calls - closes int // the connection's Close calls - } - tests := map[string]struct { - conn bool - want outcome - }{ - "without a connection": {want: outcome{}}, - "twice": {conn: true, want: outcome{first: errCloseConn, closes: 1}}, - } - for name, tc := range tests { - t.Run(name, func(t *testing.T) { - h := NewHandler() - c := &closeErrConn{} - if tc.conn { - h.(*snmpHandler).Conn = c - } - var got outcome - if v, _ := recoverPanic(func() { got.first = h.Close() }); v != nil { - got.panics = true - } else { - got.second = h.Close() - } - got.connSet, got.closes = h.(*snmpHandler).Conn != nil, c.closes - assert.Equal(t, tc.want, got) - }) - } -} - // TestConnectReplacesConnection pins what a second Connect does with the // client's connection: when it opens a new one, it closes the first; when its // dial fails, the client keeps the first. @@ -563,10 +529,9 @@ func TestRequestWithoutConnection(t *testing.T) { } // TestCloseDuringRequest checks, on a loopback socket, Close as Netdata's SNMP -// topology uses it: two goroutines close the client, through the Handler, -// while a request waits for its answer. The request ends at once with -// net.ErrClosed, the next one fails the same way without being sent, and -// Connect opens the client again. +// topology uses it: two goroutines close the client while a request waits for +// its answer. The request ends at once with net.ErrClosed, the next one fails +// the same way without being sent, and Connect opens the client again. func TestCloseDuringRequest(t *testing.T) { port, reads := udpAgent(t, func(n int, req []byte) []byte { if n == 1 { @@ -574,35 +539,30 @@ func TestCloseDuringRequest(t *testing.T) { } return replyTo(req, nil, sysDescr) }) - h := NewHandler() - h.SetTarget("127.0.0.1") - h.SetPort(port) - h.SetTimeout(10 * time.Second) - h.SetRetries(0) - require.NoError(t, h.Connect()) - defer h.Close() - - closers := closeOnRelease(h, 2, func() { <-reads }) + x := &Client{Target: "127.0.0.1", Port: port, Community: "public", Version: Version2c, Timeout: 10 * time.Second} + require.NoError(t, x.Connect()) + defer x.Close() + + closers := closeOnRelease(x, 2, func() { <-reads }) start := time.Now() - _, err := h.Get([]string{engineOID}) + _, err := x.Get([]string{engineOID}) require.ErrorIs(t, err, net.ErrClosed) assert.Less(t, time.Since(start), 5*time.Second, "the request ends before its timeout") closers.Wait() - _, err = h.Get([]string{engineOID}) + _, err = x.Get([]string{engineOID}) require.ErrorIs(t, err, net.ErrClosed) - require.NoError(t, h.Connect()) - res, err := h.Get([]string{engineOID}) + require.NoError(t, x.Connect()) + res, err := x.Get([]string{engineOID}) require.NoError(t, err) assert.Equal(t, []VarBind{sysDescr}, res.VarBinds) assert.Len(t, reads, 1, "the agent read the request after Connect, not the one after Close") } // TestCloseDuringWalk checks, on a loopback socket, Close as Netdata's SNMP -// topology uses it during a walk: two goroutines close the client, through the -// Handler, while the walk waits for an answer. The walk ends at once with -// net.ErrClosed. +// topology uses it during a walk: two goroutines close the client while the +// walk waits for an answer. The walk ends at once with net.ErrClosed. func TestCloseDuringWalk(t *testing.T) { const root = ".1.3.6.1.2.1.2.2.1.2" port, reads := udpAgent(t, func(n int, req []byte) []byte { @@ -620,15 +580,11 @@ func TestCloseDuringWalk(t *testing.T) { } return replyTo(req, nil, VarBind{Name: next, Value: OctetStringValue([]byte("codec"))}) }) - h := NewHandler() - h.SetTarget("127.0.0.1") - h.SetPort(port) - h.SetTimeout(10 * time.Second) - h.SetRetries(0) - require.NoError(t, h.Connect()) - defer h.Close() - - closers := closeOnRelease(h, 2, func() { + x := &Client{Target: "127.0.0.1", Port: port, Community: "public", Version: Version2c, Timeout: 10 * time.Second} + require.NoError(t, x.Connect()) + defer x.Close() + + closers := closeOnRelease(x, 2, func() { for n := range reads { if n == 5 { return @@ -636,7 +592,7 @@ func TestCloseDuringWalk(t *testing.T) { } }) start := time.Now() - _, err := h.BulkWalkAll(root) + _, err := x.BulkWalkAll(root) require.ErrorIs(t, err, net.ErrClosed) assert.Less(t, time.Since(start), 5*time.Second, "the walk ends before its request's timeout") closers.Wait() @@ -711,9 +667,9 @@ func TestCloseDuringRequestConnReplaced(t *testing.T) { } } -// closeOnRelease starts n goroutines that close h once release returns, and +// closeOnRelease starts n goroutines that close x once release returns, and // returns their WaitGroup. -func closeOnRelease(h Handler, n int, release func()) *sync.WaitGroup { +func closeOnRelease(x *Client, n int, release func()) *sync.WaitGroup { released := make(chan struct{}) go func() { release() @@ -723,7 +679,7 @@ func closeOnRelease(h Handler, n int, release func()) *sync.WaitGroup { for range n { closers.Go(func() { <-released - _ = h.Close() + _ = x.Close() }) } return &closers