Skip to content

Instantly share code, notes, and snippets.

@santosh
Created April 29, 2020 18:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save santosh/1d37aac8044d017503db77c0dd93205b to your computer and use it in GitHub Desktop.
Save santosh/1d37aac8044d017503db77c0dd93205b to your computer and use it in GitHub Desktop.
How to test this func in handler.go?

I can run those tests on my local machine where I have mongo instance spinned up. But what about CI/CD services like Travis-CI?

How do I approach this?

func Registration(w http.ResponseWriter, r *http.Request) {
var res model.ResponseResult
var user model.User
w.Header().Set("Content-Type", "application/json")
jsonDecoder := json.NewDecoder(r.Body)
jsonDecoder.DisallowUnknownFields()
defer r.Body.Close()
// check if there is proper json body or error
if err := jsonDecoder.Decode(&user); err != nil {
res.Error = err.Error()
// return 400 status codes
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(res)
return
}
// Connect to mongodb
client, _ := mongo.NewClient(options.Client().ApplyURI("mongodb://127.0.0.1:27017"))
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err := client.Connect(ctx)
if err != nil {
panic(err)
}
defer client.Disconnect(ctx)
// Check if username already exists in users datastore, if so, 400
// else insert user right away
collection := client.Database("test").Collection("users")
filter := bson.D{{"username", user.Username}}
var foundUser model.User
err = collection.FindOne(context.TODO(), filter).Decode(&foundUser)
if foundUser.Username == user.Username {
res.Error = UserExists
// return 400 status codes
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(res)
return
}
pass, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
if err != nil {
res.Error = err.Error()
// return 400 status codes
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(res)
return
}
user.Password = string(pass)
insertResult, err := collection.InsertOne(context.TODO(), user)
if err != nil {
res.Error = err.Error()
// return 400 status codes
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(res)
return
}
// return 200
w.WriteHeader(http.StatusOK)
res.Result = fmt.Sprintf("%s: %s", UserCreated, insertResult.InsertedID)
json.NewEncoder(w).Encode(res)
return
}
func TestRegistration(t *testing.T) {
t.Run("test if user already exists", func(t *testing.T) {
jsonStr := []byte(`{"username":"santosh", "password": "password"}`)
requestOne, _ := http.NewRequest("POST", "/register", bytes.NewBuffer(jsonStr))
requestTwo, _ := http.NewRequest("POST", "/register", bytes.NewBuffer(jsonStr))
responseOne := httptest.NewRecorder()
responseTwo := httptest.NewRecorder()
Registration(responseOne, requestOne)
Registration(responseTwo, requestTwo)
assertStatus(t, responseTwo.Code, http.StatusBadRequest)
})
t.Run("test if returns 200 on success", func(t *testing.T) {
jsonStr := []byte(`{"username":"john", "password": "password"}`)
request, _ := http.NewRequest("POST", "/register", bytes.NewBuffer(jsonStr))
response := httptest.NewRecorder()
Registration(response, request)
got := response.Code
want := http.StatusOK
assertStatus(t, got, want)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment