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/[email protected]&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: ""の解析:無効な構文
なぜ応答を変換できないのですか?
チェックされたスレッド:
文字列を整数に変換するこのGolangコードが失敗するのはなぜですか。
編集:@ chmike回答の後。
これはマイクロサービスの一部です。すべての応答はに書き込まれAPI-Gateway
ます。関数を使用する。
しかし、ここでは単体テストを実行しUserRegister
て、期待どおりに機能するかどうかを確認したいだけです。
この関数はステータスのUserRegister
書き込みres
や設定を行いません。結果として、から空の文字列を取得res
しTestUserRegister
ます。content
空の文字列であり、変換する整数がAtoi
ないため、空の文字列から整数への変換は失敗します。
私は何が起こるのかしか説明できません。あなたが何をしたいのか、質問に答えたくないので、問題を解決するために何をすべきかを言うことはできません。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加