[lectures/04-testing] Add coverage and t.Cleanup() examples.

This commit is contained in:
Arseny Balobanov 2021-03-11 17:35:16 +03:00
parent 6c077a5e20
commit 90065aac82
6 changed files with 84 additions and 16 deletions

View file

@ -3,14 +3,13 @@ package example
import (
"testing"
gomock "github.com/golang/mock/gomock"
"github.com/golang/mock/gomock"
)
func TestFoo(t *testing.T) {
ctrl := gomock.NewController(t)
// Assert that Bar() is invoked.
defer ctrl.Finish()
defer ctrl.Finish() // Assert that Bar() is invoked.
m := NewMockFoo(ctrl)

View file

@ -276,7 +276,23 @@ Good example
* Coverage
- Пример в goland.
.play size/size.go /func/,/^}/
* Coverage
.play size/size_test.go /func/,/^}/
go test -cover
PASS
coverage: 42.9% of statements
ok gitlab.com/slon/shad-go/lectures/04-testing/size 0.001s
* Coverage
go test -coverprofile=coverage.out
go tool cover -html=coverage.out
.image size/coverage.png
* Benchmark Functions
@ -435,6 +451,20 @@ Good example
// ...
}
* t.Cleanup()
func newEnv(t *testing.T) *env {
// ...
t.Cleanup(func() {
DB.Close()
})
}
func TestA(t *testing.T) {
env := newEnv(t)
// ...
}
* Fixture Composition
type MyFixture struct {
@ -480,7 +510,7 @@ Good example
* White box testing
.play mocks/mocks.go /var/,/OMIT/
.play mocks/mocks.go /func CheckQuota/,/OMIT/
* White box testing

View file

@ -13,17 +13,6 @@ func bytesInUse(username string) int {
return 10000000000
}
var notifyUser = doNotifyUser
func doNotifyUser(username, msg string) {
auth := smtp.PlainAuth("", sender, password, hostname)
err := smtp.SendMail(hostname+":587", auth, sender,
[]string{username}, []byte(msg))
if err != nil {
log.Printf("smtp.SendEmail(%s) failed: %s", username, err)
}
}
func CheckQuota(username string) {
used := bytesInUse(username)
const quota = 1000000000 // 1GB
@ -35,4 +24,15 @@ func CheckQuota(username string) {
notifyUser(username, msg)
}
var notifyUser = doNotifyUser
func doNotifyUser(username, msg string) {
auth := smtp.PlainAuth("", sender, password, hostname)
err := smtp.SendMail(hostname+":587", auth, sender,
[]string{username}, []byte(msg))
if err != nil {
log.Printf("smtp.SendEmail(%s) failed: %s", username, err)
}
}
// OMIT

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

View file

@ -0,0 +1,17 @@
package size
func Size(a int) string {
switch {
case a < 0:
return "negative"
case a == 0:
return "zero"
case a < 10:
return "small"
case a < 100:
return "big"
case a < 1000:
return "huge"
}
return "enormous"
}

View file

@ -0,0 +1,22 @@
package size
import "testing"
func TestSize(t *testing.T) {
type Test struct {
in int
out string
}
var tests = []Test{
{-1, "negative"},
{5, "small"},
}
for i, test := range tests {
size := Size(test.in)
if size != test.out {
t.Errorf("#%d: Size(%d)=%s; want %s", i, test.in, size, test.out)
}
}
}