php editor Baicao introduces you to a unit testing tool called "httptest", which can help developers test when retrying http requests. This tool can not only simulate various http requests, but also automatically retry requests to ensure the stability and reliability of the code. Using the httptest tool, developers can easily unit test http requests, and can easily retry requests to deal with network instability or other abnormal situations. The use of this tool can greatly improve development efficiency and reduce the possibility of errors. It is a tool worth trying for every PHP developer.
Question content
I'm trying to write unit tests for a component called HttpRequest
that wraps HTTP requests and handles response unmarshalling. Recently, I added a feature to this component that allows it to retry HTTP requests if it encounters a "connection refused" error on the first try.
To use the HttpRequest component, I call it once: user, err := HttpRequest[User](config)
. The config parameter contains all the necessary information to perform the request, such as URL, method, timeout, number of retries, and request body. It also unmarshals the response body into an instance of the specified type (User
in this case)
The problem arises when I try to test a scenario where the initial request fails with a "Connection refused" error but the second attempt succeeds. The retry happens inside the component, so I only make one call to the component.
I found it challenging to create unit tests for this situation because in order for the request to fail with "Connection refused" there doesn't need to be a listener on the port being called. The problem is that when using httptest
it always listens on the port when the instance is created, even when using httptest.NewUnstartedServer
. Therefore, I will never encounter a "connection refused" error in my client code after creating the httptest
instance.
However, I don't know which port it will listen on until I create the httptest
instance. httptest
always chooses a random port, and there is no way to programmatically specify a port. This means I can't make the HttpRequest call before creating the httptest
instance.
Does anyone have any ideas on how to effectively unit test this scenario?
Solution
newunstartedserver
Very simple:
func newunstartedserver(handler http.handler) *server { return &server{ listener: newlocallistener(), config: &http.server{handler: handler}, } }
If you choose a port that suits you, you can do this:
func mynewunstartedserver(port int, handler http.handler) *httptest.server { addr := fmt.sprintf("127.0.0.1:%d", port) l, err := net.listen("tcp", addr) if err != nil { addr = fmt.sprintf("[::1]::%d", port) if l, err = net.listen("tcp6", addr); err != nil { panic(fmt.sprintf("httptest: failed to listen on a port: %v", err)) } } return &httptest.server{ listener: l, config: &http.server{handler: handler}, } }
The code to create the listener is modified from httptest.newlocallistener
.
Another option is to implement the http.roundtripper
interface and create a http.client
using this roundtripper. The following is an example http/client_test.go copied from net/:
type recordingTransport struct { req *Request } func (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err error) { t.req = req return nil, errors.New("dummy impl") } func TestGetRequestFormat(t *testing.T) { setParallel(t) defer afterTest(t) tr := &recordingTransport{} client := &Client{Transport: tr} url := "http://dummy.faketld/" client.Get(url) // Note: doesn't hit network if tr.req.Method != "GET" { t.Errorf("expected method %q; got %q", "GET", tr.req.Method) } if tr.req.URL.String() != url { t.Errorf("expected URL %q; got %q", url, tr.req.URL.String()) } if tr.req.Header == nil { t.Errorf("expected non-nil request Header") } }
The above is the detailed content of Unit test http request retries using httptest. For more information, please follow other related articles on the PHP Chinese website!

The main differences between Golang and Python are concurrency models, type systems, performance and execution speed. 1. Golang uses the CSP model, which is suitable for high concurrent tasks; Python relies on multi-threading and GIL, which is suitable for I/O-intensive tasks. 2. Golang is a static type, and Python is a dynamic type. 3. Golang compiled language execution speed is fast, and Python interpreted language development is fast.

Golang is usually slower than C, but Golang has more advantages in concurrent programming and development efficiency: 1) Golang's garbage collection and concurrency model makes it perform well in high concurrency scenarios; 2) C obtains higher performance through manual memory management and hardware optimization, but has higher development complexity.

Golang is widely used in cloud computing and DevOps, and its advantages lie in simplicity, efficiency and concurrent programming capabilities. 1) In cloud computing, Golang efficiently handles concurrent requests through goroutine and channel mechanisms. 2) In DevOps, Golang's fast compilation and cross-platform features make it the first choice for automation tools.

Golang and C each have their own advantages in performance efficiency. 1) Golang improves efficiency through goroutine and garbage collection, but may introduce pause time. 2) C realizes high performance through manual memory management and optimization, but developers need to deal with memory leaks and other issues. When choosing, you need to consider project requirements and team technology stack.

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

ChooseGolangforhighperformanceandconcurrency,idealforbackendservicesandnetworkprogramming;selectPythonforrapiddevelopment,datascience,andmachinelearningduetoitsversatilityandextensivelibraries.

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use