测试无法捕获日志输出

Test fails to capture logging output

我正在尝试测试我的 UserRegister 功能,需要 http 请求。

如果用户输入已经存在的电子邮件,UserRegister returns 错误日志(使用 logrus)。

logs "github.com/sirupsen/logrus"

func UserRegister(res http.ResponseWriter, req *http.Request) {

    requestID := req.FormValue("uid")
    email := req.FormValue("email")

    logs.WithFields(logs.Fields{
        "Service":  "User Service",
        "package":  "register",
        "function": "UserRegister",
        "uuid":     requestID,
        "email":    email,
    }).Info("Received data to insert to users table")

    // check user entered new email address
    hasAccount := checkemail.Checkmail(email, requestID) // returns true/false

    if hasAccount != true { // User doesn't have an account

        db := dbConn()

        // Inserting token to login_token table
        insertUser, err := db.Prepare("INSERT INTO users (email) VALUES(?)")
        if err != nil {
            logs.WithFields(logs.Fields{
                "Service":  "User Service",
                "package":  "register",
                "function": "UserRegister",
                "uuid":     requestID,
                "Error":    err,
            }).Error("Couldnt prepare insert statement for users table")
        }
        insertUser.Exec(email)
        defer db.Close()
        return
    } // user account created

    logs.WithFields(logs.Fields{
        "Service":  "User Service",
        "package":  "register",
        "function": "UserRegister",
        "uuid":     requestID,
        "email":    email,
    }).Error("User has an account for this email")


}

在我的测试模块中,我使用了以下内容。

func TestUserRegister(t *testing.T) {
    rec := httptest.NewRecorder()
    req, _ := http.NewRequest("POST", "http://localhost:7071/register?email=sachit45345h@gmail.com&uid=sjfkjsdkf9w89w83490w", nil)

    UserRegister(rec, req)

    expected := "User has an account for this email"

    res := rec.Result()
    content, err := ioutil.ReadAll(res.Body)

    if err != nil {
        t.Error("Couldnt read body", err)
    }

    val, err := strconv.Atoi(string(bytes.TrimSpace(content)))

    if err != nil {
        log.Println("Error parsing response", err)
    }
    if string(val) != expected { 
        t.Errorf("Expected %s, got %s", expected, string(content))
    }

}

结果:解析响应时出错strconv.Atoi:解析“”:语法无效

为什么响应不能转换?

已检查的主题:

Why is this Golang code to convert a string to an integer failing.

编辑:@chmike 回答后。

这是微服务的一部分。所有回复都写到API-Gateway。使用函数。

但这里我只想执行单元测试并检查我的 UserRegister 是否按预期工作。

您正在阅读的 http 响应不是对您的请求的响应。您创建一个响应并期望它包含一些内容。它不会。所以你最终试图从一个空字符串创建一个整数。

查看一些示例,了解真正的响应来自何处。 https://golang.org/pkg/net/http

函数 UserRegister 从不写入 res 或设置状态。结果,您从 TestUserRegister 中的 res 得到了一个空字符串。 content 是一个空字符串,使用 Atoi 将空字符串转换为整数失败,因为没有要转换的整数。

我只能解释发生了什么。我无法告诉你如何解决问题,因为你没有解释你想做什么或进入问题。