繁体   English   中英

在 Go 中对 SSH 客户端进行单元测试

[英]Unit Testing an SSH Client in Go

我用 Go 写了一个 SSH 客户端,我想写一些测试。 问题是我以前从未真正编写过正确的单元测试,而且大多数教程似乎都专注于为添加两个数字的函数或其他一些玩具问题编写测试。 我已经阅读了关于模拟、使用接口和其他技术的文章,但是我在应用它们时遇到了麻烦。 此外,我的客户端将同时使用以允许一次快速配置多个设备。 不确定这是否会改变我编写测试的方式或添加额外的测试。 任何帮助表示赞赏。

这是我的代码。 基本上, Device有 4 个主要功能:分别用于连接到设备、向其发送一组配置命令、捕获会话的输出和关闭客户端的ConnectSendOutput / ErrClose

package device

import (
    "bufio"
    "fmt"
    "golang.org/x/crypto/ssh"
    "io"
    "net"
    "time"
)

// A Device represents a remote network device.
type Device struct {
    Host    string         // the device's hostname or IP address
    client  *ssh.Client    // the client connection
    session *ssh.Session   // the connection to the remote shell
    stdin   io.WriteCloser // the remote shell's standard input
    stdout  io.Reader      // the remote shell's standard output
    stderr  io.Reader      // the remote shell's standard error
}

// Connect establishes an SSH connection to a device and sets up the session IO.
func (d *Device) Connect(user, password string) error {
    // Create a client connection
    client, err := ssh.Dial("tcp", net.JoinHostPort(d.Host, "22"), configureClient(user, password))
    if err != nil {
        return err
    }
    d.client = client
    // Create a session
    session, err := client.NewSession()
    if err != nil {
        return err
    }
    d.session = session
    return nil
}

// configureClient sets up the client configuration for login
func configureClient(user, password string) *ssh.ClientConfig {
    var sshConfig ssh.Config
    sshConfig.SetDefaults()
    sshConfig.Ciphers = append(sshConfig.Ciphers, "aes128-cbc", "aes256-cbc", "3des-cbc", "des-cbc", "aes192-cbc")
    config := &ssh.ClientConfig{
        Config:          sshConfig,
        User:            user,
        Auth:            []ssh.AuthMethod{ssh.Password(password)},
        HostKeyCallback: ssh.InsecureIgnoreHostKey(),
        Timeout:         time.Second * 5,
    }
    return config
}

// setupIO creates the pipes connected to the remote shell's standard input, output, and error
func (d *Device) setupIO() error {
    // Setup standard input pipe
    stdin, err := d.session.StdinPipe()
    if err != nil {
        return err
    }
    d.stdin = stdin
    // Setup standard output pipe
    stdout, err := d.session.StdoutPipe()
    if err != nil {
        return err
    }
    d.stdout = stdout
    // Setup standard error pipe
    stderr, err := d.session.StderrPipe()
    if err != nil {
        return err
    }
    d.stderr = stderr
    return nil
}

// Send sends cmd(s) to the device's standard input. A device only accepts one call
// to Send, as it closes the session and its standard input pipe.
func (d *Device) Send(cmds ...string) error {
    if d.session == nil {
        return fmt.Errorf("device: session is closed")
    }
    defer d.session.Close()
    // Start the shell
    if err := d.startShell(); err != nil {
        return err
    }
    // Send commands
    for _, cmd := range cmds {
        if _, err := d.stdin.Write([]byte(cmd + "\r")); err != nil {
            return err
        }
    }
    defer d.stdin.Close()
    // Wait for the commands to exit
    d.session.Wait()
    return nil
}

// startShell requests a pseudo terminal (VT100) and starts the remote shell.
func (d *Device) startShell() error {
    modes := ssh.TerminalModes{
        ssh.ECHO:          0, // disable echoing
        ssh.OCRNL:         0,
        ssh.TTY_OP_ISPEED: 14400,
        ssh.TTY_OP_OSPEED: 14400,
    }
    err := d.session.RequestPty("vt100", 0, 0, modes)
    if err != nil {
        return err
    }
    if err := d.session.Shell(); err != nil {
        return err
    }
    return nil
}

// Output returns the remote device's standard output output.
func (d *Device) Output() ([]string, error) {
    return readPipe(d.stdout)
}

// Err returns the remote device's standard error output.
func (d *Device) Err() ([]string, error) {
    return readPipe(d.stdout)
}

// reapPipe reads an io.Reader line by line
func readPipe(r io.Reader) ([]string, error) {
    var lines []string
    scanner := bufio.NewScanner(r)
    for scanner.Scan() {
        lines = append(lines, scanner.Text())
    }
    if err := scanner.Err(); err != nil {
        return nil, err
    }
    return lines, nil
}

// Close closes the client connection.
func (d *Device) Close() error {
    return d.client.Close()
}

// String returns the string representation of a `Device`.
func (d *Device) String() string {
    return fmt.Sprintf("%s", d.Host)
}

你很好地指出,单元测试教程几乎总是玩具问题(为什么总是斐波那契?),而我们拥有的是数据库和 http 服务器。 帮助我的一个重要认识是,您只能对可以控制单元输入和输出的事物进行单元测试。 configureClientreadPipe (给它一个strings.Reader )将是不错的选择。 从那里开始。

任何通过直接与磁盘、网络、标准输出等通信而离开程序的东西,比如Connect方法,你会认为它是程序外部接口的一部分。 你不单元测试那些。 您对它们进行集成测试。

Device更改为接口而不是结构,并创建一个实现它的MockDevice 真正的设备现在可能是SSHDevice 您可以通过插入 MockDevice 对程序的其余部分(使用 Device 接口)进行单元测试,以将自己与网络隔离。

SSHDevice将在您的集成测试中进行测试。 启动一个真正的 ssh 服务器(可能是你在 Go 中使用 crypto/ssh 包编写的一个测试服务器,但任何 sshd 都可以工作)。 使用SSHDevice启动您的程序,让它们相互通信,并检查输出。 您将经常使用os/exec包。 编写集成测试比编写单元测试更有趣!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM