The variable dg is defined in the ./repos/discordgo/discord_test.go file. It is a global variable that holds a *Session instance, which is used for testing interactions with the Discord API. Here's the relevant snippet:
go
var (
dg *Session // Stores a global discordgo user session
dgBot *Session // Stores a global discordgo bot session
envOAuth2Token = os.Getenv("DG_OAUTH2_TOKEN") // Token to use when authenticating using OAuth2 token
envBotToken = os.Getenv("DGB_TOKEN") // Token to use when authenticating the bot account
...
)
How dg is initialized
dg is initialized in the TestMain function, which is the entry point for the test suite:
go
func TestMain(m *testing.M) {
fmt.Println("Init is being called.")
if envBotToken != "" {
if d, err := New(envBotToken); err == nil {
dgBot = d
}
}
if envOAuth2Token == "" {
envOAuth2Token = os.Getenv("DGU_TOKEN")
}
if envOAuth2Token != "" {
if d, err := New(envOAuth2Token); err == nil {
dg = d
}
}
os.Exit(m.Run())
}
TestMain checks for environment variables (DG_OAUTH2_TOKEN and DGB_TOKEN) to retrieve authentication tokens.
It uses the New function from ./repos/discordgo/discord.go to create a new Session for both user (dg) and bot (dgBot) accounts:
go
func New(token string) (s *Session, err error) {
s = &Session{
...
Token: token,
}
return
}
If the tokens are invalid or not set, the corresponding sessions (dg or dgBot) will remain nil.
How the tests interact with the Discord API
The tests interact with the Discord API using the dg and dgBot session objects. Here's a breakdown of how they work:
1. Environment variables for configuration
The tests rely on specific environment variables to configure the test environment. For example:
DG_OAUTH2_TOKEN is used to authenticate a user session (dg).
DGB_TOKEN is used to authenticate a bot session (dgBot).
Other variables like DG_GUILD, DG_CHANNEL, DG_VOICE_CHANNEL, etc., provide specific IDs for testing functionality like sending messages, managing guilds, and interacting with voice channels.
2. Example test: TestNewToken
This test validates that a valid token can create a Session using the New function:
go
func TestNewToken(t *testing.T) {
if envOAuth2Token == "" {
t.Skip("Skipping New(token), DGU_TOKEN not set")
}
d, err := New(envOAuth2Token)
if err != nil {
t.Fatalf("New(envToken) returned error: %+v", err)
}
if d == nil {
t.Fatal("New(envToken), d is nil, should be Session{}")
}
if d.Token == "" {
t.Fatal("New(envToken), d.Token is empty, should be a valid Token.")
}
}
It uses the envOAuth2Token to create a session.
It verifies that the session is not nil and that the token is properly set.
3. Tests interacting with the Discord API
Many tests use the dg or dgBot session to interact with the Discord API. For example:
Sending a message:
go
func TestChannelMessageSend(t *testing.T) {
if envChannel == "" {
t.Skip("Skipping, DG_CHANNEL not set.")
}
if dg == nil {
t.Skip("Skipping, dg not set.")
}
_, err := dg.ChannelMessageSend(envChannel, "Running REST API Tests!")
if err != nil {
t.Errorf("ChannelMessageSend returned error: %+v", err)
}
}
This test sends a message to the channel specified by DG_CHANNEL (retrieved from environment variables).
The ChannelMessageSend function in ./repos/discordgo/restapi.go is called to perform the actual API request.
Creating a user channel:
go
func TestUserChannelCreate(t *testing.T) {
if dg == nil {
t.Skip("Cannot TestUserChannelCreate, dg not set.")
}
if envAdmin == "" {
t.Skip("Skipped, DG_ADMIN not set.")
}
_, err := dg.UserChannelCreate(envAdmin)
if err != nil {
t.[Redacted Person](err.Error())
}
}
This test creates a private channel with the user specified by DG_ADMIN.
It uses the UserChannelCreate function from ./repos/discordgo/restapi.go to make the API call.
Handling test limitations
Skipping tests
Tests are skipped if the required environment variables or session objects are not set:
go
if envChannel == "" {
t.Skip("Skipping, DG_CHANNEL not set.")
}
if dg == nil {
t.Skip("Skipping, dg not set.")
}
Rate limits
The Discord API enforces rate limits. To handle these, the Session object has a built-in rate limiter in ./repos/discordgo/restapi.go:
go
if resp.StatusCode == 429 { // TOO MANY REQUESTS - Rate limiting
rl := TooManyRequests{}
err = Unmarshal(response, &rl)
time.Sleep(rl.RetryAfter)
response, err = s.RequestWithLockedBucket(method, urlStr, contentType, b, ...)
}
Tests that could trigger rate limits (e.g., frequent username changes) are disabled or commented out:
go
/* Running this causes an error due to 2/hour rate limit on username changes
func TestUserUpdate(t *testing.T) { ... }
*/
Cleanup
Some tests include cleanup steps to avoid leaving resources on Discord, such as deleting scheduled events: