php小編百草為大家介紹了一個名為"httptest"的單元測試工具,它能夠幫助開發者在進行http請求重試時進行測試。這個工具不僅可以模擬各種http請求,還能夠自動重試請求,以確保程式碼的穩定性和可靠性。使用httptest工具,開發者可以輕鬆進行http請求的單元測試,並且可以輕鬆地對請求進行重試,以應對網路不穩定或其他異常情況。這種工具的使用能大幅提升開發效率,減少出錯的可能性,是每個php開發者都值得嘗試的工具。
問題內容
我正在努力為名為 HttpRequest
的元件編寫單元測試,該元件包裝 HTTP 請求並處理回應解組。最近,我為該元件添加了一項功能,允許它在第一次嘗試時遇到「連接被拒絕」錯誤時重試 HTTP 請求。
要使用 HttpRequest 元件,我這樣呼叫一次:user, err := HttpRequest[User](config)
。 config 參數包含執行請求的所有必要訊息,例如 URL、方法、逾時、重試次數和請求正文。它也將回應正文解組為指定類型的實例(在本例中為 User
)
當我嘗試測試初始請求失敗並出現「連線被拒絕」錯誤但第二次嘗試成功的場景時,就會出現問題。重試發生在元件內部,因此我只對元件進行一次呼叫。
我發現為這種情況建立單元測試具有挑戰性,因為為了使請求因「連接被拒絕」而失敗,被呼叫的連接埠上不需要有偵聽器。問題是,當使用 httptest
時,它總是在建立實例時偵聽端口,即使使用 httptest.NewUnstartedServer
也是如此。因此,在建立 httptest
實例後,我的客戶端程式碼中將永遠不會遇到「連線被拒絕」錯誤。
但是,在建立 httptest
實例之前,我不知道它將偵聽哪個連接埠。 httptest
總是選擇一個隨機端口,並且無法以程式設計方式指定一個端口。這意味著我無法在創建 httptest
實例之前進行 HttpRequest 呼叫。
有人對如何有效地對這種場景進行單元測試有任何想法嗎?
解決方法
newunstartedserver
非常簡單:
func newunstartedserver(handler http.handler) *server { return &server{ listener: newlocallistener(), config: &http.server{handler: handler}, } }
如果自己選擇一個連接埠適合您,您可以這樣做:
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}, } }
建立監聽器的程式碼修改自httptest.newlocallistener
。
另一個選擇是實作 http.roundtripper
介面並使用此 roundtripper 建立一個 http.client
。以下是從 net/ 複製的範例http/client_test.go:
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") } }
以上是使用 httptest 單元測試 http 請求重試的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Toensureinitfunctionsareeffectiveandmaintainable:1)Minimizesideeffectsbyreturningvaluesinsteadofmodifyingglobalstate,2)Ensureidempotencytohandlemultiplecallssafely,and3)Breakdowncomplexinitializationintosmaller,focusedfunctionstoenhancemodularityandm

goisidealforbeginnersandsubableforforcloudnetworkservicesduetoitssimplicity,效率和concurrencyFeatures.1)installgromtheofficialwebsitealwebsiteandverifywith'.2)

開發者應遵循以下最佳實踐:1.謹慎管理goroutines以防止資源洩漏;2.使用通道進行同步,但避免過度使用;3.在並發程序中顯式處理錯誤;4.了解GOMAXPROCS以優化性能。這些實踐對於高效和穩健的軟件開發至關重要,因為它們確保了資源的有效管理、同步的正確實現、錯誤的適當處理以及性能的優化,從而提升軟件的效率和可維護性。

Goexcelsinproductionduetoitsperformanceandsimplicity,butrequirescarefulmanagementofscalability,errorhandling,andresources.1)DockerusesGoforefficientcontainermanagementthroughgoroutines.2)UberscalesmicroserviceswithGo,facingchallengesinservicemanageme

我們需要自定義錯誤類型,因為標準錯誤接口提供的信息有限,自定義類型能添加更多上下文和結構化信息。 1)自定義錯誤類型能包含錯誤代碼、位置、上下文數據等,2)提高調試效率和用戶體驗,3)但需注意其複雜性和維護成本。

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建築物內currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用輔助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

Atom編輯器mac版下載
最受歡迎的的開源編輯器

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中