登录
首页 >  Golang >  Go问答

如何在golang中为包含通道、filewalk和api调用的程序编写单元测试?

来源:stackoverflow

时间:2024-04-22 13:12:41 293浏览 收藏

珍惜时间,勤奋学习!今天给大家带来《如何在golang中为包含通道、filewalk和api调用的程序编写单元测试?》,正文内容主要涉及到等等,如果你正在学习Golang,或者是对Golang有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!

问题内容

我的程序整体如下。

func main() {

    flag.Parse()

    if *token == "" {
        log.Fatal(Red + "please provide a client token => -token={$token}")
    }

    tokenSource := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: *token})
    oauthClient := oauth2.NewClient(context.TODO(), tokenSource)
    client := putio.NewClient(oauthClient)

    //paths := make(chan string)
    var wg = new(sync.WaitGroup)
    for i := 0; i < 50; i++ {
        wg.Add(1)
        go worker(paths, wg, client)
    }
    WalkFilePath()
    //if err := filepath.Walk(*rootpath, func(path string, info os.FileInfo, err error) error {
    //  if err != nil {
    //      return fmt.Errorf("Failed to walk directory: %T %w", err, err)
    //  }
    //  if !info.IsDir() {
    //      paths <- path
    //  }
    //  return nil
    //}); err != nil {
    //  panic(fmt.Errorf("failed Walk: %w", err))
    //}
    close(paths)
    wg.Wait()
}

// walks the file path and sends paths to channel
func WalkFilePath() {
    if err := filepath.Walk(*rootpath, func(path string, info os.FileInfo, err error) error {
        if err != nil {
            return fmt.Errorf("Failed to walk directory: %T %w", err, err)
        }
        if !info.IsDir() {
            paths <- path
        }
        return nil
    }); err != nil {
        panic(fmt.Errorf("failed Walk: %w", err))
    }
}

func worker(paths <-chan string, wg *sync.WaitGroup, client *putio.Client) {
    defer wg.Done()
    for path := range paths {
        f, err := os.Open(path)
        if err != nil {
            log.Printf(Red + "Failed to open file %v for reading" + Reset, f.Name())
        }
        upload, err := client.Files.Upload(context.TODO(), f, path, 0)
        if err != nil {
            log.Printf(Red + "Failed to upload file %v" + Reset, upload.File.Name)
        }
        log.Printf(Green+ "File %v has been uploaded succesfully" + Reset, upload.File.Name)
    }
}

代码是我写的。这是我能做的最干净的事情,我被告知为该程序编写一个单元测试。我很困惑。例如,考虑 walkfilepath 函数。我应该提供什么以及我应该期望测试该功能得到什么样的结果。因为它包含了channel通讯意义goroutines。有没有办法清楚地为这个程序编写单元测试?或者我应该更改代码结构,这在这种情况下对我来说不好。顺便说一句,程序运行正常。


正确答案


像大多数事情一样,go 对如何测试非常有自己的看法。请务必阅读https://go.dev/doc/tutorial/add-a-test

walkfilepath 的输入应该pathsrootpath。您的 walkfilepath 无法从任何地方获取 pathsrootpath,因此此代码不会按原样编译(测试当然有助于捕获这些内容)。

walkfilepath 的测试可能会像这样进行:

  1. 在项目中的 testdata/(目录 expressly set aside for data used for testing)下创建文件系统结构。创建子目录和文件。例如,可能如下所示:

    testdata/
       walktest/
          dir1/
             file1.txt
          dir2/
              file2.txt
              dir3/
                 file3.txt
  2. 现在您可以定义将从频道中获取的预期数据。

    expected_paths := []string{
       "testdata/walktest/dir1/file1.txt",
       "testdata/walktest/dir2/file2.txt",
       "testdata/walktest/dir3/file3.txt"
    }
  3. 现在您需要更改 walkfilepath 以获取 rootpathpaths 的参数。

    func walkfilepath(rootdir string, paths chan<- string) {
  4. 现在您已准备好编写测试。

    func TestWalkFilePath(t *testing.T(
       paths := make(chan string)
       go WalkFilePath("testdata/walktest")
       results := make([]string,0)
       for path := range paths {
         results = append(results, path)
       }
       exp, res := strings.Join(expected_paths, ""), strings.Join(results, "")
       if exp != res {
         t.Errorf("Expected %s got %s", exp, res)
       }
    }

在单元测试中使用通道和 goroutine 是完全正常且有效的。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>