如何在单元测试 Golang 中模拟 netconf 会话

2024年 2月 12日 63.7k 0

如何在单元测试 golang 中模拟 netconf 会话

问题内容

我正在使用 juniper 的 netconf 包(“github.com/juniper/go-netconf/netconf”)在我的代码中建立 netconf 会话。

我想知道如何在单元测试中模拟 netconf 会话。

我的方法是:

func testmyfunction(t *testing.t) {
getsshconnection = mockgetsshconnection
got := myfunction()
want := 123
if !reflect.deepequal(got, want) {
t.errorf("error expectation not met, want %v, got %v", want, got)
}
}

登录后复制

func mockgetsshconnection() (*netconf.session, error) {
var sess netconf.session
sess.sessionid = 123
return &sess, nil
}

登录后复制

当 myfunction() 有一行延迟 sess.close() 并且由于 nil 指针取消引用而引发错误时,就会出现问题

func MyFunction() int {
sess, err := getSSHConnection() // returns (*netconf.Session, error)
if err == nil && sess != nil {
defer sess.Close() -> Problem happens here
// Calls RPC here and rest of the code here

}
return 0
}

登录后复制

那么,我可以对mockgetsshconnection()方法进行哪些更改,以便sess.close()不会抛出错误?

解决方法

nil 指针错误源自 close 函数 当底层transport调用close时。幸运的是 transport 是一个 interface 类型,您可以轻松地在 netconf.session 的实际实例中模拟和使用它。例如像这样:

type MockTransport struct{}

func (t *MockTransport) Send([]byte) error {
return nil
}

func (t *MockTransport) Receive() ([]byte, error) {
return []byte{}, nil
}

func (t *MockTransport) Close() error {
return nil
}

func (t *MockTransport) ReceiveHello() (*netconf.HelloMessage, error) {
return &netconf.HelloMessage{SessionID: 123}, nil
}

func (t *MockTransport) SendHello(*netconf.HelloMessage) error {
return nil
}

func (t *MockTransport) SetVersion(version string) {
}

func mockGetSSHConnection() (*netconf.Session, error) {
t := MockTransport{}
sess := netconf.NewSession(&t)
return sess, nil
}

登录后复制

请注意,您要测试的函数当前返回 0 而不是会话的 sessionid 。因此,您应该在测试成功之前修复该问题。

以上就是如何在单元测试 Golang 中模拟 netconf 会话的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论