This repository has been archived by the owner on Sep 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main_test.go
103 lines (82 loc) · 2.34 KB
/
main_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package main
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
func TestRoot(t *testing.T) {
req, err := http.NewRequest(http.MethodGet, "/", nil)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
rec := httptest.NewRecorder()
// serve the request
setupRouter().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("Expected status code %d but got %d", http.StatusOK, rec.Code)
}
var responseBody map[string]string
err = json.Unmarshal(rec.Body.Bytes(), &responseBody)
if err != nil {
t.Fatalf("Failed to unmarshal response body: %v", err)
}
expectedResponse := map[string]string{"message": "Hello, world!"}
if !reflect.DeepEqual(expectedResponse, responseBody) {
t.Errorf("Expected response %v but got %v", expectedResponse, responseBody)
}
}
func TestUsers(t *testing.T) {
req, err := http.NewRequest(http.MethodGet, "/users", nil)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
rec := httptest.NewRecorder()
// serve the request
setupRouter().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("Expected status code %d but got %d", http.StatusOK, rec.Code)
}
var users []User
err = json.Unmarshal(rec.Body.Bytes(), &users)
if err != nil {
t.Fatalf("Failed to unmarshal response body: %v", err)
}
if !reflect.DeepEqual(Users, users) {
t.Errorf("Expected response %v but got %v", Users, users)
}
}
func TestCreateUser(t *testing.T) {
payload := map[string]string{
"name": "Hank",
}
payloadBytes, _ := json.Marshal(payload)
req, err := http.NewRequest(http.MethodPost, "/users/create", bytes.NewReader(payloadBytes))
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
rec := httptest.NewRecorder()
// serve the request
setupRouter().ServeHTTP(rec, req)
if rec.Code != http.StatusCreated {
t.Errorf("Expected status code %d but got %d", http.StatusCreated, rec.Code)
}
var user User
err = json.Unmarshal(rec.Body.Bytes(), &user)
if err != nil {
t.Fatalf("Failed to unmarshal response body: %v", err)
}
expectedUser := User{
ID: len(Users),
Name: "Hank",
}
if user != expectedUser {
t.Errorf("Expected user %+v but got %+v", expectedUser, user)
}
lastUser := Users[len(Users)-1]
if len(Users) != lastUser.ID {
t.Errorf("Expected %d users in the list but got %d", lastUser.ID, len(Users))
}
}