【问题标题】:How to end to end/integration test a Go app that use a reverse proxy to manage subdomain?如何端到端/集成测试使用反向代理管理子域的 Go 应用程序?
【发布时间】:2020-10-26 09:37:55
【问题描述】:

我有一个使用 Gin gonic 的 Go 应用程序和一个 Nginx 反向代理,它们将流量发送到 domain.com 上的另一个应用程序,并将所有 *.domain.com 子域流量直接发送到我的 Go 应用程序。

然后我的 Go 应用程序有一个中间件,它将读取 nginx 从 Context 传递给它的主机名,并允许我的处理程序知道正在请求哪个子域,并为所述子域返回正确的数据和 cookie。

这是一个非常简单的设置,从我在 postman 中的测试来看,它似乎工作正常,因为我所有的子域中的所有路由都是相同的,所以这样我只能为所有子域使用一个路由器,而不是每个子域一个路由器。

现在,当我尝试进行端到端测试时,我的大问题就来了。

我正在这样设置我的测试:

  router := initRouter()
  w := httptest.NewRecorder()
  req, _ := http.NewRequest("POST", "/api/login", bytes.NewBuffer(jsonLogin))
  req.Header.Set("Content-Type", "application/json")
  router.ServeHTTP(w, req)
  assert.Equal(t, 200, w.Code)

initRouter() 返回一个 gin 引擎,其中加载了我的所有路由和中间件,其余作为基本测试设置。

显然测试将失败,因为 gin 上下文永远不会从上下文中接收子域,并且表现得好像所有内容都来自 localhost:8000。

有没有办法:

  • “模拟”一个子域,以便路由器认为呼叫来自 foo.localhost.com 而不是 localhost

  • 设置我的测试套装,以便通过 nginx 路由测试请求。我更喜欢解决方案 1,因为这样设置/维护会很麻烦。

编辑:

根据 httptest 文档,我尝试将 foo.localhost 硬编码为 NewRequest 的参数,但它并没有像我需要的那样表现:

NewRequest 返回一个新的传入服务器请求,适合传递给 http.Handler 进行测试。

目标是 RFC 7230 “请求目标”:它可以是路径或绝对 URL。如果 target 是绝对 URL,则使用 URL 中的主机名。否则,使用“example.com”。

当硬编码 http://foo.localhost.com/api/login 或 foo.localhost.com/api/login 作为请求目标时,它直接将其传递给我的路由器“foo.localhost.com/api/login”,而 nginx 只会点击 /api/直接登录并从c.Request.Host解析

编辑 2:

我目前正在探索使用手动设置主机:

req.Header.Set("Host", "foo.localhost")

【问题讨论】:

  • 嗨,欢迎来到 StackOverflow。请你稍微修改一下你的帖子。标题必须是一个问题 - 我不太了解上下文,无法为您构建它。
  • FTR:如果你不通过 nginx,你几乎不能称之为端到端测试。
  • 是的。我想就我的 go 应用程序的范围而言,这是端到端/集成测试?

标签: go nginx testing integration-testing


【解决方案1】:

http.NewRequest 返回的请求不适合直接传递给ServeHTTP。请改用 httptest.NewRequest 返回的。

直接设置the Host field

package main

import (
    "net/http"
    "net/http/httptest"
    "testing"
)

func TestHelloWorld(t *testing.T) {
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        if r.Host != "foobar" {
            t.Errorf("Host is %q, want foobar", r.Host)
        }
    })

    w := httptest.NewRecorder()
    r := httptest.NewRequest("GET", "/api/login", nil)
    r.Host = "foobar"

    mux.ServeHTTP(w, r)
}

【讨论】:

  • 哦,太好了。 Works.my 语法 (req.Header.Set("Host", "foo.localhost") ) 不正确。非常感谢。
猜你喜欢
  • 2020-12-29
  • 2016-03-02
  • 2020-01-06
  • 1970-01-01
  • 2021-07-22
  • 1970-01-01
  • 1970-01-01
  • 2020-02-13
  • 1970-01-01
相关资源
最近更新 更多