当前位置:网站首页>Go language core 36 lecture (go language practice and application I) -- learning notes
Go language core 36 lecture (go language practice and application I) -- learning notes
2022-06-24 01:52:00 【Zhengziming】
23 | Basic rules and procedures of testing ( On )
In the days to come , I will take you to study in Go On the way to advanced language programming , Additional knowledge that must be mastered , such as :Go Program testing 、 Program monitoring , as well as Go Correct usage of various common code packages in language standard library .
From the last century to today , Programmers , Especially domestic programmers , They all enjoy writing programs , Even forget to eat and sleep ( For example, I am an example ).
Because this is how we ordinary people train ourselves 、 Change life 、 Even a unique way to change the world . however , The same procedure , We tend to stay away from writing programs for testing . Why is that ?
My personal feeling , In terms of human nature , We all more or less deny “ Self denial ”. We don't want to see our program have Bug( That is, program errors or defects ), Especially the one just written with great effort , And confidently deliver the program .
however , What I want to say is , Whether people will progress and how fast , It depends on the denial of self , This includes the depth of negation , And how often you deny yourself . This is actually “ There's no making without breaking ” The meaning of this word .
For programs and software , Find problems early 、 Fixing problems is actually very important . In this context of network interconnection , The program we do 、 Tools or software products can often be distributed faster 、 further . however , meanwhile , Their mistakes and defects will be the same , And it may affect thousands or even more users in a short time .
You might say :“ In the open source mode, this is the advantage , I just want more people to help me find and even correct mistakes , We can also work together 、 Common maintenance procedures .” But it's actually two different things , Collaborators are often converted by early or core users , But it is absolutely impossible to say that the users of the program will certainly become collaborators .
When many users start complaining about the program , It's likely to indicate that your personal design for this is about to collapse . You'll find that , Or one day you will find , The more people pay attention to and love the program , Its test ( Especially automated testing ) The more you do , The more standardized the test process is .
Even if you want people to collect firewood, the flame is high , Let others like your program first . Besides, , For good programs and software , Testing must be a very important link . therefore , Build a fortress for your program with testing as soon as possible !
There are many kinds of tests for programs or software , such as : unit testing 、API test 、 Integration testing 、 Gray scale test , wait . In this module, I will mainly explain unit testing .
Leading content :go Basic knowledge of program testing
Let's talk about unit testing , It is also called programmer testing . seeing the name of a thing one thinks of its function , This is one of the things programmers should do to check themselves .
Go The founders of language have attached great importance to program testing from the beginning , And for Go The developers of the program provide a wealth of API And tools . Take advantage of these API And tools , We can create test source files , And for the program entities in the command source file and library source file , Write test cases .
stay Go In language , A test case is often represented by one or more test functions , But in most cases , Only one test function per test case is enough . Test functions are often used to describe and guarantee some aspect of the function of a program entity , such as , What kind of input will this function take under normal circumstances , What kind of output , And such as , Under what circumstances will this function report an error or perform abnormally , wait .
We can Go Programming three types of tests , namely : A functional test (test)、 The benchmark (benchmark, Also called performance testing ), And sample tests (example).
For the first two types of tests , From the name, you should be able to guess their purpose . Strictly speaking, the example test is also a function test , It just pays more attention to what the program prints .
In general , A test source file will only target a command source file , Or library source file ( Hereinafter referred to as the tested source file ) Do a test , So we always ( And should ) Put them in the same code package .
The main name of the test source file should be called the leader with the main name of the tested source file , And it has to be “_test” For the suffix . for example , If the name of the tested source file is demo52.go, Then the name of the test source file for it should be demo52_test.go.
Each test source file must contain at least one test function . also , Grammatically speaking , In each test source file , Can contain test functions used to do any kind of test , Even if you plug in all three types of test functions, there is no problem . That's what I usually do , Just control the grouping and number of test functions .
We can target different program entities according to these test functions , Divide them into different logical groups , also , Use annotations and help class variables or functions to do segmentation . meanwhile , We can also according to the sequence of program entities in the tested source file , To arrange the order of test functions in the test source file .
Besides , Not just the name of the test source file , For the name and signature of the test function ,Go Language is also clearly stipulated . Do you know the content of this regulation ?
therefore , Our problem today is :Go What rules does the language have for the name and signature of the test function ?
The typical answer I give here is the following three contents .
- For function test functions , Its name must be Test The prefix , And there should be only one... In the parameter list *testing.T Parameter declaration of type .
- For performance test functions , Its name must be Benchmark The prefix , And the only parameter type must be *testing.B Type of .
- For example test functions , Its name must be Example The prefix , However, the parameter list of the function is not mandatory .
Problem analysis
I usually ask this question for two purposes .
- The first purpose, of course, is to investigate Go Basic rules of program testing . If you often write test source files , Then this question should be easy to answer .
- The second purpose is as an introduction , Leads to the second question , namely :go test What is the main test flow of command execution ? But I won't ask you here , Let me just say the answer .
We need to remember one thing first , Only the name of the test source file is correct , The name and signature of the test function are also correct , When we run go test When ordered , The test code can be run .
go test When the command starts running , Will do some preparatory work first , such as , Determine the internal commands needed , Check the validity of the code package or source file we specified , And judge whether the mark we give is legal , wait .
After the preparations have been successfully completed ,go test The command will be for each code package under test , Build in turn 、 Execute the required test functions in the package , Clean up temporary documents , Print test results . This is usually the main test process .
Please note that “ successively ” Two words . For each tested code package ,go test The command serially executes each step in the test process .
however , In order to speed up the test , It usually performs function tests on multiple tested code packages concurrently , It's just , At the end of printing the test results , It will be carried out one by one in the order we give , This makes us feel that it is executing the test process in full serial .
On the other hand , Because concurrent testing will bias the results of performance testing , Therefore, performance testing is generally carried out in serial . More specifically , Only after all the building steps have been completed ,go test Command will really start performance testing .
also , The next code package performance test , It will not start until the results of the performance test of the previous code package are printed , And the execution of performance test functions will also be serial .
Once it's clear Go The specific process of program testing , Some of our doubts will naturally have an answer . such as , That's called testIntroduce Why didn't the test function execute , And such as , Why even simple performance tests are slower to execute than functional tests , wait .
demo52.go
package main
import (
"errors"
"flag"
"fmt"
)
var name string
func init() {
flag.StringVar(&name, "name", "everyone", "The greeting object.")
}
func main() {
flag.Parse()
greeting, err := hello(name)
if err != nil {
fmt.Printf("error: %s\n", err)
return
}
fmt.Println(greeting, introduce())
}
// hello Used to generate greeting content .
func hello(name string) (string, error) {
if name == "" {
return "", errors.New("empty name")
}
return fmt.Sprintf("Hello, %s!", name), nil
}
// introduce Used to generate introductory content .
func introduce() string {
return "Welcome to my Golang column."
}demo52_test.go
package main
import (
"fmt"
"testing"
)
func TestHello(t *testing.T) {
var name string
greeting, err := hello(name)
if err == nil {
t.Errorf("The error is nil, but it should not be. (name=%q)",
name)
}
if greeting != "" {
t.Errorf("Nonempty greeting, but it should not be. (name=%q)",
name)
}
name = "Robert"
greeting, err = hello(name)
if err != nil {
t.Errorf("The error is not nil, but it should be. (name=%q)",
name)
}
if greeting == "" {
t.Errorf("Empty greeting, but it should not be. (name=%q)",
name)
}
expected := fmt.Sprintf("Hello, %s!", name)
if greeting != expected {
t.Errorf("The actual greeting %q is not the expected. (name=%q)",
greeting, name)
}
t.Logf("The expected greeting is %q.\n", expected)
}
func testIntroduce(t *testing.T) { // Notice the name of the test function .
intro := introduce()
expected := "Welcome to my Golang column."
if intro != expected {
t.Errorf("The actual introduce %q is not the expected.",
intro)
}
t.Logf("The expected introduce is %q.\n", expected)
}summary
At the beginning of this article , I'm trying to explain to you the importance of program testing . At least half of the companies I've worked in don't pay attention to program testing , Or no energy to do program testing .
Especially small and medium-sized companies , They often rely entirely on the software quality assurance team , Even real users to help them test . In these cases , Discovery of software errors or defects 、 The feedback and repair cycle is usually long , The cost will also be great , It may also have a very bad impact .
Go Language is a programming language that attaches great importance to program testing , It not only comes with testing package , There are also commands dedicated to program testing go test. If we want to really make good use of a tool , You need to understand its core logic first . therefore , The first question I ask you today is about go test The basic rules and main flow of commands . After knowing this , Maybe you are right Go Program testing will enter a deeper understanding .
Thinking questions
In addition to the , You also know or have used testing.T The type and testing.B Which methods of type ? What are they used for ? You can leave me a message , Let's talk about it .
Note source code
边栏推荐
- DCOM horizontal movement of Intranet penetration
- Build and enable all plug-ins of kubesphere high availability cluster
- Echo framework: implementing service end flow limiting Middleware
- How to set up AI speech synthesis? What is the function of speech synthesis?
- Tencent cloud Weibo was selected into the analysis report on the status quo of China's low code platform market in 2021 by Forrester, an international authoritative research institution
- LeetCode 120. Triangle minimum path sum
- November 15, 2021: add four numbers II. Here are four integer arrays nums1, num
- Research Report on global and Chinese titanium concentrate market scale and investment prospects 2022-2028
- [read together] Web penetration attack and defense practice (I)
- Practical case - Tencent security hosting service MSS helped "zero accident" during the period of digital Guangdong re insurance!
猜你喜欢

Stm32g474 infrared receiving based on irtim peripherals

It's too difficult for me. Ali has had 7 rounds of interviews (5 years of experience and won the offer of P7 post)
![[SQL injection 13] referer injection foundation and Practice (based on burpseuite tool and sqli labs less19 target platform)](/img/b5/a8c4bbaf868dd20b7dc9449d2a4378.jpg)
[SQL injection 13] referer injection foundation and Practice (based on burpseuite tool and sqli labs less19 target platform)

I, a 27 year old female programmer, feel that life is meaningless, not counting the accumulation fund deposit of 430000
![[SQL injection 12] user agent injection foundation and Practice (based on burpsuite tool and sqli labs LESS18 target machine platform)](/img/c8/f6c2a62b8ab8fa88bd2b3d8f35f592.jpg)
[SQL injection 12] user agent injection foundation and Practice (based on burpsuite tool and sqli labs LESS18 target machine platform)
随机推荐
Tcapulusdb database: the king behind the "Tianya Mingyue swordsman Tour"
[latest] how to realize hybrid cloud active / standby redundant communication through cloud networking and VPN connection?
Introduction to trusted service manager
Note 3 of disruptor: basic operation of ring queue (without disruptor class)
Typescript type system
What is function point analysis - FPA
Grp: implement GRP timeout interceptor
NFS operations and deployment
Moment. JS how to use epoch time to construct objects
Devops learning notes (II)
How to do AI speech synthesis? How to download the voice of AI speech synthesis?
Gin framework: implementing timeout Middleware
NFS file systems - mount and optimize
[new function!] How anycast CLB supports multi location & dynamically accelerated load balancing services and high-speed Internet forwarding!
Tencent music, slow down?
Tcapulusdb Jun · industry news collection
Smart supply chain collaborative management platform for the home industry integrated upstream and downstream collaboration of the supply chain to improve management efficiency
Railway patrol system - Railway Intelligent Patrol communication system
[dry goods] four tools linkage of automated batch hole digging process
Tcapulusdb pays high tribute to Chinese journalists!