Go Language Learning Note 11

Source: Internet
Author: User
Tags tag name cpu usage disk usage

6. Program Testing and documentation

6.1 Program Testing

3. Sample Test

Sample test functions can also be added to the test source file, but writing a sample test function does not require an APIthat uses the testing code package.

(1). Writing sample test functions

The name of the sample test function needs to start with "Example". At the end of the function body of such a function there can be several comment lines. Their role is to compare whether the content appearing on the standard output coincides with what is expected during the execution of the test function. However, in order to interpret these annotations correctly, the following conditions need to be met:

    • These comment lines must appear at the end of the function body, and there is no code between them and the "}" as the body terminator of the current function. Otherwise, the comment line is not valid for the sample test.

    • In the first line of comments, it should always be Outputimmediately after the single-line comment leader//, otherwise these comment lines are not valid for the sample test.

    • The content on the right side of the output: and subsequent comment lines represent a single line of content in the standard output, respectively.

The next Test source file, Et_test.go, is located in the testing/et code package under the work area src :

package etimport (    "fmt")func ExampleHello() {    fmt.Println("Hello, Huazie")    // Output: Hello, Huazie}

(2). Run the sample test

Using the Go Test command to test the above source file Et_test.go , run as follows:

Call FMT. the print content produced by the PRINTLN function does not actually appear on the standard output, but is only used to compare with the content in the sample comment line. Now modify the FMT. the contents of Println are "Hello, Huazie1" and the results are as follows:

Now change the sample test function Examplehello to this:

func ExampleHello() {    for i := 0; i < 3; i++ {        fmt.Println("Hello, Huazie")    }    // Output: Hello, Huazie    // Hello, Huazie    // Hello, Huazie}

Run as follows:

The test still passes, but it is important to note that multiple sample comment lines at the end of the function body of the sample test function must be contiguous, and no rows can be spaced between them, even if it is a blank line. The command program treats only the comment lines in the function body of the sample test function immediately next to the current function body Terminator "}" as a sample comment line. If there is no sample comment line in a sample test function, the function will only be compiled and not executed.

(3). Name of the sample test function

Sample test function naming rules:

    • When the object being tested is the entire code package, the name of the sample test function should be example, which is the uniform prefix of the sample test function name as the function name.

    • When the object being tested is a function, for function f, the name of the sample test function should be examplef.

    • When the object being tested is a type, for type T, the name of the sample test function should be examplet.

    • When the object being tested is a method in a type, for method M of type T, the name of the sample test function should be examplet_m.

If you need to add a suffix to the name of the sample test function, you need to use an underscore to separate the suffix from the rest of the name. Also, the first letter of the suffix must be lowercase. For example, the name of a sample test function that has a method M for type T and needs to include the suffix "basic" should be examplet_m_basic.

4. Test run record

In the hardware environment, the main research on the computer load status , such as CPU utilization , memory usage , disk usage , etc.
In the aspect of software system, mainly include memory allocation , concurrent processing quantity and deadlock , etc.

(1). Collection of resource Usage

tags related to the collection of resource usage

Tag Name Tag Description
-cpuprofile Cpu.out Logs the CPU usage and writes to the specified file until the test exits.
Cpu.out can be replaced by any other name as the filename of the specified file
-memprofile Mem.out Records memory usage and writes the memory usage profile to the specified file after all tests have passed.
Mem.out can be replaced by any other name as the filename of the specified file
-memprofilerate N This flag controls the behavior of recording memory allocation operations, which are written to the memory usage profile.
n represents the sampling interval for the parser, in bytes. Whenever n bytes of memory are allocated, the parser will sample

Now execute the -cpuprofile tag's go test command to run the tests in the standard library's Net code package. For example:

E:\software\go\goc2p\pprof>go test-cpuprofile cpu.out Net

The go Test command does not allow the -cpuprofile tag to be used when multiple code packages are tested, as follows:

After the above test run is completed, a net.test.exe executable file and cpu.out file are generated in the current directory, and you can use go tool pprof command to interactively review this profile, as follows:

When the -memprofile tag is valid, the test runner logs the usage of the memory (the allocation of heap memory during program run) while the test is running.

Use the -memprofilerate tag to set the sampling interval for the parser, in bytes. A smaller value means better sampling because the sampling interval is shorter. Inside the testing package, the value of the-memprofilerate tag is assigned to a variable of type int in the runtime package Memprofilerate , the default value for this variable is 512K bytes. If set to 0, the stop sampling is represented.

The test command statements for the -memprofile tag and the -memprofilerate tag are as follows:
E:\software\go\goc2p\pprof>go test-memprofile mem.out-memprofilerate Net

After executing the above command, a net.test.exe executable and cpu.out file is generated in the current directory, which can be viewed interactively using the go tool pprof command. As follows:

(2). Log Program Blocking events

tags related to the logger blocking event

Tag Name Tag Description
-blockprofile Block.out Records the Goroutine blocking event and writes the profile to the specified file after all tests have passed.
Block.out can be replaced by any other name as the filename of the specified file
-blockprofilerate N This flag is used to control the time interval at which the Goroutine blocking event is logged, n in units of times, and the default value is 1

The test command statements for the -blockprofile and -blockprofilerate tags are as follows:
E:\software\go\goc2p\pprof>go test-blockprofile block.out-blockprofilerate Net

The value of the -blockprofilerate tag is also the APIin the runtime of the standard library code package--function setblockprofilerate -- Passed to the Go runtime system. When an incoming parameter is 0 , it is the equivalent of completely canceling the record operation. When an incoming parameter is 1 , each blocking event is logged. The default value for the -blockprofilerate tag is 1.

5. Test coverage

Test coverage refers to how much of the code in the code package that is being tested is used in the test that was just executed. If this test results in the execution of 90% of the statements in the current code package, then the test coverage for the test is 90%.

The tag that the Go Test command can accept for test coverage

tr> TD align= "left" >-coverpkg
Tag Name using the example Description
-cover -cover Enable test coverage Analysis
-covermode -covermode=set Auto add -cover tag and set different test coverage statistics modes, the supported modes are the following 3.
Set : Records only if the statement has been executed
Count : Number of times the statement was executed
Atomic : Record the number of times a statement is executed and ensure that it is counted correctly while concurrently executing, but performance can be affected by a certain amount of time
These modes cannot be used simultaneously, and by default, the statistical mode of test coverage is set
-coverpkg bufio,net Auto add -cover tag and test coverage statistics for the program in the code package that is listed after the tag.
By default, the test runner only counts the programs in the code packages that are directly tested. The
tag means that programs in other code packages that are used indirectly in the test can also be counted.
In addition, the code package needs to be specified by its import path, and multiple import paths are separated by a comma ",".
-coverprofile -coverprofile cover.out automatically adds the -cover tag and writes a summary of the coverage of all passed tests to the specified file

Add the -cover tag after the go Test command to turn on test coverage statistics. As follows:

The markup -coverpkg can get the execution rate of the program in the code package that is used indirectly during the test. As follows:

After using the -coverpkg tag to specify the code package to be counted, the code that is not specified is certainly not counted, even if the code package is directly tested.

The tag -coverprofile causes the test runner to write statistical information about the test coverage to the specified file. The file will be placed in the directory where the go Test command is executed. As follows:

For cover.out content, you can use the cover tool provided by the go language to view it and run it with the go tool cover command. Two features of the cover tool:

    1. Overrides the code in a source file according to the specified rules and outputs the specified target.

    2. Reads the statistics file for test coverage and renders it in the specified manner.

For the first feature, after running the Go test command with a test coverage-related tag, the Test runner uses the cover tool to rewrite the non-test source files in the code package under test before they are compiled. The overridden method is determined by the test coverage statistics mode specified by the -covermode tag when the go Test command is run. By default, this statistic mode is set .

Set statistic mode

Under the testing/ct , like the following source code file Ct_demo.go, as follows:

 PackageCtfuncTypecategoryof (vInterface{})string{SwitchV. (type) { Case BOOL:return "Boolean"     Case int,UINT,int8,uint8,Int16,uint16,Int32,UInt32,Int64,UInt64:return "integer"     Case float32,float64:return "Float"     Case complex64,complex128:return "Complex"     Case string:return "string"}return "Unknown"//If only non-basic type, return "Unknown" uniformly}

After running the go test–cover command, the test Runner cover tool will rewrite the typecategoryof function as follows:

funcTypecategoryof (vInterface{})string{Gocover.count[0] =1    SwitchV. (type) { Case BOOL: Gocover.count[2] =1        return "Boolean"     Case int,UINT,int8,uint8,Int16,uint16,Int32,UInt32,Int64,UInt64: Gocover.count[3] =1        return "integer"     Case float32,float64: Gocover.count[4] =1        return "Float"     Case complex64,complex128: Gocover.count[5] =1        return "Complex"     Case string: Gocover.count[6] =1        return "string"} gocover.count[1] =1    return "Unknown"}

A counter (represented by Gocover.count ) will be placed on each of the process branches of the original source code. Whenever a process branch is executed, the corresponding counter is assigned a value of 1, in such a way that it can only indicate whether the branch has been executed.

The variable gocover represents the value of an anonymous struct type whose value is used to store the count value of each branch, the number of rows in the current source file where each branch starts and ends, and the number of bars in each branch of the statement. The variable gocover can be called an execution count variable, and its name can be communicated to the cover tool through the -var tag.

The test target of the Go Test command can be one or more code packages, while the cover tool can only rewrite one source file at a time. If there are multiple source files being tested, the go Test command runs the cover tool once for each file. To make the name of the execution count variable in each source file that is rewritten is not duplicated, thego Test command has different values for the -var tag that is passed to the cover tool for different source files.

Count Statistics mode

In the set statistics mode, the following statement:

GoCover.Count[0] = 1

will be written as

GoCover.Count[0]++

This is equivalent to logging each execution of a branch.

Atomic statistical mode

The statement of the set statistic pattern is written as follows:

_cover_atomic_.AddUint32(&CoverVar.Count[11)

Where cover_atomic is the alias of the code package sync/atomic , you need to import the following statement in the source code:

import"sync/atomic"

Atomic Statistical patterns are typically used only in scenarios where concurrent execution is present, because the execution of atomic operations results in some performance loss. The set and count statistics patterns are much more common than it is, and they have a much smaller impact on the execution cost of the original program.

Pass the test coverage statistic pattern that needs to be used directly to the cover tool through the -mode tag. Its usage and meaning are consistent with the -covermode tag of the go Test command. In fact, thego Test command takes the value of the -covermode tag intact as the value of the -mode tag that is passed to it by running the cover tool. However, the-mode tag does not have a default value, so you must add a -mode tag when rewriting a source code file using the cover tool.

By default, the rewritten source code is output to the standard output. However, you can also use the- o flag to store the code in the specified file.

Use the cover tool to override the Ct_demo.go under the testing\ct code package in the workspace src directory, as follows:

E:\software\go\goc2p\src\testing\ct>go tool cover-mode=set-var= "Gocover"-O ct _out.go ct_demo.go

At this time ct_out.go is ct_demo.go is rewritten after the source file, you can run the view on their own.

For the second feature of the cover tool:
View the previous go test cnet/ctcp-coverprofile=cover.out command to generate a test coverage profile Cover.outfor the cnet/ctcp code package, Run as follows:

Tag -func allows the cover tool to print the test coverage profile of each function included in the profile to standard output.

In the above output, in addition to the last line, each line contains 3 pieces of information, namely: the relative path of the source file in which the function resides, the function name, and the percentage of the number of statements that were tested in the function that accounted for the total number of statements in the function. The percentage in the last line of content is the percentage of the total number of statements in the code package that have been tested to the number of statements in the code package.

Now with the -html tag, you can see more graphical information to visualize the response statistics. As follows:

Go Tool cover-html=cover.out

The command returns immediately and no content is present on the standard output. Instead, the current operating system's default browser is started and displays the HTML -formatted paging file that the cover tool has just generated from the profile. As follows:

In this HTML page, the statements being tested are shown in green, the statements that are not tested are shown in red, and statements that are not in the test coverage calculation are grayed out. The top-left corner can also be used to select different source files in the code package under test to see their test coverage by using the drop-down box. When you hover the mouse cursor over the green statement, the number of executions of the statement will appear near the cursor, and you can try it yourself.

The above HTML paging file shows the profile generated in set statistics mode. In the count and Atomic statistics mode, you can try it yourself, as follows:

Cover Tools Acceptable tags

Tag Name using the example Description
-func -func=cover.out Output the test coverage profile for each of the tested functions according to the contents of the profile (that is, cover.out)
-html -html=cover.out Convert the contents of the profile into an HTML-formatted file and view it using the default Web browser in the current operating system
-mode -mode=count The statistical mode used to set the test profile, see the-covermode tag of the Go Test command
-O -o=cover.out Output the rewritten source code to the specified file, if you do not add this tag, then the rewritten source code will be output to the standard output
-var -var=gocover Set the name of an extra variable that is added to the original source code

6.2 Program Documentation

In the go language, you can use the godoc command to start a Web service on your computer that can be used to view all the code package documents in all the workspaces in this computer. Enter the following command on the command line and execute:

Godoc-http=:9090–index

In the browser, you can view the following input address as follows:

1. Writing Program notes

The go language incorporates the features of the C and C + + languages in the annotation style. You can use both C + + language-style line annotations:
Line Comment
You can also use C -style block annotations:
/*
block Annotations
*/

Note: no matter which style of comment is not nested in the case.

2. Comments for the Code package

Each code package should contain a separate code package comment. This comment should be a general introduction to the functionality and purpose of the current code package. As a rule, code package annotations should be stored in the doc.go file in the current code package directory. In this doc.go file, you should have the same Code package declaration statement as the other source files in the package, and insert the code package comments on top of the declaration statement as a block comment.

When there is only one source file in the code package, it is recommended that the source file has the same primary file name as the current code package. Of course, if only one source file or code package comment is short in the code package, you can also insert the comment above the code package declaration statement in the source file with the same name as the current code package.

In the standard library, code package comments for the FMT are placed in the $GOROOT/src/fmt/doc.go , and the corresponding document pages are as follows:

What appears in overview is the code package Comment line for the FMT package, which is defined in fmt/doc.go .

3. Notes for program Entities

In the (linked) index column, the index of the document that contains the program entities that are exported by all lessons in the current code. Click to display the following information:

Click one of the index type state after the page is positioned at the anchor point of the program entity document that corresponds to the index. For example:

Click on the underlined state and click on the page to jump to declare FMT. the source code for State is as follows:

The document of the program entity is its declaration code and the line comment immediately above it, which also embodies the idea of "code as a comment".

4. Annotations for constants and variables

The Go language syntax allows you to declare a set of constants or variables at once, and the program entity declarations write comments such as the following example:

// IP address lengths (bytes).const (    4    16)

The above code is located in the code package net source file ip.go. For such a set of declarations, the description is uniformly placed above the keyword const(or the keyword var) and adjacent to the comment line, rather than adding a comment for each constant (or variable) declaration, respectively.

This article explains the sample test , test run record , test coverage , and program documentation for the Go Language program.

Finally, we enclose the local Go language community (one for each update)

Go Friends : The community is committed to providing the best environment for learning and communication for go language enthusiasts. The community organizers are passionate about the go language and are happy to share it with skill. This includes the founder of Beego . Community Homepage Address: http://golanghome.com

Go Language Learning Note 11

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.