Go test less-known features

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. Most go programmers know and like to use ' Go test ', a test tool that comes from the official go ' GC ' toolchain. (Want to execute test code) This command is probably the simplest, and it can be done beautifully. As we all know, running the ' Go Test ' command will execute the test code of the package under the current directory, it will look for ' *_test.go ' files, and in these files, look for ' testxxx (*testing. T) {} ' named functions and arguments (that is, receive ' *testing. T ' parameter of the function, named ' testxxx ', ' Xxx ' can be any name that does not begin with lowercase characters. This test code does not affect the normal compilation process and is only used when executing ' go test '. But there are a lot of hidden things here. # # black Box Test Package--Typically, in the Go language, the test and the code to be tested are in the same package (the system under test) to access the Code for internal implementation details. To support black-box testing, ' Go test ' supports the use of the "_test" suffix and can be compiled into a separate package form. Example: ' go//in Example.gopackage examplevar start IntFunc Add (n int) int {start + = Nreturn start}//in Example_test.gopackag E Example_testimport ("testing"). "Bitbucket.org/splice/blog/example") func Testadd (t *testing. T) {Got: = ADD (1) if got! = 1 {T.errorf ("got%d, want 1", Got)}} "You can see the infamous [point import] in the code (HTTPS://GOLANG.ORG/REF/SPEC#IMPORT_ declarations). However, when a black-box test is made on a package, it is a practical example of a symbol that is imported (in the package) to be exported within the scope of the current package. Test code [in the usual case should be avoided into the environment under test] (Https://code.google.com/p/go-wiki/wiki/CodeReviewComments#Import_Dot). As explained in the chapter on link symbols in point import, the black boxThe test mode can also be used to break the problem of cyclic import (when the tested package "a" is imported by "B", and "a" test is also required to import "B"-the test can be moved to the "A_test" package, then "a" and "B" can be imported (at the same time), so there is no problem of looping # # Skip Test (skipping tests) some tests may require a specific context. For example, some tests may need to call an external command, use a special file, or require an environment variable that can be set. When the conditions are not met, (if) you do not want to let those tests fail, you can simply skip those tests: "' Gofunc testsomeprotectedresource (t *testing. T) {if OS. Getenv ("some_access_token") = = "" {T.skip ("skipping test; $SOME _access_token Not set ")}//... the actual test}" if ' Go test-v ' is called (note the redundant ("V") flag), the output will alert the skipped test: ' ' = = = ' RUN testsom Eprotectedresource---skip:testsomeprotectedresource (0.00 seconds) example_test.go:17:skipping test; $SOME _access_token not set "is usually implemented with the '-short ' command line flag to implement this skipped feature, and if the flag is set, it is reflected in the code, ' testing. Short () ' will simply return true (just like the '-V ' flag, if it is set by judging ' testing '). Verbose () ', you can print out additional debug logs. When the test needs to run for a long time, and you are in a hurry, you can execute ' go test-short ', and (if) the developer who provided the package has just implemented this function, the long-running test will be skipped. This is what happens when the Go test is installed from the source code (usually), and there is an example of the Stdlib library that has been skipped for a long time test: "' Gofunc testcountmallocs (t *testing. T) {if testing. Short () {T.skip ("skipping malloc count on short mode")}Rest of Test ...} The skip is just an option, the '-short ' flag is just a sign, and depending on the developer, they can choose to run the test (whether this flag is in effect) to avoid some slow-running assertions being executed. There is also the '-timeout ' flag, which can be used to force exit tests that have not finished running within the time limit. For example, run this command ' go test-timeout 1s ' to perform the following test: ' ' Gofunc testwilltimeout (t *testing. T) {time. Sleep (2 * time. Second)//pass if timeout > 2s} ' will have the following output (truncated): ' ' = = = RUN testwilltimeoutpanic:test timed out after 1s ' if you want to perform a specific test function without is to execute all the test sets, just run ' go test-run testnameregexp '. # # # Parallel Execution Test (parallelizing tests) by default, the tests for a specified package are performed sequentially, but it is also possible to flag some tests for safe concurrent execution by using ' t.parallel () ' Inside the function being tested (as in the default case, Assume that the parameter name is ' t '). In the case of parallel execution, only tests that are marked as parallel will be executed in parallel, so there is no point in having only one test function. It should be called first in the body of the test function (after any conditions that need to be skipped) because it resets the test time: ' ' Gofunc testparallel (t *testing. T) {T.parallel ()//actual test ...} "In concurrent cases, the number of simultaneous tests is determined by default depending on ' Gomaxprocs '. It can be specified by '-parallel n ' (' Go test-parallel 4 ') Another method that can be implemented in parallel, although not a function-level granularity, but a packet-level granularity, is similar to executing ' go test p1 p2 P3 ' (that is, multiple test packages are called simultaneously) 。 In this case, the package is compiled first and executed at the same time. Of course, this is good for the total time, but it can also cause errors to become unpredictable, such as when some resources are used at the same time by multiple packages (for example, some tests require access to the database and some rows are deleted, and those rows are used by other test packages). To maintain controllability, the '-p ' flag can be used to specify compilation and testing andNumber of rounds. When there are multiple test packages in the repository, and each package is in a different subdirectory, a command that can execute all the packages is ' go test. ', which contains the current directory and all subdirectories. When executed without the '-p ' flag, the total run time should be close to the time of the longest running package (plus compile time). Run ' Go test-p 1 ... ' so that the compilation and test tools can only be executed in one package, the total time should be close to the sum of the time of all the independent package tests plus the compilation time. You can try it yourself and execute ' go test-p 3 ... ' to see the impact on the run time. Also, another place that can be parallelized (you should test it) is in the code of the package. Thanks to the great parallel primitives of Go, in fact, unless Gomaxprocs is explicitly set to Gomaxprocs=1 through environment variables or in code, it is less common that a goroutines in a package is useless. Want to use 2 CPU, can execute ' gomaxprocs=2 go test ', want to use 4 CPU, can execute ' gomaxprocs=4 go test ', but there is a better way: ' Go test-cpu=1,2,4 ' will execute 3 times, its The Gomaxprocs values are 1, 2, and 4, respectively. The '-cpu ' logo, paired with the detection sign of the data competition '-race ', simply goes into heaven (or hell, depending on how it is run). Competitive probing is a magical tool that has to be used in high-concurrency-focused development (to prevent deadlock problems), but the discussion has gone beyond the scope of this article. If you are interested in this, you can read [this article] (http://blog.golang.org/race-detector) on the Go official blog. # # More content the ' Go Test ' tool supports running benchmarks and assertions in a similar way to test functions (! )。 The ' godoc ' tool can even understand the syntax in the example and include it in the generated document. You have to mention code coverage and performance testing, and the test tools support these two features. For those interested and want to know more, you can access [the cover story] (http://blog.golang.org/cover) and [Profiling Go programs] (http://blog.golang.org/ Profiling-go-programs), which are all in the Go blog. Before you write your own test code, it is recommended to look at the ' testing/iotest ' in the standard library, ' Testing/quick ' and ' net/http/httptest ' packages.

via:https://splice.com/blog/lesser-known-features-go-test/

Author: MARTIN Angers Translator: gogeof proofreading: polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

1472 Reads
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.