1package fetcher
2
3import (
4 "testing"
5
6 "github.com/floatpane/matcha/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, 10, 10)
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 // Skip emails with zero/invalid dates when checking sort order.
38 if len(emails) > 1 {
39 var validEmails []Email
40 for _, e := range emails {
41 if !e.Date.IsZero() {
42 validEmails = append(validEmails, e)
43 }
44 }
45 if len(validEmails) > 1 {
46 if validEmails[0].Date.Before(validEmails[len(validEmails)-1].Date) {
47 t.Error("Emails do not appear to be sorted from newest to oldest.")
48 }
49 }
50 }
51
52 // Check a sample email for expected content.
53 for _, email := range emails {
54 if email.Subject == "" && email.From == "" {
55 t.Errorf("Fetched email has empty subject and from fields: %+v", email)
56 }
57 }
58}