summaryrefslogtreecommitdiffstats
path: root/tests/Inc/MailerTest.php
blob: e1b361f6717fa9e26ef1cb8cd6813463c932db33 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php

use PHPUnit\Framework\TestCase;

/**
 * Mailer tests using the SQLite-backed Database test backend (no MySQL required).
 *
 */
class MailerTest extends TestCase
{
	protected function setUp(): void
	{
		Database::resetSchema();
		EventLog::reset();
	}

	public function testQueueInsertsOneRowPerRecipient(): void
	{
		Mailer::queue(5, ['a@example.com', 'b@example.com'], 'Hello', "Body\ntext");

		$rows = Database::queryAll('SELECT rcpt, subject, body, configid FROM mail_queue ORDER BY rcpt');
		$this->assertCount(2, $rows);
		$this->assertSame('a@example.com', $rows[0]['rcpt']);
		$this->assertSame('b@example.com', $rows[1]['rcpt']);
		foreach ($rows as $r) {
			$this->assertSame('Hello', $r['subject']);
			$this->assertSame("Body\ntext", $r['body']);
			$this->assertSame(5, (int)$r['configid']);
		}
	}

	public function testFlushQueueDropsTooOldMailsAndDeletesWithoutSending(): void
	{
		$tooOld = time() - 50000; // older than 12h cutoff used in flushQueue
		Database::exec('INSERT INTO mail_queue (configid, rcpt, subject, body, dateline, nexttry) VALUES (:configid, :rcpt, :subject, :body, :dateline, 0)', [
			'configid' => 1,
			'rcpt' => 'user@example.org',
			'subject' => 'Old Notice',
			'body' => 'Old body',
			'dateline' => $tooOld,
		]);

		Mailer::flushQueue();

		$cnt = Database::queryFirst('SELECT COUNT(*) AS c FROM mail_queue');
		$this->assertSame(0, (int)$cnt['c'], 'Too-old mails should be deleted');

		// EventLog::info should contain the drop message
		$this->assertNotEmpty(EventLog::$info);
		$this->assertStringContainsString('Dropping queued mail', EventLog::$info[0][0]);
	}

	public function testFlushQueueWithInvalidConfigLogsFailureAndDeletes(): void
	{
		$recent = time();
		// Insert one recent mail referencing a non-existent config (42)
		Database::exec('INSERT INTO mail_queue (configid, rcpt, subject, body, dateline, nexttry) VALUES (:configid, :rcpt, :subject, :body, :dateline, 0)', [
			'configid' => 42,
			'rcpt' => 'rcpt@example.org',
			'subject' => 'Test Subject',
			'body' => 'First body',
			'dateline' => $recent,
		]);

		Mailer::flushQueue();

		// Should log one failure about invalid config id
		$this->assertNotEmpty(EventLog::$failure);
		$this->assertStringContainsString('Invalid mailer config id', EventLog::$failure[0]);

		$cnt = Database::queryFirst('SELECT COUNT(*) AS c FROM mail_queue');
		$this->assertSame(0, (int)$cnt['c'], 'Mail should be deleted when config is invalid');
	}
}