SlideShare a Scribd company logo
1 of 35
Download to read offline
⬢
–
–
–
⬢
–
–
–
–
–
⬢
⬢
○
○
○
○
⬢
⬢
⬢
⬢
⬢
⬢
⬢
⬢
⬢
⬢
⬢
⬢
⬢
func plus(a, b int) int {
return a + b
}
func TestPlus(t *testing.T) {
res := plus(1, 1)
if 2 != res {
t.Errorf( "Result not match: %d" , res)
}
}
# go test
PASS
ok mhmxs/golang-dot-testing 0.006s
func TestPlusTable(t *testing.T) {
tests := []struct {
a int
b int
out int
}{
{1, 1, 2},
{1, 2, 3},
}
for _, i := range tests {
res := plus(i.a, i.b)
if i.out != res {
t.Errorf( "Result not match: %d" , res)
}
}
}
# go test
PASS
ok mhmxs/golang-dot-testing 0.006s
# go test -cover -coverprofile=cover.out
PASS
coverage: 100.0% of statements
ok mhmxs/golang-dot-testing 0.006s
# go tool cover -html=cover.out
func racer() {
m := map[int]string{}
go func() {
m[1] = "a"
}()
m[2] = "b"
}
func TestRacer(t *testing.T) {
racer()
}
# go test -race
==================
WARNING: DATA RACE
Write at 0x00c4200da000 by goroutine 9:
runtime.mapassign_fast64()
/usr/local/Cellar/go/1.9.2/libexec/src/runtime/hashmap_fast.go:510 +0x0
mhmxs/golang-dot-testing/basics.racer.func1()
/Users/rkovacs/GitHub/src/mhmxs/golang-dot-testing/basics/basics.go:10 +0x51
Previous write at 0x00c4200da000 by goroutine 8:
runtime.mapassign_fast64()
/usr/local/Cellar/go/1.9.2/libexec/src/runtime/hashmap_fast.go:510 +0x0
mhmxs/golang-dot-testing/basics.racer()
/Users/rkovacs/GitHub/src/mhmxs/golang-dot-testing/basics/basics.go:12 +0xa3
mhmxs/golang-dot-testing/basics.TestRacer()
/Users/rkovacs/GitHub/src/mhmxs/golang-dot-testing/basics/basics_test.go:32 +0x2f
testing.tRunner()
/usr/local/Cellar/go/1.9.2/libexec/src/testing/testing.go:746 +0x16c
Goroutine 9 (running) created at:
mhmxs/golang-dot-testing/basics.racer()
/Users/rkovacs/GitHub/src/mhmxs/golang-dot-testing/basics/basics.go:9 +0x80
mhmxs/golang-dot-testing/basics.TestRacer()
/Users/rkovacs/GitHub/src/mhmxs/golang-dot-testing/basics/basics_test.go:32 +0x2f
testing.tRunner()
/usr/local/Cellar/go/1.9.2/libexec/src/testing/testing.go:746 +0x16c
Goroutine 8 (finished) created at:
testing.(*T).Run()
/usr/local/Cellar/go/1.9.2/libexec/src/testing/testing.go:789 +0x568
testing.runTests.func1()
/usr/local/Cellar/go/1.9.2/libexec/src/testing/testing.go:1004 +0xa7
testing.tRunner()
/usr/local/Cellar/go/1.9.2/libexec/src/testing/testing.go:746 +0x16c
testing.runTests()
/usr/local/Cellar/go/1.9.2/libexec/src/testing/testing.go:1002 +0x521
testing.(*M).Run()
/usr/local/Cellar/go/1.9.2/libexec/src/testing/testing.go:921 +0x206
main.main()
mhmxs/golang-dot-testing/basics/_test/_testmain.go:48 +0x1d3
==================
FAIL
exit status 1
FAIL mhmxs/golang-dot-testing/basics 0.011s
⬢
○
○
○
○
○
⬢
⬢
* What I discovered
⬢
⬢
⬢
func main() {
monkey.Patch(fmt.Println, func(a ...interface{}) (n int, err error) {
s := make([]interface{}, len(a))
for i, v := range a {
s[i] = strings.Replace(fmt.Sprint(v), "hell", "*bleep*", -1)
}
return fmt.Fprintln(os.Stdout, s ...)
})
fmt.Println( "what the hell?" ) // what the *bleep*?
}
type Authenticator struct {
Username string
Password string
}
func (a *Authenticator) Wrap(handler func(w http.ResponseWriter, req *http.Request)) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
valid := CheckAuth(a.Username, a.Password, r)
if !valid {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("401 Unauthorized"))
return
}
w.Header().Set("Content-Type", "application/json")
http.HandlerFunc(handler).ServeHTTP(w, r)
})
}
func CheckAuth(user string, pass string, r *http.Request) bool {
return user == pass
}
type TestWriter struct {
header http.Header
status int
message string
}
func (w *TestWriter) Header() http.Header {
return w.header
}
func (w *TestWriter) Write(b []byte) (int, error) {
w.message = string(b)
return len(b), nil
}
func (w *TestWriter) WriteHeader(s int) {
w.status = s
}
func TestAuthenticatorWrap1 (t *testing.T) {
req, _ := http.NewRequest( "GET", "http://google.com" , nil)
writer := new(TestWriter)
auth := Authenticator{Username: "user", Password: "pass"}
handler := auth.Wrap(func(w http.ResponseWriter, req *http.Request) {})
handler.ServeHTTP(writer, req)
if writer.status != 401 {
t.Errorf( "writer.status %d == %d" , 401, writer.status)
}
}
func TestAuthenticatorWrap2 (t *testing.T) {
req, _ := http.NewRequest( "GET", "http://google.com" , nil)
writer := httptest.NewRecorder()
auth := Authenticator{Username: "user", Password: "pass"}
handler := auth.Wrap(func(w http.ResponseWriter, req *http.Request) {})
handler.ServeHTTP(writer, req)
if writer.Code != 401 {
t.Errorf( "writer.status %d == %d" , 401, writer.Code)
}
}
func DescribeCredential (c *cli.Context) {
client := NewOAuth2HTTPClient( "localhost", "user", "password")
params := credentials.NewGetCredentialParams().WithName(c.String(FlName.Name))
resp, err := client.Credentials.GetCredential(params)
if err != nil {
panic(err.Error())
}
println(resp.Payload.ID)
}
type credentialClient interface {
GetCredential( *credentials.GetCredentialParams) ( *credentials.GetCredentialOK, error)
}
func describeCredentialImpl (nameFinder func(string) string, client credentialClient) int64 {
params := credentials.NewGetCredentialParams().WithName(nameFinder(FlName.Name))
resp, err := client.GetCredential(params)
if err != nil {
panic(err.Error())
}
return resp.Payload.ID
}
func DescribeCredential (c *cli.Context) {
client := NewOAuth2HTTPClient( "localhost", "user", "password")
println(describeCredentialImpl(c.String, client.Credentials))
}
type mockClient struct{}
func (mc mockClient) GetCredential(params *credentials.GetCredentialParams) ( *credentials.GetCredentialOK, error) {
return &credentials.GetCredentialOK{Payload: &models.CredentialResponse{ID: 0}}, nil
}
func TestDesribeCredential (t *testing.T) {
nameFinder := func(in string) string {
return "name"
}
if 0 != describeCredentialImpl(nameFinder, mockClient{}) {
t.Error( "ID not match" )
}
}
type mockClient struct {
names chan (string)
}
func (mc mockClient) GetCredential(params *credentials.GetCredentialParams) ( *credentials.GetCredentialOK, error) {
mc.names <- params.Name
defer close(mc.names)
return &credentials.GetCredentialOK{Payload: &models.CredentialResponse{ID: 0}}, nil
}
func TestDesribeCredentialParams (t *testing.T) {
...
mc := mockClient{make( chan string)}
go describeCredentialImpl(nameFinder, mc)
if "name" != <-mc.names {
t.Error( "Name not match" )
}
}
func PrintErrorAndExit (msg string) {
println(msg)
os.Exit(1)
}
var exit = os.Exit
func PrintErrorAndExit (msg string) {
println(msg)
exit(1)
}
func TestPrintErrorAndExit (t *testing.T) {
exitCode := 0
exit = func(c int) {
exitCode = c
}
defer func() {
exit = os.Exit
}()
PrintErrorAndExit( "message")
if 1 != exitCode {
t.Error( "Code not match" )
}
}
func PrintErrorAndExit (msg string) {
println(msg)
panic(msg)
}
func TestPrintErrorAndExit (t *testing.T) {
defer func() {
if r := recover(); r != nil {
if r != "message" {
t.Error( "message not match" )
}
}
}()
PrintErrorAndExit( "message")
t.Error("exit not happen" )
}
func main() {
defer func() {
if r := recover(); r != nil {
os.Exit( 1)
}
}()
...
}
⬢
⬢
⬢
type MyMock struct{
mock.Mock
}
func TestTestify(t *testing.T) {
assert.Equal(t, 1, 1, "Not match. WTF?")
mock := new(MyMock)
mock.On("DoSomething", "input").Return("output")
funcUnderTest(mock)
mock.AssertExpectations(t)
}
type ExampleTestSuite struct {
suite.Suite
VariableThatShouldStartAtFive int
}
func (suite *ExampleTestSuite) SetupTest() {
suite.VariableThatShouldStartAtFive = 5
}
func (suite *ExampleTestSuite) TestExample() {
assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive)
}
func TestExampleTestSuite(t *testing.T) {
suite.Run(t, new(ExampleTestSuite))
}
⬢
⬢
⬢
⬢
⬢
⬢
⬢
⬢
$ go test
------------------------------------------------------
FAIL: hello_test.go:16: S.TestHelloWorld
hello_test.go:17:
c.Check(42, Equals, "42")
... obtained int = 42
... expected string = "42"
hello_test.go:18:
c.Check(io.ErrClosedPipe, ErrorMatches, "BOOM")
... error string = "io: read/write on closed pipe"
... regex string = "BOOM"
OOPS: 0 passed, 1 FAILED
--- FAIL: hello_test.Test
FAIL
⬢
○
○
○
⬢
○
○
○
⬢
func TestCalc(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Calculator Suite")
}
var _ = Describe("Calculator", func() {
Describe("Add numbers", func() {
Context("1 and 2", func() {
It("should be 3", func() {
Expect(Add(1, 2)).To(Equal(3))
})
})
})
Describe("Subtract numbers", func() {
Context("3 from 5", func() {
It("should be 2", func() {
Expect(Subtract(5, 3)).To(Equal(2))
})
})
})
})
⬢
⬢
⬢
⬢
⬢
⬢
func TestCalculator(t *testing.T) {
g := Goblin(t)
g.Describe("Calculator", func() {
g.It("should add two numbers ", func() {
g.Assert(Add(1, 2)).Equal(3)
})
g.It("should subtract two numbers", func() {
g.Assert(Subtract(5, 3)).Equal(2)
})
g.It("should multiply two numbers", func() {
g.Assert(Multiply(5, 6)).Equal(30)
})
g.It("should divide two numbers", func() {
g.Assert(Divide(10, 2)).Equal(float64(5))
})
})
}
⬢
⬢
⬢
⬢
func TestAddWithGoConvey(t *testing.T) {
Convey("Adding two numbers", t, func() {
x := 1
y := 2
Convey("should produce the expected result", func() {
So(Add(x, y), ShouldEqual, 3)
})
})
}
⬢
⬢
⬢
⬢
⬢
Golang dot-testing

More Related Content

What's hot

The Ring programming language version 1.6 book - Part 9 of 189
The Ring programming language version 1.6 book - Part 9 of 189The Ring programming language version 1.6 book - Part 9 of 189
The Ring programming language version 1.6 book - Part 9 of 189Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 88 of 184
The Ring programming language version 1.5.3 book - Part 88 of 184The Ring programming language version 1.5.3 book - Part 88 of 184
The Ring programming language version 1.5.3 book - Part 88 of 184Mahmoud Samir Fayed
 
javascript function & closure
javascript function & closurejavascript function & closure
javascript function & closureHika Maeng
 
The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180Mahmoud Samir Fayed
 
The Ring programming language version 1.6 book - Part 34 of 189
The Ring programming language version 1.6 book - Part 34 of 189The Ring programming language version 1.6 book - Part 34 of 189
The Ring programming language version 1.6 book - Part 34 of 189Mahmoud Samir Fayed
 
The Ring programming language version 1.5.4 book - Part 79 of 185
The Ring programming language version 1.5.4 book - Part 79 of 185The Ring programming language version 1.5.4 book - Part 79 of 185
The Ring programming language version 1.5.4 book - Part 79 of 185Mahmoud Samir Fayed
 
The Ring programming language version 1.5.4 book - Part 78 of 185
The Ring programming language version 1.5.4 book - Part 78 of 185The Ring programming language version 1.5.4 book - Part 78 of 185
The Ring programming language version 1.5.4 book - Part 78 of 185Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 92 of 210
The Ring programming language version 1.9 book - Part 92 of 210The Ring programming language version 1.9 book - Part 92 of 210
The Ring programming language version 1.9 book - Part 92 of 210Mahmoud Samir Fayed
 
Polynomial addition
Polynomial additionPolynomial addition
Polynomial additionraviahuja11
 
The Ring programming language version 1.9 book - Part 40 of 210
The Ring programming language version 1.9 book - Part 40 of 210The Ring programming language version 1.9 book - Part 40 of 210
The Ring programming language version 1.9 book - Part 40 of 210Mahmoud Samir Fayed
 
The Ring programming language version 1.7 book - Part 85 of 196
The Ring programming language version 1.7 book - Part 85 of 196The Ring programming language version 1.7 book - Part 85 of 196
The Ring programming language version 1.7 book - Part 85 of 196Mahmoud Samir Fayed
 
Working of while loop
Working of while loopWorking of while loop
Working of while loopNeeru Mittal
 
csc 208
csc 208csc 208
csc 208priska
 
The Ring programming language version 1.5.2 book - Part 26 of 181
The Ring programming language version 1.5.2 book - Part 26 of 181The Ring programming language version 1.5.2 book - Part 26 of 181
The Ring programming language version 1.5.2 book - Part 26 of 181Mahmoud Samir Fayed
 
Laporan multiclient chatting client server
Laporan multiclient chatting client serverLaporan multiclient chatting client server
Laporan multiclient chatting client servertrilestari08
 

What's hot (20)

The Ring programming language version 1.6 book - Part 9 of 189
The Ring programming language version 1.6 book - Part 9 of 189The Ring programming language version 1.6 book - Part 9 of 189
The Ring programming language version 1.6 book - Part 9 of 189
 
The Ring programming language version 1.5.3 book - Part 88 of 184
The Ring programming language version 1.5.3 book - Part 88 of 184The Ring programming language version 1.5.3 book - Part 88 of 184
The Ring programming language version 1.5.3 book - Part 88 of 184
 
javascript function & closure
javascript function & closurejavascript function & closure
javascript function & closure
 
The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180
 
Python unit 3 and Unit 4
Python unit 3 and Unit 4Python unit 3 and Unit 4
Python unit 3 and Unit 4
 
The Ring programming language version 1.6 book - Part 34 of 189
The Ring programming language version 1.6 book - Part 34 of 189The Ring programming language version 1.6 book - Part 34 of 189
The Ring programming language version 1.6 book - Part 34 of 189
 
The Ring programming language version 1.5.4 book - Part 79 of 185
The Ring programming language version 1.5.4 book - Part 79 of 185The Ring programming language version 1.5.4 book - Part 79 of 185
The Ring programming language version 1.5.4 book - Part 79 of 185
 
The Ring programming language version 1.5.4 book - Part 78 of 185
The Ring programming language version 1.5.4 book - Part 78 of 185The Ring programming language version 1.5.4 book - Part 78 of 185
The Ring programming language version 1.5.4 book - Part 78 of 185
 
The Ring programming language version 1.9 book - Part 92 of 210
The Ring programming language version 1.9 book - Part 92 of 210The Ring programming language version 1.9 book - Part 92 of 210
The Ring programming language version 1.9 book - Part 92 of 210
 
Polynomial addition
Polynomial additionPolynomial addition
Polynomial addition
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
java assignment
java assignmentjava assignment
java assignment
 
The Ring programming language version 1.9 book - Part 40 of 210
The Ring programming language version 1.9 book - Part 40 of 210The Ring programming language version 1.9 book - Part 40 of 210
The Ring programming language version 1.9 book - Part 40 of 210
 
The Ring programming language version 1.7 book - Part 85 of 196
The Ring programming language version 1.7 book - Part 85 of 196The Ring programming language version 1.7 book - Part 85 of 196
The Ring programming language version 1.7 book - Part 85 of 196
 
Working of while loop
Working of while loopWorking of while loop
Working of while loop
 
csc 208
csc 208csc 208
csc 208
 
Ann
AnnAnn
Ann
 
The Ring programming language version 1.5.2 book - Part 26 of 181
The Ring programming language version 1.5.2 book - Part 26 of 181The Ring programming language version 1.5.2 book - Part 26 of 181
The Ring programming language version 1.5.2 book - Part 26 of 181
 
C#
C#C#
C#
 
Laporan multiclient chatting client server
Laporan multiclient chatting client serverLaporan multiclient chatting client server
Laporan multiclient chatting client server
 

Similar to Golang dot-testing

Testing CLI tools with Go
Testing CLI tools with GoTesting CLI tools with Go
Testing CLI tools with GoRicardo Gerardi
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기진성 오
 
Go: It's Not Just For Google
Go: It's Not Just For GoogleGo: It's Not Just For Google
Go: It's Not Just For GoogleEleanor McHugh
 
Are we ready to Go?
Are we ready to Go?Are we ready to Go?
Are we ready to Go?Adam Dudczak
 
Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17LogeekNightUkraine
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my dayTor Ivry
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoThe Software House
 
JBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java ProgrammersJBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java ProgrammersTikal Knowledge
 
using python module: doctest
using python module: doctestusing python module: doctest
using python module: doctestmitnk
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
Parsing swiftly-Cocoaheads-2015-02-12
Parsing swiftly-Cocoaheads-2015-02-12Parsing swiftly-Cocoaheads-2015-02-12
Parsing swiftly-Cocoaheads-2015-02-12griotspeak
 
Function recap
Function recapFunction recap
Function recapalish sha
 
Function recap
Function recapFunction recap
Function recapalish sha
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
design and analysis of algorithm Lab files
design and analysis of algorithm Lab filesdesign and analysis of algorithm Lab files
design and analysis of algorithm Lab filesNitesh Dubey
 
Advanced Java - Practical File
Advanced Java - Practical FileAdvanced Java - Practical File
Advanced Java - Practical FileFahad Shaikh
 

Similar to Golang dot-testing (20)

Testing CLI tools with Go
Testing CLI tools with GoTesting CLI tools with Go
Testing CLI tools with Go
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
Go: It's Not Just For Google
Go: It's Not Just For GoogleGo: It's Not Just For Google
Go: It's Not Just For Google
 
Golang dot-testing-lite
Golang dot-testing-liteGolang dot-testing-lite
Golang dot-testing-lite
 
Are we ready to Go?
Are we ready to Go?Are we ready to Go?
Are we ready to Go?
 
Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 
JBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java ProgrammersJBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java Programmers
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
using python module: doctest
using python module: doctestusing python module: doctest
using python module: doctest
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Parsing swiftly-Cocoaheads-2015-02-12
Parsing swiftly-Cocoaheads-2015-02-12Parsing swiftly-Cocoaheads-2015-02-12
Parsing swiftly-Cocoaheads-2015-02-12
 
Function recap
Function recapFunction recap
Function recap
 
Function recap
Function recapFunction recap
Function recap
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Functions
FunctionsFunctions
Functions
 
design and analysis of algorithm Lab files
design and analysis of algorithm Lab filesdesign and analysis of algorithm Lab files
design and analysis of algorithm Lab files
 
Advanced Java - Practical File
Advanced Java - Practical FileAdvanced Java - Practical File
Advanced Java - Practical File
 

Recently uploaded

Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 

Recently uploaded (20)

Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 

Golang dot-testing

  • 1.
  • 3.
  • 4.
  • 6.
  • 8.
  • 9. func plus(a, b int) int { return a + b } func TestPlus(t *testing.T) { res := plus(1, 1) if 2 != res { t.Errorf( "Result not match: %d" , res) } } # go test PASS ok mhmxs/golang-dot-testing 0.006s
  • 10. func TestPlusTable(t *testing.T) { tests := []struct { a int b int out int }{ {1, 1, 2}, {1, 2, 3}, } for _, i := range tests { res := plus(i.a, i.b) if i.out != res { t.Errorf( "Result not match: %d" , res) } } } # go test PASS ok mhmxs/golang-dot-testing 0.006s
  • 11. # go test -cover -coverprofile=cover.out PASS coverage: 100.0% of statements ok mhmxs/golang-dot-testing 0.006s # go tool cover -html=cover.out
  • 12. func racer() { m := map[int]string{} go func() { m[1] = "a" }() m[2] = "b" } func TestRacer(t *testing.T) { racer() } # go test -race ================== WARNING: DATA RACE Write at 0x00c4200da000 by goroutine 9: runtime.mapassign_fast64() /usr/local/Cellar/go/1.9.2/libexec/src/runtime/hashmap_fast.go:510 +0x0 mhmxs/golang-dot-testing/basics.racer.func1() /Users/rkovacs/GitHub/src/mhmxs/golang-dot-testing/basics/basics.go:10 +0x51 Previous write at 0x00c4200da000 by goroutine 8: runtime.mapassign_fast64() /usr/local/Cellar/go/1.9.2/libexec/src/runtime/hashmap_fast.go:510 +0x0 mhmxs/golang-dot-testing/basics.racer() /Users/rkovacs/GitHub/src/mhmxs/golang-dot-testing/basics/basics.go:12 +0xa3 mhmxs/golang-dot-testing/basics.TestRacer() /Users/rkovacs/GitHub/src/mhmxs/golang-dot-testing/basics/basics_test.go:32 +0x2f testing.tRunner() /usr/local/Cellar/go/1.9.2/libexec/src/testing/testing.go:746 +0x16c Goroutine 9 (running) created at: mhmxs/golang-dot-testing/basics.racer() /Users/rkovacs/GitHub/src/mhmxs/golang-dot-testing/basics/basics.go:9 +0x80 mhmxs/golang-dot-testing/basics.TestRacer() /Users/rkovacs/GitHub/src/mhmxs/golang-dot-testing/basics/basics_test.go:32 +0x2f testing.tRunner() /usr/local/Cellar/go/1.9.2/libexec/src/testing/testing.go:746 +0x16c Goroutine 8 (finished) created at: testing.(*T).Run() /usr/local/Cellar/go/1.9.2/libexec/src/testing/testing.go:789 +0x568 testing.runTests.func1() /usr/local/Cellar/go/1.9.2/libexec/src/testing/testing.go:1004 +0xa7 testing.tRunner() /usr/local/Cellar/go/1.9.2/libexec/src/testing/testing.go:746 +0x16c testing.runTests() /usr/local/Cellar/go/1.9.2/libexec/src/testing/testing.go:1002 +0x521 testing.(*M).Run() /usr/local/Cellar/go/1.9.2/libexec/src/testing/testing.go:921 +0x206 main.main() mhmxs/golang-dot-testing/basics/_test/_testmain.go:48 +0x1d3 ================== FAIL exit status 1 FAIL mhmxs/golang-dot-testing/basics 0.011s
  • 13.
  • 15.
  • 16. ⬢ ⬢ ⬢ func main() { monkey.Patch(fmt.Println, func(a ...interface{}) (n int, err error) { s := make([]interface{}, len(a)) for i, v := range a { s[i] = strings.Replace(fmt.Sprint(v), "hell", "*bleep*", -1) } return fmt.Fprintln(os.Stdout, s ...) }) fmt.Println( "what the hell?" ) // what the *bleep*? }
  • 17.
  • 18. type Authenticator struct { Username string Password string } func (a *Authenticator) Wrap(handler func(w http.ResponseWriter, req *http.Request)) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { valid := CheckAuth(a.Username, a.Password, r) if !valid { w.WriteHeader(http.StatusUnauthorized) w.Write([]byte("401 Unauthorized")) return } w.Header().Set("Content-Type", "application/json") http.HandlerFunc(handler).ServeHTTP(w, r) }) } func CheckAuth(user string, pass string, r *http.Request) bool { return user == pass }
  • 19. type TestWriter struct { header http.Header status int message string } func (w *TestWriter) Header() http.Header { return w.header } func (w *TestWriter) Write(b []byte) (int, error) { w.message = string(b) return len(b), nil } func (w *TestWriter) WriteHeader(s int) { w.status = s } func TestAuthenticatorWrap1 (t *testing.T) { req, _ := http.NewRequest( "GET", "http://google.com" , nil) writer := new(TestWriter) auth := Authenticator{Username: "user", Password: "pass"} handler := auth.Wrap(func(w http.ResponseWriter, req *http.Request) {}) handler.ServeHTTP(writer, req) if writer.status != 401 { t.Errorf( "writer.status %d == %d" , 401, writer.status) } }
  • 20. func TestAuthenticatorWrap2 (t *testing.T) { req, _ := http.NewRequest( "GET", "http://google.com" , nil) writer := httptest.NewRecorder() auth := Authenticator{Username: "user", Password: "pass"} handler := auth.Wrap(func(w http.ResponseWriter, req *http.Request) {}) handler.ServeHTTP(writer, req) if writer.Code != 401 { t.Errorf( "writer.status %d == %d" , 401, writer.Code) } }
  • 21. func DescribeCredential (c *cli.Context) { client := NewOAuth2HTTPClient( "localhost", "user", "password") params := credentials.NewGetCredentialParams().WithName(c.String(FlName.Name)) resp, err := client.Credentials.GetCredential(params) if err != nil { panic(err.Error()) } println(resp.Payload.ID) }
  • 22. type credentialClient interface { GetCredential( *credentials.GetCredentialParams) ( *credentials.GetCredentialOK, error) } func describeCredentialImpl (nameFinder func(string) string, client credentialClient) int64 { params := credentials.NewGetCredentialParams().WithName(nameFinder(FlName.Name)) resp, err := client.GetCredential(params) if err != nil { panic(err.Error()) } return resp.Payload.ID } func DescribeCredential (c *cli.Context) { client := NewOAuth2HTTPClient( "localhost", "user", "password") println(describeCredentialImpl(c.String, client.Credentials)) }
  • 23. type mockClient struct{} func (mc mockClient) GetCredential(params *credentials.GetCredentialParams) ( *credentials.GetCredentialOK, error) { return &credentials.GetCredentialOK{Payload: &models.CredentialResponse{ID: 0}}, nil } func TestDesribeCredential (t *testing.T) { nameFinder := func(in string) string { return "name" } if 0 != describeCredentialImpl(nameFinder, mockClient{}) { t.Error( "ID not match" ) } }
  • 24. type mockClient struct { names chan (string) } func (mc mockClient) GetCredential(params *credentials.GetCredentialParams) ( *credentials.GetCredentialOK, error) { mc.names <- params.Name defer close(mc.names) return &credentials.GetCredentialOK{Payload: &models.CredentialResponse{ID: 0}}, nil } func TestDesribeCredentialParams (t *testing.T) { ... mc := mockClient{make( chan string)} go describeCredentialImpl(nameFinder, mc) if "name" != <-mc.names { t.Error( "Name not match" ) } }
  • 25. func PrintErrorAndExit (msg string) { println(msg) os.Exit(1) } var exit = os.Exit func PrintErrorAndExit (msg string) { println(msg) exit(1) } func TestPrintErrorAndExit (t *testing.T) { exitCode := 0 exit = func(c int) { exitCode = c } defer func() { exit = os.Exit }() PrintErrorAndExit( "message") if 1 != exitCode { t.Error( "Code not match" ) } }
  • 26. func PrintErrorAndExit (msg string) { println(msg) panic(msg) } func TestPrintErrorAndExit (t *testing.T) { defer func() { if r := recover(); r != nil { if r != "message" { t.Error( "message not match" ) } } }() PrintErrorAndExit( "message") t.Error("exit not happen" ) } func main() { defer func() { if r := recover(); r != nil { os.Exit( 1) } }() ... }
  • 27.
  • 28. ⬢ ⬢ ⬢ type MyMock struct{ mock.Mock } func TestTestify(t *testing.T) { assert.Equal(t, 1, 1, "Not match. WTF?") mock := new(MyMock) mock.On("DoSomething", "input").Return("output") funcUnderTest(mock) mock.AssertExpectations(t) } type ExampleTestSuite struct { suite.Suite VariableThatShouldStartAtFive int } func (suite *ExampleTestSuite) SetupTest() { suite.VariableThatShouldStartAtFive = 5 } func (suite *ExampleTestSuite) TestExample() { assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive) } func TestExampleTestSuite(t *testing.T) { suite.Run(t, new(ExampleTestSuite)) }
  • 29. ⬢ ⬢ ⬢ ⬢ ⬢ ⬢ ⬢ ⬢ $ go test ------------------------------------------------------ FAIL: hello_test.go:16: S.TestHelloWorld hello_test.go:17: c.Check(42, Equals, "42") ... obtained int = 42 ... expected string = "42" hello_test.go:18: c.Check(io.ErrClosedPipe, ErrorMatches, "BOOM") ... error string = "io: read/write on closed pipe" ... regex string = "BOOM" OOPS: 0 passed, 1 FAILED --- FAIL: hello_test.Test FAIL
  • 30.
  • 31. ⬢ ○ ○ ○ ⬢ ○ ○ ○ ⬢ func TestCalc(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Calculator Suite") } var _ = Describe("Calculator", func() { Describe("Add numbers", func() { Context("1 and 2", func() { It("should be 3", func() { Expect(Add(1, 2)).To(Equal(3)) }) }) }) Describe("Subtract numbers", func() { Context("3 from 5", func() { It("should be 2", func() { Expect(Subtract(5, 3)).To(Equal(2)) }) }) }) })
  • 32. ⬢ ⬢ ⬢ ⬢ ⬢ ⬢ func TestCalculator(t *testing.T) { g := Goblin(t) g.Describe("Calculator", func() { g.It("should add two numbers ", func() { g.Assert(Add(1, 2)).Equal(3) }) g.It("should subtract two numbers", func() { g.Assert(Subtract(5, 3)).Equal(2) }) g.It("should multiply two numbers", func() { g.Assert(Multiply(5, 6)).Equal(30) }) g.It("should divide two numbers", func() { g.Assert(Divide(10, 2)).Equal(float64(5)) }) }) }
  • 33. ⬢ ⬢ ⬢ ⬢ func TestAddWithGoConvey(t *testing.T) { Convey("Adding two numbers", t, func() { x := 1 y := 2 Convey("should produce the expected result", func() { So(Add(x, y), ShouldEqual, 3) }) }) }