我正在尝试学习如何为我的代码编写测试以编写更好的代码,但我似乎最难以确定如何实际测试我编写的代码.我已经阅读了很多教程,其中大多数似乎只涵盖了添加两个数字或模拟某些数据库或服务器的函数.
我在下面写了一个简单的函数,它将文本模板和CSV文件作为输入,并使用CSV的值执行模板.我通过反复试验,传递文件和打印值来"测试"代码,但我想学习如何为它编写适当的测试.我觉得学习测试自己的代码将有助于我更快更好地理解和学习.任何帮助表示赞赏.
// generateCmds generates configuration commands from a text template using
// the values from a CSV file. Multiple commands in the text template must
// be delimited by a semicolon. The first row of the CSV file is assumed to
// be the header row and the header values are used for key access in the
// text template.
func generateCmds(cmdTmpl string, filename string) ([]string, error) {
t, err := template.New("cmds").Parse(cmdTmpl)
if err != nil {
return nil, …Run Code Online (Sandbox Code Playgroud) 我试图在Go中计算gzip压缩文件的sha256总和,但我的输出与gzip命令的输出不匹配.
我有一个函数Compress,io.Reader在我的情况下gzip 一个文件的内容.
func Compress(r io.Reader) (io.Reader, error) {
var buf bytes.Buffer
zw := gzip.NewWriter(&buf)
if _, err := io.Copy(zw, r); err != nil {
return nil, err
}
if err := zw.Close(); err != nil {
return nil, err
}
return &buf, nil
}
Run Code Online (Sandbox Code Playgroud)
然后我有一个函数Sum256来计算读者的sha256和.
func Sum256(r io.Reader) (sum []byte, err error) {
h := sha256.New()
if _, err := io.Copy(h, r); err != nil {
return nil, err
}
return …Run Code Online (Sandbox Code Playgroud)