首页 > 其他分享 >Go - Setting Up and Tearing Down Before and After Tests

Go - Setting Up and Tearing Down Before and After Tests

时间:2023-10-18 10:01:29浏览次数:29  
标签:Tests testing teardown setup After Up up grid test

Problem: You want to set up data and an environment for testing and tear it down after the test is run.


Solution: You can create helper functions or use the TestMain feature to control the flow of the test functions.

 

Testing often needs data and an environment set up that is used in testing. These are called test fixtures . While test fixtures are usually destroyed outside of the scope of the test function, sometimes certain artifacts like files, database records, or configuration files need to be removed so they won’t interfere with subsequent testing. 

There are a couple of ways to set up and tear down test fixtures. 

The easiest way is to create helper functions. For example, you want to take an image file and flip it. In this example, you want to flip a PNG - format image of the Mona Lisa. 

The algorithm is easy; first load the image file into a two - dimensional grid of pixels (where a pixel is represented by a color.Color struct).

The specific code you want to test is the flip function that takes the grid and flips the pixels in it:

func flip(grid [][]color.Color) {
    for x := 0; x < len(grid); x++ {
        col := grid[x]
        for y := 0; y < len(col)/2; y++ {
            k := len(col) - y - 1
            col[y], col[k] = col[k], col[y]
        }
    }
}

The obvious setup is to take a PNG file and load it into a grid to get it ready for testing.

After flipping the grid, you’ll save it to a file, then load it up again to check the dimensions. This leaves a file on the filesystem after the test is run, so you need to clean that up. 

The straightforward way to do this is to call setup at the beginning of the test function and also call teardown before the end of the test function. Another way of doing this is to create a setup function that returns a teardown closure:

func setup(filename string) (teardown func(tempfile string),
    grid [][]color.Color) {
    grid = load(filename)
    teardown = func(tempfile string) {
        os.Remove(tempfile)
    }
    return
}

You can then call the teardown using defer , which will ensure that the teardown happens at the end of the function:

func TestFlip(t *testing.T) {
    teardown, grid := setup("monalisa.png")
    defer teardown("flipped.png")
    flip(grid)
    save("flipped.png", grid)
    g := load("flipped.png")
    if len(g) != 321 || len(g[0]) != 480 {
        t.Error("Grid  is  wrong  size", "width:", len(g), "length:", len(g[0]))
    }
}

A test suite is a collection of test cases. Helper functions work well for smaller test suites, but in a larger one, it is tedious to call the helper function over and over again, especially if it takes up resources. Normally you would want to set up all the test fixtures up front and then tear it all down after the test suite completes. 

The TestMain feature was added in Go 1.4, and it allows more flexible and lower - level control of setting up and tearing down test fixtures. If a test file contains the TestMain function, then Go will run TestMain instead of the tests directly. TestMain runs in the main goroutine and will run the rest of the test cases when you call m.Run . As a result, you can set up whatever you need before m.Run and tear down whatever fixtures were created after. 

When you call m.Run , it will return an exit code that you can pass to os.Exit to exit the test suite cleanly:

func TestMain(m *testing.M) {
    fmt.Println("setup")
    exitCode := m.Run()
    fmt.Println("teardown")
    os.Exit(exitCode)
}

When you run go test in the command line, you will get this:
% go test - v

setup

=== RUN TestAdd

testing_test.go:23: Result is: 3

- - - PASS: TestAdd (0.00s)

=== RUN TestAddWithTables

- - - PASS: TestAddWithTables (0.00s)

=== RUN TestFlip

- - - PASS: TestFlip (0.07s)

PASS

teardown

ok github.com/sausheong/gocookbook/ch18_testing 0.527s
As you can see, the setup runs before any test functions are run, and the teardown runs after all the test functions complete.

 

标签:Tests,testing,teardown,setup,After,Up,up,grid,test
From: https://www.cnblogs.com/zhangzhihui/p/17771390.html

相关文章

  • [LeetCode] 2530. Maximal Score After Applying K Operations
    Youaregivena 0-indexed integerarray nums andaninteger k.Youhavea startingscore of 0.Inone operation:chooseanindex i suchthat 0<=i<nums.length,increaseyour score by nums[i],andreplace nums[i] with ceil(nums[i]/3).......
  • ucup 题目乱炖
    Season2022#6299.BinaryString如果\(0\)的个数小于\(1\)的个数那么就反转\(01\)以及反转序列,接下来假设\(0\)的个数大于等于\(1\)的个数。称有\(11\)的序列为”未完全展开的“,那么序列的种类数有两个阶段:展开过程中和展开之后的。在展开之后如果知道序列那么用......
  • Work Group
    analysis我们很明显能够发现这个题目的性质:奇数是由孩子的奇数和我的偶数,或者是孩子的偶数我的奇数取一个最大值进行更新。偶数就是我的偶数和孩子的偶数,或者是孩子奇数和我的奇数取一个最大值进行更新。我们不妨用\(0\)表示已经选择了偶数个节点,用\(1\)表示已经选择了......
  • CF529B Group Photo 2 (online mirror version)
    看值域这么小,考虑枚举最大高度\(maxh\):\(h_i>maxh\)且\(w_i>maxh\),不合法。\(h_i>maxh\)且\(w_i\leqmaxh\),必须换。\(h_i\leqmaxh\)且\(w_i>maxh\),不能换。\(h_i\leqmaxh\)且\(w_i\leqmaxh\),可换可不换。因为最多只有一半的人能躺下,所以优先换\(w_i-h_i\)较大......
  • 统一过程(UP)模型
            ......
  • Vue3.2中setup语法糖的使用教程分享
    这篇文章主要为大家详细介绍了Vue3.2中setup语法糖的具体使用方法,文中的示例代码讲解详细,对我们深入了解Vue有一定的帮助,需要的可以参考一下目录2、data数据的使用3、method方法的使用4、watchEffect的使用5、watch的使用6、computed计算属性的使用7、props父子传值的使用8、emit......
  • NAKIVO Backup & Replication 10.10 - 快速高效能的备份解决方案
    NAKIVOBackup&Replication10.10-快速高效能的备份解决方案"#1DataProtectionforSMBs,EnterprisesandMSPs"请访问原文链接:https://sysin.org/blog/nakivo-backup-10/,查看最新版。原创作品,转载请保留出处。作者主页:sysin.orgNAKIVOBackup&Replication10Fast......
  • Windows Server 2016 OVF, updated Oct 2023 (sysin) - VMware 虚拟机模板
    WindowsServer2016OVF,updatedOct2023(sysin)-VMware虚拟机模板2023年10月版本更新,现在自动运行sysprep,支持ESXiHostClient部署请访问原文链接:https://sysin.org/blog/windows-server-2016-ovf/,查看最新版。原创作品,转载请保留出处。作者主页:sysin.org现在......
  • Windows Server 2019 OVF, updated Oct 2023 (sysin) - VMware 虚拟机模板
    WindowsServer2019OVF,updatedOct2023(sysin)-VMware虚拟机模板2023年10月版本更新,现在自动运行sysprep,支持ESXiHostClient部署请访问原文链接:https://sysin.org/blog/windows-server-2019-ovf/,查看最新版。原创作品,转载请保留出处。作者主页:sysin.orgWind......
  • Go - Uploading a File to a Web Application
    Problem: Youwanttouploadafiletoawebapplication. Solution: Usethenet/httppackagetocreateawebapplicationandtheiopackagetoreadthefile. UploadingfilesiscommonlydonethroughHTMLforms.YoulearnedthatHTMLformshaveanencty......