fetcher_test.go

 1package fetcher
 2
 3import (
 4	"testing"
 5
 6	"github.com/andrinoff/email-cli/config"
 7)
 8
 9// TestFetchEmails is an integration test that requires a live IMAP server and valid credentials.
10// NOTE: This test will be skipped if it cannot load a configuration file,
11// making it safe to run in a CI environment without credentials.
12// To run this test locally, ensure you have a valid `config.json` file.
13func TestFetchEmails(t *testing.T) {
14	// Attempt to load the configuration.
15	cfg, err := config.LoadConfig()
16	if err != nil {
17		// If config doesn't exist, skip the test. This is useful for CI environments.
18		t.Skipf("Skipping TestFetchEmails: could not load config: %v", err)
19	}
20
21	// If the password is a placeholder, skip the test to avoid failed auth attempts.
22	if cfg.Password == "" || cfg.Password == "supersecret" {
23		t.Skip("Skipping TestFetchEmails: placeholder or empty password found in config.")
24	}
25
26	emails, err := FetchEmails(cfg)
27	if err != nil {
28		t.Fatalf("FetchEmails() failed with error: %v", err)
29	}
30
31	if len(emails) == 0 {
32		// This is not necessarily a failure, but we can log it.
33		t.Log("FetchEmails() returned 0 emails. This might be expected.")
34	}
35
36	// Check that the emails are sorted from newest to oldest.
37	if len(emails) > 1 {
38		if emails[0].Date.Before(emails[len(emails)-1].Date) {
39			t.Error("Emails do not appear to be sorted from newest to oldest.")
40		}
41	}
42
43	// Check a sample email for expected content.
44	for _, email := range emails {
45		if email.Subject == "" && email.From == "" {
46			t.Errorf("Fetched email has empty subject and from fields: %+v", email)
47		}
48	}
49}