【问题标题】:How to test a Oauth2.0 resource of server如何测试服务器的Oauth2.0资源
【发布时间】:2021-11-06 00:09:09
【问题描述】:

我想编写验证正确文档以到达第三方服务器的Oauth2.0的测试,我应该如何完成伪代码?

import (
    "net/http"
    "net/http/httptest"
}

func testAuthServer(t *testing.T) {
    form := url.Values{}
    form.Set(...)

    r := httptest.NewRequest(http.MethodPost, authUrl, strings.NewReader(form.Encode()))
    r.Header.Set("Content-Type", "application/x-www-form-urlencoded")

    w := httptest.NewRecorder()

    // test the auth server

    if w.Code != http.StatusOK {
        ...
    }
}

【问题讨论】:

  • 只是为了确定:您可以断言发送到服务器的正文是预期的吗?你不关心服务器的URL?
  • 抱歉,authUrl 不是本地测试服务器,是现有的第三方资源。
  • 在这种情况下,您可能可以使用像 gock 这样的工具。我更新了答案。

标签: go go-testing


【解决方案1】:

您可以依赖第三方库来模拟资源。你可以看看gock

func TestServer(t *testing.T) {
    defer gock.Off()

    authURL := "http://third-party-resource.com"
    form := url.Values{}
    form.Add("foo", "bar")

    // Create the mock of the third-party resource. We assert that the code
    // calls the resource with a POST request with the body set to "foo=bar"
    gock.New(authURL).
        Post("/").
        BodyString("foo=bar").
        Reply(200)

    r, err := http.NewRequest(http.MethodPost, authURL, strings.NewReader(form.Encode()))
    if err != nil {
        t.Fatal(err)
    }

    r.Header.Set("Content-Type", "application/x-www-form-urlencoded")

    c := http.Client{}
    _, err = c.Do(r)
    if err != nil {
        t.Fatal(err)
    }

    if !gock.IsDone() {
        // The mock has not been called.
        t.Fatal(gock.GetUnmatchedRequests())
    }
}

【讨论】:

    【解决方案2】:

    最后我用普通的http客户端解决了这个问题。

    import (
        "net/http"
    }
    
    func testAuthServer(t *testing.T) {
        form := url.Values{}
        form.Set(...)
    
        authReq := http.NewRequest(http.MethodPost, authUrl, strings.NewReader(form.Encode()))
        authReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    
        authClient, _ := http.Client{}
        authResp, _ := authClient.Do(authReq)
    
        if authResp.Code != http.StatusOK {
            ...
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-27
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      • 2012-05-02
      • 2013-06-02
      • 2013-02-10
      • 1970-01-01
      相关资源
      最近更新 更多