Skip to content
This repository has been archived by the owner on Jul 11, 2024. It is now read-only.

feat: simpler integration tests #454

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 0 additions & 51 deletions client_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"context"
"fmt"
"math/rand"
"os"
"strconv"
"strings"
"sync"
Expand All @@ -17,57 +16,7 @@ import (
"github.com/andersfylling/disgord/internal/logger"
)

var token = os.Getenv("DISGORD_TOKEN_INTEGRATION_TEST")

var guildTypical = struct {
ID Snowflake
TextChannelGeneral Snowflake
VoiceChannelGeneral Snowflake
VoiceChannelOther1 Snowflake
VoiceChannelOther2 Snowflake
}{
ID: ParseSnowflakeString(os.Getenv("TEST_GUILD_TYPICAL_ID")),
TextChannelGeneral: ParseSnowflakeString(os.Getenv("TEST_GUILD_TYPICAL_TEXT_GENERAL")),
VoiceChannelGeneral: ParseSnowflakeString(os.Getenv("TEST_GUILD_TYPICAL_VOICE_GENERAL")),
VoiceChannelOther1: ParseSnowflakeString(os.Getenv("TEST_GUILD_TYPICAL_VOICE_1")),
VoiceChannelOther2: ParseSnowflakeString(os.Getenv("TEST_GUILD_TYPICAL_VOICE_2")),
}

var guildAdmin = struct {
ID Snowflake
TextChannelGeneral Snowflake
}{
ID: ParseSnowflakeString(os.Getenv("TEST_GUILD_ADMIN_ID")),
TextChannelGeneral: ParseSnowflakeString(os.Getenv("TEST_GUILD_ADMIN_TEXT_GENERAL")),
}

func validSnowflakes() {
if guildAdmin.ID.IsZero() {
panic("missing id for admin guild")
}
if guildAdmin.TextChannelGeneral.IsZero() {
panic("missing text channel for admin guild")
}
if guildTypical.ID.IsZero() {
panic("missing id for typical guild")
}
if guildTypical.TextChannelGeneral.IsZero() {
panic("missing id for typical guild TextChannelGeneral")
}
if guildTypical.VoiceChannelGeneral.IsZero() {
panic("missing id for typical guild VoiceChannelGeneral")
}
if guildTypical.VoiceChannelOther1.IsZero() {
panic("missing id for typical guild VoiceChannelOther1")
}
if guildTypical.VoiceChannelOther2.IsZero() {
panic("missing id for typical guild VoiceChannelOther2")
}
}

func TestClient(t *testing.T) {
validSnowflakes()

wg := &sync.WaitGroup{}

status := &UpdateStatusPayload{
Expand Down
156 changes: 156 additions & 0 deletions integration_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
//go:build integration
// +build integration

package disgord

import (
"github.com/andersfylling/disgord/internal/logger"
"math/rand"
"os"
"strconv"
"strings"
"sync"
"time"
)

const (
BotTokenEnvKey = "DISGORD_TOKEN_INTEGRATION_TEST"
TestGuildsNamePrefix = "3643-disgord-test-guild-"
)

var sharedTestSession = CreateTestSession()

func CreateTestSession() *TestSession {
session := &TestSession{}
session.once.Do(func() {
session.session = New(Config{
BotToken: os.Getenv(BotTokenEnvKey),
Logger: &logger.FmtPrinter{},
})

user, err := session.session.CurrentUser().Get()
if err != nil {
panic(err)
}

session.botID = user.ID
})

return session
}

type TestSession struct {
sync.Mutex
once sync.Once

botID Snowflake
session *Client
servers []*Guild
}

func (ts *TestSession) UnixInDays() int64 {
return time.Now().Unix() / 60 / 24 // seconds => hours => days
}

func (ts *TestSession) CreateGuildName() string {
int64ToStr := func(n int64) string {
return strconv.FormatInt(n, 10)
}

unixInDays := ts.UnixInDays()
randomSessionID := int64(rand.Int31n(100))
return TestGuildsNamePrefix + int64ToStr(unixInDays) + "-" + int64ToStr(randomSessionID)
}

func (ts *TestSession) GuildNameIsOlderThanOneDay(name string) bool {
suffix := strings.TrimPrefix(name, TestGuildsNamePrefix)
if len(suffix) < 2 {
return false
}

segments := strings.Split(suffix, "-")
if len(segments) < 2 {
return false
}

daysStr := segments[0]
days, err := strconv.ParseInt(daysStr, 10, 64)
if err != nil {
return false
}

if days == 0 {
return false
}

return days+1 < ts.UnixInDays()
}

func (ts *TestSession) GuildIsForTesting(guild *Guild) bool {
return strings.HasPrefix(guild.Name, TestGuildsNamePrefix)
}

func (ts *TestSession) Cleanup() {
ts.Lock()
defer ts.Unlock()

s := ts.session

// delete locally saved guilds
for _, server := range ts.servers {
_ = s.Guild(server.ID).Delete()
}

// detect generated test guilds and delete those as well
// in case the test session exited too early previously
for _, guildID := range s.GetConnectedGuilds() {
guild, err := s.Guild(guildID).Get()
if err != nil {
continue
}

if !ts.GuildIsForTesting(guild) {
continue
}

if !ts.GuildNameIsOlderThanOneDay(guild.Name) {
continue
}

_ = s.Guild(guildID).Delete()
}
}

// CreateNewServer creates a new server for testing, with a pre-determined server name prefix to easily cleanup later.
func (ts *TestSession) CreateNewServer() *Guild {
ts.Lock()
defer ts.Unlock()

name := ts.CreateGuildName()
server, err := ts.session.CreateGuild(name, &CreateGuild{
Channels: []*PartialChannel{
{
Name: "first",
Type: ChannelTypeGuildText,
},
{
Name: "second",
Type: ChannelTypeGuildText,
},
{
Name: "first-voice",
Type: ChannelTypeGuildVoice,
},
{
Name: "second-voice",
Type: ChannelTypeGuildVoice,
},
},
})
if err != nil {
panic(err)
}

ts.servers = append(ts.servers, server)
return server
}
21 changes: 9 additions & 12 deletions thread_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,30 +8,27 @@ import (
"fmt"
"testing"
"time"

"github.com/andersfylling/disgord/internal/logger"
)

func TestThreadEndpoints(t *testing.T) {
const andersfylling = Snowflake(228846961774559232)
validSnowflakes()

c := New(Config{
BotToken: token,
DisableCache: true,
Logger: &logger.FmtPrinter{},
})
c := sharedTestSession.session
server := sharedTestSession.CreateNewServer()
textChannel := server.Channels[0]
if textChannel.Type != ChannelTypeGuildText {
t.Fatal("wrong channel type") // TODO: improve using lookup
}

deadline, _ := context.WithDeadline(context.Background(), time.Now().Add(25*time.Second))

t.Run("create", func(t *testing.T) {
threadName := "HELLO WORLD1"
msg, err := c.Channel(guildAdmin.TextChannelGeneral).WithContext(deadline).CreateMessage(&CreateMessage{Content: threadName})
msg, err := c.Channel(textChannel.ID).WithContext(deadline).CreateMessage(&CreateMessage{Content: threadName})
if err != nil {
t.Fatal(err)
}

thread, err := c.Channel(guildAdmin.TextChannelGeneral).Message(msg.ID).WithContext(deadline).CreateThread(&CreateThread{
thread, err := c.Channel(textChannel.ID).Message(msg.ID).WithContext(deadline).CreateThread(&CreateThread{
Name: threadName,
AutoArchiveDuration: AutoArchiveThreadDay,
})
Expand All @@ -50,7 +47,7 @@ func TestThreadEndpoints(t *testing.T) {
t.Run("create-thread-no-message", func(t *testing.T) {
threadName := "Some Thread"
var err error
thread, err = c.Channel(guildAdmin.TextChannelGeneral).WithContext(deadline).CreateThread(&CreateThreadWithoutMessage{
thread, err = c.Channel(textChannel.ID).WithContext(deadline).CreateThread(&CreateThreadWithoutMessage{
Name: threadName,
AutoArchiveDuration: AutoArchiveThreadDay,
Type: ChannelTypeGuildPublicThread,
Expand Down