1
0
mirror of https://github.com/badkaktus/gorocket.git synced 2024-12-12 11:15:05 +02:00

Merge pull request #17 from badkaktus/tests

write tests, fix some bugs
This commit is contained in:
Nikolai 2024-02-03 22:03:49 +02:00 committed by GitHub
commit d35914029e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
24 changed files with 1950 additions and 117 deletions

25
.github/workflows/test.yaml vendored Normal file
View File

@ -0,0 +1,25 @@
# This workflow will build a golang project
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-go
name: gorocket tests
on:
push:
branches: [ "master" ]
pull_request:
branches: [ "master" ]
jobs:
tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: '1.20'
- name: Test
run: go test -v -cover ./...

View File

@ -1,3 +1,7 @@
![tests](https://github.com/badkaktus/gorocket/actions/workflows/test.yaml/badge.svg)
![gorocket logo](gorocket_logo.png)
# Golang Rocket Chat REST API client
Use this simple client if you need to connect to Rocket Chat
@ -14,6 +18,15 @@ import (
```
Create client
```go
client := gorocket.NewWithOptions("https://your-rocket-chat.com",
gorocket.WithUserID("my-user-id"),
gorocket.WithToken("my-bot-token"),
gorocket.WithTimeout(1 * time.Second),
)
```
or
```go
client := gorocket.NewClient("https://your-rocket-chat.com")
@ -31,16 +44,6 @@ if err != nil {
fmt.Printf("I'm %s", lg.Data.Me.Username)
```
or
```go
client := gorocket.NewWithOptions("https://your-rocket-chat.com",
gorocket.WithUserID("my-user-id"),
gorocket.WithToken("my-bot-token"),
gorocket.WithTimeout(1 * time.Second),
)
```
## Manage user
```go
str := gorocket.NewUser{

View File

@ -135,8 +135,8 @@ type MeResponse struct {
Success bool `json:"success"`
}
// Login login the user with the given credentials.
func (c *Client) Login(login *LoginPayload) (*LoginResponse, error) {
opt, _ := json.Marshal(login)
url := fmt.Sprintf("%s/%s/login", c.baseURL, c.apiVersion)
@ -162,6 +162,7 @@ func (c *Client) Login(login *LoginPayload) (*LoginResponse, error) {
return &res, nil
}
// Logout logout the user.
func (c *Client) Logout() (*LogoutResponse, error) {
req, err := http.NewRequest("POST", fmt.Sprintf("%s/%s/logout", c.baseURL, c.apiVersion), nil)
if err != nil {
@ -176,6 +177,7 @@ func (c *Client) Logout() (*LogoutResponse, error) {
return &res, nil
}
// Me get the user information.
func (c *Client) Me() (*MeResponse, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s/me", c.baseURL, c.apiVersion), nil)
if err != nil {

81
authentication_test.go Normal file
View File

@ -0,0 +1,81 @@
package gorocket
import (
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
)
func TestLogin(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"status":"success","data":{"authToken":"9HqLlyZOugoStsXCUfD_0YdwnNnunAJF8V47U3QHXSq","userId":"aobEdbYhXfu5hkeqG","me":{"_id":"aYjNnig8BEAWeQzMh","name":"Rocket Cat","emails":[{"address":"rocket.cat@rocket.chat","verified":false}],"status":"offline","statusConnection":"offline","username":"rocket.cat","utcOffset":-3,"active":true,"roles":["admin"],"settings":{"preferences":{}},"avatarUrl":"http://localhost:3000/avatar/test"}}}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
payload := LoginPayload{
User: "username",
Password: "password",
}
resp, err := client.Login(&payload)
require.NoError(t, err)
require.Equal(t, "success", resp.Status)
require.Equal(t, "9HqLlyZOugoStsXCUfD_0YdwnNnunAJF8V47U3QHXSq", resp.Data.AuthToken)
require.Equal(t, "aobEdbYhXfu5hkeqG", resp.Data.UserID)
require.Equal(t, "aYjNnig8BEAWeQzMh", resp.Data.Me.ID)
require.Equal(t, "Rocket Cat", resp.Data.Me.Name)
require.Equal(t, "rocket.cat@rocket.chat", resp.Data.Me.Emails[0].Address)
require.Equal(t, false, resp.Data.Me.Emails[0].Verified)
require.Equal(t, "offline", resp.Data.Me.Status)
require.Equal(t, "offline", resp.Data.Me.StatusConnection)
require.Equal(t, "rocket.cat", resp.Data.Me.Username)
require.Equal(t, -3.0, resp.Data.Me.UtcOffset)
require.Equal(t, true, resp.Data.Me.Active)
require.Equal(t, "admin", resp.Data.Me.Roles[0])
require.IsType(t, Settings{}, resp.Data.Me.Settings)
require.IsType(t, Preferences{}, resp.Data.Me.Settings.Preferences)
require.Equal(t, "http://localhost:3000/avatar/test", resp.Data.Me.AvatarURL)
}
func TestMe(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"_id":"aobEdbYhXfu5hkeqG","name":"Example User","emails":[{"address":"example@example.com","verified":true}],"status":"offline","statusConnection":"offline","username":"example","utcOffset":0,"active":true,"roles":["user","admin"],"settings":{"preferences":{"enableAutoAway":false,"idleTimeoutLimit":300,"desktopNotificationDuration":0,"audioNotifications":"mentions","desktopNotifications":"mentions","mobileNotifications":"mentions","unreadAlert":true,"useEmojis":true,"convertAsciiEmoji":true,"autoImageLoad":true,"saveMobileBandwidth":true,"collapseMediaByDefault":false,"hideUsernames":false,"hideRoles":false,"hideFlexTab":false,"hideAvatars":false,"roomsListExhibitionMode":"category","sidebarViewMode":"medium","sidebarHideAvatar":false,"sidebarShowUnread":false,"sidebarShowFavorites":true,"sendOnEnter":"normal","messageViewMode":0,"emailNotificationMode":"all","roomCounterSidebar":false,"newRoomNotification":"door","newMessageNotification":"chime","muteFocusedConversations":true,"notificationsSoundVolume":100}},"customFields":{"twitter":"@userstwi"},"avatarUrl":"http://localhost:3000/avatar/test","success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.Me()
require.NoError(t, err)
require.Equal(t, "aobEdbYhXfu5hkeqG", resp.ID)
require.Equal(t, "Example User", resp.Name)
require.Equal(t, "example@example.com", resp.Emails[0].Address)
require.True(t, resp.Emails[0].Verified)
require.Equal(t, "offline", resp.Status)
require.Equal(t, "offline", resp.StatusConnection)
require.Equal(t, "example", resp.Username)
require.Equal(t, 0.0, resp.UtcOffset)
require.True(t, resp.Active)
require.Equal(t, "user", resp.Roles[0])
require.Equal(t, "admin", resp.Roles[1])
require.IsType(t, Settings{}, resp.Settings)
require.IsType(t, Preferences{}, resp.Settings.Preferences)
require.Equal(t, "http://localhost:3000/avatar/test", resp.AvatarURL)
require.True(t, resp.Success)
}
func TestLogout(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"status":"success","data":{"message":"You've been logged out!"}}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.Logout()
require.NoError(t, err)
require.Equal(t, "success", resp.Status)
require.Equal(t, "You've been logged out!", resp.Data.Message)
}

View File

@ -15,6 +15,7 @@ type language struct {
Name string `json:"name"`
}
// GetSupportedLanguage returns a list of supported languages by the autotranslate
func (c *Client) GetSupportedLanguage(query string) (*SupportedLanguageResp, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s/autotranslate.getSupportedLanguages", c.baseURL, c.apiVersion), nil)
if err != nil {

29
autotranslate_test.go Normal file
View File

@ -0,0 +1,29 @@
package gorocket
import (
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
)
func TestGetSupportedLanguage(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"languages":[{"language":"af","name":"Africâner"},{"language":"sq","name":"Albanês"},{"language":"de","name":"Alemão"},{"language":"am","name":"Amárico"}],"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.GetSupportedLanguage("")
require.NoError(t, err)
require.Equal(t, "af", resp.Languages[0].Language)
require.Equal(t, "Africâner", resp.Languages[0].Name)
require.Equal(t, "sq", resp.Languages[1].Language)
require.Equal(t, "Albanês", resp.Languages[1].Name)
require.Equal(t, "de", resp.Languages[2].Language)
require.Equal(t, "Alemão", resp.Languages[2].Name)
require.Equal(t, "am", resp.Languages[3].Language)
require.Equal(t, "Amárico", resp.Languages[3].Name)
require.True(t, resp.Success)
}

View File

@ -194,7 +194,7 @@ type SetTopicResponse struct {
Success bool `json:"success"`
}
// Adds all of the users on the server to a channel.
// AddAllToChannel adds all of the users on the server to a channel.
func (c *Client) AddAllToChannel(params *AddAllRequest) (*AddAllResponse, error) {
opt, _ := json.Marshal(params)
@ -215,7 +215,7 @@ func (c *Client) AddAllToChannel(params *AddAllRequest) (*AddAllResponse, error)
return &res, nil
}
// Archives a channel.
// ArchiveChannel archives a channel.
func (c *Client) ArchiveChannel(param *SimpleChannelId) (*SimpleSuccessResponse, error) {
opt, _ := json.Marshal(param)
@ -236,7 +236,7 @@ func (c *Client) ArchiveChannel(param *SimpleChannelId) (*SimpleSuccessResponse,
return &res, nil
}
// Removes the channel from the user's list of channels.
// CloseChannel removes the channel from the user's list of channels.
func (c *Client) CloseChannel(param *SimpleChannelId) (*SimpleSuccessResponse, error) {
opt, _ := json.Marshal(param)
@ -257,7 +257,7 @@ func (c *Client) CloseChannel(param *SimpleChannelId) (*SimpleSuccessResponse, e
return &res, nil
}
// Gets channel counters.
// ChannelCounters gets channel counters.
func (c *Client) ChannelCounters(param *ChannelCountersRequest) (*ChannelCountersResponse, error) {
req, err := http.NewRequest("GET",
@ -265,7 +265,7 @@ func (c *Client) ChannelCounters(param *ChannelCountersRequest) (*ChannelCounter
nil)
if param.RoomName == "" && param.RoomId == "" {
return nil, fmt.Errorf("False parameters")
return nil, fmt.Errorf("false parameters")
}
url := req.URL.Query()
@ -290,7 +290,7 @@ func (c *Client) ChannelCounters(param *ChannelCountersRequest) (*ChannelCounter
return &res, nil
}
// Creates a new channel.
// CreateChannel creates a new channel.
func (c *Client) CreateChannel(param *CreateChannelRequest) (*CreateChannelResponse, error) {
opt, _ := json.Marshal(param)
@ -311,7 +311,7 @@ func (c *Client) CreateChannel(param *CreateChannelRequest) (*CreateChannelRespo
return &res, nil
}
// Delete channel.
// DeleteChannel delete channel.
func (c *Client) DeleteChannel(param *SimpleChannelRequest) (*SimpleSuccessResponse, error) {
opt, _ := json.Marshal(param)
@ -332,7 +332,7 @@ func (c *Client) DeleteChannel(param *SimpleChannelRequest) (*SimpleSuccessRespo
return &res, nil
}
// Get channel info.
// ChannelInfo get channel info.
func (c *Client) ChannelInfo(param *SimpleChannelRequest) (*ChannelInfoResponse, error) {
req, err := http.NewRequest("GET",
@ -340,7 +340,7 @@ func (c *Client) ChannelInfo(param *SimpleChannelRequest) (*ChannelInfoResponse,
nil)
if param.RoomName == "" && param.RoomId == "" {
return nil, fmt.Errorf("False parameters")
return nil, fmt.Errorf("false parameters")
}
url := req.URL.Query()
@ -365,7 +365,7 @@ func (c *Client) ChannelInfo(param *SimpleChannelRequest) (*ChannelInfoResponse,
return &res, nil
}
// Adds a user to the channel.
// ChannelInvite adds a user to the channel.
func (c *Client) ChannelInvite(param *InviteChannelRequest) (*InviteChannelResponse, error) {
opt, _ := json.Marshal(param)
@ -386,7 +386,7 @@ func (c *Client) ChannelInvite(param *InviteChannelRequest) (*InviteChannelRespo
return &res, nil
}
// Kick a user from the channel.
// ChannelKick kick a user from the channel.
func (c *Client) ChannelKick(param *InviteChannelRequest) (*InviteChannelResponse, error) {
opt, _ := json.Marshal(param)
@ -407,7 +407,7 @@ func (c *Client) ChannelKick(param *InviteChannelRequest) (*InviteChannelRespons
return &res, nil
}
// Get channels list
// ChannelList get channels list
func (c *Client) ChannelList() (*ChannelListResponse, error) {
req, err := http.NewRequest("GET",
fmt.Sprintf("%s/%s/channels.list", c.baseURL, c.apiVersion),
@ -426,7 +426,7 @@ func (c *Client) ChannelList() (*ChannelListResponse, error) {
return &res, nil
}
// Gets channel members
// ChannelMembers gets channel members
func (c *Client) ChannelMembers(param *SimpleChannelRequest) (*ChannelMembersResponse, error) {
req, err := http.NewRequest("GET",
@ -434,7 +434,7 @@ func (c *Client) ChannelMembers(param *SimpleChannelRequest) (*ChannelMembersRes
nil)
if param.RoomName == "" && param.RoomId == "" {
return nil, fmt.Errorf("False parameters")
return nil, fmt.Errorf("false parameters")
}
url := req.URL.Query()
@ -459,7 +459,7 @@ func (c *Client) ChannelMembers(param *SimpleChannelRequest) (*ChannelMembersRes
return &res, nil
}
// Adds the channel back to the user's list of channels.
// OpenChannel adds the channel back to the user's list of channels.
func (c *Client) OpenChannel(param *SimpleChannelId) (*SimpleSuccessResponse, error) {
opt, _ := json.Marshal(param)
@ -480,7 +480,7 @@ func (c *Client) OpenChannel(param *SimpleChannelId) (*SimpleSuccessResponse, er
return &res, nil
}
// Changes a channel's name.
// RenameChannel changes a channel's name.
func (c *Client) RenameChannel(param *RenameChannelRequest) (*RenameChannelResponse, error) {
opt, _ := json.Marshal(param)
@ -501,7 +501,7 @@ func (c *Client) RenameChannel(param *RenameChannelRequest) (*RenameChannelRespo
return &res, nil
}
// Sets the announcement for the channel.
// SetAnnouncementChannel sets the announcement for the channel.
func (c *Client) SetAnnouncementChannel(param *SetAnnouncementRequest) (*SetAnnouncementResponse, error) {
opt, _ := json.Marshal(param)
@ -522,7 +522,7 @@ func (c *Client) SetAnnouncementChannel(param *SetAnnouncementRequest) (*SetAnno
return &res, nil
}
// Sets the Description for the channel.
// SetDescriptionChannel sets the Description for the channel.
func (c *Client) SetDescriptionChannel(param *SetDescriptionRequest) (*SetDescriptionResponse, error) {
opt, _ := json.Marshal(param)
@ -543,7 +543,7 @@ func (c *Client) SetDescriptionChannel(param *SetDescriptionRequest) (*SetDescri
return &res, nil
}
// Sets the topic for the channel.
// SetTopicChannel sets the topic for the channel.
func (c *Client) SetTopicChannel(param *SetTopicRequest) (*SetTopicResponse, error) {
opt, _ := json.Marshal(param)
@ -564,7 +564,7 @@ func (c *Client) SetTopicChannel(param *SetTopicRequest) (*SetTopicResponse, err
return &res, nil
}
// Unarchive a channel.
// UnarchiveChannel unarchive a channel.
func (c *Client) UnarchiveChannel(param *SimpleChannelId) (*SimpleSuccessResponse, error) {
opt, _ := json.Marshal(param)

406
channels_test.go Normal file
View File

@ -0,0 +1,406 @@
package gorocket
import (
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
)
func TestAddAllToChannel(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"channel":{"_id":"ByehQjC44FwMeiLbX","name":"channelname","t":"c","usernames":["example","rocket.cat"],"msgs":0,"u":{"_id":"aobEdbYhXfu5hkeqG","username":"example"},"ts":"2016-05-30T13:42:25.304Z"},"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := AddAllRequest{
RoomId: "ByehQjC44FwMeiLbX",
}
resp, err := client.AddAllToChannel(&req)
require.NoError(t, err)
require.Equal(t, "ByehQjC44FwMeiLbX", resp.Channel.ID)
require.Equal(t, "channelname", resp.Channel.Name)
require.Equal(t, "c", resp.Channel.T)
require.Equal(t, "example", resp.Channel.Usernames[0])
require.Equal(t, "rocket.cat", resp.Channel.Usernames[1])
require.Equal(t, 0, resp.Channel.Msgs)
require.Equal(t, "aobEdbYhXfu5hkeqG", resp.Channel.U.ID)
require.Equal(t, "example", resp.Channel.U.Username)
require.Equal(t, "2016-05-30T13:42:25.304Z", resp.Channel.Ts.Format("2006-01-02T15:04:05.999Z"))
require.True(t, resp.Success)
}
func TestArchiveChannel(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := SimpleChannelId{
RoomId: "ByehQjC44FwMeiLbX",
}
resp, err := client.ArchiveChannel(&req)
require.NoError(t, err)
require.True(t, resp.Success)
}
func TestCloseChannel(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := SimpleChannelId{
RoomId: "ByehQjC44FwMeiLbX",
}
resp, err := client.CloseChannel(&req)
require.NoError(t, err)
require.True(t, resp.Success)
}
func TestChannelCounters(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"joined":true,"members":78,"unreads":2,"unreadsFrom":"2018-02-23T17:15:51.907Z","msgs":304,"latest":"2018-02-23T17:17:03.110Z","userMentions":0,"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := ChannelCountersRequest{
RoomId: "ByehQjC44FwMeiLbX",
}
resp, err := client.ChannelCounters(&req)
require.NoError(t, err)
require.True(t, resp.Success)
require.True(t, resp.Joined)
require.Equal(t, 78, resp.Members)
require.Equal(t, 2, resp.Unreads)
require.Equal(t, "2018-02-23T17:15:51.907Z", resp.UnreadsFrom.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, 304, resp.Msgs)
require.Equal(t, "2018-02-23T17:17:03.11Z", resp.Latest.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, 0, resp.UserMentions)
}
func TestCreateChannel(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"channel":{"_id":"ByehQjC44FwMeiLbX","name":"channelname","t":"c","usernames":["example"],"msgs":0,"u":{"_id":"aobEdbYhXfu5hkeqG","username":"example"},"ts":"2016-05-30T13:42:25.304Z"},"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := CreateChannelRequest{
Name: "channelname",
Members: []string{"example"},
}
resp, err := client.CreateChannel(&req)
require.NoError(t, err)
require.Equal(t, "ByehQjC44FwMeiLbX", resp.Channel.ID)
require.Equal(t, "channelname", resp.Channel.Name)
require.Equal(t, "c", resp.Channel.T)
require.Equal(t, "example", resp.Channel.Usernames[0])
require.Equal(t, 0, resp.Channel.Msgs)
require.Equal(t, "aobEdbYhXfu5hkeqG", resp.Channel.U.ID)
require.Equal(t, "example", resp.Channel.U.Username)
require.Equal(t, "2016-05-30T13:42:25.304Z", resp.Channel.Ts.Format("2006-01-02T15:04:05.999Z"))
require.True(t, resp.Success)
}
func TestDeleteChannel(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := SimpleChannelRequest{
RoomId: "ByehQjC44FwMeiLbX",
}
resp, err := client.DeleteChannel(&req)
require.NoError(t, err)
require.True(t, resp.Success)
}
func TestGetChannelInfo(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"channel":{"_id":"ByehQjC44FwMeiLbX","name":"testing","fname":"testing","t":"c","msgs":0,"usersCount":2,"u":{"_id":"HKKPmF8rZh45GMHWH","username":"marcos.defendi"},"customFields":{},"broadcast":false,"encrypted":false,"ts":"2020-05-21T13:14:07.070Z","ro":false,"default":false,"sysMes":true,"_updatedAt":"2020-05-21T13:14:07.096Z"},"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := SimpleChannelRequest{
RoomId: "ByehQjC44FwMeiLbX",
}
resp, err := client.ChannelInfo(&req)
require.NoError(t, err)
require.Equal(t, "ByehQjC44FwMeiLbX", resp.Channel.ID)
require.Equal(t, "testing", resp.Channel.Name)
require.Equal(t, "testing", resp.Channel.Fname)
require.Equal(t, "c", resp.Channel.T)
require.Equal(t, 0, resp.Channel.Msgs)
require.Equal(t, 2, resp.Channel.UsersCount)
require.Equal(t, "HKKPmF8rZh45GMHWH", resp.Channel.U.ID)
require.Equal(t, "marcos.defendi", resp.Channel.U.Username)
require.Equal(t, false, resp.Channel.Broadcast)
require.Equal(t, false, resp.Channel.Encrypted)
require.Equal(t, "2020-05-21T13:14:07.07Z", resp.Channel.Ts.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, false, resp.Channel.Ro)
require.Equal(t, false, resp.Channel.Default)
require.Equal(t, true, resp.Channel.SysMes)
require.Equal(t, "2020-05-21T13:14:07.096Z", resp.Channel.UpdatedAt.Format("2006-01-02T15:04:05.999Z"))
require.True(t, resp.Success)
}
func TestChannelInvite(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"channel":{"_id":"ByehQjC44FwMeiLbX","ts":"2016-11-30T21:23:04.737Z","t":"c","name":"testing","usernames":["testing"],"msgs":1,"_updatedAt":"2016-12-09T12:50:51.575Z","lm":"2016-12-09T12:50:51.555Z"},"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := InviteChannelRequest{
RoomId: "ByehQjC44FwMeiLbX",
}
resp, err := client.ChannelInvite(&req)
require.NoError(t, err)
require.Equal(t, "ByehQjC44FwMeiLbX", resp.Channel.ID)
require.Equal(t, "2016-11-30T21:23:04.737Z", resp.Channel.Ts.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, "c", resp.Channel.T)
require.Equal(t, "testing", resp.Channel.Name)
require.Equal(t, "testing", resp.Channel.Usernames[0])
require.Equal(t, 1, resp.Channel.Msgs)
require.Equal(t, "2016-12-09T12:50:51.575Z", resp.Channel.UpdatedAt.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, "2016-12-09T12:50:51.555Z", resp.Channel.Lm.Format("2006-01-02T15:04:05.999Z"))
require.True(t, resp.Success)
}
func TestChannelKick(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"channel":{"_id":"ByehQjC44FwMeiLbX","name":"invite-me","t":"c","usernames":["testing1"],"msgs":0,"u":{"_id":"aobEdbYhXfu5hkeqG","username":"testing1"},"ts":"2016-12-09T15:08:58.042Z","ro":false,"sysMes":true,"_updatedAt":"2016-12-09T15:22:40.656Z"},"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := InviteChannelRequest{
RoomId: "ByehQjC44FwMeiLbX",
UserId: "testing1",
}
resp, err := client.ChannelKick(&req)
require.NoError(t, err)
require.Equal(t, "ByehQjC44FwMeiLbX", resp.Channel.ID)
require.Equal(t, "invite-me", resp.Channel.Name)
require.Equal(t, "c", resp.Channel.T)
require.Equal(t, "testing1", resp.Channel.Usernames[0])
require.Equal(t, 0, resp.Channel.Msgs)
require.Equal(t, "2016-12-09T15:08:58.042Z", resp.Channel.Ts.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, "2016-12-09T15:22:40.656Z", resp.Channel.UpdatedAt.Format("2006-01-02T15:04:05.999Z"))
require.True(t, resp.Success)
}
func TestChannelList(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"channels":[{"_id":"ByehQjC44FwMeiLbX","name":"test-test","t":"c","usernames":["testing1"],"msgs":0,"u":{"_id":"aobEdbYhXfu5hkeqG","username":"testing1"},"ts":"2016-12-09T15:08:58.042Z","ro":false,"sysMes":true,"_updatedAt":"2016-12-09T15:22:40.656Z"},{"_id":"t7qapfhZjANMRAi5w","name":"testing","t":"c","usernames":["testing2"],"msgs":0,"u":{"_id":"y65tAmHs93aDChMWu","username":"testing2"},"ts":"2016-12-01T15:08:58.042Z","ro":false,"sysMes":true,"_updatedAt":"2016-12-09T15:22:40.656Z"}],"offset":0,"count":1,"total":1,"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.Count(2).ChannelList()
require.NoError(t, err)
require.Equal(t, 2, len(resp.Channels))
require.Equal(t, "ByehQjC44FwMeiLbX", resp.Channels[0].ID)
require.Equal(t, "test-test", resp.Channels[0].Name)
require.Equal(t, "c", resp.Channels[0].T)
require.Equal(t, "testing1", resp.Channels[0].Usernames[0])
require.Equal(t, 0, resp.Channels[0].Msgs)
require.Equal(t, "aobEdbYhXfu5hkeqG", resp.Channels[0].U.ID)
require.Equal(t, "testing1", resp.Channels[0].U.Username)
require.Equal(t, "2016-12-09T15:08:58.042Z", resp.Channels[0].Ts.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, false, resp.Channels[0].Ro)
require.Equal(t, true, resp.Channels[0].SysMes)
require.Equal(t, "2016-12-09T15:22:40.656Z", resp.Channels[0].UpdatedAt.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, "t7qapfhZjANMRAi5w", resp.Channels[1].ID)
require.Equal(t, "testing", resp.Channels[1].Name)
require.Equal(t, "c", resp.Channels[1].T)
require.Equal(t, "testing2", resp.Channels[1].Usernames[0])
require.Equal(t, 0, resp.Channels[1].Msgs)
require.Equal(t, "y65tAmHs93aDChMWu", resp.Channels[1].U.ID)
require.Equal(t, "testing2", resp.Channels[1].U.Username)
require.Equal(t, "2016-12-01T15:08:58.042Z", resp.Channels[1].Ts.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, false, resp.Channels[1].Ro)
require.Equal(t, true, resp.Channels[1].SysMes)
require.Equal(t, "2016-12-09T15:22:40.656Z", resp.Channels[1].UpdatedAt.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, 0, resp.Offset)
require.Equal(t, 1, resp.Count)
require.Equal(t, 1, resp.Total)
require.True(t, resp.Success)
}
func TestChannelMembers(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"members":[{"_id":"Loz7qh9ChSqHMPymx","username":"customField_apiuser.test.1529436896005","name":"customField_apiuser.test.1529436896005","status":"offline"},{"_id":"Zc3Y3cRW7ZtS7Y8Hk","username":"customField_apiuser.test.1529436997563","name":"customField_apiuser.test.1529436997563","status":"offline"}],"count":2,"offset":0,"total":35,"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := SimpleChannelRequest{
RoomId: "ByehQjC44FwMeiLbX",
}
resp, err := client.Offset(10).ChannelMembers(&req)
require.NoError(t, err)
require.Equal(t, 2, len(resp.Members))
require.Equal(t, "Loz7qh9ChSqHMPymx", resp.Members[0].ID)
require.Equal(t, "customField_apiuser.test.1529436896005", resp.Members[0].Username)
require.Equal(t, "customField_apiuser.test.1529436896005", resp.Members[0].Name)
require.Equal(t, "offline", resp.Members[0].Status)
require.Equal(t, "Zc3Y3cRW7ZtS7Y8Hk", resp.Members[1].ID)
require.Equal(t, "customField_apiuser.test.1529436997563", resp.Members[1].Username)
require.Equal(t, "customField_apiuser.test.1529436997563", resp.Members[1].Name)
require.Equal(t, "offline", resp.Members[1].Status)
require.Equal(t, 2, resp.Count)
require.Equal(t, 0, resp.Offset)
require.Equal(t, 35, resp.Total)
require.True(t, resp.Success)
}
func TestOpenChannel(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := SimpleChannelId{
RoomId: "ByehQjC44FwMeiLbX",
}
resp, err := client.OpenChannel(&req)
require.NoError(t, err)
require.True(t, resp.Success)
}
func TestRenameChannel(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"channel":{"_id":"ByehQjC44FwMeiLbX","name":"new-name","t":"c","usernames":["testing1"],"msgs":4,"u":{"_id":"aobEdbYhXfu5hkeqG","username":"testing1"},"ts":"2016-12-09T15:08:58.042Z","ro":false,"sysMes":true,"_updatedAt":"2016-12-09T15:57:44.686Z"},"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := RenameChannelRequest{
RoomId: "ByehQjC44FwMeiLbX",
NewName: "new-name",
}
resp, err := client.RenameChannel(&req)
require.NoError(t, err)
require.Equal(t, "ByehQjC44FwMeiLbX", resp.Channel.ID)
require.Equal(t, "new-name", resp.Channel.Name)
require.Equal(t, "c", resp.Channel.T)
require.Equal(t, "testing1", resp.Channel.Usernames[0])
require.Equal(t, 4, resp.Channel.Msgs)
require.Equal(t, "aobEdbYhXfu5hkeqG", resp.Channel.U.ID)
require.Equal(t, "testing1", resp.Channel.U.Username)
require.Equal(t, "2016-12-09T15:08:58.042Z", resp.Channel.Ts.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, false, resp.Channel.Ro)
require.Equal(t, true, resp.Channel.SysMes)
require.Equal(t, "2016-12-09T15:57:44.686Z", resp.Channel.UpdatedAt.Format("2006-01-02T15:04:05.999Z"))
require.True(t, resp.Success)
}
func TestSetAnnouncementChannel(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"announcement":"Test out everything","success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := SetAnnouncementRequest{
RoomId: "ByehQjC44FwMeiLbX",
Announcement: "Test out everything",
}
resp, err := client.SetAnnouncementChannel(&req)
require.NoError(t, err)
require.Equal(t, "Test out everything", resp.Announcement)
require.True(t, resp.Success)
}
func TestSetDescriptionChannel(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"description":"Test out everything","success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := SetDescriptionRequest{
RoomId: "ByehQjC44FwMeiLbX",
Description: "Test out everything",
}
resp, err := client.SetDescriptionChannel(&req)
require.NoError(t, err)
require.Equal(t, "Test out everything", resp.Description)
require.True(t, resp.Success)
}
func TestSetTopicChannel(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"topic":"Test out everything","success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := SetTopicRequest{
RoomId: "ByehQjC44FwMeiLbX",
Topic: "Test out everything",
}
resp, err := client.SetTopicChannel(&req)
require.NoError(t, err)
require.Equal(t, "Test out everything", resp.Topic)
require.True(t, resp.Success)
}
func TestUnarchiveChannel(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := SimpleChannelId{
RoomId: "ByehQjC44FwMeiLbX",
}
resp, err := client.UnarchiveChannel(&req)
require.NoError(t, err)
require.True(t, resp.Success)
}

17
chat.go
View File

@ -96,6 +96,7 @@ type DeleteMessageRequest struct {
AsUser bool `json:"asUser,omitempty"`
}
// todo add the remaining fields
type DeleteMessageResponse struct {
ID string `json:"_id"`
Ts int64 `json:"ts"`
@ -160,7 +161,7 @@ type PinMessageResponse struct {
Success bool `json:"success"`
}
// Posts a new chat message.
// PostMessage posts a new chat message.
func (c *Client) PostMessage(msg *Message) (*RespPostMessage, error) {
opt, _ := json.Marshal(msg)
@ -182,7 +183,7 @@ func (c *Client) PostMessage(msg *Message) (*RespPostMessage, error) {
return &res, nil
}
// Retrieves a single chat message by the provided id.
// GetMessage retrieves a single chat message by the provided id.
// Callee must have permission to access the room where the message resides.
func (c *Client) GetMessage(param *SingleMessageId) (*GetMessageResponse, error) {
req, err := http.NewRequest("GET",
@ -190,7 +191,7 @@ func (c *Client) GetMessage(param *SingleMessageId) (*GetMessageResponse, error)
nil)
if param.MessageId == "" {
return nil, fmt.Errorf("False parameters")
return nil, fmt.Errorf("false parameters")
}
url := req.URL.Query()
@ -212,7 +213,7 @@ func (c *Client) GetMessage(param *SingleMessageId) (*GetMessageResponse, error)
return &res, nil
}
// Chat Message Delete
// DeleteMessage deletes an existing chat message.
func (c *Client) DeleteMessage(param *DeleteMessageRequest) (*DeleteMessageResponse, error) {
opt, _ := json.Marshal(param)
@ -233,14 +234,14 @@ func (c *Client) DeleteMessage(param *DeleteMessageRequest) (*DeleteMessageRespo
return &res, nil
}
// Callee must have permission to access the room where the message resides.
// GetPinnedMessages retrieve pinned messages from a room.
func (c *Client) GetPinnedMessages(param *GetPinnedMsgRequest) (*GetPinnedMsgResponse, error) {
req, err := http.NewRequest("GET",
fmt.Sprintf("%s/%s/chat.getPinnedMessages", c.baseURL, c.apiVersion),
nil)
if param.RoomId == "" {
return nil, fmt.Errorf("False parameters")
return nil, fmt.Errorf("false parameters")
}
url := req.URL.Query()
@ -268,7 +269,7 @@ func (c *Client) GetPinnedMessages(param *GetPinnedMsgRequest) (*GetPinnedMsgRes
return &res, nil
}
// Pins a chat message to the message's channel.
// PinMessage pins a chat message to the message's channel.
func (c *Client) PinMessage(param *SingleMessageId) (*PinMessageResponse, error) {
opt, _ := json.Marshal(param)
@ -289,7 +290,7 @@ func (c *Client) PinMessage(param *SingleMessageId) (*PinMessageResponse, error)
return &res, nil
}
// Unpins a chat message to the message's channel.
// UnpinMessage unpins a chat message to the message's channel.
func (c *Client) UnpinMessage(param *SingleMessageId) (*SimpleSuccessResponse, error) {
opt, _ := json.Marshal(param)

176
chat_test.go Normal file
View File

@ -0,0 +1,176 @@
package gorocket
import (
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
)
func TestPostMessage(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"message":{"rid":"GENERAL","msg":"123456789","ts":"2018-03-01T18:02:26.825Z","u":{"_id":"i5FdM4ssFgAcQP62k","username":"rocket.cat","name":"test"},"unread":true,"mentions":[],"channels":[],"_updatedAt":"2018-03-01T18:02:26.828Z","_id":"LnCSJxxNkCy6K9X8X"},"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
payload := Message{
Text: "Hello",
}
resp, err := client.PostMessage(&payload)
require.NoError(t, err)
require.Equal(t, "GENERAL", resp.Message.Rid)
require.Equal(t, "123456789", resp.Message.Msg)
require.Equal(t, "2018-03-01T18:02:26.825Z", resp.Message.Ts.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, "i5FdM4ssFgAcQP62k", resp.Message.U.ID)
require.Equal(t, "rocket.cat", resp.Message.U.Username)
require.Equal(t, "2018-03-01T18:02:26.828Z", resp.Message.UpdatedAt.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, "LnCSJxxNkCy6K9X8X", resp.Message.ID)
require.True(t, resp.Success)
}
func TestGetMessage(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"message":{"_id":"7aDSXtjMA3KPLxLjt","rid":"GENERAL","msg":"This is a test!","ts":"2016-12-14T20:56:05.117Z","u":{"_id":"y65tAmHs93aDChMWu","username":"graywolf336"}},"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := SingleMessageId{
MessageId: "7aDSXtjMA3KPLxLjt",
}
resp, err := client.GetMessage(&req)
require.NoError(t, err)
require.Equal(t, "7aDSXtjMA3KPLxLjt", resp.Message.ID)
require.Equal(t, "GENERAL", resp.Message.Rid)
require.Equal(t, "This is a test!", resp.Message.Msg)
require.Equal(t, "2016-12-14T20:56:05.117Z", resp.Message.Ts.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, "y65tAmHs93aDChMWu", resp.Message.U.ID)
require.Equal(t, "graywolf336", resp.Message.U.Username)
require.True(t, resp.Success)
}
func TestDeleteMessage(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"_id":"jEnjsxuoDJamGjbH2","ts":1696533809813,"message":{"_id":"jEnjsxuoDJamGjbH2","rid":"6GFJ3tbmHiyHbahmC","u":{"_id":"5fRTXMt7DMJbpPJfh","username":"test.funke","name":"TestFunke"}},"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := DeleteMessageRequest{
RoomID: "6GFJ3tbmHiyHbahmC",
MsgID: "jEnjsxuoDJamGjbH2",
}
resp, err := client.DeleteMessage(&req)
require.NoError(t, err)
require.Equal(t, "jEnjsxuoDJamGjbH2", resp.ID)
require.Equal(t, int64(1696533809813), resp.Ts)
require.True(t, resp.Success)
}
func TestGetPinnedMessages(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"messages":[{"_id":"Srhca3mgthgjkEisJ","rid":"ByehQjC44FwMeiLbX","msg":"I pinned this message","ts":"2019-03-23T00:53:24.388Z","u":{"_id":"aobEdbYhXfu5hkeqG","username":"user","name":"User"},"mentions":[],"channels":[],"_updatedAt":"2019-03-23T00:53:28.813Z","pinned":true,"pinnedAt":"2019-03-23T00:53:28.813Z","pinnedBy":{"_id":"aobEdbYhXfu5hkeqG","username":"user"}},{"_id":"m3AZcKrvayKEZSKJN","rid":"GENERAL","msg":"Ola","ts":"2019-03-23T00:53:50.974Z","u":{"_id":"aobEdbYhXfu5hkeqG","username":"user","name":"user"},"mentions":[],"channels":[],"_updatedAt":"2019-03-23T00:53:53.649Z","pinned":true,"pinnedAt":"2019-03-23T00:53:53.649Z","pinnedBy":{"_id":"aobEdbYhXfu5hkeqG","username":"user"}}],"count":2,"offset":0,"total":2,"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := GetPinnedMsgRequest{
RoomId: "GENERAL",
Count: 2,
Offset: 0,
}
resp, err := client.Sort(map[string]int{"ts": -1}).GetPinnedMessages(&req)
require.NoError(t, err)
require.Equal(t, 2, resp.Count)
require.Equal(t, 0, resp.Offset)
require.Equal(t, 2, resp.Total)
require.True(t, resp.Success)
require.Equal(t, "Srhca3mgthgjkEisJ", resp.Messages[0].ID)
require.Equal(t, "ByehQjC44FwMeiLbX", resp.Messages[0].Rid)
require.Equal(t, "I pinned this message", resp.Messages[0].Msg)
require.Equal(t, "2019-03-23T00:53:24.388Z", resp.Messages[0].Ts.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, "aobEdbYhXfu5hkeqG", resp.Messages[0].U.ID)
require.Equal(t, "user", resp.Messages[0].U.Username)
require.Equal(t, "User", resp.Messages[0].U.Name)
require.Equal(t, 0, len(resp.Messages[0].Mentions))
require.Equal(t, 0, len(resp.Messages[0].Channels))
require.Equal(t, "2019-03-23T00:53:28.813Z", resp.Messages[0].UpdatedAt.Format("2006-01-02T15:04:05.999Z"))
require.True(t, resp.Messages[0].Pinned)
require.Equal(t, "2019-03-23T00:53:28.813Z", resp.Messages[0].PinnedAt.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, "aobEdbYhXfu5hkeqG", resp.Messages[0].PinnedBy.ID)
require.Equal(t, "user", resp.Messages[0].PinnedBy.Username)
require.Equal(t, "m3AZcKrvayKEZSKJN", resp.Messages[1].ID)
require.Equal(t, "GENERAL", resp.Messages[1].Rid)
require.Equal(t, "Ola", resp.Messages[1].Msg)
require.Equal(t, "2019-03-23T00:53:50.974Z", resp.Messages[1].Ts.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, "aobEdbYhXfu5hkeqG", resp.Messages[1].U.ID)
require.Equal(t, "user", resp.Messages[1].U.Username)
require.Equal(t, "user", resp.Messages[1].U.Name)
require.Equal(t, 0, len(resp.Messages[1].Mentions))
require.Equal(t, 0, len(resp.Messages[1].Channels))
require.Equal(t, "2019-03-23T00:53:53.649Z", resp.Messages[1].UpdatedAt.Format("2006-01-02T15:04:05.999Z"))
require.True(t, resp.Messages[1].Pinned)
require.Equal(t, "2019-03-23T00:53:53.649Z", resp.Messages[1].PinnedAt.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, "aobEdbYhXfu5hkeqG", resp.Messages[1].PinnedBy.ID)
require.Equal(t, "user", resp.Messages[1].PinnedBy.Username)
}
func TestPinMessage(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"message":{"t":"message_pinned","rid":"GENERAL","ts":"2017-09-27T20:39:57.921Z","msg":"","u":{"_id":"Z3cpiYN6CNK2oXWKv","username":"graywolf336"},"groupable":false,"attachments":[{"text":"Hello","author_name":"graywolf336","author_icon":"/avatar/graywolf336?_dc=0","ts":"2017-09-27T19:36:01.683Z"}],"_updatedAt":"2017-09-27T20:39:57.921Z","_id":"hmzxXKSWmMkoQyiAd"},"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := SingleMessageId{
MessageId: "jEnjsxuoDJamGjbH2",
}
resp, err := client.PinMessage(&req)
require.NoError(t, err)
require.Equal(t, "message_pinned", resp.Message.T)
require.Equal(t, "GENERAL", resp.Message.Rid)
require.Equal(t, "2017-09-27T20:39:57.921Z", resp.Message.Ts.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, "", resp.Message.Msg)
require.Equal(t, "Z3cpiYN6CNK2oXWKv", resp.Message.U.ID)
require.Equal(t, "graywolf336", resp.Message.U.Username)
require.False(t, resp.Message.Groupable)
require.Equal(t, "Hello", resp.Message.Attachments[0].Text)
require.Equal(t, "graywolf336", resp.Message.Attachments[0].AuthorName)
require.Equal(t, "/avatar/graywolf336?_dc=0", resp.Message.Attachments[0].AuthorIcon)
require.Equal(t, "2017-09-27T19:36:01.683Z", resp.Message.Attachments[0].Ts.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, "2017-09-27T20:39:57.921Z", resp.Message.UpdatedAt.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, "hmzxXKSWmMkoQyiAd", resp.Message.ID)
require.True(t, resp.Success)
}
func TestUnpinMessage(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := SingleMessageId{
MessageId: "jEnjsxuoDJamGjbH2",
}
resp, err := client.UnpinMessage(&req)
require.NoError(t, err)
require.True(t, resp.Success)
}

5
go.mod
View File

@ -2,4 +2,7 @@ module github.com/badkaktus/gorocket
go 1.13
require github.com/google/go-querystring v1.1.0
require (
github.com/google/go-querystring v1.1.0
github.com/stretchr/testify v1.8.4
)

23
go.sum Normal file
View File

@ -0,0 +1,23 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@ -3,10 +3,11 @@ package gorocket
import (
"context"
"encoding/json"
"github.com/google/go-querystring/query"
"log"
"net/http"
"time"
"github.com/google/go-querystring/query"
)
type Client struct {

BIN
gorocket_logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

86
gorocket_test.go Normal file
View File

@ -0,0 +1,86 @@
package gorocket
import (
"net/http"
"net/http/httptest"
"testing"
"time"
)
func NewTestServer(responseHandler http.HandlerFunc) *httptest.Server {
return httptest.NewServer(responseHandler)
}
func NewTestClientWithCustomHandler(t *testing.T, server *httptest.Server) *Client {
client := NewClient(server.URL)
if client.HTTPClient.Timeout != 5*time.Minute {
t.Errorf("Expected timeout to be 5 minutes, got %v", client.HTTPClient.Timeout)
}
if client.baseURL != server.URL {
t.Errorf("Expected base URL to be %s, got %s", server.URL, client.baseURL)
}
if client.apiVersion != "api/v1" {
t.Errorf("Expected API version to be api/v1, got %s", client.apiVersion)
}
return client
}
func NewTestClient(t *testing.T) *Client {
responseHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
server := NewTestServer(responseHandler)
defer server.Close()
client := NewClient(server.URL)
if client.HTTPClient.Timeout != 5*time.Minute {
t.Errorf("Expected timeout to be 5 minutes, got %v", client.HTTPClient.Timeout)
}
if client.baseURL != server.URL {
t.Errorf("Expected base URL to be %s, got %s", server.URL, client.baseURL)
}
if client.apiVersion != "api/v1" {
t.Errorf("Expected API version to be api/v1, got %s", client.apiVersion)
}
return client
}
func TestNewClient(t *testing.T) {
NewTestClient(t)
}
func TestClientWithOptions(t *testing.T) {
server := NewTestServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
client := NewWithOptions(
server.URL,
WithTimeout(5*time.Minute),
WithUserID("user"),
WithXToken("token"),
)
if client.HTTPClient.Timeout != 5*time.Minute {
t.Errorf("Expected timeout to be 5 minutes, got %v", client.HTTPClient.Timeout)
}
if client.baseURL != server.URL {
t.Errorf("Expected base URL to be %s, got %s", server.URL, client.baseURL)
}
if client.apiVersion != "api/v1" {
t.Errorf("Expected API version to be api/v1, got %s", client.apiVersion)
}
}

View File

@ -80,7 +80,9 @@ type InviteGroupResponse struct {
Ts time.Time `json:"ts"`
T string `json:"t"`
Name string `json:"name"`
Usernames []string `json:"usernames"`
Usernames []string `json:"usernames,omitempty"`
U UChat `json:"u"`
Username string `json:"username,omitempty"`
Msgs int `json:"msgs"`
UpdatedAt time.Time `json:"_updatedAt"`
Lm time.Time `json:"lm"`
@ -118,16 +120,17 @@ type GroupMembersResponse struct {
}
type GroupMessage struct {
ID string `json:"_id"`
Rid string `json:"rid"`
Msg string `json:"msg"`
Ts time.Time `json:"ts"`
U U `json:"u"`
UpdatedAt time.Time `json:"_updatedAt"`
Reactions []interface{} `json:"reactions"`
Mentions []U `json:"mentions"`
Channels []interface{} `json:"channels"`
Starred []interface{} `json:"starred"`
ID string `json:"_id"`
Rid string `json:"rid"`
Msg string `json:"msg"`
Ts time.Time `json:"ts"`
U U `json:"u"`
UpdatedAt time.Time `json:"_updatedAt"`
// todo create struct for these and uncomment in test
// Reactions []interface{} `json:"reactions"`
// Mentions []U `json:"mentions"`
// Channels []interface{} `json:"channels"`
// Starred []interface{} `json:"starred"`
}
type GroupMessagesResponse struct {
@ -153,7 +156,7 @@ type AddGroupPermissionRequest struct {
UserId string `json:"userId"`
}
// Archives a group.
// ArchiveGroup archives a group.
func (c *Client) ArchiveGroup(param *SimpleGroupId) (*SimpleSuccessResponse, error) {
opt, _ := json.Marshal(param)
@ -174,7 +177,7 @@ func (c *Client) ArchiveGroup(param *SimpleGroupId) (*SimpleSuccessResponse, err
return &res, nil
}
// Removes the group from the user's list of groups.
// CloseGroup closes a group.
func (c *Client) CloseGroup(param *SimpleGroupId) (*SimpleSuccessResponse, error) {
opt, _ := json.Marshal(param)
@ -195,7 +198,7 @@ func (c *Client) CloseGroup(param *SimpleGroupId) (*SimpleSuccessResponse, error
return &res, nil
}
// Gets group counters.
// GroupCounters gets counters of the group.
func (c *Client) GroupCounters(param *GroupCountersRequest) (*GroupCountersResponse, error) {
req, err := http.NewRequest("GET",
@ -203,7 +206,7 @@ func (c *Client) GroupCounters(param *GroupCountersRequest) (*GroupCountersRespo
nil)
if param.RoomName == "" && param.RoomId == "" {
return nil, fmt.Errorf("False parameters")
return nil, fmt.Errorf("false parameters")
}
url := req.URL.Query()
@ -228,7 +231,7 @@ func (c *Client) GroupCounters(param *GroupCountersRequest) (*GroupCountersRespo
return &res, nil
}
// Creates a new group.
// CreateGroup creates a group.
func (c *Client) CreateGroup(param *CreateGroupRequest) (*CreateGroupResponse, error) {
opt, _ := json.Marshal(param)
@ -249,7 +252,7 @@ func (c *Client) CreateGroup(param *CreateGroupRequest) (*CreateGroupResponse, e
return &res, nil
}
// Delete group.
// DeleteGroup deletes a group.
func (c *Client) DeleteGroup(param *SimpleGroupId) (*SimpleSuccessResponse, error) {
opt, _ := json.Marshal(param)
@ -270,7 +273,7 @@ func (c *Client) DeleteGroup(param *SimpleGroupId) (*SimpleSuccessResponse, erro
return &res, nil
}
// Get group info.
// GroupInfo gets group information.
func (c *Client) GroupInfo(param *SimpleGroupRequest) (*GroupInfoResponse, error) {
req, err := http.NewRequest("GET",
@ -278,7 +281,7 @@ func (c *Client) GroupInfo(param *SimpleGroupRequest) (*GroupInfoResponse, error
nil)
if param.RoomName == "" && param.RoomId == "" {
return nil, fmt.Errorf("False parameters")
return nil, fmt.Errorf("false parameters")
}
url := req.URL.Query()
@ -303,7 +306,7 @@ func (c *Client) GroupInfo(param *SimpleGroupRequest) (*GroupInfoResponse, error
return &res, nil
}
// Adds a user to the group.
// GroupInvite invites a user to the group.
func (c *Client) GroupInvite(param *InviteGroupRequest) (*InviteGroupResponse, error) {
opt, _ := json.Marshal(param)
@ -324,7 +327,7 @@ func (c *Client) GroupInvite(param *InviteGroupRequest) (*InviteGroupResponse, e
return &res, nil
}
// Kick a user from the group.
// GroupKick removes a user from the group.
func (c *Client) GroupKick(param *InviteGroupRequest) (*InviteGroupResponse, error) {
opt, _ := json.Marshal(param)
@ -345,7 +348,7 @@ func (c *Client) GroupKick(param *InviteGroupRequest) (*InviteGroupResponse, err
return &res, nil
}
// Get groups list
// GroupList gets the list of groups the caller is part of.
func (c *Client) GroupList() (*GroupListResponse, error) {
req, err := http.NewRequest("GET",
fmt.Sprintf("%s/%s/groups.list", c.baseURL, c.apiVersion),
@ -364,7 +367,7 @@ func (c *Client) GroupList() (*GroupListResponse, error) {
return &res, nil
}
// Gets group members
// GroupMembers gets the list of members of a group.
func (c *Client) GroupMembers(param *SimpleGroupRequest) (*GroupMembersResponse, error) {
req, err := http.NewRequest("GET",
@ -372,7 +375,7 @@ func (c *Client) GroupMembers(param *SimpleGroupRequest) (*GroupMembersResponse,
nil)
if param.RoomName == "" && param.RoomId == "" {
return nil, fmt.Errorf("False parameters")
return nil, fmt.Errorf("false parameters")
}
url := req.URL.Query()
@ -397,15 +400,14 @@ func (c *Client) GroupMembers(param *SimpleGroupRequest) (*GroupMembersResponse,
return &res, nil
}
// Gets group messages
// GroupMessages gets the messages from a group.
func (c *Client) GroupMessages(param *SimpleGroupRequest) (*GroupMessagesResponse, error) {
req, err := http.NewRequest("GET",
fmt.Sprintf("%s/%s/groups.messages", c.baseURL, c.apiVersion),
nil)
if param.RoomName == "" && param.RoomId == "" {
return nil, fmt.Errorf("False parameters")
return nil, fmt.Errorf("false parameters")
}
url := req.URL.Query()
@ -430,7 +432,7 @@ func (c *Client) GroupMessages(param *SimpleGroupRequest) (*GroupMessagesRespons
return &res, nil
}
// Adds the group back to the user's list of groups.
// OpenGroup opens a group.
func (c *Client) OpenGroup(param *SimpleGroupId) (*SimpleSuccessResponse, error) {
opt, _ := json.Marshal(param)
@ -451,7 +453,7 @@ func (c *Client) OpenGroup(param *SimpleGroupId) (*SimpleSuccessResponse, error)
return &res, nil
}
// Changes a group's name.
// RenameGroup renames a group.
func (c *Client) RenameGroup(param *RenameGroupRequest) (*RenameGroupResponse, error) {
opt, _ := json.Marshal(param)
@ -472,10 +474,10 @@ func (c *Client) RenameGroup(param *RenameGroupRequest) (*RenameGroupResponse, e
return &res, nil
}
// Add leader for the group.
// AddLeaderGroup adds a leader for the group.
func (c *Client) AddLeaderGroup(param *AddGroupPermissionRequest) (*SimpleSuccessResponse, error) {
if param.UserId == "" && param.RoomId == "" {
return nil, fmt.Errorf("False parameters")
return nil, fmt.Errorf("false parameters")
}
opt, _ := json.Marshal(param)
@ -497,10 +499,10 @@ func (c *Client) AddLeaderGroup(param *AddGroupPermissionRequest) (*SimpleSucces
return &res, nil
}
// Add owner for the group.
// AddOwnerGroup adds an owner for the group.
func (c *Client) AddOwnerGroup(param *AddGroupPermissionRequest) (*SimpleSuccessResponse, error) {
if param.UserId == "" && param.RoomId == "" {
return nil, fmt.Errorf("False parameters")
return nil, fmt.Errorf("false parameters")
}
opt, _ := json.Marshal(param)
@ -522,7 +524,7 @@ func (c *Client) AddOwnerGroup(param *AddGroupPermissionRequest) (*SimpleSuccess
return &res, nil
}
// Sets the announcement for the group.
// SetAnnouncementGroup sets the announcement for the group.
func (c *Client) SetAnnouncementGroup(param *SetAnnouncementRequest) (*SetAnnouncementResponse, error) {
opt, _ := json.Marshal(param)
@ -543,7 +545,7 @@ func (c *Client) SetAnnouncementGroup(param *SetAnnouncementRequest) (*SetAnnoun
return &res, nil
}
// Sets the Description for the group.
// SetDescriptionGroup sets the description for the group.
func (c *Client) SetDescriptionGroup(param *SetDescriptionRequest) (*SetDescriptionResponse, error) {
opt, _ := json.Marshal(param)
@ -564,7 +566,7 @@ func (c *Client) SetDescriptionGroup(param *SetDescriptionRequest) (*SetDescript
return &res, nil
}
// Sets the topic for the group.
// SetTopicGroup sets the topic for the group.
func (c *Client) SetTopicGroup(param *SetTopicRequest) (*SetTopicResponse, error) {
opt, _ := json.Marshal(param)
@ -585,7 +587,7 @@ func (c *Client) SetTopicGroup(param *SetTopicRequest) (*SetTopicResponse, error
return &res, nil
}
// Unarchive a group.
// UnarchiveGroup unarchives a group.
func (c *Client) UnarchiveGroup(param *SimpleGroupId) (*SimpleSuccessResponse, error) {
opt, _ := json.Marshal(param)

440
groups_test.go Normal file
View File

@ -0,0 +1,440 @@
package gorocket
import (
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
)
func TestArchiveGroup(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := SimpleGroupId{
RoomId: "GENERAL",
}
resp, err := client.ArchiveGroup(&req)
require.NoError(t, err)
require.True(t, resp.Success)
}
func TestCloseGroup(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
req := SimpleGroupId{
RoomId: "GENERAL",
}
resp, err := client.CloseGroup(&req)
require.NoError(t, err)
require.True(t, resp.Success)
}
func TestGroupCounters(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"joined":true,"members":1,"unreads":1,"unreadsFrom":"2018-02-18T21:51:20.091Z","msgs":1,"latest":"2018-02-23T17:20:17.345Z","userMentions":0,"success":true}`,
}))
defer server.Close()
req := GroupCountersRequest{
RoomId: "GENERAL",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.GroupCounters(&req)
require.NoError(t, err)
require.True(t, resp.Success)
require.True(t, resp.Joined)
require.Equal(t, 1, resp.Members)
require.Equal(t, 1, resp.Unreads)
require.Equal(t, "2018-02-18T21:51:20.091Z", resp.UnreadsFrom.Format("2006-01-02T15:04:05.000Z"))
require.Equal(t, 1, resp.Msgs)
require.Equal(t, "2018-02-23T17:20:17.345Z", resp.Latest.Format("2006-01-02T15:04:05.000Z"))
require.Equal(t, 0, resp.UserMentions)
}
func TestCreateGroup(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"group":{"_id":"NtR6RQ7NvzA9ejecX","name":"testing","t":"p","msgs":0,"u":{"_id":"aobEdbYhXfu5hkeqG","username":"tester"},"ts":"2016-12-09T16:53:06.761Z","ro":false,"sysMes":true,"_updatedAt":"2016-12-09T16:53:06.761Z"},"success":true}`,
}))
defer server.Close()
req := CreateGroupRequest{
Name: "GENERAL",
ReadOnly: false,
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.CreateGroup(&req)
require.NoError(t, err)
require.True(t, resp.Success)
require.Equal(t, "NtR6RQ7NvzA9ejecX", resp.Group.ID)
require.Equal(t, "testing", resp.Group.Name)
require.Equal(t, "p", resp.Group.T)
require.Equal(t, 0, resp.Group.Msgs)
require.Equal(t, "aobEdbYhXfu5hkeqG", resp.Group.U.ID)
require.Equal(t, "tester", resp.Group.U.Username)
require.Equal(t, "2016-12-09T16:53:06.761Z", resp.Group.Ts.Format("2006-01-02T15:04:05.000Z"))
}
func TestDeleteGroup(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"success":true}`,
}))
defer server.Close()
req := SimpleGroupId{
RoomId: "GENERAL",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.DeleteGroup(&req)
require.NoError(t, err)
require.True(t, resp.Success)
}
func TestGroupInfo(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"group":{"_id":"ByehQjC44FwMeiLbX","name":"testing","fname":"testing","t":"p","msgs":0,"usersCount":2,"u":{"_id":"HKKPmF8rZh45GMHWH","username":"marcos.defendi"},"customFields":{},"broadcast":false,"encrypted":false,"ts":"2020-05-21T13:16:24.749Z","ro":false,"default":false,"sysMes":true,"_updatedAt":"2020-05-21T13:16:24.772Z"},"success":true}`,
}))
defer server.Close()
req := SimpleGroupRequest{
RoomId: "GENERAL",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.GroupInfo(&req)
require.NoError(t, err)
require.True(t, resp.Success)
require.Equal(t, "ByehQjC44FwMeiLbX", resp.Group.ID)
require.Equal(t, "testing", resp.Group.Name)
require.Equal(t, "testing", resp.Group.Fname)
require.Equal(t, "p", resp.Group.T)
require.Equal(t, 0, resp.Group.Msgs)
require.Equal(t, 2, resp.Group.UsersCount)
require.Equal(t, "HKKPmF8rZh45GMHWH", resp.Group.U.ID)
require.Equal(t, "marcos.defendi", resp.Group.U.Username)
require.False(t, resp.Group.Broadcast)
require.False(t, resp.Group.Encrypted)
require.Equal(t, "2020-05-21T13:16:24.749Z", resp.Group.Ts.Format("2006-01-02T15:04:05.000Z"))
require.False(t, resp.Group.Ro)
require.False(t, resp.Group.Default)
require.True(t, resp.Group.SysMes)
require.Equal(t, "2020-05-21T13:16:24.772Z", resp.Group.UpdatedAt.Format("2006-01-02T15:04:05.000Z"))
}
func TestGroupInvite(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"group":{"_id":"ByehQjC44FwMeiLbX","ts":"2016-11-30T21:23:04.737Z","t":"p","name":"testing","username":"testing","u":{"_id":"aobEdbYhXfu5hkeqG","username":"testing1"},"msgs":1,"_updatedAt":"2016-12-09T12:50:51.575Z","lm":"2016-12-09T12:50:51.555Z"},"success":true}`,
}))
defer server.Close()
req := InviteGroupRequest{
RoomId: "GENERAL",
UserId: "1234",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.GroupInvite(&req)
require.NoError(t, err)
require.True(t, resp.Success)
require.Equal(t, "ByehQjC44FwMeiLbX", resp.Group.ID)
require.Equal(t, "2016-11-30T21:23:04.737Z", resp.Group.Ts.Format("2006-01-02T15:04:05.000Z"))
require.Equal(t, "p", resp.Group.T)
require.Equal(t, "testing", resp.Group.Name)
require.Equal(t, "testing", resp.Group.Username)
require.Equal(t, "aobEdbYhXfu5hkeqG", resp.Group.U.ID)
require.Equal(t, "testing1", resp.Group.U.Username)
require.Equal(t, 1, resp.Group.Msgs)
require.Equal(t, "2016-12-09T12:50:51.575Z", resp.Group.UpdatedAt.Format("2006-01-02T15:04:05.000Z"))
require.Equal(t, "2016-12-09T12:50:51.555Z", resp.Group.Lm.Format("2006-01-02T15:04:05.000Z"))
}
func TestGroupKick(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"group":{"_id":"ByehQjC44FwMeiLbX","ts":"2016-11-30T21:23:04.737Z","t":"p","name":"testing","username":"testing","u":{"_id":"aobEdbYhXfu5hkeqG","username":"testing1"},"msgs":1,"_updatedAt":"2016-12-09T12:50:51.575Z","lm":"2016-12-09T12:50:51.555Z"},"success":true}`,
}))
defer server.Close()
req := InviteGroupRequest{
RoomId: "GENERAL",
UserId: "1234",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.GroupKick(&req)
require.NoError(t, err)
require.True(t, resp.Success)
require.Equal(t, "ByehQjC44FwMeiLbX", resp.Group.ID)
require.Equal(t, "2016-11-30T21:23:04.737Z", resp.Group.Ts.Format("2006-01-02T15:04:05.000Z"))
require.Equal(t, "p", resp.Group.T)
require.Equal(t, "testing", resp.Group.Name)
require.Equal(t, "testing", resp.Group.Username)
require.Equal(t, "aobEdbYhXfu5hkeqG", resp.Group.U.ID)
require.Equal(t, "testing1", resp.Group.U.Username)
require.Equal(t, 1, resp.Group.Msgs)
require.Equal(t, "2016-12-09T12:50:51.575Z", resp.Group.UpdatedAt.Format("2006-01-02T15:04:05.000Z"))
require.Equal(t, "2016-12-09T12:50:51.555Z", resp.Group.Lm.Format("2006-01-02T15:04:05.000Z"))
}
func TestGroupList(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"groups":[{"_id":"ByehQjC44FwMeiLbX","name":"test-test","t":"p","msgs":0,"u":{"_id":"aobEdbYhXfu5hkeqG","username":"testing1"},"ts":"2016-12-09T15:08:58.042Z","ro":false,"sysMes":true,"_updatedAt":"2016-12-09T15:22:40.656Z"},{"_id":"t7qapfhZjANMRAi5w","name":"testing","t":"p","msgs":0,"u":{"_id":"y65tAmHs93aDChMWu","username":"testing2"},"ts":"2016-12-01T15:08:58.042Z","ro":false,"sysMes":true,"_updatedAt":"2016-12-09T15:22:40.656Z"}],"offset":0,"count":1,"total":1,"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.GroupList()
require.NoError(t, err)
require.True(t, resp.Success)
require.Equal(t, 0, resp.Offset)
require.Equal(t, 1, resp.Count)
require.Equal(t, 1, resp.Total)
require.Equal(t, 2, len(resp.Groups))
require.Equal(t, "ByehQjC44FwMeiLbX", resp.Groups[0].ID)
require.Equal(t, "test-test", resp.Groups[0].Name)
require.Equal(t, "p", resp.Groups[0].T)
require.Equal(t, 0, resp.Groups[0].Msgs)
require.Equal(t, "aobEdbYhXfu5hkeqG", resp.Groups[0].U.ID)
require.Equal(t, "testing1", resp.Groups[0].U.Username)
require.Equal(t, "2016-12-09T15:08:58.042Z", resp.Groups[0].Ts.Format("2006-01-02T15:04:05.000Z"))
require.False(t, resp.Groups[0].Ro)
require.True(t, resp.Groups[0].SysMes)
require.Equal(t, "2016-12-09T15:22:40.656Z", resp.Groups[0].UpdatedAt.Format("2006-01-02T15:04:05.000Z"))
require.Equal(t, "t7qapfhZjANMRAi5w", resp.Groups[1].ID)
require.Equal(t, "testing", resp.Groups[1].Name)
require.Equal(t, "p", resp.Groups[1].T)
require.Equal(t, 0, resp.Groups[1].Msgs)
require.Equal(t, "y65tAmHs93aDChMWu", resp.Groups[1].U.ID)
require.Equal(t, "testing2", resp.Groups[1].U.Username)
require.Equal(t, "2016-12-01T15:08:58.042Z", resp.Groups[1].Ts.Format("2006-01-02T15:04:05.000Z"))
require.False(t, resp.Groups[1].Ro)
require.True(t, resp.Groups[1].SysMes)
require.Equal(t, "2016-12-09T15:22:40.656Z", resp.Groups[1].UpdatedAt.Format("2006-01-02T15:04:05.000Z"))
}
func TestGroupMembers(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"members":[{"_id":"Q4GkX6RMepGDdQ7YJ","status":"online","name":"Marcos Defendi","utcOffset":-3,"username":"marcos.defendi"},{"_id":"rocket.cat","name":"Rocket.Cat","username":"rocket.cat","status":"online","utcOffset":0}],"count":2,"offset":0,"total":2,"success":true}`,
}))
defer server.Close()
req := SimpleGroupRequest{
RoomId: "GENERAL",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.GroupMembers(&req)
require.NoError(t, err)
require.True(t, resp.Success)
require.Equal(t, 2, resp.Count)
require.Equal(t, 0, resp.Offset)
require.Equal(t, 2, resp.Total)
require.Equal(t, 2, len(resp.Members))
require.Equal(t, "Q4GkX6RMepGDdQ7YJ", resp.Members[0].ID)
require.Equal(t, "online", resp.Members[0].Status)
require.Equal(t, "Marcos Defendi", resp.Members[0].Name)
require.Equal(t, "marcos.defendi", resp.Members[0].Username)
require.Equal(t, "rocket.cat", resp.Members[1].ID)
require.Equal(t, "Rocket.Cat", resp.Members[1].Name)
require.Equal(t, "rocket.cat", resp.Members[1].Username)
require.Equal(t, "online", resp.Members[1].Status)
}
func TestGroupMessages(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"messages":[{"_id":"CeXwh5eBbdrtvnqG6","rid":"agh2Sucgb54RQ8dDo","msg":"s","ts":"2018-10-05T13:48:21.616Z","u":{"_id":"KPkEYwKKBKZnEEPpt","username":"marcos.defendi","name":"Marcos Defendi"},"_updatedAt":"2018-10-05T13:48:49.535Z","reactions":{":frowning2:":{"usernames":["marcos.defendi"]}},"mentions":[],"channels":[],"starred":{"_id":"KPkEYwKKBKZnEEPpt"}},{"_id":"MrAeupRiF9TvhMesK","t":"room_changed_privacy","rid":"agh2Sucgb54RQ8dDo","ts":"2018-10-05T00:11:16.998Z","msg":"Private Group","u":{"_id":"rocketchat.internal.admin.test","username":"rocketchat.internal.admin.test"},"groupable":false,"_updatedAt":"2018-10-05T00:11:16.998Z"}],"count":2,"offset":0,"total":2,"success":true}`,
}))
defer server.Close()
req := SimpleGroupRequest{
RoomId: "GENERAL",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.GroupMessages(&req)
require.NoError(t, err)
require.True(t, resp.Success)
require.Equal(t, 2, resp.Count)
require.Equal(t, 0, resp.Offset)
require.Equal(t, 2, resp.Total)
require.Equal(t, 2, len(resp.Messages))
require.Equal(t, "CeXwh5eBbdrtvnqG6", resp.Messages[0].ID)
require.Equal(t, "agh2Sucgb54RQ8dDo", resp.Messages[0].Rid)
require.Equal(t, "s", resp.Messages[0].Msg)
require.Equal(t, "2018-10-05T13:48:21.616Z", resp.Messages[0].Ts.Format("2006-01-02T15:04:05.000Z"))
require.Equal(t, "KPkEYwKKBKZnEEPpt", resp.Messages[0].U.ID)
require.Equal(t, "marcos.defendi", resp.Messages[0].U.Username)
require.Equal(t, "Marcos Defendi", resp.Messages[0].U.Name)
require.Equal(t, "2018-10-05T13:48:49.535Z", resp.Messages[0].UpdatedAt.Format("2006-01-02T15:04:05.000Z"))
// require.Equal(t, 1, len(resp.Messages[0].Reactions))
// require.Equal(t, 0, len(resp.Messages[0].Mentions))
// require.Equal(t, 0, len(resp.Messages[0].Channels))
require.Equal(t, "MrAeupRiF9TvhMesK", resp.Messages[1].ID)
require.Equal(t, "agh2Sucgb54RQ8dDo", resp.Messages[1].Rid)
require.Equal(t, "2018-10-05T00:11:16.998Z", resp.Messages[1].Ts.Format("2006-01-02T15:04:05.000Z"))
require.Equal(t, "rocketchat.internal.admin.test", resp.Messages[1].U.ID)
require.Equal(t, "rocketchat.internal.admin.test", resp.Messages[1].U.Username)
require.Equal(t, "Private Group", resp.Messages[1].Msg)
require.Equal(t, "2018-10-05T00:11:16.998Z", resp.Messages[1].UpdatedAt.Format("2006-01-02T15:04:05.000Z"))
}
func TestOpenGroup(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"success":true}`,
}))
defer server.Close()
req := SimpleGroupId{
RoomId: "GENERAL",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.OpenGroup(&req)
require.NoError(t, err)
require.True(t, resp.Success)
}
func TestRenameGroup(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"group":{"_id":"ByehQjC44FwMeiLbX","name":"new-name","t":"p","usernames":["testing1"],"msgs":4,"u":{"_id":"aobEdbYhXfu5hkeqG","username":"testing1"},"ts":"2016-12-09T15:08:58.042Z","ro":false,"sysMes":true,"_updatedAt":"2016-12-09T15:57:44.686Z"},"success":true}`,
}))
defer server.Close()
req := RenameGroupRequest{
RoomId: "GENERAL",
NewName: "new-name",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.RenameGroup(&req)
require.NoError(t, err)
require.True(t, resp.Success)
require.Equal(t, "ByehQjC44FwMeiLbX", resp.Group.ID)
require.Equal(t, "new-name", resp.Group.Name)
require.Equal(t, "p", resp.Group.T)
require.Equal(t, 1, len(resp.Group.Usernames))
require.Equal(t, "testing1", resp.Group.Usernames[0])
require.Equal(t, 4, resp.Group.Msgs)
require.Equal(t, "aobEdbYhXfu5hkeqG", resp.Group.U.ID)
require.Equal(t, "testing1", resp.Group.U.Username)
require.Equal(t, "2016-12-09T15:08:58.042Z", resp.Group.Ts.Format("2006-01-02T15:04:05.000Z"))
require.False(t, resp.Group.Ro)
require.True(t, resp.Group.SysMes)
require.Equal(t, "2016-12-09T15:57:44.686Z", resp.Group.UpdatedAt.Format("2006-01-02T15:04:05.000Z"))
}
func TestAddLeaderGroup(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"success":true}`,
}))
defer server.Close()
req := AddGroupPermissionRequest{
RoomId: "GENERAL",
UserId: "1234",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.AddLeaderGroup(&req)
require.NoError(t, err)
require.True(t, resp.Success)
}
func TestAddOwnerGroup(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"success":true}`,
}))
defer server.Close()
req := AddGroupPermissionRequest{
RoomId: "GENERAL",
UserId: "1234",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.AddOwnerGroup(&req)
require.NoError(t, err)
require.True(t, resp.Success)
}
func TestSetAnnouncementGroup(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"announcement": "Test out everything","success":true}`,
}))
defer server.Close()
req := SetAnnouncementRequest{
RoomId: "GENERAL",
Announcement: "Test out everything",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.SetAnnouncementGroup(&req)
require.NoError(t, err)
require.True(t, resp.Success)
require.Equal(t, "Test out everything", resp.Announcement)
}
func TestSetDescriptionGroup(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"description": "Test out everything","success":true}`,
}))
defer server.Close()
req := SetDescriptionRequest{
RoomId: "GENERAL",
Description: "Test out everything",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.SetDescriptionGroup(&req)
require.NoError(t, err)
require.True(t, resp.Success)
require.Equal(t, "Test out everything", resp.Description)
}
func TestSetTopicGroup(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"topic": "Test out everything","success":true}`,
}))
defer server.Close()
req := SetTopicRequest{
RoomId: "GENERAL",
Topic: "Test out everything",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.SetTopicGroup(&req)
require.NoError(t, err)
require.True(t, resp.Success)
require.Equal(t, "Test out everything", resp.Topic)
}
func TestUnarchiveGroup(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"success":true}`,
}))
defer server.Close()
req := SimpleGroupId{
RoomId: "GENERAL",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.UnarchiveGroup(&req)
require.NoError(t, err)
require.True(t, resp.Success)
}

26
helper.go Normal file
View File

@ -0,0 +1,26 @@
package gorocket
import (
"net/http"
"testing"
"github.com/stretchr/testify/require"
)
type HandlerHelper struct {
Code int
ResponseBody string
}
func getHandler(t *testing.T, param *HandlerHelper) http.HandlerFunc {
httpStatus := param.Code
if httpStatus == 0 {
httpStatus = http.StatusOK
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(httpStatus)
_, err := w.Write([]byte(param.ResponseBody))
require.NoError(t, err)
})
}

View File

@ -34,8 +34,6 @@ func (c *Client) Hooks(msg *HookMessage, token string) (*HookResponse, error) {
url,
bytes.NewBuffer(opt))
fmt.Println(url)
req.Header.Set("Accept", "application/json; charset=utf-8")
req.Header.Set("Content-Type", "application/json; charset=utf-8")
@ -45,7 +43,6 @@ func (c *Client) Hooks(msg *HookMessage, token string) (*HookResponse, error) {
}
res, err := c.HTTPClient.Do(req)
defer res.Body.Close()
if err != nil {

34
hooks_test.go Normal file
View File

@ -0,0 +1,34 @@
package gorocket
import (
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
)
func TestHooks(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
msg := HookMessage{
Text: "Hello",
Attachments: []HookAttachment{
{
Title: "Title",
TitleLink: "http://example.com",
Text: "Text",
ImageURL: "http://example.com/image.png",
Color: "#ff0000",
},
},
}
resp, err := client.Hooks(&msg, "token")
require.NoError(t, err)
require.True(t, resp.Success)
}

28
info.go
View File

@ -7,7 +7,8 @@ import (
)
type RespInfo struct {
Info struct {
Version string `json:"version"`
Info struct {
Version string `json:"version"`
Build Build `json:"build"`
Commit Commit `json:"commit"`
@ -37,11 +38,20 @@ type Commit struct {
}
type RespDirectory struct {
Result []Result `json:"result"`
Count int `json:"count"`
Offset int `json:"offset"`
Total int `json:"total"`
Success bool `json:"success"`
Result []DirectoryResult `json:"result"`
Count int `json:"count"`
Offset int `json:"offset"`
Total int `json:"total"`
Success bool `json:"success"`
}
type DirectoryResult struct {
ID string `json:"_id"`
CreatedAt time.Time `json:"createdAt"`
Emails []Email `json:"emails"`
Name string `json:"name"`
Username string `json:"username"`
AvatarETag string `json:"avatarETag"`
}
type Result struct {
@ -88,6 +98,7 @@ type UsersInfo struct {
Name string `json:"name"`
Username string `json:"username"`
StatusText string `json:"statusText"`
AvatarETag string `json:"avatarETag,omitempty"`
}
type RoomsInfo struct {
@ -298,6 +309,7 @@ type RespStatisticsList struct {
Success bool `json:"success"`
}
// Info returns information about the server
func (c *Client) Info() (*RespInfo, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/info", c.baseURL), nil)
if err != nil {
@ -312,6 +324,7 @@ func (c *Client) Info() (*RespInfo, error) {
return &res, nil
}
// Directory returns a list of channels
func (c *Client) Directory() (*RespDirectory, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s/directory", c.baseURL, c.apiVersion), nil)
if err != nil {
@ -326,6 +339,7 @@ func (c *Client) Directory() (*RespDirectory, error) {
return &res, nil
}
// Spotlight returns a list of users and rooms that match the provided query
func (c *Client) Spotlight(query string) (*RespSpotlight, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s/spotlight?query=%s", c.baseURL, c.apiVersion, query), nil)
@ -341,6 +355,7 @@ func (c *Client) Spotlight(query string) (*RespSpotlight, error) {
return &res, nil
}
// Statistics returns statistics about the server
func (c *Client) Statistics() (*RespStatistics, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s/statistics", c.baseURL, c.apiVersion), nil)
if err != nil {
@ -355,6 +370,7 @@ func (c *Client) Statistics() (*RespStatistics, error) {
return &res, nil
}
// StatisticsList returns a list of statistics
func (c *Client) StatisticsList() (*RespStatisticsList, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s/statistics.list", c.baseURL, c.apiVersion), nil)
if err != nil {

201
info_test.go Normal file
View File

@ -0,0 +1,201 @@
package gorocket
import (
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
)
func TestInfo(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"version":"6.5.2","info":{"version":"6.5.2","build":{"date":"2024-01-03T03:33:06.277Z","nodeVersion":"v14.21.4","arch":"x64","platform":"linux","osRelease":"5.15.0-1053-azure","totalMemory":16768364544,"freeMemory":812339200,"cpus":4},"marketplaceApiVersion":"1.41.0","commit":{"hash":"3ebc8e0868c859d2d8e636787645c29a89dea1e5","date":"Tue Jan 2 23:38:47 2024 -0300","author":"Diego Sampaio","subject":"chore: fix dep version","tag":"6.5.2","branch":"HEAD"}},"minimumClientVersions":{"desktop":"3.9.6","mobile":"4.39.0"},"supportedVersions":{"signed":"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9"},"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.Info()
require.NoError(t, err)
require.Equal(t, "6.5.2", resp.Version)
require.Equal(t, "6.5.2", resp.Info.Version)
require.Equal(t, "2024-01-03T03:33:06.277Z", resp.Info.Build.Date.Format("2006-01-02T15:04:05.000Z"))
require.Equal(t, "v14.21.4", resp.Info.Build.NodeVersion)
require.Equal(t, "x64", resp.Info.Build.Arch)
require.Equal(t, "linux", resp.Info.Build.Platform)
require.Equal(t, "5.15.0-1053-azure", resp.Info.Build.OsRelease)
require.Equal(t, int64(16768364544), resp.Info.Build.TotalMemory)
require.Equal(t, 812339200, resp.Info.Build.FreeMemory)
require.Equal(t, 4, resp.Info.Build.Cpus)
require.Equal(t, "1.41.0", resp.Info.MarketplaceAPIVersion)
require.Equal(t, "3ebc8e0868c859d2d8e636787645c29a89dea1e5", resp.Info.Commit.Hash)
require.Equal(t, "Tue Jan 2 23:38:47 2024 -0300", resp.Info.Commit.Date)
require.Equal(t, "Diego Sampaio", resp.Info.Commit.Author)
require.Equal(t, "chore: fix dep version", resp.Info.Commit.Subject)
require.Equal(t, "6.5.2", resp.Info.Commit.Tag)
require.Equal(t, "HEAD", resp.Info.Commit.Branch)
}
func TestDirectory(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"result":[{"_id":"jRca8kibJx8NkLJxt","createdAt":"2018-04-13T12:46:26.517Z","emails":[{"address":"user.test.1523623548558@rocket.chat","verified":false}],"name":"EditedRealNameuser.test.1523623548558","username":"editedusernameuser.test.1523623548558","avatarETag":"6YbLtc4v9b4conXon"}],"count":1,"offset":0,"total":1,"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.Directory()
require.NoError(t, err)
require.Equal(t, 1, resp.Count)
require.Equal(t, 0, resp.Offset)
require.Equal(t, 1, resp.Total)
require.Equal(t, "jRca8kibJx8NkLJxt", resp.Result[0].ID)
require.Equal(t, "2018-04-13T12:46:26.517Z", resp.Result[0].CreatedAt.Format("2006-01-02T15:04:05.000Z"))
require.Equal(t, "user.test.1523623548558@rocket.chat", resp.Result[0].Emails[0].Address)
require.Equal(t, false, resp.Result[0].Emails[0].Verified)
require.Equal(t, "EditedRealNameuser.test.1523623548558", resp.Result[0].Name)
require.Equal(t, "editedusernameuser.test.1523623548558", resp.Result[0].Username)
require.Equal(t, "6YbLtc4v9b4conXon", resp.Result[0].AvatarETag)
}
func TestSpotlight(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"users":[{"_id":"rocket.cat","name":"Rocket.Cat","username":"rocket.cat","status":"online","avatarETag":"5BB9B5ny5DkKdrwkq"}],"rooms":[],"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.Spotlight("rocket")
require.NoError(t, err)
require.Equal(t, 1, len(resp.Users))
require.Equal(t, "rocket.cat", resp.Users[0].ID)
require.Equal(t, "Rocket.Cat", resp.Users[0].Name)
require.Equal(t, "rocket.cat", resp.Users[0].Username)
require.Equal(t, "online", resp.Users[0].Status)
require.Equal(t, "5BB9B5ny5DkKdrwkq", resp.Users[0].AvatarETag)
require.Equal(t, 0, len(resp.Rooms))
}
func TestStatistics(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"_id":"wufRdmSrjmSMhBdTN","uniqueId":"wD4EP3M7FeFzJZgk9","installedAt":"2018-02-18T19:40:45.369Z","version":"0.61.0-develop","totalUsers":88,"activeUsers":88,"nonActiveUsers":0,"onlineUsers":0,"awayUsers":1,"offlineUsers":87,"totalRooms":81,"totalChannels":41,"totalPrivateGroups":37,"totalDirect":3,"totlalLivechat":0,"totalMessages":2408,"totalChannelMessages":730,"totalPrivateGroupMessages":1869,"totalDirectMessages":25,"totalLivechatMessages":0,"lastLogin":"2018-02-24T12:44:45.045Z","lastMessageSentAt":"2018-02-23T18:14:03.490Z","lastSeenSubscription":"2018-02-23T17:58:54.779Z","os":{"type":"Linux","platform":"linux","arch":"x64","release":"4.13.0-32-generic","uptime":76242,"loadavg":[0.0576171875,0.04638671875,0.00439453125],"totalmem":5787901952,"freemem":1151168512,"cpus":[{"model":"Intel(R) Xeon(R) CPU E5620 @ 2.40GHz","speed":2405,"times":{"user":6437000,"nice":586500,"sys":1432200,"idle":750117500,"irq":0}},{"model":"Intel(R) Xeon(R) CPU E5620 @ 2.40GHz","speed":2405,"times":{"user":7319700,"nice":268800,"sys":1823600,"idle":747642700,"irq":0}},{"model":"Intel(R) Xeon(R) CPU E5620 @ 2.40GHz","speed":2405,"times":{"user":7484600,"nice":1003500,"sys":1446000,"idle":748873400,"irq":0}},{"model":"Intel(R) Xeon(R) CPU E5620 @ 2.40GHz","speed":2405,"times":{"user":8378200,"nice":548500,"sys":1443200,"idle":747053300,"irq":0}}]},"process":{"nodeVersion":"v8.9.4","pid":11736,"uptime":16265.506},"deploy":{"method":"tar","platform":"selfinstall"},"migration":{"_id":"control","version":106,"locked":false,"lockedAt":"2018-02-23T18:13:13.948Z","buildAt":"2018-02-18T17:22:51.212Z"},"instanceCount":1,"createdAt":"2018-02-24T13:13:00.236Z","_updatedAt":"2018-02-24T13:13:00.236Z","success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.Statistics()
require.NoError(t, err)
require.Equal(t, "wufRdmSrjmSMhBdTN", resp.ID)
require.Equal(t, "wD4EP3M7FeFzJZgk9", resp.UniqueID)
require.Equal(t, "2018-02-18T19:40:45.369Z", resp.InstalledAt.Format("2006-01-02T15:04:05.000Z"))
require.Equal(t, "0.61.0-develop", resp.Version)
require.Equal(t, 88, resp.TotalUsers)
require.Equal(t, 88, resp.ActiveUsers)
require.Equal(t, 0, resp.NonActiveUsers)
require.Equal(t, 0, resp.OnlineUsers)
require.Equal(t, 1, resp.AwayUsers)
require.Equal(t, 87, resp.OfflineUsers)
require.Equal(t, 81, resp.TotalRooms)
require.Equal(t, 41, resp.TotalChannels)
require.Equal(t, 37, resp.TotalPrivateGroups)
require.Equal(t, 3, resp.TotalDirect)
require.Equal(t, 0, resp.TotalLivechat)
require.Equal(t, 2408, resp.TotalMessages)
require.Equal(t, 730, resp.TotalChannelMessages)
require.Equal(t, 1869, resp.TotalPrivateGroupMessages)
require.Equal(t, 25, resp.TotalDirectMessages)
require.Equal(t, 0, resp.TotalLivechatMessages)
require.Equal(t, "2018-02-24T12:44:45.045Z", resp.LastLogin.Format("2006-01-02T15:04:05.000Z"))
require.Equal(t, "2018-02-23T18:14:03.490Z", resp.LastMessageSentAt.Format("2006-01-02T15:04:05.000Z"))
require.Equal(t, "2018-02-23T17:58:54.779Z", resp.LastSeenSubscription.Format("2006-01-02T15:04:05.000Z"))
require.Equal(t, "Linux", resp.Os.Type)
require.Equal(t, "linux", resp.Os.Platform)
require.Equal(t, "x64", resp.Os.Arch)
require.Equal(t, "4.13.0-32-generic", resp.Os.Release)
require.Equal(t, 76242, resp.Os.Uptime)
require.Equal(t, int64(5787901952), resp.Os.Totalmem)
require.Equal(t, 1151168512, resp.Os.Freemem)
require.Equal(t, 4, len(resp.Os.Cpus))
require.Equal(t, "Intel(R) Xeon(R) CPU E5620 @ 2.40GHz", resp.Os.Cpus[0].Model)
require.Equal(t, 2405, resp.Os.Cpus[0].Speed)
require.Equal(t, 6437000, resp.Os.Cpus[0].Times.User)
require.Equal(t, 586500, resp.Os.Cpus[0].Times.Nice)
require.Equal(t, 1432200, resp.Os.Cpus[0].Times.Sys)
require.Equal(t, 750117500, resp.Os.Cpus[0].Times.Idle)
require.Equal(t, 0, resp.Os.Cpus[0].Times.Irq)
require.Equal(t, "Intel(R) Xeon(R) CPU E5620 @ 2.40GHz", resp.Os.Cpus[1].Model)
require.Equal(t, 2405, resp.Os.Cpus[1].Speed)
require.Equal(t, 7319700, resp.Os.Cpus[1].Times.User)
require.Equal(t, 268800, resp.Os.Cpus[1].Times.Nice)
require.Equal(t, 1823600, resp.Os.Cpus[1].Times.Sys)
require.Equal(t, 747642700, resp.Os.Cpus[1].Times.Idle)
require.Equal(t, 0, resp.Os.Cpus[1].Times.Irq)
require.Equal(t, "Intel(R) Xeon(R) CPU E5620 @ 2.40GHz", resp.Os.Cpus[2].Model)
require.Equal(t, 2405, resp.Os.Cpus[2].Speed)
require.Equal(t, 7484600, resp.Os.Cpus[2].Times.User)
require.Equal(t, 1003500, resp.Os.Cpus[2].Times.Nice)
require.Equal(t, 1446000, resp.Os.Cpus[2].Times.Sys)
require.Equal(t, 748873400, resp.Os.Cpus[2].Times.Idle)
require.Equal(t, 0, resp.Os.Cpus[2].Times.Irq)
require.Equal(t, "Intel(R) Xeon(R) CPU E5620 @ 2.40GHz", resp.Os.Cpus[3].Model)
require.Equal(t, 2405, resp.Os.Cpus[3].Speed)
require.Equal(t, 8378200, resp.Os.Cpus[3].Times.User)
require.Equal(t, 548500, resp.Os.Cpus[3].Times.Nice)
require.Equal(t, 1443200, resp.Os.Cpus[3].Times.Sys)
require.Equal(t, 747053300, resp.Os.Cpus[3].Times.Idle)
require.Equal(t, 0, resp.Os.Cpus[3].Times.Irq)
require.Equal(t, "v8.9.4", resp.Process.NodeVersion)
require.Equal(t, 11736, resp.Process.Pid)
require.Equal(t, 16265.506, resp.Process.Uptime)
require.Equal(t, "tar", resp.Deploy.Method)
require.Equal(t, "selfinstall", resp.Deploy.Platform)
require.Equal(t, "control", resp.Migration.ID)
require.Equal(t, 106, resp.Migration.Version)
require.Equal(t, false, resp.Migration.Locked)
require.Equal(t, 1, resp.InstanceCount)
require.Equal(t, "2018-02-24T13:13:00.236Z", resp.CreatedAt.Format("2006-01-02T15:04:05.000Z"))
require.Equal(t, "2018-02-24T13:13:00.236Z", resp.UpdatedAt.Format("2006-01-02T15:04:05.000Z"))
}
func TestStatisticsList(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"statistics":[{"_id":"v3D4mvobwfznKozH8","uniqueId":"wD4EP3M7FeFzJZgk9","installedAt":"2018-02-18T19:40:45.369Z","version":"0.61.0-develop","totalUsers":88,"activeUsers":88,"nonActiveUsers":0,"onlineUsers":0,"awayUsers":1,"offlineUsers":87,"totalRooms":81,"totalChannels":41,"totalPrivateGroups":37,"totalDirect":3,"totlalLivechat":0,"totalMessages":2408,"totalChannelMessages":730,"totalPrivateGroupMessages":1869,"totalDirectMessages":25,"totalLivechatMessages":0,"lastLogin":"2018-02-24T12:44:45.045Z","lastMessageSentAt":"2018-02-23T18:14:03.490Z","lastSeenSubscription":"2018-02-23T17:58:54.779Z","instanceCount":1,"createdAt":"2018-02-24T15:13:00.312Z","_updatedAt":"2018-02-24T15:13:00.312Z"}],"count":1,"offset":0,"total":1,"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.StatisticsList()
require.NoError(t, err)
require.Equal(t, 1, resp.Count)
require.Equal(t, 0, resp.Offset)
require.Equal(t, 1, resp.Total)
require.Equal(t, "v3D4mvobwfznKozH8", resp.Statistics[0].ID)
require.Equal(t, "wD4EP3M7FeFzJZgk9", resp.Statistics[0].UniqueID)
require.Equal(t, "2018-02-18T19:40:45.369Z", resp.Statistics[0].InstalledAt.Format("2006-01-02T15:04:05.000Z"))
require.Equal(t, "0.61.0-develop", resp.Statistics[0].Version)
require.Equal(t, 88, resp.Statistics[0].TotalUsers)
require.Equal(t, 88, resp.Statistics[0].ActiveUsers)
require.Equal(t, 0, resp.Statistics[0].NonActiveUsers)
require.Equal(t, 0, resp.Statistics[0].OnlineUsers)
require.Equal(t, 1, resp.Statistics[0].AwayUsers)
require.Equal(t, 87, resp.Statistics[0].OfflineUsers)
require.Equal(t, 81, resp.Statistics[0].TotalRooms)
require.Equal(t, 41, resp.Statistics[0].TotalChannels)
require.Equal(t, 37, resp.Statistics[0].TotalPrivateGroups)
require.Equal(t, 3, resp.Statistics[0].TotalDirect)
require.Equal(t, 0, resp.Statistics[0].TotalLivechat)
require.Equal(t, 2408, resp.Statistics[0].TotalMessages)
require.Equal(t, 730, resp.Statistics[0].TotalChannelMessages)
require.Equal(t, 1869, resp.Statistics[0].TotalPrivateGroupMessages)
require.Equal(t, 25, resp.Statistics[0].TotalDirectMessages)
require.Equal(t, 0, resp.Statistics[0].TotalLivechatMessages)
require.Equal(t, "2018-02-24T12:44:45.045Z", resp.Statistics[0].LastLogin.Format("2006-01-02T15:04:05.000Z"))
require.Equal(t, "2018-02-23T18:14:03.490Z", resp.Statistics[0].LastMessageSentAt.Format("2006-01-02T15:04:05.000Z"))
require.Equal(t, "2018-02-23T17:58:54.779Z", resp.Statistics[0].LastSeenSubscription.Format("2006-01-02T15:04:05.000Z"))
require.Equal(t, 1, resp.Statistics[0].InstanceCount)
require.Equal(t, "2018-02-24T15:13:00.312Z", resp.Statistics[0].CreatedAt.Format("2006-01-02T15:04:05.000Z"))
require.Equal(t, "2018-02-24T15:13:00.312Z", resp.Statistics[0].UpdatedAt.Format("2006-01-02T15:04:05.000Z"))
}

View File

@ -114,19 +114,20 @@ type GetStatusResponse struct {
}
type UsersInfoResponse struct {
User singleUserInfo `json:"user"`
User SingleUserInfo `json:"user"`
Success bool `json:"success"`
}
type singleUserInfo struct {
ID string `json:"_id"`
Type string `json:"type"`
Status string `json:"status"`
Active bool `json:"active"`
Name string `json:"name"`
UtcOffset float64 `json:"utcOffset"`
Username string `json:"username"`
AvatarETag string `json:"avatarETag,omitempty"`
type SingleUserInfo struct {
ID string `json:"_id"`
CreatedAt time.Time `json:"createdAt"`
Type string `json:"type"`
Status string `json:"status"`
Active bool `json:"active"`
Name string `json:"name"`
UtcOffset float64 `json:"utcOffset"`
Username string `json:"username"`
AvatarETag string `json:"avatarETag,omitempty"`
}
type UserRegisterRequest struct {
@ -182,7 +183,7 @@ type userUpdateInfo struct {
Name string `json:"name"`
}
// Gets all connected users presence
// UsersPresence gets all connected users presence
func (c *Client) UsersPresence(query string) (*UsersPresenceResponse, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s/users.presence?from=%s", c.baseURL, c.apiVersion, query), nil)
@ -198,7 +199,7 @@ func (c *Client) UsersPresence(query string) (*UsersPresenceResponse, error) {
return &res, nil
}
// Create a new user. Requires create-user permission.
// UsersCreate creates a new user.
func (c *Client) UsersCreate(user *NewUser) (*UserCreateResponse, error) {
opt, _ := json.Marshal(user)
@ -219,7 +220,7 @@ func (c *Client) UsersCreate(user *NewUser) (*UserCreateResponse, error) {
return &res, nil
}
// Deletes an existing user. Requires delete-user permission.
// UsersDelete deletes a user.
func (c *Client) UsersDelete(user *UsersDelete) (*SimpleSuccessResponse, error) {
opt, _ := json.Marshal(user)
@ -240,7 +241,7 @@ func (c *Client) UsersDelete(user *UsersDelete) (*SimpleSuccessResponse, error)
return &res, nil
}
// Create a user authentication token.
// UsersCreateToken creates a user token.
func (c *Client) UsersCreateToken(user *SimpleUserRequest) (*CreateTokenResponse, error) {
opt, _ := json.Marshal(user)
@ -261,12 +262,12 @@ func (c *Client) UsersCreateToken(user *SimpleUserRequest) (*CreateTokenResponse
return &res, nil
}
// Deactivate Idle users. Requires edit-other-user-active-status permission.
// UsersDeactivateIdle deactivates idle users.
func (c *Client) UsersDeactivateIdle(params *DeactivateRequest) (*DeactivateResponse, error) {
opt, _ := json.Marshal(params)
req, err := http.NewRequest("POST",
fmt.Sprintf("%s/%s/users.createToken", c.baseURL, c.apiVersion),
fmt.Sprintf("%s/%s/users.deactivateIdle", c.baseURL, c.apiVersion),
bytes.NewBuffer(opt))
if err != nil {
@ -282,14 +283,14 @@ func (c *Client) UsersDeactivateIdle(params *DeactivateRequest) (*DeactivateResp
return &res, nil
}
// Deletes your own user. Requires Allow Users to Delete Own Account enabled. Accessible from Administration -> Accounts.
// UsersDeleteOwnAccount deletes your own account.
func (c *Client) UsersDeleteOwnAccount(pass string) (*SimpleSuccessResponse, error) {
param := struct {
password string `json:"password"`
Password string `json:"password"`
}{}
param.password = fmt.Sprintf("%x", sha256.Sum256([]byte(pass)))
param.Password = fmt.Sprintf("%x", sha256.Sum256([]byte(pass)))
opt, _ := json.Marshal(param)
@ -310,12 +311,12 @@ func (c *Client) UsersDeleteOwnAccount(pass string) (*SimpleSuccessResponse, err
return &res, nil
}
// Send email to reset your password.
// UsersForgotPassword send an email to reset your password
func (c *Client) UsersForgotPassword(email string) (*SimpleSuccessResponse, error) {
param := struct {
email string `json:"email"`
Email string `json:"email"`
}{
email: email,
Email: email,
}
opt, _ := json.Marshal(param)
@ -337,7 +338,7 @@ func (c *Client) UsersForgotPassword(email string) (*SimpleSuccessResponse, erro
return &res, nil
}
// Generate Personal Access Token. Requires create-personal-access-tokens permission.
// UsersGeneratePersonalAccessToken generates a personal access token
func (c *Client) UsersGeneratePersonalAccessToken(params *GetNewToken) (*NewTokenResponse, error) {
opt, _ := json.Marshal(params)
@ -358,12 +359,12 @@ func (c *Client) UsersGeneratePersonalAccessToken(params *GetNewToken) (*NewToke
return &res, nil
}
// Gets a user's Status if the query string userId or username is provided, otherwise it gets the callee's.
// UsersGetStatus gets the status of a user
func (c *Client) UsersGetStatus(user *SimpleUserRequest) (*GetStatusResponse, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s/users.getStatus", c.baseURL, c.apiVersion), nil)
if user.Username == "" && user.UserId == "" {
return nil, fmt.Errorf("False parameters")
return nil, fmt.Errorf("false parameters")
}
url := req.URL.Query()
@ -387,7 +388,7 @@ func (c *Client) UsersGetStatus(user *SimpleUserRequest) (*GetStatusResponse, er
return &res, nil
}
// Retrieves information about a user, the result is only limited to what the callee has access to view.
// UsersInfo gets the information of a user
func (c *Client) UsersInfo(user *SimpleUserRequest) (*UsersInfoResponse, error) {
opt, _ := json.Marshal(user)
@ -396,7 +397,7 @@ func (c *Client) UsersInfo(user *SimpleUserRequest) (*UsersInfoResponse, error)
bytes.NewBuffer(opt))
if user.Username == "" && user.UserId == "" {
return nil, fmt.Errorf("False parameters")
return nil, fmt.Errorf("false parameters")
}
url := req.URL.Query()
@ -421,7 +422,7 @@ func (c *Client) UsersInfo(user *SimpleUserRequest) (*UsersInfoResponse, error)
return &res, nil
}
// Register a new user.
// UsersRegister registers a new user
func (c *Client) UsersRegister(user *UserRegisterRequest) (*UsersInfoResponse, error) {
opt, _ := json.Marshal(user)
@ -442,7 +443,7 @@ func (c *Client) UsersRegister(user *UserRegisterRequest) (*UsersInfoResponse, e
return &res, nil
}
// Sets a user Status when the status message and state is given.
// UsersSetStatus sets the status of a user
func (c *Client) UsersSetStatus(status *SetStatus) (*SimpleSuccessResponse, error) {
opt, _ := json.Marshal(status)
@ -463,7 +464,7 @@ func (c *Client) UsersSetStatus(status *SetStatus) (*SimpleSuccessResponse, erro
return &res, nil
}
// Update an existing user.
// UsersUpdate updates a user
func (c *Client) UsersUpdate(user *UserUpdateRequest) (*UserUpdateResponse, error) {
opt, _ := json.Marshal(user)

279
users_test.go Normal file
View File

@ -0,0 +1,279 @@
package gorocket
import (
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
)
func TestUsersPresence(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"users":[{"_id":"rocket.cat","name":"Rocket.Cat","username":"rocket.cat","status":"online","utcOffset":0,"avatarETag":"5BB9B5ny5DkKdrwkq"},{"_id":"rocketchat.internal.admin.test","name":"RocketChat Internal Admin Test","username":"rocketchat.internal.admin.test","status":"online","utcOffset":-2,"avatarETag":"iEbEm4bTT327NJjXt"}],"full":true,"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.UsersPresence("rocket")
require.NoError(t, err)
require.Equal(t, 2, len(resp.Users))
require.Equal(t, "rocket.cat", resp.Users[0].ID)
require.Equal(t, "Rocket.Cat", resp.Users[0].Name)
require.Equal(t, "rocket.cat", resp.Users[0].Username)
require.Equal(t, "online", resp.Users[0].Status)
require.Equal(t, 0.0, resp.Users[0].UtcOffset)
require.Equal(t, "5BB9B5ny5DkKdrwkq", resp.Users[0].AvatarETag)
require.Equal(t, "rocketchat.internal.admin.test", resp.Users[1].ID)
require.Equal(t, "RocketChat Internal Admin Test", resp.Users[1].Name)
require.Equal(t, "rocketchat.internal.admin.test", resp.Users[1].Username)
require.Equal(t, "online", resp.Users[1].Status)
require.Equal(t, -2.0, resp.Users[1].UtcOffset)
require.Equal(t, "iEbEm4bTT327NJjXt", resp.Users[1].AvatarETag)
require.True(t, resp.Full)
require.True(t, resp.Success)
}
func TestUsersCreate(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"user":{"_id":"BsNr28znDkG8aeo7W","createdAt":"2016-09-13T14:57:56.037Z","services":{"password":{"bcrypt":"$2a$i7BFS55uFYRf5TE4ErSUH8HymMNAbpMAvsOcl2C"}},"username":"uniqueusername","emails":[{"address":"email@user.tld","verified":false}],"type":"user","status":"offline","active":true,"roles":["user"],"_updatedAt":"2016-09-13T14:57:56.175Z","name":"name","settings":{}},"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
payload := NewUser{
Email: "email@user.tld",
Name: "name",
Password: "password",
Username: "uniqueusername",
}
resp, err := client.UsersCreate(&payload)
require.NoError(t, err)
require.Equal(t, "BsNr28znDkG8aeo7W", resp.User.ID)
require.Equal(t, "2016-09-13T14:57:56.037Z", resp.User.CreatedAt.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, "2016-09-13T14:57:56.175Z", resp.User.UpdatedAt.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, "uniqueusername", resp.User.Username)
require.Equal(t, "email@user.tld", resp.User.Emails[0].Address)
require.Equal(t, false, resp.User.Emails[0].Verified)
require.Equal(t, "user", resp.User.Type)
require.Equal(t, "offline", resp.User.Status)
require.Equal(t, true, resp.User.Active)
require.Equal(t, "user", resp.User.Roles[0])
require.Equal(t, "name", resp.User.Name)
require.True(t, resp.Success)
}
func TestUsersDelete(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"success":true}`,
}))
defer server.Close()
req := UsersDelete{
Username: "blabla",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.UsersDelete(&req)
require.NoError(t, err)
require.True(t, resp.Success)
}
func TestUsersCreateToken(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"data":{"authToken":"9HqLlyZOugoStsXCUfD_0YdwnNnunAJF8V47U3QHXSq","userId":"aobEdbYhXfu5hkeqG"},"success":true}`,
}))
defer server.Close()
req := SimpleUserRequest{
Username: "username",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.UsersCreateToken(&req)
require.NoError(t, err)
require.Equal(t, "9HqLlyZOugoStsXCUfD_0YdwnNnunAJF8V47U3QHXSq", resp.Data.AuthToken)
require.Equal(t, "aobEdbYhXfu5hkeqG", resp.Data.UserID)
require.True(t, resp.Success)
}
func TestUsersDeactivateIdle(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"count": 1,"success":true}`,
}))
defer server.Close()
req := DeactivateRequest{
DaysIdle: "2",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.UsersDeactivateIdle(&req)
require.NoError(t, err)
require.True(t, resp.Success)
require.Equal(t, 1, resp.Count)
}
func TestUsersDeleteOwnAccount(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.UsersDeleteOwnAccount("password")
require.NoError(t, err)
require.True(t, resp.Success)
}
func TestUsersForgotPassword(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"success":true}`,
}))
defer server.Close()
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.UsersForgotPassword("rocket@cat.com")
require.NoError(t, err)
require.True(t, resp.Success)
}
func TestUsersGeneratePersonalAccessToken(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"token":"2jdk99wuSjXPO201XlAks9sjDjAhSJmskAKW301mSuj9Sk","success":true}`,
}))
defer server.Close()
req := GetNewToken{
Token: "test",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.UsersGeneratePersonalAccessToken(&req)
require.NoError(t, err)
require.Equal(t, "2jdk99wuSjXPO201XlAks9sjDjAhSJmskAKW301mSuj9Sk", resp.Token)
require.True(t, resp.Success)
}
func TestUsersGetStatus(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"message":"Latest status","connectionStatus":"online","status":"online","success":true}`,
}))
defer server.Close()
req := SimpleUserRequest{
Username: "rocket.cat",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.UsersGetStatus(&req)
require.NoError(t, err)
require.Equal(t, "Latest status", resp.Message)
require.Equal(t, "online", resp.ConnectionStatus)
require.Equal(t, "online", resp.Status)
require.True(t, resp.Success)
}
func TestUsersInfo(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"user":{"_id":"5fRTXMt7DMJbpPJfh","createdAt":"2023-07-10T16:44:58.548Z","services":{"password":true,"email2fa":{"enabled":true,"changedAt":"2023-07-10T16:44:58.546Z"},"resume":{"loginTokens":[{"when":"2023-10-05T18:55:02.996Z","hashedToken":"..."},{"when":"2023-10-05T19:09:30.415Z","hashedToken":"....."},{"when":"2023-10-10T23:40:46.098Z","hashedToken":"...."}]}},"username":"test.john","emails":[{"address":"test.john@test.com","verified":true}],"type":"user","status":"offline","active":true,"roles":["user","admin"],"name":"Test John","requirePasswordChange":false,"lastLogin":"2023-10-10T23:40:46.093Z","statusConnection":"offline","utcOffset":1,"statusText":"","avatarETag":"GFoEi6wv3uAxnzDcD","nickname":"tesuser2","canViewAllInfo":true},"success":true}`,
}))
defer server.Close()
req := SimpleUserRequest{
Username: "test.john",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.UsersInfo(&req)
require.NoError(t, err)
require.Equal(t, "5fRTXMt7DMJbpPJfh", resp.User.ID)
require.Equal(t, "2023-07-10T16:44:58.548Z", resp.User.CreatedAt.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, "test.john", resp.User.Username)
require.Equal(t, "user", resp.User.Type)
require.Equal(t, "offline", resp.User.Status)
require.Equal(t, true, resp.User.Active)
require.Equal(t, "Test John", resp.User.Name)
require.Equal(t, 1.0, resp.User.UtcOffset)
require.Equal(t, "GFoEi6wv3uAxnzDcD", resp.User.AvatarETag)
require.True(t, resp.Success)
}
func TestUsersRegister(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"user":{"_id":"nSYqWzZ4GsKTX4dyK","type":"user","status":"offline","active":true,"name":"Example User","utcOffset":0,"username":"example"},"success":true}`,
}))
defer server.Close()
req := UserRegisterRequest{
Email: "rocket@chat.com",
Name: "Example User",
Pass: "password",
Username: "example",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.UsersRegister(&req)
require.NoError(t, err)
require.Equal(t, "nSYqWzZ4GsKTX4dyK", resp.User.ID)
require.Equal(t, "user", resp.User.Type)
require.Equal(t, "offline", resp.User.Status)
require.Equal(t, true, resp.User.Active)
require.Equal(t, "Example User", resp.User.Name)
require.Equal(t, 0.0, resp.User.UtcOffset)
require.Equal(t, "example", resp.User.Username)
require.True(t, resp.Success)
}
func TestUsersSetStatus(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"success":true}`,
}))
defer server.Close()
req := SetStatus{
Message: "I am online",
Status: "online",
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.UsersSetStatus(&req)
require.NoError(t, err)
require.True(t, resp.Success)
}
func TestUsersUpdate(t *testing.T) {
server := httptest.NewServer(getHandler(t, &HandlerHelper{
ResponseBody: `{"user":{"_id":"BsNr28znDkG8aeo7W","createdAt":"2016-09-13T14:57:56.037Z","services":{"password":{"bcrypt":"$2a$10$5I5nUzqNEs8jKhi7BFS55uFYRf5TE4ErSUH8HymMNAbpMAvsOcl2C"}},"username":"uniqueusername","emails":[{"address":"newemail@user.tld","verified":false}],"type":"user","status":"offline","active":true,"roles":["user"],"_updatedAt":"2016-09-13T14:57:56.175Z","name":"new name","customFields":{"twitter":"userstwitter"}},"success":true}`,
}))
defer server.Close()
req := UserUpdateRequest{
UserId: "BsNr28znDkG8aeo7W",
Data: UserUpdateData{Name: "new name"},
}
client := NewTestClientWithCustomHandler(t, server)
resp, err := client.UsersUpdate(&req)
require.NoError(t, err)
require.Equal(t, "BsNr28znDkG8aeo7W", resp.User.ID)
require.Equal(t, "2016-09-13T14:57:56.037Z", resp.User.CreatedAt.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, "2016-09-13T14:57:56.175Z", resp.User.UpdatedAt.Format("2006-01-02T15:04:05.999Z"))
require.Equal(t, "uniqueusername", resp.User.Username)
require.Equal(t, "newemail@user.tld", resp.User.Emails[0].Address)
require.Equal(t, false, resp.User.Emails[0].Verified)
require.Equal(t, "user", resp.User.Roles[0])
require.Equal(t, "new name", resp.User.Name)
require.True(t, resp.Success)
}