How to use Put method of user_test Package

Best Mock code snippet using user_test.Put

Run Mock automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

user_test.go

Source: user_test.go Github

copy
1package user_test
2
3import (
4	"encoding/json"
5	"fmt"
6	genid "github.com/srlemon/gen-id"
7	"github.com/stretchr/testify/assert"
8	"testing"
9	"user_center/app"
10	"user_center/app/Http/Controllers/API/Admin/Context/User/DetailUser"
11	"user_center/app/Http/Controllers/API/Admin/Context/User/ForbiddenUser"
12	"user_center/app/Http/Controllers/API/Admin/Context/User/ListUser"
13	"user_center/app/Http/Controllers/API/Admin/Context/User/StoreUser"
14	"user_center/app/Http/Controllers/API/Admin/Context/User/UpdateUser"
15	"user_center/app/Http/Controllers/API/Admin/Responses"
16	"user_center/app/Model"
17	"user_center/boot"
18	"user_center/pkg/db"
19	"user_center/pkg/test"
20)
21
22var httptest *test.Http
23
24func TestMain(m *testing.M) {
25	boot.SetInTest()
26	boot.Boot()
27	httptest = test.New(app.GetEngineRouter())
28	m.Run()
29}
30
31// go test -v test/Feature/Admin/User/user_test.go -test.run TestStore
32func TestStore(t *testing.T) {
33	w := httptest.Post("/api/admin/user/store", StoreUser.Req{
34		Account:  genid.NewGeneratorData().Name,
35		Phone:    genid.NewGeneratorData().PhoneNum,
36		Email:    genid.NewGeneratorData().Email,
37		Passwd:   "123456",
38		Nickname: genid.NewGeneratorData().GeneratorName(),
39		Birthday: "2021-11-12 00:00:00",
40	})
41	fmt.Println(w.Body)
42	//t.Logf("resp: %s", w.Body)
43	//assert.Equal(t, w.Code, 200)
44	//r := Responses.Response{}
45	//err = json.Unmarshal(w.Body.Bytes(), &r)
46	//assert.Nil(t, err)
47	//assert.Equal(t, 0, r.Code)
48
49}
50
51// go test -v test/Feature/Admin/User/user_test.go -test.run TestDetail
52func TestDetail(t *testing.T) {
53
54	resp := httptest.Get("/api/admin/user/detail", DetailUser.Req{
55		ID: 8,
56	})
57	fmt.Println(resp.Body)
58}
59
60func TestFindPasswordToken(t *testing.T) {
61	user := &Model.UserAuth{}
62	err := db.Def().First(&user).Error
63	assert.Nil(t, err)
64	assert.NotEmpty(t, user.Phone)
65	resp := httptest.Get("/api/auth/find/password/token", StoreUser.Req{
66		Phone: user.Phone,
67	})
68	t.Logf("resp: %s", resp.Body)
69	assert.Equal(t, resp.Code, 200)
70	r := Responses.Response{}
71	err = json.Unmarshal(resp.Body.Bytes(), &r)
72	if body, ok := r.Body.(map[string]interface{}); !ok {
73		t.Error("响应处理失败", body)
74		t.FailNow()
75	} else {
76		assert.NotEmpty(t, body["find_password_token"])
77	}
78}
79
80// go test -v test/Feature/Admin/User/user_test.go -test.run TestList
81func TestList(t *testing.T) {
82	resp := httptest.Get("/api/admin/user/list", ListUser.Req{
83		Page: 1,
84		Size: 2,
85	})
86	fmt.Println(resp.Body)
87}
88
89// go test -v test/Feature/Admin/User/user_test.go -test.run TestUpdate
90func TestUpdate(t *testing.T) {
91	w := httptest.Call("PUT", "/api/admin/user/update", UpdateUser.Req{
92		ID:       3,
93		Account:  genid.NewGeneratorData().Name,
94		Phone:    genid.NewGeneratorData().PhoneNum,
95		Email:    genid.NewGeneratorData().Email,
96		Nickname: genid.NewGeneratorData().GeneratorName(),
97		Birthday: "2021-11-13 00:00:00",
98	})
99	fmt.Println(w.Body)
100}
101
102// go test -v test/Feature/Admin/User/user_test.go -test.run TestForbidden
103func TestForbidden(t *testing.T) {
104	w := httptest.Call("POST", "/api/admin/user/forbidden", ForbiddenUser.Req{
105		ID:          1,
106		IsForbidden: 2,
107	})
108	fmt.Println(w.Body)
109}
110
Full Screen

Do_user.go

Source: Do_user.go Github

copy
1//操作数据库的方法
2
3package db
4
5import (
6	"fmt"
7	"github.com/emicklei/go-restful"
8	"io"
9	"net/http"
10	"strconv"
11)
12
13
14// GET http://localhost:8080/users
15//查询所有用户
16
17func  FindAllUsers(request *restful.Request, response *restful.Response) {
18
19	stmt,_:= Mysqldb.Prepare(`select * from user_test`)
20	defer stmt.Close()
21	rows,err:=stmt.Query()
22	if err!=nil {
23		fmt.Println("插入错误")
24	}
25	user:= User{}
26	Usr :=make([]User,0)
27	for rows.Next() {
28
29		rows.Scan(&user.Id,&user.Name,&user.Age,&user.Gender,&user.Grade,&user.Address)
30		Usr =append(Usr,user)
31	}
32	fmt.Println(Usr)
33	response.WriteEntity(Usr)
34	/*
35	   list := []User{}
36	   	for _, each := range u.users {
37	   		list = append(list, each)
38	   	}
39	   	response.WriteEntity(list)
40
41	*/
42}
43
44// GET http://localhost:8080/users/lastid
45//根据id查询用户
46
47func  FindUser(request *restful.Request, response *restful.Response) {
48	id := request.PathParameter("user-id")
49	ID, _:= strconv.Atoi(id)//int Id
50	user:=User{}
51	stmt,_:= Mysqldb.Prepare(`select id,name,age,gender,grade,address from user_test where id=?`)
52	defer stmt.Close()
53	_,err:=stmt.Exec(ID)
54	err1:= stmt.QueryRow(ID).Scan(&user.Id, &user.Name, &user.Age, &user.Gender, &user.Grade, &user.Address)
55	if err!=nil {
56		fmt.Println("执行查询错误")
57	}else {
58		fmt.Printf("%d,%s,%d,%s,%d,%s\n",user.Id,user.Name,user.Age,user.Gender,user.Grade,user.Address)
59	}
60	if err1!=nil{
61		fmt.Println("查询扫描错误")
62		io.WriteString(response.ResponseWriter,"用户不能找到")
63	}else {
64		response.WriteEntity(user)
65	}
66
67}
68
69// PUT http://localhost:8080/users/1
70//根据id更新用户
71
72func  UpdateUser(request *restful.Request, response *restful.Response) {
73	id := request.PathParameter("user-id")
74	ID, _:= strconv.Atoi(id)//int id
75
76	stmt,_:=Mysqldb.Prepare(`update user_test set address=? where id=?`)
77	defer stmt.Close()
78	_,err:=stmt.Exec("根据id更新的地点",ID)
79	if err!=nil {
80		fmt.Println("更新失败")
81	}else {
82		fmt.Printf("id=%d所在行更新成功\n",ID)
83		io.WriteString(response.ResponseWriter,"更新完成")
84	}
85
86	/*usr := new(User)
87	err := request.ReadEntity(&usr)
88	if err == nil {
89		u.users[usr.id] =*usr
90		response.WriteEntity(usr)
91	} else {
92		response.WriteError(http.StatusInternalServerError, err)
93	}*/
94}
95
96// POST http://localhost:8080/users/add
97//末尾行创建用户 (u *UserResource)
98
99func  CreateUser(request *restful.Request, response *restful.Response) {
100	//name,age,gender,grade,address
101	stmt,_:=Mysqldb.Prepare(`insert into user_test (name,age,gender,grade,address) values (?,?,?,?,?)`)
102	defer stmt.Close()
103	res,err:=stmt.Exec("增加姓名",0,"男",0,"新增地点")
104	var LastId,_ =res.LastInsertId()
105	fmt.Printf("lastid=%d所在行",LastId)
106	if err!=nil {
107		fmt.Println("插入失败")
108		io.WriteString(response.ResponseWriter,"末尾行添加用户失败")
109	}else {
110		fmt.Println("插入成功")
111		io.WriteString(response.ResponseWriter,"末尾行添加用户成功")
112	}
113	//usr := User{name: request.PathParameter("user-name")}//name:user-name
114	//usr:=new(User)
115	//uid:=request.PathParameter("user-id")
116	/*
117			usr:=User{id:request.PathParameter("user-id")}
118			err:=request.ReadEntity(&usr.id)
119			if err==nil {
120				u.users[usr.id]=usr
121				response.WriteEntity(usr)
122			}else {
123				response.AddHeader("Content-Type","text/plain")
124				response.WriteErrorString(http.StatusInternalServerError,err.Error())
125			}
126
127		if err!=nil {
128				fmt.Println("插入失败")
129			}
130
131			err1 := request.ReadEntity(&usr)
132			if err1 == nil {
133				u.users[usr.name] = *usr//User{name:user-name}
134				response.WriteEntity(usr)
135			} else {
136				response.WriteError(http.StatusInternalServerError, err1)
137			}
138	*/
139
140
141}
142//POST http://localhost:8080/users/add/{user-id}
143//根据id创建用户
144
145func  CreateUserById(request *restful.Request, response *restful.Response) {
146	id := request.PathParameter("user-id")
147	ID, _:= strconv.Atoi(id)//int Id
148	stmt, _ := Mysqldb.Prepare(`insert into user_test (id,name,age,gender,grade,address) values (?,?,?,?,?,?)`)
149	defer stmt.Close()
150	_, err := stmt.Exec(ID,"根据id增加的姓名", 10, "男", 99, "默认地点")
151	if err != nil {
152		fmt.Println("根据id新增行失败" )
153	}
154	fmt.Printf("根据id=%d新增所在行成功\n", ID)
155
156
157	usr := User{Id: ID}
158	err1 := request.ReadEntity(&usr)
159	if err1 == nil {
160		//u.users[usr.Id] = usr
161		response.WriteHeaderAndEntity(http.StatusCreated, usr)
162	} else {
163		response.AddHeader("Content-Type", "text/plain")
164		response.WriteErrorString(http.StatusInternalServerError, err.Error())
165	}
166
167	/*
168		usr:=User{id:Id}
169		err1:=request.ReadEntity(&usr.id)
170		if err1==nil {
171				//u.users[usr.id]=usr
172				response.WriteEntity(usr)
173			}else {
174				//response.AddHeader("Content-Type","text/plain")
175				response.WriteErrorString(http.StatusInternalServerError,err.Error())
176			}
177	*/
178}
179
180// DELETE http://localhost:8080/users/
181//删除尾行用户
182func  RemoveUser(request *restful.Request, response *restful.Response) {
183	stmt,_:=Mysqldb.Prepare(`delete from user_test order by id desc limit 1`)
184	defer stmt.Close()
185	//const Id=19
186	_,err:=stmt.Exec()
187	if err!=nil {
188		fmt.Println("尾行删除失败")
189		io.WriteString(response.ResponseWriter,"尾行删除失败")
190	}else{
191		fmt.Printf("尾行删除成功\n")
192		io.WriteString(response.ResponseWriter,"尾行删除成功")
193	}
194}
195
196// DELETE http://localhost:8080/users/1
197//根据id删除用户
198
199func  RemoveUserById(request *restful.Request, response *restful.Response) {
200	id := request.PathParameter("user-id")
201	//delete(u.users, id)//map[id]User
202	stmt,_:=Mysqldb.Prepare(`delete from user_test where id=?`)
203	defer stmt.Close()
204	//const Id=19
205	_,err:=stmt.Exec(id)
206	if err!=nil {
207		fmt.Println("删除失败")
208		io.WriteString(response.ResponseWriter,"删除失败")
209	}else{
210		fmt.Printf("id=%s所在行删除成功\n",id)
211		io.WriteString(response.ResponseWriter,"根据id删除成功")
212	}
213
214}
215
Full Screen

usuario_test.go

Source: usuario_test.go Github

copy
1package handlers
2
3import (
4	"bytes"
5	"encoding/json"
6	"fmt"
7	"net/http"
8	"testing"
9
10	"github.com/blackadress/vaula/models"
11	"github.com/blackadress/vaula/utils"
12)
13
14func TestEmptyUsuarioTable(t *testing.T) {
15	utils.ClearTableUsuario(a.DB)
16	ensureAuthorizedUserExists()
17
18	token := getTestJWT()
19	token_str := fmt.Sprintf("Bearer %s", token.AccessToken)
20
21	req, _ := http.NewRequest("GET", "/users", nil)
22	req.Header.Set("Authorization", token_str)
23	response := executeRequest(req, a)
24
25	checkResponseCode(t, http.StatusOK, response.Code)
26
27	var data []models.User
28	_ = json.Unmarshal(response.Body.Bytes(), &data)
29
30	if len(data) != 1 {
31		t.Errorf("Expected an array with one element. Got %#v", response.Body.String())
32	}
33}
34
35func TestUnauthorizedToken(t *testing.T) {
36	utils.ClearTableUsuario(a.DB)
37	ensureAuthorizedUserExists()
38
39	token_str := "Bearer token_invalido"
40	req, _ := http.NewRequest("GET", "/users", nil)
41	req.Header.Set("Authorization", token_str)
42	response := executeRequest(req, a)
43
44	checkResponseCode(t, http.StatusUnauthorized, response.Code)
45}
46
47func TestGetNonExistentUsuario(t *testing.T) {
48	utils.ClearTableUsuario(a.DB)
49	ensureAuthorizedUserExists()
50	token := getTestJWT()
51	token_str := fmt.Sprintf("Bearer %s", token.AccessToken)
52
53	req, _ := http.NewRequest("GET", "/users/11", nil)
54	req.Header.Set("Authorization", token_str)
55	response := executeRequest(req, a)
56
57	checkResponseCode(t, http.StatusNotFound, response.Code)
58
59	var m map[string]string
60	json.Unmarshal(response.Body.Bytes(), &m)
61	if m["error"] != "User not found" {
62		t.Errorf(
63			"Expected the 'error' key of the response to be set to 'User not found'. Got '%s'",
64			m["error"])
65	}
66}
67
68func TestCreateUser(t *testing.T) {
69	utils.ClearTableUsuario(a.DB)
70
71	var jsonStr = []byte(`
72	{
73		"username": "user_test",
74		"password": "1234",
75		"email": "[email protected]",
76		"activo": true
77	}`)
78	req, _ := http.NewRequest("POST", "/users", bytes.NewBuffer(jsonStr))
79	req.Header.Set("Content-Type", "application/json")
80
81	response := executeRequest(req, a)
82	checkResponseCode(t, http.StatusCreated, response.Code)
83
84	var m map[string]interface{}
85	json.Unmarshal(response.Body.Bytes(), &m)
86
87	if m["username"] != "user_test" {
88		t.Errorf("Expected user username to be 'user_test'. Got '%v'", m["username"])
89	}
90
91	if m["password"] == "1234" {
92		t.Errorf("Expected password to have been hashed, it is still '%v'", m["password"])
93	}
94
95	if m["email"] != "[email protected]" {
96		t.Errorf("Expected user email to be '[email protected]'. Got '%v'", m["email"])
97	}
98
99	if m["activo"] != true {
100		t.Errorf("Expected user activo to be 'true'. Got '%v'", m["activo"])
101	}
102
103	if m["id"] != 1.0 {
104		t.Errorf("Expected user ID to be '1'. Got '%v'", m["id"])
105	}
106}
107
108func TestGetUser(t *testing.T) {
109	utils.ClearTableUsuario(a.DB)
110	utils.AddUsers(1, a.DB)
111	ensureAuthorizedUserExists()
112
113	token := getTestJWT()
114	token_str := fmt.Sprintf("Bearer %s", token.AccessToken)
115
116	req, _ := http.NewRequest("GET", "/users/1", nil)
117	req.Header.Set("Authorization", token_str)
118	response := executeRequest(req, a)
119
120	checkResponseCode(t, http.StatusOK, response.Code)
121}
122
123func TestUpdateUser(t *testing.T) {
124	utils.ClearTableUsuario(a.DB)
125	utils.AddUsers(1, a.DB)
126	ensureAuthorizedUserExists()
127
128	token := getTestJWT()
129	token_str := fmt.Sprintf("Bearer %s", token.AccessToken)
130
131	req, _ := http.NewRequest("GET", "/users/1", nil)
132	req.Header.Set("Authorization", token_str)
133	response := executeRequest(req, a)
134	var originalUser map[string]interface{}
135	json.Unmarshal(response.Body.Bytes(), &originalUser)
136
137	var jsonStr = []byte(`{
138		"username": "user_test_updated",
139		"password": "1234_updated",
140		"email": "[email protected]"}`)
141
142	req, _ = http.NewRequest("PUT", "/users/1", bytes.NewBuffer(jsonStr))
143	req.Header.Set("Content-Type", "application/json")
144	req.Header.Set("Authorization", token_str)
145	response = executeRequest(req, a)
146
147	checkResponseCode(t, http.StatusOK, response.Code)
148
149	var m map[string]interface{}
150	json.Unmarshal(response.Body.Bytes(), &m)
151
152	if m["id"] != originalUser["id"] {
153		t.Errorf("Expected the id to remain the same (%v). Got %v", originalUser["id"], m["id"])
154	}
155
156	if m["username"] == originalUser["username"] {
157		t.Errorf(
158			"Expected the username to change from '%s' to '%s'. Got '%v'",
159			originalUser["username"],
160			m["username"],
161			originalUser["username"],
162		)
163	}
164
165	if m["password"] == originalUser["password"] {
166		t.Errorf(
167			"Expected the password to change from '%s' to '%s'. Got '%v'",
168			originalUser["password"],
169			m["password"],
170			originalUser["password"],
171		)
172	}
173
174	if m["email"] == originalUser["email"] {
175		t.Errorf(
176			"Expected the email to change from '%s', to '%s'. Got '%v'",
177			originalUser["email"],
178			m["email"],
179			originalUser["email"],
180		)
181	}
182}
183
184func TestDeleteUser(t *testing.T) {
185	utils.ClearTableUsuario(a.DB)
186	utils.AddUsers(1, a.DB)
187	ensureAuthorizedUserExists()
188	token := getTestJWT()
189	token_str := fmt.Sprintf("Bearer %s", token.AccessToken)
190
191	req, _ := http.NewRequest("GET", "/users/1", nil)
192	req.Header.Set("Authorization", token_str)
193	response := executeRequest(req, a)
194	checkResponseCode(t, http.StatusOK, response.Code)
195
196	req, _ = http.NewRequest("DELETE", "/users/1", nil)
197	req.Header.Set("Authorization", token_str)
198	response = executeRequest(req, a)
199	checkResponseCode(t, http.StatusOK, response.Code)
200}
201
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)