首頁  >  文章  >  後端開發  >  表單變數在測試中不可用

表單變數在測試中不可用

PHPz
PHPz轉載
2024-02-06 08:09:07354瀏覽

表單變數在測試中不可用

問題內容

我是 Go 新手。我使用 DeepMap OpenAPI 產生器和使用 pgxpool 的 Postgres 編寫了一個基於 Echo 伺服器建構的 API 伺服器。它運作良好並且已經使用了一年,但這並不意味著它寫得正確:)。

測試伺服器一直使用 shell 腳本和一系列 Curl 調用,效果很好,但我正在嘗試更新測試以使用 Go 的測試框架。我已經進行了一些基本測試,但是任何需要表單值的東西都不起作用——處理程序函數看不到任何表單值,所以我猜請求沒有封裝它們,但我不明白為什麼。

下面是CreateNode()方法的第一部分,它實作了產生的API介面的一部分。我省略了身體;失敗的部分是上下文中出現的內容。

func (si *ServerImplementation) CreateNode(ctx echo.Context) error {
        vals, err := ctx.FormParams()
        info("In CreateNode() with FormParams %v", vals)
        ...

這是測試函數:

func TestCreateNode(t *testing.T) {
        // not the actual expected return
        expected := "Node created, hooray\n"

        // initialize database with current schema
        api := &ServerImplementation{}
        err := api.Init("host=localhost database=pgx_test user=postgres")
        if err != nil {
                t.Fatal(err)
        }

        // handle teardown in this deferred function
        t.Cleanup(func() {
                t.Log("Cleaning up API")
                api.Close()
        })

        // start up webserver
        e := echo.New()

        // this didn't work either
        //f := make(url.Values)
        //f.Set("name", "node1")
        //req := httptest.NewRequest(http.MethodPost, "/nodes/", strings.NewReader(f.Encode()))
        //req.Header.Add("Content-Type", "multipart/form-data")

        req := httptest.NewRequest(echo.POST, "/", strings.NewReader(`{"name":"node1"}`))
        req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
        rec := httptest.NewRecorder()
        ctx := e.NewContext(req, rec)

        if assert.NoError(t, api.CreateNode(ctx)) {
                assert.Equal(t, http.StatusOK, rec.Code)
                assert.Equal(t, expected, rec.Body.String())
        }
}

我不會打擾完整的測試輸出,因為當 CreateNode() 沒有收到任何值時,一切都會失敗:

=== RUN   TestCreateNode
2023/08/26 15:09:43 INFO:    In CreateNode() with FormParams map[]
2023/08/26 15:09:43 INFO:    No name provided in CreateNode()

據我所知,我正在密切關注類似的範例。我希望這是足夠的細節,但不想用不必要的支援程式碼來超載問題。

節點的端點是/nodes ,API 的基本URL 是/api ,但這兩者都沒有在這裡反映出來,從我看到的例子來看它們是不必要的。 Echo 的範例總是使用 / 作為端點。


正確答案


好吧,我是叮噹。

我把很多例子拼湊在一起,試圖讓一些東西發揮作用,只有一次我在測試功能中嘗試了以下操作:

req.Header.Set("Testing", "Yes")

並在 CreateNode 中將其彈出:

info("Header: %v", ctx.Request().Header)

這給了我:

2023/08/26 20:04:36 INFO:    Header: map[Content-Type:[application/x-www-form-urlencoded] Testing:[Yes]]

我看到該請求進展順利,這與我形成請求的方式有關。

我再次檢查了範例,意識到我正在根據一個範例設定表單值,但從另一個範例設定內容類型。作品如下:

f := make(url.Values)
        f.Set("name", "node1")
        req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(f.Encode()))
        req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationForm)

當然,透過 JSON 執行此操作是行不通的,因為 CreateNode() 不是如何解析傳入資訊的。

這只是我的馬虎!

以上是表單變數在測試中不可用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除