discord_test.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. package discordgo
  2. import (
  3. "fmt"
  4. "os"
  5. "runtime"
  6. "sync/atomic"
  7. "testing"
  8. "time"
  9. )
  10. //////////////////////////////////////////////////////////////////////////////
  11. ////////////////////////////////////////////////////// VARS NEEDED FOR TESTING
  12. var (
  13. dg *Session // Stores a global discordgo user session
  14. dgBot *Session // Stores a global discordgo bot session
  15. envOAuth2Token = os.Getenv("DG_OAUTH2_TOKEN") // Token to use when authenticating using OAuth2 token
  16. envBotToken = os.Getenv("DGB_TOKEN") // Token to use when authenticating the bot account
  17. envGuild = os.Getenv("DG_GUILD") // Guild ID to use for tests
  18. envChannel = os.Getenv("DG_CHANNEL") // Channel ID to use for tests
  19. envVoiceChannel = os.Getenv("DG_VOICE_CHANNEL") // Channel ID to use for tests
  20. envAdmin = os.Getenv("DG_ADMIN") // User ID of admin user to use for tests
  21. )
  22. func TestMain(m *testing.M) {
  23. fmt.Println("Init is being called.")
  24. if envBotToken != "" {
  25. if d, err := New(envBotToken); err == nil {
  26. dgBot = d
  27. }
  28. }
  29. if envOAuth2Token == "" {
  30. envOAuth2Token = os.Getenv("DGU_TOKEN")
  31. }
  32. if envOAuth2Token != "" {
  33. if d, err := New(envOAuth2Token); err == nil {
  34. dg = d
  35. }
  36. }
  37. os.Exit(m.Run())
  38. }
  39. //////////////////////////////////////////////////////////////////////////////
  40. /////////////////////////////////////////////////////////////// START OF TESTS
  41. // TestNewToken tests the New() function with a Token.
  42. func TestNewToken(t *testing.T) {
  43. if envOAuth2Token == "" {
  44. t.Skip("Skipping New(token), DGU_TOKEN not set")
  45. }
  46. d, err := New(envOAuth2Token)
  47. if err != nil {
  48. t.Fatalf("New(envToken) returned error: %+v", err)
  49. }
  50. if d == nil {
  51. t.Fatal("New(envToken), d is nil, should be Session{}")
  52. }
  53. if d.Token == "" {
  54. t.Fatal("New(envToken), d.Token is empty, should be a valid Token.")
  55. }
  56. }
  57. func TestOpenClose(t *testing.T) {
  58. if envOAuth2Token == "" {
  59. t.Skip("Skipping TestClose, DGU_TOKEN not set")
  60. }
  61. d, err := New(envOAuth2Token)
  62. if err != nil {
  63. t.Fatalf("TestClose, New(envToken) returned error: %+v", err)
  64. }
  65. if err = d.Open(); err != nil {
  66. t.Fatalf("TestClose, d.Open failed: %+v", err)
  67. }
  68. // We need a better way to know the session is ready for use,
  69. // this is totally gross.
  70. start := time.Now()
  71. for {
  72. d.RLock()
  73. if d.DataReady {
  74. d.RUnlock()
  75. break
  76. }
  77. d.RUnlock()
  78. if time.Since(start) > 10*time.Second {
  79. t.Fatal("DataReady never became true.yy")
  80. }
  81. runtime.Gosched()
  82. }
  83. // TODO find a better way
  84. // Add a small sleep here to make sure heartbeat and other events
  85. // have enough time to get fired. Need a way to actually check
  86. // those events.
  87. time.Sleep(2 * time.Second)
  88. // UpdateStatus - maybe we move this into wsapi_test.go but the websocket
  89. // created here is needed. This helps tests that the websocket was setup
  90. // and it is working.
  91. if err = d.UpdateGameStatus(0, time.Now().String()); err != nil {
  92. t.Errorf("UpdateStatus error: %+v", err)
  93. }
  94. if err = d.Close(); err != nil {
  95. t.Fatalf("TestClose, d.Close failed: %+v", err)
  96. }
  97. }
  98. func TestAddHandler(t *testing.T) {
  99. testHandlerCalled := int32(0)
  100. testHandler := func(s *Session, m *MessageCreate) {
  101. atomic.AddInt32(&testHandlerCalled, 1)
  102. }
  103. interfaceHandlerCalled := int32(0)
  104. interfaceHandler := func(s *Session, i interface{}) {
  105. atomic.AddInt32(&interfaceHandlerCalled, 1)
  106. }
  107. bogusHandlerCalled := int32(0)
  108. bogusHandler := func(s *Session, se *Session) {
  109. atomic.AddInt32(&bogusHandlerCalled, 1)
  110. }
  111. d := Session{}
  112. d.AddHandler(testHandler)
  113. d.AddHandler(testHandler)
  114. d.AddHandler(interfaceHandler)
  115. d.AddHandler(bogusHandler)
  116. d.handleEvent(messageCreateEventType, &MessageCreate{})
  117. d.handleEvent(messageDeleteEventType, &MessageDelete{})
  118. <-time.After(500 * time.Millisecond)
  119. // testHandler will be called twice because it was added twice.
  120. if atomic.LoadInt32(&testHandlerCalled) != 2 {
  121. t.Fatalf("testHandler was not called twice.")
  122. }
  123. // interfaceHandler will be called twice, once for each event.
  124. if atomic.LoadInt32(&interfaceHandlerCalled) != 2 {
  125. t.Fatalf("interfaceHandler was not called twice.")
  126. }
  127. if atomic.LoadInt32(&bogusHandlerCalled) != 0 {
  128. t.Fatalf("bogusHandler was called.")
  129. }
  130. }
  131. func TestRemoveHandler(t *testing.T) {
  132. testHandlerCalled := int32(0)
  133. testHandler := func(s *Session, m *MessageCreate) {
  134. atomic.AddInt32(&testHandlerCalled, 1)
  135. }
  136. d := Session{}
  137. r := d.AddHandler(testHandler)
  138. d.handleEvent(messageCreateEventType, &MessageCreate{})
  139. r()
  140. d.handleEvent(messageCreateEventType, &MessageCreate{})
  141. <-time.After(500 * time.Millisecond)
  142. // testHandler will be called once, as it was removed in between calls.
  143. if atomic.LoadInt32(&testHandlerCalled) != 1 {
  144. t.Fatalf("testHandler was not called once.")
  145. }
  146. }
  147. func TestScheduledEvents(t *testing.T) {
  148. if dgBot == nil {
  149. t.Skip("Skipping, dgBot not set.")
  150. }
  151. beginAt := time.Now().Add(1 * time.Hour)
  152. endAt := time.Now().Add(2 * time.Hour)
  153. event, err := dgBot.GuildScheduledEventCreate(envGuild, &GuildScheduledEventParams{
  154. Name: "Test Event",
  155. PrivacyLevel: GuildScheduledEventPrivacyLevelGuildOnly,
  156. ScheduledStartTime: &beginAt,
  157. ScheduledEndTime: &endAt,
  158. Description: "Awesome Test Event created on livestream",
  159. EntityType: GuildScheduledEventEntityTypeExternal,
  160. EntityMetadata: &GuildScheduledEventEntityMetadata{
  161. Location: "https://discord.com",
  162. },
  163. })
  164. defer dgBot.GuildScheduledEventDelete(envGuild, event.ID)
  165. if err != nil || event.Name != "Test Event" {
  166. t.Fatal(err)
  167. }
  168. events, err := dgBot.GuildScheduledEvents(envGuild, true)
  169. if err != nil {
  170. t.Fatal(err)
  171. }
  172. var foundEvent *GuildScheduledEvent
  173. for _, e := range events {
  174. if e.ID == event.ID {
  175. foundEvent = e
  176. break
  177. }
  178. }
  179. if foundEvent.Name != event.Name {
  180. t.Fatal("err on GuildScheduledEvents endpoint. Missing Scheduled Event")
  181. }
  182. getEvent, err := dgBot.GuildScheduledEvent(envGuild, event.ID, true)
  183. if err != nil {
  184. t.Fatal(err)
  185. }
  186. if getEvent.Name != event.Name {
  187. t.Fatal("err on GuildScheduledEvent endpoint. Mismatched Scheduled Event")
  188. }
  189. eventUpdated, err := dgBot.GuildScheduledEventEdit(envGuild, event.ID, &GuildScheduledEventParams{Name: "Test Event Updated"})
  190. if err != nil {
  191. t.Fatal(err)
  192. }
  193. if eventUpdated.Name != "Test Event Updated" {
  194. t.Fatal("err on GuildScheduledEventUpdate endpoint. Scheduled Event Name mismatch")
  195. }
  196. // Usage of 1 and 1 is just the pseudo data with the purpose to run all branches in the function without crashes.
  197. // see https://github.com/bwmarrin/discordgo/pull/1032#discussion_r815438303 for more details.
  198. users, err := dgBot.GuildScheduledEventUsers(envGuild, event.ID, 1, true, "1", "1")
  199. if err != nil {
  200. t.Fatal(err)
  201. }
  202. if len(users) != 0 {
  203. t.Fatal("err on GuildScheduledEventUsers. Mismatch of event maybe occured")
  204. }
  205. err = dgBot.GuildScheduledEventDelete(envGuild, event.ID)
  206. if err != nil {
  207. t.Fatal(err)
  208. }
  209. }
  210. func TestComplexScheduledEvents(t *testing.T) {
  211. if dgBot == nil {
  212. t.Skip("Skipping, dgBot not set.")
  213. }
  214. beginAt := time.Now().Add(1 * time.Hour)
  215. endAt := time.Now().Add(2 * time.Hour)
  216. event, err := dgBot.GuildScheduledEventCreate(envGuild, &GuildScheduledEventParams{
  217. Name: "Test Voice Event",
  218. PrivacyLevel: GuildScheduledEventPrivacyLevelGuildOnly,
  219. ScheduledStartTime: &beginAt,
  220. ScheduledEndTime: &endAt,
  221. Description: "Test event on voice channel",
  222. EntityType: GuildScheduledEventEntityTypeVoice,
  223. ChannelID: envVoiceChannel,
  224. })
  225. if err != nil || event.Name != "Test Voice Event" {
  226. t.Fatal(err)
  227. }
  228. defer dgBot.GuildScheduledEventDelete(envGuild, event.ID)
  229. _, err = dgBot.GuildScheduledEventEdit(envGuild, event.ID, &GuildScheduledEventParams{
  230. EntityType: GuildScheduledEventEntityTypeExternal,
  231. EntityMetadata: &GuildScheduledEventEntityMetadata{
  232. Location: "https://discord.com",
  233. },
  234. })
  235. if err != nil {
  236. t.Fatal("err on GuildScheduledEventEdit. Change of entity type to external failed")
  237. }
  238. _, err = dgBot.GuildScheduledEventEdit(envGuild, event.ID, &GuildScheduledEventParams{
  239. ChannelID: envVoiceChannel,
  240. EntityType: GuildScheduledEventEntityTypeVoice,
  241. EntityMetadata: nil,
  242. })
  243. if err != nil {
  244. t.Fatal("err on GuildScheduledEventEdit. Change of entity type to voice failed")
  245. }
  246. }