I watched the tutorial DIY Golang Web Server: No Dependencies Needed! from Flo Woelki and want to create some test classes for it.
Goal:
- Add a user to
userCache
and test if the number of user inuserCache
is increased by 1
Steps:
- Start the server with
go run main.go
– see source code here - Open a second terminal and run the test
go test -run Test_PostUser
– this should add a user to the userCache - Open
http://127.0.0.1:8080/userlist
in the browser and check if the new users was added to the list
Problem
After running the test with go test -run Test_PostUser
the func Test_PostUser
should have added another user to the list. But if i open http://127.0.0.1:8080/userlist
in the browser it shows only 2 users
- Expected: userlist has 3 users after running
go test -run Test_PostUser
- Got: userlist has only 2 users (the initial users that are created a start)
Main func
This is the code inside main
func main() {
// Initialize users
userCache[1] = User{Name: "John"}
userCache[2] = User{Name: "Mandy"}
mux := http.NewServeMux()
mux.HandleFunc("POST /users", createUser)
mux.HandleFunc("GET /users/{id}", getUser) // https://youtu.be/eqvDSkuBihs?t=844
mux.HandleFunc("GET /userlist", getUserlist)
fmt.Println("Server listening to 8080")
http.ListenAndServe(":8080", mux)
}
Func to create a user
// https://youtu.be/eqvDSkuBihs?t=541
func createUser(w http.ResponseWriter, r *http.Request) {
var user User
err := json.NewDecoder(r.Body).Decode(&user) // pass memory address of created user struct
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if user.Name == "" {
http.Error(w, "Name is required", http.StatusBadRequest)
return
}
// without mutex this would not be thread safe
// writes and reads could happen at same time --> race condition
cacheMutex.Lock()
userCache[len(userCache)+1] = user
cacheMutex.Unlock()
w.WriteHeader(http.StatusNoContent)
}
Test func
My test method that should add a user to usercache
func Test_PostUser(t *testing.T) {
// Define the URL and the data to which the POST request will be sent
url := "http://127.0.0.1:8080/users"
data := User{Name: "Max"}
// Marshal the data to JSON
jsonData, err := json.Marshal(data)
if err != nil {
t.Errorf("Error marshalling JSON: %v", err)
}
// Create a new POST request
req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(jsonData))
if err != nil {
t.Errorf("Error creating request: %v", err)
}
// Set the content type header to application/json
req.Header.Set("Content-Type", "application/json")
// Create an HTTP client and send the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
t.Errorf("Error sending request: %v", err)
}
defer resp.Body.Close()
}
Question
- What am i missing?
- Why is the user not added to the usercache or why is the user not part of
GET /userlist
?
See full source code here