| 1 | package slack |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "image" |
| 8 | "image/draw" |
| 9 | "image/png" |
| 10 | "io" |
| 11 | "io/ioutil" |
| 12 | "net/http" |
| 13 | "os" |
| 14 | "reflect" |
| 15 | "strconv" |
| 16 | "strings" |
| 17 | "sync/atomic" |
| 18 | "testing" |
| 19 | ) |
| 20 | |
| 21 | func getTestUserProfileCustomField() UserProfileCustomField { |
| 22 | return UserProfileCustomField{ |
| 23 | Value: "test value", |
| 24 | Alt: "", |
| 25 | Label: "", |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | func getTestUserProfileCustomFields() UserProfileCustomFields { |
| 30 | return UserProfileCustomFields{ |
| 31 | fields: map[string]UserProfileCustomField{ |
| 32 | "Xxxxxx": getTestUserProfileCustomField(), |
| 33 | }} |
| 34 | } |
| 35 | |
| 36 | func getTestUserProfile() UserProfile { |
| 37 | return UserProfile{ |
| 38 | StatusText: "testStatus", |
| 39 | StatusEmoji: ":construction:", |
| 40 | RealName: "Test Real Name", |
| 41 | RealNameNormalized: "Test Real Name Normalized", |
| 42 | DisplayName: "Test Display Name", |
| 43 | DisplayNameNormalized: "Test Display Name Normalized", |
| 44 | Email: "[email protected]", |
| 45 | Image24: "https://s3-us-west-2.amazonaws.com/slack-files2/avatars/2016-10-18/92962080834_ef14c1469fc0741caea1_24.jpg", |
| 46 | Image32: "https://s3-us-west-2.amazonaws.com/slack-files2/avatars/2016-10-18/92962080834_ef14c1469fc0741caea1_32.jpg", |
| 47 | Image48: "https://s3-us-west-2.amazonaws.com/slack-files2/avatars/2016-10-18/92962080834_ef14c1469fc0741caea1_48.jpg", |
| 48 | Image72: "https://s3-us-west-2.amazonaws.com/slack-files2/avatars/2016-10-18/92962080834_ef14c1469fc0741caea1_72.jpg", |
| 49 | Image192: "https://s3-us-west-2.amazonaws.com/slack-files2/avatars/2016-10-18/92962080834_ef14c1469fc0741caea1_192.jpg", |
| 50 | Image512: "https://s3-us-west-2.amazonaws.com/slack-files2/avatars/2016-10-18/92962080834_ef14c1469fc0741caea1_512.jpg", |
| 51 | Fields: getTestUserProfileCustomFields(), |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | func getTestUserWithId(id string) User { |
| 56 | return User{ |
| 57 | ID: id, |
| 58 | Name: "Test User", |
| 59 | Deleted: false, |
| 60 | Color: "9f69e7", |
| 61 | RealName: "testuser", |
| 62 | TZ: "America/Los_Angeles", |
| 63 | TZLabel: "Pacific Daylight Time", |
| 64 | TZOffset: -25200, |
| 65 | Profile: getTestUserProfile(), |
| 66 | IsBot: false, |
| 67 | IsAdmin: false, |
| 68 | IsOwner: false, |
| 69 | IsPrimaryOwner: false, |
| 70 | IsRestricted: false, |
| 71 | IsUltraRestricted: false, |
| 72 | Updated: 1555425715, |
| 73 | Has2FA: false, |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | func getTestUser() User { |
| 78 | return getTestUserWithId("UXXXXXXXX") |
| 79 | } |
| 80 | |
| 81 | func getTestUsers() []User { |
| 82 | return []User{ |
| 83 | getTestUserWithId("UYYYYYYYY"), |
| 84 | getTestUserWithId("UZZZZZZZZ"), |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | func getUserIdentity(rw http.ResponseWriter, r *http.Request) { |
| 89 | rw.Header().Set("Content-Type", "application/json") |
| 90 | response := []byte(`{ |
| 91 | "ok": true, |
| 92 | "user": { |
| 93 | "id": "UXXXXXXXX", |
| 94 | "name": "Test User", |
| 95 | "email": "[email protected]", |
| 96 | "image_24": "https:\/\/s3-us-west-2.amazonaws.com\/slack-files2\/avatars\/2016-10-18\/92962080834_ef14c1469fc0741caea1_24.jpg", |
| 97 | "image_32": "https:\/\/s3-us-west-2.amazonaws.com\/slack-files2\/avatars\/2016-10-18\/92962080834_ef14c1469fc0741caea1_32.jpg", |
| 98 | "image_48": "https:\/\/s3-us-west-2.amazonaws.com\/slack-files2\/avatars\/2016-10-18\/92962080834_ef14c1469fc0741caea1_48.jpg", |
| 99 | "image_72": "https:\/\/s3-us-west-2.amazonaws.com\/slack-files2\/avatars\/2016-10-18\/92962080834_ef14c1469fc0741caea1_72.jpg", |
| 100 | "image_192": "https:\/\/s3-us-west-2.amazonaws.com\/slack-files2\/avatars\/2016-10-18\/92962080834_ef14c1469fc0741caea1_192.jpg", |
| 101 | "image_512": "https:\/\/s3-us-west-2.amazonaws.com\/slack-files2\/avatars\/2016-10-18\/92962080834_ef14c1469fc0741caea1_512.jpg" |
| 102 | }, |
| 103 | "team": { |
| 104 | "id": "TXXXXXXXX", |
| 105 | "name": "team-name", |
| 106 | "domain": "team-domain", |
| 107 | "image_34": "https:\/\/s3-us-west-2.amazonaws.com\/slack-files2\/avatars\/2016-10-18\/92962080834_ef14c1469fc0741caea1_34.jpg", |
| 108 | "image_44": "https:\/\/s3-us-west-2.amazonaws.com\/slack-files2\/avatars\/2016-10-18\/92962080834_ef14c1469fc0741caea1_44.jpg", |
| 109 | "image_68": "https:\/\/s3-us-west-2.amazonaws.com\/slack-files2\/avatars\/2016-10-18\/92962080834_ef14c1469fc0741caea1_68.jpg", |
| 110 | "image_88": "https:\/\/s3-us-west-2.amazonaws.com\/slack-files2\/avatars\/2016-10-18\/92962080834_ef14c1469fc0741caea1_88.jpg", |
| 111 | "image_102": "https:\/\/s3-us-west-2.amazonaws.com\/slack-files2\/avatars\/2016-10-18\/92962080834_ef14c1469fc0741caea1_102.jpg", |
| 112 | "image_132": "https:\/\/s3-us-west-2.amazonaws.com\/slack-files2\/avatars\/2016-10-18\/92962080834_ef14c1469fc0741caea1_132.jpg", |
| 113 | "image_230": "https:\/\/s3-us-west-2.amazonaws.com\/slack-files2\/avatars\/2016-10-18\/92962080834_ef14c1469fc0741caea1_230.jpg", |
| 114 | "image_original": "https:\/\/s3-us-west-2.amazonaws.com\/slack-files2\/avatars\/2016-10-18\/92962080834_ef14c1469fc0741caea1_original.jpg" |
| 115 | } |
| 116 | }`) |
| 117 | rw.Write(response) |
| 118 | } |
| 119 | |
| 120 | func getUserInfo(rw http.ResponseWriter, r *http.Request) { |
| 121 | rw.Header().Set("Content-Type", "application/json") |
| 122 | response, _ := json.Marshal(struct { |
| 123 | Ok bool `json:"ok"` |
| 124 | User User `json:"user"` |
| 125 | }{ |
| 126 | Ok: true, |
| 127 | User: getTestUser(), |
| 128 | }) |
| 129 | rw.Write(response) |
| 130 | } |
| 131 | |
| 132 | func getUsersInfo(rw http.ResponseWriter, r *http.Request) { |
| 133 | rw.Header().Set("Content-Type", "application/json") |
| 134 | response, _ := json.Marshal(struct { |
| 135 | Ok bool `json:"ok"` |
| 136 | Users []User `json:"users"` |
| 137 | }{ |
| 138 | Ok: true, |
| 139 | Users: getTestUsers(), |
| 140 | }) |
| 141 | rw.Write(response) |
| 142 | } |
| 143 | |
| 144 | func getUserByEmail(rw http.ResponseWriter, r *http.Request) { |
| 145 | rw.Header().Set("Content-Type", "application/json") |
| 146 | response, _ := json.Marshal(struct { |
| 147 | Ok bool `json:"ok"` |
| 148 | User User `json:"user"` |
| 149 | }{ |
| 150 | Ok: true, |
| 151 | User: getTestUser(), |
| 152 | }) |
| 153 | rw.Write(response) |
| 154 | } |
| 155 | |
| 156 | func httpTestErrReply(w http.ResponseWriter, clientErr bool, msg string) { |
| 157 | if clientErr { |
| 158 | w.WriteHeader(http.StatusBadRequest) |
| 159 | } else { |
| 160 | w.WriteHeader(http.StatusInternalServerError) |
| 161 | } |
| 162 | |
| 163 | w.Header().Set("Content-Type", "application/json") |
| 164 | |
| 165 | body, _ := json.Marshal(&SlackResponse{ |
| 166 | Ok: false, Error: msg, |
| 167 | }) |
| 168 | |
| 169 | w.Write(body) |
| 170 | } |
| 171 | |
| 172 | func newProfileHandler(up *UserProfile) (setter func(http.ResponseWriter, *http.Request)) { |
| 173 | return func(w http.ResponseWriter, r *http.Request) { |
| 174 | if up == nil { |
| 175 | httpTestErrReply(w, false, "err: UserProfile is nil") |
| 176 | return |
| 177 | } |
| 178 | |
| 179 | if err := r.ParseForm(); err != nil { |
| 180 | httpTestErrReply(w, true, fmt.Sprintf("err parsing form: %s", err.Error())) |
| 181 | return |
| 182 | } |
| 183 | |
| 184 | values := r.Form |
| 185 | |
| 186 | if v, ok := values["user"]; ok { |
| 187 | if len(v) == 0 || v[0] == "" { |
| 188 | httpTestErrReply(w, true, `POST data must not include an empty in a "user" field`) |
| 189 | return |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | if len(values["profile"]) == 0 { |
| 194 | httpTestErrReply(w, true, `POST data must include a "profile" field`) |
| 195 | return |
| 196 | } |
| 197 | |
| 198 | profile := []byte(values["profile"][0]) |
| 199 | |
| 200 | userProfile := UserProfile{} |
| 201 | |
| 202 | if err := json.Unmarshal(profile, &userProfile); err != nil { |
| 203 | httpTestErrReply(w, true, fmt.Sprintf("err parsing JSON: %s\n\njson: `%s`", err.Error(), profile)) |
| 204 | return |
| 205 | } |
| 206 | |
| 207 | *up = userProfile |
| 208 | |
| 209 | // TODO(theckman): enhance this to return a full User object |
| 210 | fmt.Fprint(w, `{"ok":true}`) |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | func TestGetUserIdentity(t *testing.T) { |
| 215 | http.HandleFunc("/users.identity", getUserIdentity) |
| 216 | |
| 217 | once.Do(startServer) |
| 218 | api := New("testing-token", OptionAPIURL("http://"+serverAddr+"/")) |
| 219 | |
| 220 | identity, err := api.GetUserIdentity() |
| 221 | if err != nil { |
| 222 | t.Errorf("Unexpected error: %s", err) |
| 223 | return |
| 224 | } |
| 225 | |
| 226 | // t.Fatal refers to -> t.Errorf & return |
| 227 | if identity.User.ID != "UXXXXXXXX" { |
| 228 | t.Fatal(ErrIncorrectResponse) |
| 229 | } |
| 230 | if identity.User.Name != "Test User" { |
| 231 | t.Fatal(ErrIncorrectResponse) |
| 232 | } |
| 233 | if identity.User.Email != "[email protected]" { |
| 234 | t.Fatal(ErrIncorrectResponse) |
| 235 | } |
| 236 | if identity.Team.ID != "TXXXXXXXX" { |
| 237 | t.Fatal(ErrIncorrectResponse) |
| 238 | } |
| 239 | if identity.Team.Name != "team-name" { |
| 240 | t.Fatal(ErrIncorrectResponse) |
| 241 | } |
| 242 | if identity.Team.Domain != "team-domain" { |
| 243 | t.Fatal(ErrIncorrectResponse) |
| 244 | } |
| 245 | if identity.User.Image24 == "" { |
| 246 | t.Fatal(ErrIncorrectResponse) |
| 247 | } |
| 248 | if identity.Team.Image34 == "" { |
| 249 | t.Fatal(ErrIncorrectResponse) |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | func TestGetUserInfo(t *testing.T) { |
| 254 | http.HandleFunc("/users.info", getUserInfo) |
| 255 | expectedUser := getTestUser() |
| 256 | |
| 257 | once.Do(startServer) |
| 258 | api := New("testing-token", OptionAPIURL("http://"+serverAddr+"/")) |
| 259 | |
| 260 | user, err := api.GetUserInfo("UXXXXXXXX") |
| 261 | if err != nil { |
| 262 | t.Errorf("Unexpected error: %s", err) |
| 263 | return |
| 264 | } |
| 265 | if !reflect.DeepEqual(expectedUser, *user) { |
| 266 | t.Fatal(ErrIncorrectResponse) |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | func TestGetUsersInfo(t *testing.T) { |
| 271 | http.DefaultServeMux = new(http.ServeMux) |
| 272 | http.HandleFunc("/users.info", getUsersInfo) |
| 273 | expectedUsers := getTestUsers() |
| 274 | |
| 275 | once.Do(startServer) |
| 276 | api := New("testing-token", OptionAPIURL("http://"+serverAddr+"/")) |
| 277 | |
| 278 | user, err := api.GetUsersInfo("UYYYYYYYY", "UZZZZZZZZ") |
| 279 | if err != nil { |
| 280 | t.Errorf("Unexpected error: %s", err) |
| 281 | return |
| 282 | } |
| 283 | if !reflect.DeepEqual(expectedUsers, *user) { |
| 284 | t.Fatal(ErrIncorrectResponse) |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | func TestGetUserByEmail(t *testing.T) { |
| 289 | http.HandleFunc("/users.lookupByEmail", getUserByEmail) |
| 290 | expectedUser := getTestUser() |
| 291 | |
| 292 | once.Do(startServer) |
| 293 | api := New("testing-token", OptionAPIURL("http://"+serverAddr+"/")) |
| 294 | |
| 295 | user, err := api.GetUserByEmail("[email protected]") |
| 296 | if err != nil { |
| 297 | t.Errorf("Unexpected error: %s", err) |
| 298 | return |
| 299 | } |
| 300 | if !reflect.DeepEqual(expectedUser, *user) { |
| 301 | t.Fatal(ErrIncorrectResponse) |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | func TestUserProfileSet(t *testing.T) { |
| 306 | up := &UserProfile{} |
| 307 | |
| 308 | setUserProfile := newProfileHandler(up) |
| 309 | |
| 310 | http.HandleFunc("/users.profile.set", setUserProfile) |
| 311 | |
| 312 | once.Do(startServer) |
| 313 | api := New("testing-token", OptionAPIURL("http://"+serverAddr+"/")) |
| 314 | |
| 315 | testSetUserCustomStatus(api, up, t) |
| 316 | testUnsetUserCustomStatus(api, up, t) |
| 317 | |
| 318 | up.RealName = "Test User" |
| 319 | testSetUserCustomStatusWithUser(api, "Test User", up, t) |
| 320 | |
| 321 | up.RealName = "Real Name Test" |
| 322 | testSetUserRealName(api, up, t) |
| 323 | } |
| 324 | |
| 325 | func testSetUserRealName(api *Client, up *UserProfile, t *testing.T) { |
| 326 | const ( |
| 327 | realName = "Real Name Test" |
| 328 | ) |
| 329 | if err := api.SetUserRealName(realName); err != nil { |
| 330 | t.Fatalf(`SetUserRealName(%q) = %#v, want <nil>`, realName, err) |
| 331 | } |
| 332 | |
| 333 | if up.RealName != realName { |
| 334 | t.Fatalf(`UserProfile.RealName = %q, want %q`, up.RealName, realName) |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | func testSetUserCustomStatus(api *Client, up *UserProfile, t *testing.T) { |
| 339 | const ( |
| 340 | statusText = "testStatus" |
| 341 | statusEmoji = ":construction:" |
| 342 | statusExpiration = 1551619082 |
| 343 | ) |
| 344 | if err := api.SetUserCustomStatus(statusText, statusEmoji, statusExpiration); err != nil { |
| 345 | t.Fatalf(`SetUserCustomStatus(%q, %q, %q) = %#v, want <nil>`, statusText, statusEmoji, statusExpiration, err) |
| 346 | } |
| 347 | |
| 348 | if up.StatusText != statusText { |
| 349 | t.Fatalf(`UserProfile.StatusText = %q, want %q`, up.StatusText, statusText) |
| 350 | } |
| 351 | |
| 352 | if up.StatusEmoji != statusEmoji { |
| 353 | t.Fatalf(`UserProfile.StatusEmoji = %q, want %q`, up.StatusEmoji, statusEmoji) |
| 354 | } |
| 355 | if up.StatusExpiration != statusExpiration { |
| 356 | t.Fatalf(`UserProfile.StatusExpiration = %q, want %q`, up.StatusExpiration, statusExpiration) |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | func testSetUserCustomStatusWithUser(api *Client, user string, up *UserProfile, t *testing.T) { |
| 361 | const ( |
| 362 | statusText = "testStatus" |
| 363 | statusEmoji = ":construction:" |
| 364 | statusExpiration = 1551619082 |
| 365 | ) |
| 366 | if err := api.SetUserCustomStatusWithUser(user, statusText, statusEmoji, statusExpiration); err != nil { |
| 367 | t.Fatalf(`SetUserCustomStatusWithUser(%q, %q, %q, %q) = %#v, want <nil>`, user, statusText, statusEmoji, statusExpiration, err) |
| 368 | } |
| 369 | |
| 370 | if up.StatusText != statusText { |
| 371 | t.Fatalf(`UserProfile.StatusText = %q, want %q`, up.StatusText, statusText) |
| 372 | } |
| 373 | |
| 374 | if up.StatusEmoji != statusEmoji { |
| 375 | t.Fatalf(`UserProfile.StatusEmoji = %q, want %q`, up.StatusEmoji, statusEmoji) |
| 376 | } |
| 377 | if up.StatusExpiration != statusExpiration { |
| 378 | t.Fatalf(`UserProfile.StatusExpiration = %q, want %q`, up.StatusExpiration, statusExpiration) |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | func testUnsetUserCustomStatus(api *Client, up *UserProfile, t *testing.T) { |
| 383 | if err := api.UnsetUserCustomStatus(); err != nil { |
| 384 | t.Fatalf(`UnsetUserCustomStatus() = %#v, want <nil>`, err) |
| 385 | } |
| 386 | |
| 387 | if up.StatusText != "" { |
| 388 | t.Fatalf(`UserProfile.StatusText = %q, want %q`, up.StatusText, "") |
| 389 | } |
| 390 | |
| 391 | if up.StatusEmoji != "" { |
| 392 | t.Fatalf(`UserProfile.StatusEmoji = %q, want %q`, up.StatusEmoji, "") |
| 393 | } |
| 394 | } |
| 395 | |
| 396 | func TestGetUsers(t *testing.T) { |
| 397 | http.DefaultServeMux = new(http.ServeMux) |
| 398 | http.HandleFunc("/users.list", getUserPage(4)) |
| 399 | |
| 400 | once.Do(startServer) |
| 401 | api := New("testing-token", OptionAPIURL("http://"+serverAddr+"/")) |
| 402 | |
| 403 | users, err := api.GetUsers() |
| 404 | if err != nil { |
| 405 | t.Errorf("Unexpected error: %s", err) |
| 406 | return |
| 407 | } |
| 408 | |
| 409 | if !reflect.DeepEqual([]User{ |
| 410 | getTestUserWithId("U000"), |
| 411 | getTestUserWithId("U001"), |
| 412 | getTestUserWithId("U002"), |
| 413 | getTestUserWithId("U003"), |
| 414 | }, users) { |
| 415 | t.Fatal(ErrIncorrectResponse) |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | // returns n pages users. |
| 420 | func getUserPage(max int64) func(rw http.ResponseWriter, r *http.Request) { |
| 421 | var n int64 |
| 422 | return func(rw http.ResponseWriter, r *http.Request) { |
| 423 | var cpage int64 |
| 424 | sresp := SlackResponse{ |
| 425 | Ok: true, |
| 426 | } |
| 427 | members := []User{ |
| 428 | getTestUserWithId(fmt.Sprintf("U%03d", n)), |
| 429 | } |
| 430 | rw.Header().Set("Content-Type", "application/json") |
| 431 | if cpage = atomic.AddInt64(&n, 1); cpage == max { |
| 432 | response, _ := json.Marshal(userResponseFull{ |
| 433 | SlackResponse: sresp, |
| 434 | Members: members, |
| 435 | }) |
| 436 | rw.Write(response) |
| 437 | return |
| 438 | } |
| 439 | response, _ := json.Marshal(userResponseFull{ |
| 440 | SlackResponse: sresp, |
| 441 | Members: members, |
| 442 | Metadata: ResponseMetadata{Cursor: strconv.Itoa(int(cpage))}, |
| 443 | }) |
| 444 | rw.Write(response) |
| 445 | } |
| 446 | } |
| 447 | |
| 448 | // returns n pages of users and sends rate limited errors in between successful pages. |
| 449 | func getUserPagesWithRateLimitErrors(max int64) func(rw http.ResponseWriter, r *http.Request) { |
| 450 | var n int64 |
| 451 | doRateLimit := false |
| 452 | return func(rw http.ResponseWriter, r *http.Request) { |
| 453 | defer func() { |
| 454 | doRateLimit = !doRateLimit |
| 455 | }() |
| 456 | if doRateLimit { |
| 457 | rw.Header().Set("Retry-After", "1") |
| 458 | rw.WriteHeader(http.StatusTooManyRequests) |
| 459 | return |
| 460 | } |
| 461 | var cpage int64 |
| 462 | sresp := SlackResponse{ |
| 463 | Ok: true, |
| 464 | } |
| 465 | members := []User{ |
| 466 | getTestUserWithId(fmt.Sprintf("U%03d", n)), |
| 467 | } |
| 468 | rw.Header().Set("Content-Type", "application/json") |
| 469 | if cpage = atomic.AddInt64(&n, 1); cpage == max { |
| 470 | response, _ := json.Marshal(userResponseFull{ |
| 471 | SlackResponse: sresp, |
| 472 | Members: members, |
| 473 | }) |
| 474 | rw.Write(response) |
| 475 | return |
| 476 | } |
| 477 | response, _ := json.Marshal(userResponseFull{ |
| 478 | SlackResponse: sresp, |
| 479 | Members: members, |
| 480 | Metadata: ResponseMetadata{Cursor: strconv.Itoa(int(cpage))}, |
| 481 | }) |
| 482 | rw.Write(response) |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | func TestSetUserPhoto(t *testing.T) { |
| 487 | file, fileContent, teardown := createUserPhoto(t) |
| 488 | defer teardown() |
| 489 | |
| 490 | params := UserSetPhotoParams{CropX: 0, CropY: 0, CropW: 32} |
| 491 | |
| 492 | http.HandleFunc("/users.setPhoto", setUserPhotoHandler(fileContent, params)) |
| 493 | |
| 494 | once.Do(startServer) |
| 495 | api := New(validToken, OptionAPIURL("http://"+serverAddr+"/")) |
| 496 | |
| 497 | err := api.SetUserPhoto(file.Name(), params) |
| 498 | if err != nil { |
| 499 | t.Fatalf("unexpected error: %+v\n", err) |
| 500 | } |
| 501 | } |
| 502 | |
| 503 | func setUserPhotoHandler(wantBytes []byte, wantParams UserSetPhotoParams) http.HandlerFunc { |
| 504 | const maxMemory = 1 << 20 // 1 MB |
| 505 | |
| 506 | return func(w http.ResponseWriter, r *http.Request) { |
| 507 | if err := r.ParseMultipartForm(maxMemory); err != nil { |
| 508 | httpTestErrReply(w, false, fmt.Sprintf("failed to parse multipart/form: %+v", err)) |
| 509 | return |
| 510 | } |
| 511 | |
| 512 | // Test for expected token |
| 513 | actualToken := strings.Split(r.Header.Get("Authorization"), "Bearer ")[1] |
| 514 | if actualToken != validToken { |
| 515 | httpTestErrReply(w, true, fmt.Sprintf("expected multipart form value token=%v", validToken)) |
| 516 | return |
| 517 | } |
| 518 | |
| 519 | // Test for expected crop params |
| 520 | if wantParams.CropX != DEFAULT_USER_PHOTO_CROP_X { |
| 521 | if cx, err := strconv.Atoi(r.Form.Get("crop_x")); err != nil || cx != wantParams.CropX { |
| 522 | httpTestErrReply(w, true, fmt.Sprintf("expected multipart form value crop_x=%d", wantParams.CropX)) |
| 523 | return |
| 524 | } |
| 525 | } |
| 526 | if wantParams.CropY != DEFAULT_USER_PHOTO_CROP_Y { |
| 527 | if cy, err := strconv.Atoi(r.Form.Get("crop_y")); err != nil || cy != wantParams.CropY { |
| 528 | httpTestErrReply(w, true, fmt.Sprintf("expected multipart form value crop_y=%d", wantParams.CropY)) |
| 529 | return |
| 530 | } |
| 531 | } |
| 532 | if wantParams.CropW != DEFAULT_USER_PHOTO_CROP_W { |
| 533 | if cw, err := strconv.Atoi(r.Form.Get("crop_w")); err != nil || cw != wantParams.CropW { |
| 534 | httpTestErrReply(w, true, fmt.Sprintf("expected multipart form value crop_w=%d", wantParams.CropW)) |
| 535 | return |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | // Test for expected image |
| 540 | f, ok := r.MultipartForm.File["image"] |
| 541 | if !ok || len(f) == 0 { |
| 542 | httpTestErrReply(w, true, `expected multipart form file "image"`) |
| 543 | return |
| 544 | } |
| 545 | file, err := f[0].Open() |
| 546 | if err != nil { |
| 547 | httpTestErrReply(w, true, fmt.Sprintf("failed to open uploaded file: %+v", err)) |
| 548 | return |
| 549 | } |
| 550 | gotBytes, err := ioutil.ReadAll(file) |
| 551 | if err != nil { |
| 552 | httpTestErrReply(w, true, fmt.Sprintf("failed to read uploaded file: %+v", err)) |
| 553 | return |
| 554 | } |
| 555 | if !bytes.Equal(wantBytes, gotBytes) { |
| 556 | httpTestErrReply(w, true, "uploaded bytes did not match expected bytes") |
| 557 | return |
| 558 | } |
| 559 | |
| 560 | w.Header().Set("Content-Type", "application/json") |
| 561 | fmt.Fprint(w, `{"ok":true}`) |
| 562 | } |
| 563 | } |
| 564 | |
| 565 | // createUserPhoto generates a temp photo for testing. It returns the file handle, the file |
| 566 | // contents, and a function that can be called to remove the file. |
| 567 | func createUserPhoto(t *testing.T) (*os.File, []byte, func()) { |
| 568 | photo := image.NewRGBA(image.Rect(0, 0, 64, 64)) |
| 569 | draw.Draw(photo, photo.Bounds(), image.Black, image.ZP, draw.Src) |
| 570 | |
| 571 | f, err := ioutil.TempFile(os.TempDir(), "profile.png") |
| 572 | if err != nil { |
| 573 | t.Fatalf("failed to create test photo: %+v\n", err) |
| 574 | } |
| 575 | |
| 576 | var buf bytes.Buffer |
| 577 | if err := png.Encode(io.MultiWriter(&buf, f), photo); err != nil { |
| 578 | t.Fatalf("failed to write test photo: %+v\n", err) |
| 579 | } |
| 580 | |
| 581 | teardown := func() { |
| 582 | if err := os.Remove(f.Name()); err != nil { |
| 583 | t.Fatalf("failed to remove test photo: %+v\n", err) |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | return f, buf.Bytes(), teardown |
| 588 | } |
| 589 | |
| 590 | func getUserProfileHandler(rw http.ResponseWriter, r *http.Request) { |
| 591 | rw.Header().Set("Content-Type", "application/json") |
| 592 | profile := getTestUserProfile() |
| 593 | resp, _ := json.Marshal(&getUserProfileResponse{ |
| 594 | SlackResponse: SlackResponse{Ok: true}, |
| 595 | Profile: &profile}) |
| 596 | rw.Write(resp) |
| 597 | } |
| 598 | |
| 599 | func TestGetUserProfile(t *testing.T) { |
| 600 | http.HandleFunc("/users.profile.get", getUserProfileHandler) |
| 601 | once.Do(startServer) |
| 602 | api := New("testing-token", OptionAPIURL("http://"+serverAddr+"/")) |
| 603 | profile, err := api.GetUserProfile(&GetUserProfileParameters{UserID: "UXXXXXXXX"}) |
| 604 | if err != nil { |
| 605 | t.Fatalf("Unexpected error: %s", err) |
| 606 | } |
| 607 | exp := getTestUserProfile() |
| 608 | if profile.DisplayName != exp.DisplayName { |
| 609 | t.Fatalf(`profile.DisplayName = "%s", wanted "%s"`, profile.DisplayName, exp.DisplayName) |
| 610 | } |
| 611 | } |
| 612 | |
| 613 | func TestSetFieldsMap(t *testing.T) { |
| 614 | p := &UserProfile{} |
| 615 | exp := map[string]UserProfileCustomField{ |
| 616 | "Xxxxxx": getTestUserProfileCustomField(), |
| 617 | } |
| 618 | p.SetFieldsMap(exp) |
| 619 | act := p.FieldsMap() |
| 620 | if !reflect.DeepEqual(act, exp) { |
| 621 | t.Fatalf(`p.FieldsMap() = %v, wanted %v`, act, exp) |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | func TestUserProfileCustomFieldsUnmarshalJSON(t *testing.T) { |
| 626 | fields := &UserProfileCustomFields{} |
| 627 | if err := json.Unmarshal([]byte(`[]`), fields); err != nil { |
| 628 | t.Fatal(err) |
| 629 | } |
| 630 | if err := json.Unmarshal([]byte(`{ |
| 631 | "Xxxxxx": { |
| 632 | "value": "test value", |
| 633 | "alt": "" |
| 634 | } |
| 635 | }`), fields); err != nil { |
| 636 | t.Fatal(err) |
| 637 | } |
| 638 | act := fields.ToMap()["Xxxxxx"].Value |
| 639 | exp := "test value" |
| 640 | if act != exp { |
| 641 | t.Fatalf(`fields.ToMap()["Xxxxxx"]["value"] = "%s", wanted "%s"`, act, exp) |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | func TestUserProfileCustomFieldsMarshalJSON(t *testing.T) { |
| 646 | fields := UserProfileCustomFields{} |
| 647 | b, err := json.Marshal(fields) |
| 648 | if err != nil { |
| 649 | t.Fatal(err) |
| 650 | } |
| 651 | if string(b) != "[]" { |
| 652 | t.Fatalf(`string(b) = "%s", wanted "[]"`, string(b)) |
| 653 | } |
| 654 | fields = getTestUserProfileCustomFields() |
| 655 | if _, err := json.Marshal(fields); err != nil { |
| 656 | t.Fatal(err) |
| 657 | } |
| 658 | } |
| 659 | |
| 660 | func TestUserProfileCustomFieldsToMap(t *testing.T) { |
| 661 | m := map[string]UserProfileCustomField{ |
| 662 | "Xxxxxx": getTestUserProfileCustomField(), |
| 663 | } |
| 664 | fields := UserProfileCustomFields{fields: m} |
| 665 | act := fields.ToMap() |
| 666 | if !reflect.DeepEqual(act, m) { |
| 667 | t.Fatalf(`fields.ToMap() = %v, wanted %v`, act, m) |
| 668 | } |
| 669 | } |
| 670 | |
| 671 | func TestUserProfileCustomFieldsLen(t *testing.T) { |
| 672 | fields := UserProfileCustomFields{ |
| 673 | fields: map[string]UserProfileCustomField{ |
| 674 | "Xxxxxx": getTestUserProfileCustomField(), |
| 675 | }} |
| 676 | if fields.Len() != 1 { |
| 677 | t.Fatalf(`fields.Len() = %d, wanted 1`, fields.Len()) |
| 678 | } |
| 679 | } |
| 680 | |
| 681 | func TestUserProfileCustomFieldsSetMap(t *testing.T) { |
| 682 | fields := UserProfileCustomFields{} |
| 683 | m := map[string]UserProfileCustomField{ |
| 684 | "Xxxxxx": getTestUserProfileCustomField(), |
| 685 | } |
| 686 | fields.SetMap(m) |
| 687 | if !reflect.DeepEqual(fields.fields, m) { |
| 688 | t.Fatalf(`fields.fields = %v, wanted %v`, fields.fields, m) |
| 689 | } |
| 690 | } |
| 691 | |
| 692 | func TestGetUsersHandlesRateLimit(t *testing.T) { |
| 693 | http.DefaultServeMux = new(http.ServeMux) |
| 694 | http.HandleFunc("/users.list", getUserPagesWithRateLimitErrors(4)) |
| 695 | |
| 696 | once.Do(startServer) |
| 697 | api := New("testing-token", OptionAPIURL("http://"+serverAddr+"/")) |
| 698 | |
| 699 | users, err := api.GetUsers() |
| 700 | if err != nil { |
| 701 | t.Errorf("Unexpected error: %s", err) |
| 702 | return |
| 703 | } |
| 704 | |
| 705 | if !reflect.DeepEqual([]User{ |
| 706 | getTestUserWithId("U000"), |
| 707 | getTestUserWithId("U001"), |
| 708 | getTestUserWithId("U002"), |
| 709 | getTestUserWithId("U003"), |
| 710 | }, users) { |
| 711 | t.Fatal(ErrIncorrectResponse) |
| 712 | } |
| 713 | } |
| 714 | |
| 715 | func TestGetUsersReturnsServerError(t *testing.T) { |
| 716 | http.DefaultServeMux = new(http.ServeMux) |
| 717 | http.HandleFunc("/users.list", func(w http.ResponseWriter, r *http.Request) { |
| 718 | w.WriteHeader(http.StatusInternalServerError) |
| 719 | }) |
| 720 | |
| 721 | once.Do(startServer) |
| 722 | api := New("testing-token", OptionAPIURL("http://"+serverAddr+"/")) |
| 723 | |
| 724 | _, err := api.GetUsers() |
| 725 | |
| 726 | if err == nil { |
| 727 | t.Errorf("Expected error but got nil") |
| 728 | return |
| 729 | } |
| 730 | |
| 731 | expectedErr := "slack server error: 500 Internal Server Error" |
| 732 | if err.Error() != expectedErr { |
| 733 | t.Errorf("Expected: %s. Got: %s", expectedErr, err.Error()) |
| 734 | } |
| 735 | } |