Socialify

Folder ..

Viewing user_test.go
71 lines (64 loc) • 2.4 KB

 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
package tests

import (
	"encoding/json"
	"net/http"
	"pagoda/config"
	"pagoda/database"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestRegister(t *testing.T) {
	registerURL := "/user/register"
	headers := map[string]string{"Content-Type": "application/x-www-form-urlencoded"}

	tests := []testCase{
		{
			description:  "register new user with valid data",
			method:       http.MethodPost,
			url:          registerURL,
			headers:      headers,
			formData:     buildFormData(database.User{Username: "testuser", Email: "[email protected]", Password: "password"}),
			expectedCode: http.StatusCreated,
			validate: func(t *testing.T, resp *http.Response, body []byte) {
				var response config.SuccessResponse
				err := json.Unmarshal(body, &response)
				require.NoError(t, err, "Failed to unmarshal response body")

				var user database.User
				userJSON, err := json.Marshal(response.Data)
				require.NoError(t, err, "Failed to marshal user data")
				err = json.Unmarshal(userJSON, &user)
				require.NoError(t, err, "Failed to unmarshal user data")

				assert.Equal(t, "testuser", user.Username, "Username mismatch")
				assert.Equal(t, "[email protected]", user.Email, "Email mismatch")
				assert.NotEmpty(t, user.ID, "User ID should not be empty")
				assert.NotEmpty(t, user.JoinedAt, "JoinedAt should not be empty")
				assert.Empty(t, user.Password, "Password should not be returned")
			},
		},
		{
			description:  "register new user with invalid data",
			method:       http.MethodPost,
			url:          registerURL,
			headers:      headers,
			formData:     buildFormData(database.User{Username: "anotheruser", Email: "[email protected]"}),
			expectedCode: http.StatusBadRequest,
		},
		{
			description:  "register new user with existing username",
			method:       http.MethodPost,
			url:          registerURL,
			headers:      headers,
			formData:     buildFormData(database.User{Username: "testuser", Email: "[email protected]", Password: "password"}),
			expectedCode: http.StatusNotAcceptable,
		},
		{
			description:  "register new user with existing email",
			method:       http.MethodPost,
			url:          registerURL,
			headers:      headers,
			formData:     buildFormData(database.User{Username: "anotheruser", Email: "[email protected]", Password: "password"}),
			expectedCode: http.StatusNotAcceptable,
		},
	}

	runTests(t, tests)
}