技术控

    今日:92| 主题:49531
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Using Subtests and Sub-benchmarks

[复制链接]
轻描淡写 发表于 2016-10-4 14:02:28
121 0

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
Introduction

  In Go 1.7, the    testingpackage introduces a Run method on the          T    and          B    types that allows for the creation of subtests and sub-benchmarks. The introduction of subtests and sub-benchmarks enables better handling of failures, fine-grained control of which tests to run from the command line, control of parallelism, and often results in simpler and more maintainable code.  
  Table-driven tests basics

  Before digging into the details, let's first discuss a common way of writing tests in Go. A series of related checks can be implemented by looping over a slice of test cases:
  1. func TestTime(t *testing.T) {
  2.     testCases := []struct {
  3.         gmt  string
  4.         loc  string
  5.         want string
  6.     }{
  7.         {"12:31", "Europe/Zuri", "13:31"},     // incorrect location name
  8.         {"12:31", "America/New_York", "7:31"}, // should be 07:31
  9.         {"08:08", "Australia/Sydney", "18:08"},
  10.     }
  11.     for _, tc := range testCases {
  12.         loc, err := time.LoadLocation(tc.loc)
  13.         if err != nil {
  14.             t.Fatalf("could not load location %q", tc.loc)
  15.         }
  16.         gmt, _ := time.Parse("15:04", tc.gmt)
  17.         if got := gmt.In(loc).Format("15:04"); got != tc.want {
  18.             t.Errorf("In(%s, %s) = %s; want %s", tc.gmt, tc.loc, got, tc.want)
  19.         }
  20.     }
  21. }
复制代码
This approach, commonly referred to as table-driven tests, reduces the amount of repetitive code compared to repeating the same code for each test and makes it straightforward to add more test cases.
  Table-driven benchmarks

  Before Go 1.7 it was not possible to use the same table-driven approach for benchmarks. A benchmark tests the performance of an entire function, so iterating over benchmarks would just measure all of them as a single benchmark.
  A common workaround was to define separate top-level benchmarks that each call a common function with different parameters. For instance, before 1.7 the    strconvpackage's benchmarks for    AppendFloatlooked something like this:  
  1. func benchmarkAppendFloat(b *testing.B, f float64, fmt byte, prec, bitSize int) {
  2.     dst := make([]byte, 30)
  3.     b.ResetTimer() // Overkill here, but for illustrative purposes.
  4.     for i := 0; i < b.N; i++ {
  5.         AppendFloat(dst[:0], f, fmt, prec, bitSize)
  6.     }
  7. }
  8. func BenchmarkAppendFloatDecimal(b *testing.B) { benchmarkAppendFloat(b, 33909, 'g', -1, 64) }
  9. func BenchmarkAppendFloat(b *testing.B)        { benchmarkAppendFloat(b, 339.7784, 'g', -1, 64) }
  10. func BenchmarkAppendFloatExp(b *testing.B)     { benchmarkAppendFloat(b, -5.09e75, 'g', -1, 64) }
  11. func BenchmarkAppendFloatNegExp(b *testing.B)  { benchmarkAppendFloat(b, -5.11e-95, 'g', -1, 64) }
  12. func BenchmarkAppendFloatBig(b *testing.B)     { benchmarkAppendFloat(b, 123456789123456789123456789, 'g', -1, 64) }
  13. ...
复制代码
Using the    Runmethod available in Go 1.7, the same set of benchmarks is now expressed as a single top-level benchmark:  
  1. func BenchmarkAppendFloat(b *testing.B) {
  2.     benchmarks := []struct{
  3.         name    string
  4.         float   float64
  5.         fmt     byte
  6.         prec    int
  7.         bitSize int
  8.     }{
  9.         {"Decimal", 33909, 'g', -1, 64},
  10.         {"Float", 339.7784, 'g', -1, 64},
  11.         {"Exp", -5.09e75, 'g', -1, 64},
  12.         {"NegExp", -5.11e-95, 'g', -1, 64},
  13.         {"Big", 123456789123456789123456789, 'g', -1, 64},
  14.         ...
  15.     }
  16.     dst := make([]byte, 30)
  17.     for _, bm := range benchmarks {
  18.         b.Run(bm.name, func(b *testing.B) {
  19.             for i := 0; i < b.N; i++ {
  20.                 AppendFloat(dst[:0], bm.float, bm.fmt, bm.prec, bm.bitSize)
  21.             }
  22.         })
  23.     }
  24. }
复制代码
Each invocation of the    Runmethod creates a separate benchmark. An enclosing benchmark function that calls a    Runmethod is only run once and is not measured.  
  The new code has more lines of code, but is more maintainable, more readable, and consistent with the table-driven approach commonly used for testing. Moreover, common setup code is now shared between runs while eliminating the need to reset the timer.
  Table-driven tests using subtests

  Go 1.7 also introduces a    Runmethod for creating subtests. This test is a rewritten version of our earlier example using subtests:  
  1. func TestTime(t *testing.T) {
  2.     testCases := []struct {
  3.         gmt  string
  4.         loc  string
  5.         want string
  6.     }{
  7.         {"12:31", "Europe/Zuri", "13:31"},
  8.         {"12:31", "America/New_York", "7:31"},
  9.         {"08:08", "Australia/Sydney", "18:08"},
  10.     }
  11.     for _, tc := range testCases {
  12.         t.Run(fmt.Sprintf("%s in %s", tc.gmt, tc.loc), func(t *testing.T) {
  13.             loc, err := time.LoadLocation(tc.loc)
  14.             if err != nil {
  15.                 t.Fatal("could not load location")
  16.             }
  17.             gmt, _ := time.Parse("15:04", tc.gmt)
  18.             if got := gmt.In(loc).Format("15:04"); got != tc.want {
  19.                 t.Errorf("got %s; want %s", got, tc.want)
  20.             }
  21.         })
  22.     }
  23. }
复制代码
The first thing to note is the difference in output from the two implementations. The original implementation prints:
  1. --- FAIL: TestTime (0.00s)
  2.     time_test.go:62: could not load location "Europe/Zuri"
复制代码
Even though there are two errors, execution of the test halts on the call to    Fatalfand the second test never runs.  
  The implementation using    Runprints both:  
  1. --- FAIL: TestTime (0.00s)
  2.     --- FAIL: TestTime/12:31_in_Europe/Zuri (0.00s)
  3.         time_test.go:84: could not load location
  4.     --- FAIL: TestTime/12:31_in_America/New_York (0.00s)
  5.         time_test.go:88: got 07:31; want 7:31
复制代码
     Fataland its siblings causes a subtest to be skipped but not its parent or subsequent subtests.  
  Another thing to note is the shorter error messages in the new implementation. Since the subtest name uniquely identifies the subtest there is no need to identify the test again within the error messages.
  There are several other benefits to using subtests or sub-benchmarks, as clarified by the following sections.
  Running specific tests or benchmarks

  Both subtests and sub-benchmarks can be singled out on the command line using the          -runor      -benchflag    . Both flags take a slash-separated list of regular expressions that match the corresponding parts of the full name of the subtest or sub-benchmark.  
  The full name of a subtest or sub-benchmark is a slash-separated list of its name and the names of all of its parents, starting with the top-level. The name is the corresponding function name for top-level tests and benchmarks, and the first argument to    Runotherwise. To avoid display and parsing issues, a name is sanitized by replacing spaces with underscores and escaping non-printable characters. The same sanitizing is applied to the regular expressions passed to the    -runor    -benchflags.  
  A few examples:
  Run tests that use a timezone in Europe:
  1. $ go test -run=TestTime/"in Europe"
  2. --- FAIL: TestTime (0.00s)
  3.     --- FAIL: TestTime/12:31_in_Europe/Zuri (0.00s)
  4.         time_test.go:85: could not load location
复制代码
Run only tests for times after noon:
  1. $ go test -run=Time/12:[0-9] -v
  2. === RUN   TestTime
  3. === RUN   TestTime/12:31_in_Europe/Zuri
  4. === RUN   TestTime/12:31_in_America/New_York
  5. --- FAIL: TestTime (0.00s)
  6.     --- FAIL: TestTime/12:31_in_Europe/Zuri (0.00s)
  7.         time_test.go:85: could not load location
  8.     --- FAIL: TestTime/12:31_in_America/New_York (0.00s)
  9.         time_test.go:89: got 07:31; want 7:31
复制代码
Perhaps a bit surprising, using    -run=TestTime/New_Yorkwon't match any tests. This is because the slash present in the location names is treated as a separator as well. Instead use:  
  1. $ go test -run=Time//New_York
  2. --- FAIL: TestTime (0.00s)
  3.     --- FAIL: TestTime/12:31_in_America/New_York (0.00s)
  4.         time_test.go:88: got 07:31; want 7:31
复制代码
Note the    //in the string passed to    -run. The    /in time zone name    America/New_Yorkis handled as if it were a separator resulting from a subtest. The first regular expression of the pattern (    TestTime) matches the top-level test. The second regular expression (the empty string) matches anything, in this case the time and the continent part of the location. The third regular expression (    New_York) matches the city part of the location.  
  Treating slashes in names as separators allows the user to refactor hierarchies of tests without the need to change the naming. It also simplifies the escaping rules. The user should escape slashes in names, for instance by replacing them with backslashes, if this poses a problem.
  A unique sequence number is appended to test names that are not unique. So one could just pass an empty string to    Runif there is no obvious naming scheme for subtests and the subtests can easily be identified by their sequence number.  
  Setup and Tear-down

  Subtests and sub-benchmarks can be used to manage common setup and tear-down code:
  1. func TestFoo(t *testing.T) {
  2.     // <setup code>
  3.     t.Run("A=1", func(t *testing.T) { ... })
  4.     t.Run("A=2", func(t *testing.T) { ... })
  5.     t.Run("B=1", func(t *testing.T) {
  6.         if !test(foo{B:1}) {
  7.             t.Fail()
  8.         }
  9.     })
  10.     // <tear-down code>
  11. }
复制代码
The setup and tear-down code will run if any of the enclosed subtests are run and will run at most once. This applies even if any of the subtests calls    Skip,    Fail, or    Fatal.  
  Control of Parallelism

  Subtests allow fine-grained control over parallelism. To understand how to use subtests in the way it is important to understand the semantics of parallel tests.
  Each test is associated with a test function. A test is called a parallel test if its test function calls the Parallel method on its instance of    testing.T. A parallel test never runs concurrently with a sequential test and its execution is suspended until its calling test function, that of the parent test, has returned. The    -parallelflag defines the maximum number of parallel tests that can run in parallel.  
  A test blocks until its test function returns and all of its subtests have completed. This means that the parallel tests that are run by a sequential test will complete before any other consecutive sequential test is run.
  This behavior is identical for tests created by    Runand top-level tests. In fact, under the hood top-level tests are implemented as subtests of a hidden master test.  
  Run a group of tests in parallel

  The above semantics allows for running a group of tests in parallel with each other but not with other parallel tests:
  1. func benchmarkAppendFloat(b *testing.B, f float64, fmt byte, prec, bitSize int) {
  2.     dst := make([]byte, 30)
  3.     b.ResetTimer() // Overkill here, but for illustrative purposes.
  4.     for i := 0; i < b.N; i++ {
  5.         AppendFloat(dst[:0], f, fmt, prec, bitSize)
  6.     }
  7. }
  8. func BenchmarkAppendFloatDecimal(b *testing.B) { benchmarkAppendFloat(b, 33909, 'g', -1, 64) }
  9. func BenchmarkAppendFloat(b *testing.B)        { benchmarkAppendFloat(b, 339.7784, 'g', -1, 64) }
  10. func BenchmarkAppendFloatExp(b *testing.B)     { benchmarkAppendFloat(b, -5.09e75, 'g', -1, 64) }
  11. func BenchmarkAppendFloatNegExp(b *testing.B)  { benchmarkAppendFloat(b, -5.11e-95, 'g', -1, 64) }
  12. func BenchmarkAppendFloatBig(b *testing.B)     { benchmarkAppendFloat(b, 123456789123456789123456789, 'g', -1, 64) }
  13. ...0
复制代码
The outer test will not complete until all parallel tests started by    Runhave completed. As a result, no other parallel tests can run in parallel to these parallel tests.  
  Note that we need to capture the range variable to ensure that    tcgets bound to the correct instance.  
  Cleaning up after a group of parallel tests

  In the previous example we used the semantics to wait on a group of parallel tests to complete before commencing other tests. The same technique can be used to clean up after a group of parallel tests that share common resources:
  1. func benchmarkAppendFloat(b *testing.B, f float64, fmt byte, prec, bitSize int) {
  2.     dst := make([]byte, 30)
  3.     b.ResetTimer() // Overkill here, but for illustrative purposes.
  4.     for i := 0; i < b.N; i++ {
  5.         AppendFloat(dst[:0], f, fmt, prec, bitSize)
  6.     }
  7. }
  8. func BenchmarkAppendFloatDecimal(b *testing.B) { benchmarkAppendFloat(b, 33909, 'g', -1, 64) }
  9. func BenchmarkAppendFloat(b *testing.B)        { benchmarkAppendFloat(b, 339.7784, 'g', -1, 64) }
  10. func BenchmarkAppendFloatExp(b *testing.B)     { benchmarkAppendFloat(b, -5.09e75, 'g', -1, 64) }
  11. func BenchmarkAppendFloatNegExp(b *testing.B)  { benchmarkAppendFloat(b, -5.11e-95, 'g', -1, 64) }
  12. func BenchmarkAppendFloatBig(b *testing.B)     { benchmarkAppendFloat(b, 123456789123456789123456789, 'g', -1, 64) }
  13. ...1
复制代码
The behavior of waiting on a group of parallel tests is identical to that of the previous example.
  Conclusion

  Go 1.7's addition of subtests and sub-benchmarks allows you to write structured tests and benchmarks in a natural way that blends nicely into the existing tools. One way to think about this is that earlier versions of the testing package had a 1-level hierarchy: the package-level test was structured as a set of individual tests and benchmarks. Now that structure has been extended to those individual tests and benchmarks, recursively. In fact, in the implementation, the top-level tests and benchmarks are tracked as if they were subtests and sub-benchmarks of an implicit master test and benchmark: the treatment really is the same at all levels.
  The ability for tests to define this structure enables fine-grained execution of specific test cases, shared setup and teardown, and better control over test parallelism. We are excited to see what other uses people find. Enjoy.
友荐云推荐




上一篇:Livecoding #24: A choropleth in React.js
下一篇:Code in the wild to infect millions of IoT devices for crippling DDoS attacks
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表