测试无法捕获日志记录输出

时间:2020-01-09 01:01:18

标签: go testng microservices go-testing

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

如果用户输入已经存在的电子邮件,则UserRegister将返回错误日志(使用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是否按预期工作。

2 个答案:

答案 0 :(得分:2)

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

看一些例子,看看真正的回应来自哪里。 https://golang.org/pkg/net/http

答案 1 :(得分:2)

函数UserRegister永远不会写入res或设置状态。结果,您从res中的TestUserRegister中得到了一个空字符串。 content是一个空字符串,并且由于没有整数可转换,因此无法使用Atoi将空字符串转换为整数。

我只能解释会发生什么。我无法告诉您如何解决该问题,因为您没有解释自己想做什么或遇到问题。