0

I am trying to test my UserRegister functionality, it takes http request.

If user enters already existing email, UserRegister returns an error log (using 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")


}

In my test module, I used following.

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))
    }

}

Result : Error parsing response strconv.Atoi: parsing "": invalid syntax

Why response can not be converted?

Checked threads:

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

Edit : after @chmike answer.

This is a part of microservice. All the responses are written to API-Gateway. Using a function.

But here I just want to perform unit test and check whether my UserRegister works as expected.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Sachith Muhandiram
  • 2,819
  • 10
  • 45
  • 94
  • 3
    Aou are parsing body of your response as string. `strconv.Atoi` posted in your code has nothing to do with log. Looks like you return empty body response in case of error. Share full code for handler if you need more help. – Dmitry Harnitski Jan 09 '20 at 02:31

2 Answers2

2

The http response you are reading is not the response to your request. You create a response and expect it to have something in it. it will not. So you end up trying to create an integer from an empty string.

Look at some examples to see where the real response would come from. https://golang.org/pkg/net/http

Sean F
  • 4,344
  • 16
  • 30
2

The function UserRegister never writes to res or sets the status. As a consequence you get an empty string from res in TestUserRegister. content is an empty string and the conversion of an empty string to an integer with Atoi fails since there is no integer to convert.

I can only explain what happens. I can’t tell you what to do to fix the problem because you don’t explain what you want to do or get in the question.

chmike
  • 20,922
  • 21
  • 83
  • 106
  • added details to the question. – Sachith Muhandiram Jan 09 '20 at 08:04
  • 1
    @SachithMuhandiram the given details doesn’t help. You must provide a feedback on the success or failure in the `UserRegister` function. You must decide what this feedback is. It could be the status set to 200 in case of success and another value in case of failure, or you could write data in `res`. In the test function you should test the status or the content according to the feedback you choose to use. If you use `Atoi`, I suppose you expected the feedback to be an integer provided in the content of the response. Why don’t you write that integer in `res` in the `UserRegister` function ? – chmike Jan 09 '20 at 08:11
  • Thanks for the guide. It seems I will have to restructure my app with setting response and decision making on `statusCode` – Sachith Muhandiram Jan 09 '20 at 08:14