Тёмный

justforfunc #16: unit testing HTTP servers 

justforfunc: Programming in Go
Подписаться 39 тыс.
Просмотров 71 тыс.
50% 1

Let's cover the basics of unit testing in Go and then show how you can test http.HandlerFunc and http.Handler.
You'll learn how to use "testing", including subtests and examples, and "net/http/httptest" with ResponseRecorder and Server.
References:
- testing: golang.org/pkg/testing/
- net/http/httptest: golang.org/pkg/net/http/httptest
- Testable Examples in Go: blog.golang.org/examples
- source code: github.com/campoy/justforfunc...

Наука

Опубликовано:

 

23 июл 2017

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 101   
@JustForFunc
@JustForFunc 7 лет назад
1:42 - Basic Unit Tests 14:27 - Sub tests: 16:12 - Examples as tests 20:03 - Testing HTTP Handlers 39:27 - Testing HTTP routing
@Zyian
@Zyian 7 лет назад
One of my favorite things about this series is seeing the collection of stickers grow each video.
@sureshrajput5794
@sureshrajput5794 6 лет назад
Hello, Francesc. Thanks for the video. It helped lot to get into basic testing. Can you please record a video how to mock Handlers dependencies that can be anything like connecting to database or invoking external API's and like so.
@jongschneider
@jongschneider 6 лет назад
I love it! Keep up the good work. As a new programmer working with Go, deep dives into the basics of the language are extremely helpful.
@mattbrun1455
@mattbrun1455 5 лет назад
Extremely informative video and still holding its value very well as time goes on. Thank you very much for taking your time to help grow the gophers!
@zacharykeener1990
@zacharykeener1990 6 лет назад
Wasn't expecting to find a video on exactly what I was looking for, but I did. Thanks for the video! One of the live coding videos I've seen.
@ashhammond
@ashhammond 4 года назад
Excellant video my man. Your channel has been recommended to me, so far, I like your style and topics.
@geoblk3000
@geoblk3000 7 лет назад
I learned more from this video than any other tutorial on testing that's currently out there. Keep up the good work! Let me know if you have a Patreon account, I would like to donate.
@CarloLobrano
@CarloLobrano 3 года назад
This series is wonderful. I watched it first in 2017 and I come back from time to time. I also use a similar approach to testing and error handling in C now, since my job doesn't allow me to use golang, but it's super effective.
@leffenx
@leffenx 7 лет назад
Just a great joy to learn from this series :-) Thanks for providing nice tutorials !
@YaleKaul
@YaleKaul 2 года назад
This is really excellent! One tip I discovered just yesterday: if you put "localhost:8080" instead of ":8080" into your ListenAndServe method, it will make that annoying MacOS popup go away (but only after you've run it once)
@kalleidoskop2
@kalleidoskop2 3 года назад
Been coding in go for 3 years, still picked up some tricks! Great content, thanks!
@EnTransic
@EnTransic Год назад
i miss this series. i wish there was one that was comparable. justforfunc RULES!
@codesworth
@codesworth 7 лет назад
Great episode as usual!
@mybigbeak
@mybigbeak 7 лет назад
Sweet video. Learned a bunch of cool stuff. Really cool example docs thing
@blondie9990
@blondie9990 4 года назад
I really enjoyed this episode particularly. I have not been writing tests in my code. It was interesting to see how to write tests for network services that I assumed you couldn't easily write tests for. I learned allot.
@marcoazevedo5878
@marcoazevedo5878 6 лет назад
Awesome episode! I had no idea about this way to test router. Thank you so much for this video. By the way I'm really enjoying to learn Go. It is not only pragmatic and fun but also have an impressive and powerful standard library.
@hotscriptgg
@hotscriptgg 5 лет назад
This helped me a lot. Thank you Sir.
@blablu46
@blablu46 6 лет назад
Really helpful. Keep up the good work!
@andreaswestberg536
@andreaswestberg536 7 лет назад
thanks been w8ing for this one :)
@nwjlions
@nwjlions 7 лет назад
Great episode. I learnt a lot.
@JorgeGomez-xc2er
@JorgeGomez-xc2er 2 года назад
Very good explanation bro , congratulations!
@AshwiniKondalakadu
@AshwiniKondalakadu 3 года назад
This is sooper cool.. quite informative.. thanks a lot Francesc!!
@Trammael
@Trammael Год назад
This is the clearest explanation I've seen, thanks! (or read :) )
@alexeymavrin
@alexeymavrin Год назад
Thanks for this hi-quality video!
@tlpf666
@tlpf666 5 лет назад
very good explanations, thank you very much for doing that dude.
@user-gb9ik8qq9w
@user-gb9ik8qq9w 2 года назад
thank you for the lesson!
@enriquegarcia5863
@enriquegarcia5863 7 лет назад
you are too good to be true, but..... YOU ARE REAL !! Thanks for your videos :))
@farishuskovic8486
@farishuskovic8486 5 лет назад
I saw you at Gophercon 2018 in Denver. You had a machine learning talk. I learned that machine learning uses lots of math and is very complicated. I like this channel tho.
@RandomShowerThoughts
@RandomShowerThoughts 5 лет назад
Great video!
@rodolforodriguez8808
@rodolforodriguez8808 6 лет назад
you are awesome. thank you so much :)
@FrediVosberg
@FrediVosberg 7 лет назад
Thanks for this video. A nice compilation of testing 101. I wish you've had made it 12 months ago :) A little note, though: To clean the test code of the webserver a little bit up I would suggest httptest.ResponseRecorder.Body.String(): play.golang.org/p/lga8FW7XKg
@JustForFunc
@JustForFunc 7 лет назад
How didn't I know about this? So obviously useful! Thanks
@elamperti
@elamperti 6 лет назад
Thank you! :D
@benoitmasson
@benoitmasson 6 лет назад
Hi Francesc, thanks for the great videos, they're really helpful. One thing I don't really get in this one though is the routing part: it seems to me you're testing global server functionalities, not really routing. For example, if in your sample the server was (incorrectly) routing "/double" to a squareHandler() function, you wouldn't see anything wrong since the expected result is 2*2 = 2^2 = 4. To avoid that, you would have to be exhaustive in the tests in TestRouting() but that would create a lot of duplicate code with the handler testing… Is there a simple way to test that a request to a given route is sent to the desired handler? Or what would you think of renaming all handler tests from TestHandler() to testHandler() to make them private, removing all httptest.ResponseRecorder-related code, and call them as sub-tests in the TestRouting() function? Then, `go test` would test every route once with exhaustive tests, and to test only a subset of handlers one could `go test -run Routing/HandlerFoo`, for example.
@Chemaclass
@Chemaclass 7 лет назад
I like it!
@plaguewielder2037
@plaguewielder2037 2 года назад
great one and it helped me a lot, thanks , but why your last video is for 5 years ago? where are you?
@Jopolion007
@Jopolion007 7 лет назад
Hello, Francesc. Thanks a lot for your videos, they are really greate and useful for me as a new gopher. May I to ask you to cover the question about testing more difficult logick inside handlers? Like requests to third-side API's, saving some data in data base and something like that, what happens, then someone makes request to server. Although I find your lessons very cool, more complex examples would be quite good. Thanks again!
@JustForFunc
@JustForFunc 7 лет назад
+Jopolion007 it's coming soon :)
@AntonGalitsyn
@AntonGalitsyn 7 лет назад
+1, Francesc, this approach will work for stateless handlers for sure, but real apps often are more complex, you may have backing services, for example DB, MQ or object storage like s3. Also handlers often decorated with middlewares like auth. Unit testing will cover something, but your application router may have errors without functional tests with mocks or half-real backends in docker.
@StephenRayner
@StephenRayner 5 лет назад
excellent!
@ivan9074
@ivan9074 7 лет назад
awesome!!
@shrodeseva
@shrodeseva 4 года назад
Why is table based testing the idiomatic way in Go? Is there no way to do test setup / teardown functions to minimise repetition, and this is the alternative? Or is there some other benefit vs. just writing one function per test case like in other programming languages?
@lobobogard9236
@lobobogard9236 2 года назад
thnx so much the best tutorial I am doing my portafolio in one project in golang was very difficult to understand I found many diff ways to do the test but in the end I understand with you examples i hope you still doing more examples tester one question i have how resolve if I need inside of the method to access to database for information for continue my test? from mexico
@mizutv6747
@mizutv6747 6 лет назад
Thanks Francesc
@shamim520778774
@shamim520778774 5 лет назад
Awesome
@SuperBluesblues
@SuperBluesblues 4 года назад
Great Video . Thank you very much!! Very well explained.!! Can you make videos on Sql mocking. Thanks again!
@LewisCowles
@LewisCowles 5 лет назад
Have you considered testing exception and error cases first, then and only then testing desired cases?
@slavasemushin
@slavasemushin 4 года назад
Thanks for great video! I noticed that we used http.NewRequest() and also I found that there is also httptest.NewRequest() that looks more suitable in this case (see stackoverflow.com/questions/45682353/httptest-newrequest-vs-http-newrequest-which-one-to-use-in-tests-and-why). Is there a particular reason why we used the one from http package? Thanks!
@Acid31337
@Acid31337 7 лет назад
I'll try to test my WebSocket game server! (Hope it can be done without mock-everything exercise. :-) )
@loveleshsharma9938
@loveleshsharma9938 5 лет назад
That was really good. It would be more helpful if you can share how to test client side code which hits an http endpoint and gets a response...
@VsMVids
@VsMVids 7 лет назад
Nice video as usual! Is there any recommendation for naming test within the same pkg and not the same pkg. For example: * sum.go (package sum) * sum_test.go (package sum) * sum_external_test.go (package sumexternal) Or? Any suggestion?
@JustForFunc
@JustForFunc 7 лет назад
+VS VS I simply use package sum in my tests, except for the examples, which I call examples_test.go But your proposal doesn't sound wrong
@jishwash
@jishwash 7 лет назад
wooohooo
@sluongng
@sluongng 7 лет назад
Please do an episode with relational database
@jamesrylandmiller4378
@jamesrylandmiller4378 7 лет назад
How about an episode or two on gRPC and gRPC testing strategies?
@nleiva
@nleiva 7 лет назад
I just added some of the tips from this video on my gRPC testing if helps: github.com/nleiva/xrgrpc/blob/master/client_test.go. Test table, _test package name, etc... Very informative video as always.
@JensHausherr
@JensHausherr 7 лет назад
Thanks for the video. Any reason why you are using the regular http.NewRequest to create the request for testing instead of the httptest.NewRequest to create the test request?
@JustForFunc
@JustForFunc 7 лет назад
+Jens Hausherr I've never found it *that* useful so I forget about it It would remove a couple lines of error handling, yes
@JensHausherr
@JensHausherr 7 лет назад
Thanks for the response. I got the impression from the documentation that it adds some convenience features to the "real" NewRequest, but I'll still have to find a case where this makes a real difference
@code_stank
@code_stank 7 лет назад
Have you ever thought about streaming on twitch or something like that? That would be cool for something like a Q&A session or show us projects you're working on.
@JustForFunc
@JustForFunc 7 лет назад
Yeah, I thought about it, but I'm not sure it would be that useful really Plus my laptop would probably catch fire if I'm recording + writing code + livestreaming my screen
@mayurupadhyay3216
@mayurupadhyay3216 7 лет назад
Hello Francesc, thanks for this vedio.. would you plz share one which covers golang API ( POST ) load testing for performnc bnchmrk with different JSON inputs... Thanks again!
@tarasy
@tarasy 4 года назад
Quan començes a programar en Go i trobes aquest canal... Super ben explicat, thanks!
@kasinathkottukkal
@kasinathkottukkal 5 лет назад
Why both functions Ints() and Ints() needed? Just Ints() should be sufficient right?
@danielgil3131
@danielgil3131 6 лет назад
Hi, if we use the t.Run(tc.name, func(t *testing.T) { ...}) for creating subtests and inside the func we have several error condition checks but we want that after the first t.Errorf() is hit, do not follow the current iteration, it shall begin the next one, how could we do this? I've tried using break and continue but do not seems the solution. Should we use in this case t.Fatalf() instead? Best regards
@Wiintb
@Wiintb 2 года назад
Where did you get the gopher sticker? I want one!
@guild_navigator
@guild_navigator 7 лет назад
I've got the same EV RE320 mic. What's that XLR-USB interface you're using?
@pranaylonkar19
@pranaylonkar19 4 года назад
Hello, I have written some unit test cases & an init function to initialize some config variables (reading config from file). But it is breaking because when I run test cases, they call init function then throughs error (file not found). Is there any way to skip the execution of init function while running unit test cases?
@renanbastos93
@renanbastos93 4 года назад
How to test methods to consume external API?
@epnur
@epnur 7 лет назад
Thanks! Although it seems `TestDoubleHandler()` only has downsides vs `TestRouting()` Not sure what to think of it...
@JustForFunc
@JustForFunc 7 лет назад
+Benjamin Thomas unit testing is about testing a specific part, so ignoring the routing has its benefits as it makes the test more specific
@epnur
@epnur 7 лет назад
For sure, but we're only interested in the status code and the body of `net/http/httptest ResponseRecorder` and `net/http Response`, and feeding the arguments via building a url, so I still can't see how the recorder could be useful? Also per the docs, one could do this (to avoid testing the routing), so I'm even more puzzled by that ResponseRecorder! ```go srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { doubleHandler(w, r) })) ```
@matheusbica
@matheusbica 4 года назад
Hello, just one question, I am trying to a Handle that also receives a file parameter with the CSV content. I would like to know how I would add this file to the test? I am currently testing my web service like this: curl -F file=@path/matrix.csv "localhost:8080/sum" How could I add the file part to the request in a POST? Thank you!
@zaretix
@zaretix 6 лет назад
How would you test functions that execute html-templates?
@Muffins3001
@Muffins3001 5 лет назад
I've been wondering the same thing. In Django there is assertTemplateUsed (or something like that), but I haven't seen anything similar in go. Have you found anything on testing the right template?
@DavidGomez-ry5gr
@DavidGomez-ry5gr 5 лет назад
We like seeing you!!!, but I think it will be better to place your video to a place that do not block any of the code. BTW, keep the good work.
@user-zl5gi8sv7u
@user-zl5gi8sv7u 3 года назад
how is he not getting an error for using nil as type int?
@tehremotube
@tehremotube 3 года назад
Which extension are you using that highlights the coverage on the screen? I can not find it, but really want it!
@tehremotube
@tehremotube 3 года назад
Nevermind, I paused it and see its the official Go extension and you're using the Go: Toggle Test Coverage in Current Package. Love it!
@AparicioTomas
@AparicioTomas 4 года назад
This package is also pretty handy for testing and mocking HTTP traffic, especially traffic performed by third-party dependencies of your code: github.com/h2non/gock
@danielgil3131
@danielgil3131 6 лет назад
Hi Francesc, I've tried to create the examples_test.go for my project and everything works fine until I want to generate an example of a method associated to a type. Here is an example, this is the content of my main.go file: type TestType struct{ Name string } func (t *TestType) TestFunc() { fmt.Printf("hello %s", t.Name) } and this is the content of my examples_test.go file: func ExampleTestFunc() { tt := connectors.TestType{Name: "gopher"} tt.TestFunc() // Output: // hello gopher } and when I generate the documentation with godoc there is no mention of the ExampleTestFunc. How could we add examples in this case? P.S. you mention something about goconvey at the beginning of the video but you haven't talk about this tool, will you explain it in the second part of this testing series? Thanks in advance.
@arcticspacefox864
@arcticspacefox864 5 лет назад
R U in Berlin?
@siddheshtamhanekar3144
@siddheshtamhanekar3144 4 года назад
TestRouting tests whole flow from input to output then the testDoubleHandler becomes redundant do we still need it @justforfunc
@devillecodes
@devillecodes 4 года назад
Yes. Francesc did mention it briefly, but TestRouting should focus on testing that we call the correct handler function for the particular route, whereas the route handler test focusses on ensuring the actual behaviour of the handler function is correct. Including all of this in TestRouter makes it more difficult to debug any test failures. It's maybe not easy to see that with only one route, but it becomes a lot more difficult to debug as you add more routes. The more granular the tests the easier it is to immediately identify what broke and where to fix it. This also reminded me of a very wise mentor once telling me: A good quality test failing provides you with a near-perfect bug report.
@theofelippe3728
@theofelippe3728 6 лет назад
7:16 "2 + 3 is 4..." :)
@JustForFunc
@JustForFunc 6 лет назад
Off-by-one error!!
@jaxonpickett6372
@jaxonpickett6372 6 лет назад
How do you make the examples runnable in godoc? I've scoured the internet and the standard library for concrete examples with no luck.
@JustForFunc
@JustForFunc 6 лет назад
+Jaxon Pickett this only works for the stdlib since they use the playground Check the episode on contributing to the Go project for more detail
@StephenRayner
@StephenRayner 5 лет назад
godoc -http=:6060 -play
@jjuel5
@jjuel5 7 лет назад
When I move the tests into their own pacakge I get the error "Cannot find package 'path/to/package'" in any of: So any ideas on what I need to do?
@JustForFunc
@JustForFunc 7 лет назад
hard to tell by just your message ... could you create a repo? Also, check github.com/campoy/justforfunc and find the code for episode 16 there
@jjuel5
@jjuel5 7 лет назад
Well here is the file I am having issues with in the playground. play.golang.com/p/2cilZREUs1 Then it says: can't load package: package github.com/jjuel/JFF_Testing/sum: cannot find package "github.com/jjuel/JFF_Testing/sum" in any of: And that path is definitely in my $GOPATH. Do I need to install the sum package or is there something I am missing? I have verified my code is exactly the same as your repo except for obviously importing my local sum package. I do not currently have it in a github repo though. Thank you for the help!
@jjuel5
@jjuel5 7 лет назад
Okay so I don't know if it was the fact that I put them into a folder named sum or what, but it is working now.
@williamthomas8087
@williamthomas8087 6 лет назад
Thanks for following up with this, and stating the problem. I had the same issue!
@jusongchen
@jusongchen 5 лет назад
非常好的教学视频,谢谢你!
@StephenRayner
@StephenRayner 5 лет назад
godoc -http=:6060 -play
@vitoted2819
@vitoted2819 5 лет назад
How about an episode on crypto
@JustForFunc
@JustForFunc 5 лет назад
crypto: -graphy -currency -rchydism
@theyruinedyoutubeagain
@theyruinedyoutubeagain 7 лет назад
Francesc, do you mind sharing your vscode config, a la github.com/andreis/cfg/tree/master/vscode ? You can list your installed extensions by running `code --list-extensions`
@JustForFunc
@JustForFunc 7 лет назад
I just use vscode-go, that's pretty much it :) For more details: gist.github.com/campoy/97ac0623d2c1e893caa53ccf5655fa49
Далее
justforfunc #19: mastering io.Pipes
41:24
Просмотров 33 тыс.
REST API with Go, Chi and Handler Testing
34:57
Просмотров 20 тыс.
Go Testing By Example (GopherCon Australia 2023)
38:45
Go Tooling  in Action
41:51
Просмотров 115 тыс.
Golang Testing (full tutorial)
13:38
Просмотров 26 тыс.
justforfunc #37: sync.Pool from the pool
27:11
Просмотров 17 тыс.
Go Class: 15 Networking with HTTP
32:43
Просмотров 10 тыс.
🚀  TDD, Where Did It All Go Wrong (Ian Cooper)
1:03:55
Просмотров 553 тыс.
2 ways to test your Go HTTP server
14:15
Просмотров 2,1 тыс.
😮Новый ДИРЕКТОР Apple🍏
0:29
Просмотров 37 тыс.
Choose a phone for your mom
0:20
Просмотров 7 млн