aboutsummaryrefslogtreecommitdiffstats
path: root/tests/test_messagebuilder.cpp
blob: 289006cd5b8a080c11afb36c02e3622b74b6a5b1 (plain)
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
/*
 * qtmaildir - a Qt6 mail client for notmuch-indexed Maildirs
 * Copyright (C) 2026 Danilo M. <danix@danix.xyz>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <QDir>
#include <QFile>
#include <QObject>
#include <QRegularExpression>
#include <QTemporaryDir>
#include <QTest>

#include "config.h"
#include "messagebuilder.h"
#include "types.h"

/// MessageBuilder's tests assert on the GENERATED BYTES, never by round-tripping
/// through MimeParser. A builder and a parser that agree can be wrong together:
/// both are ours, and a shared misunderstanding of a charset or a part order
/// would show as a green suite and as mojibake on the recipient's screen.
class TestMessageBuilder : public QObject
{
    Q_OBJECT

private slots:
    void initTestCase();

    void plainOnlyWhenSendHtmlIsOff();
    void multipartAlternativeWhenSendHtmlIsOn();
    void thePlainPartCarriesTheMarkdownSourceUnmodified();
    void theHtmlPartIsRenderedFromTheSameSource();
    void anAccentedBodyIsUtf8QuotedPrintable();
    void anAccentedSubjectIsRfc2047Utf8();
    void inReplyToAndReferencesAreCarried();
    void attachmentsProduceMultipartMixed();
    void aMissingAttachmentFailsTheBuild();
    void everyMessageCarriesADateAndMessageId();
    void recipientsAppearInTheirOwnHeaders();
    void anAccountWithNoAddressFailsRatherThanBuildingHeaderlessMail();

private:
    Account m_account;

    /// A message with the fixture account and one recipient, so each test can
    /// change only the field it is about.
    OutgoingMessage baseMessage() const
    {
        OutgoingMessage m;
        m.accountKey = m_account.key;
        m.to = QStringList{QStringLiteral("someone@example.org")};
        m.subject = QStringLiteral("A subject");
        m.markdownBody = QStringLiteral("Hello there.");
        return m;
    }
};

void TestMessageBuilder::initTestCase()
{
    m_account.key = QStringLiteral("work");
    m_account.name = QStringLiteral("Danilo M.");
    m_account.address = QStringLiteral("user@example.org");
    m_account.maildir = QStringLiteral("work");
    m_account.sendCommand = QStringLiteral("/bin/true");
}

/// With the HTML toggle off the message must be a single text/plain part.
/// A multipart/alternative carrying one alternative is not merely wasteful: it
/// makes every message an attachment-bearing shape to some clients, and the
/// toggle exists precisely so a user can send mail nothing has to negotiate.
void TestMessageBuilder::plainOnlyWhenSendHtmlIsOff()
{
    OutgoingMessage m = baseMessage();
    m.sendHtml = false;

    const MessageBuilder::Result r = MessageBuilder::build(m, m_account);
    QVERIFY2(r.ok(), qPrintable(r.error));

    const QString text = QString::fromUtf8(r.bytes);
    QVERIFY(text.contains(QStringLiteral("Content-Type: text/plain")));
    QVERIFY(!text.contains(QStringLiteral("multipart/alternative")));
    QVERIFY(!text.contains(QStringLiteral("text/html")));
}

/// With the toggle on both parts must be present, and text/plain must come
/// FIRST. Order is load-bearing in multipart/alternative: a client renders the
/// LAST part it understands, so least-rich first. Reversed, every HTML-capable
/// client would show the markdown source and the rendered part would never be
/// seen by anyone.
void TestMessageBuilder::multipartAlternativeWhenSendHtmlIsOn()
{
    OutgoingMessage m = baseMessage();
    m.sendHtml = true;

    const MessageBuilder::Result r = MessageBuilder::build(m, m_account);
    QVERIFY2(r.ok(), qPrintable(r.error));

    const QString text = QString::fromUtf8(r.bytes);
    QVERIFY(text.contains(QStringLiteral("multipart/alternative")));

    const int plain = text.indexOf(QStringLiteral("text/plain"));
    const int html = text.indexOf(QStringLiteral("text/html"));
    QVERIFY(plain >= 0);
    QVERIFY(html >= 0);
    QVERIFY2(plain < html, "text/plain must precede text/html in multipart/alternative");
}

/// The markdown SOURCE is the plain part, not a stripped-of-syntax rendering of
/// it. `**bold**` reads as emphasis to a human, and a plain-text renderer would
/// mean inventing a second renderer whose output could disagree with the HTML
/// one. The draft the user autosaves is this same text, which is the other
/// reason it must not be rewritten on the way out.
void TestMessageBuilder::thePlainPartCarriesTheMarkdownSourceUnmodified()
{
    OutgoingMessage m = baseMessage();
    m.sendHtml = true;
    m.markdownBody = QStringLiteral("**bold** and - [ ] a task");

    const MessageBuilder::Result r = MessageBuilder::build(m, m_account);
    QVERIFY2(r.ok(), qPrintable(r.error));

    const QString text = QString::fromUtf8(r.bytes);
    QVERIFY2(text.contains(QStringLiteral("**bold** and - [ ] a task")),
             qPrintable(text));
}

/// The HTML part comes from the same source through MarkdownRenderer, so the
/// two parts can never describe different messages.
void TestMessageBuilder::theHtmlPartIsRenderedFromTheSameSource()
{
    OutgoingMessage m = baseMessage();
    m.sendHtml = true;
    m.markdownBody = QStringLiteral("**bold**");

    const MessageBuilder::Result r = MessageBuilder::build(m, m_account);
    QVERIFY2(r.ok(), qPrintable(r.error));

    const QString text = QString::fromUtf8(r.bytes);
    QVERIFY2(text.contains(QStringLiteral("<strong>bold</strong>")), qPrintable(text));
}

/// Measured 2026-08-20: g_mime_text_part_set_text() encodes with whatever
/// charset is set at the moment it is CALLED, so setting the charset afterwards
/// RELABELS the part without re-encoding it. That produces a part headed
/// charset=utf-8 whose bytes are latin-1 (`Perch=E9`), which looks correct in
/// every header and arrives as mojibake. Asserting on the label alone would
/// pass against exactly that bug, so this asserts on the BYTES too: =C3=A9 must
/// be there and =E9 must not.
void TestMessageBuilder::anAccentedBodyIsUtf8QuotedPrintable()
{
    OutgoingMessage m = baseMessage();
    m.markdownBody = QStringLiteral("perché è così");

    const MessageBuilder::Result r = MessageBuilder::build(m, m_account);
    QVERIFY2(r.ok(), qPrintable(r.error));

    const QString text = QString::fromUtf8(r.bytes);
    QVERIFY2(text.contains(QStringLiteral("charset=utf-8"), Qt::CaseInsensitive),
             qPrintable(text));
    QVERIFY2(text.contains(QStringLiteral("=C3=A9")), qPrintable(text));
    QVERIFY2(!text.contains(QStringLiteral("=E9\n")) && !text.contains(QStringLiteral("=E9 ")),
             "latin-1 bytes under a utf-8 label");
}

/// Measured 2026-08-20: GMime encodes a header as iso-8859-1 unless told
/// otherwise, so g_mime_message_set_subject(msg, text, NULL) produced
/// =?iso-8859-1?B?...?=. The explicit "utf-8" argument is what makes an Italian
/// subject survive.
void TestMessageBuilder::anAccentedSubjectIsRfc2047Utf8()
{
    OutgoingMessage m = baseMessage();
    m.subject = QStringLiteral("Perché no");

    const MessageBuilder::Result r = MessageBuilder::build(m, m_account);
    QVERIFY2(r.ok(), qPrintable(r.error));

    const QString text = QString::fromUtf8(r.bytes);
    QVERIFY2(text.contains(QStringLiteral("=?UTF-8?"), Qt::CaseInsensitive), qPrintable(text));
    QVERIFY2(!text.contains(QStringLiteral("=?iso-8859-1?"), Qt::CaseInsensitive),
             qPrintable(text));
}

/// Not optional decoration. Without In-Reply-To and References a reply appears
/// as an orphan thread in the sender's own client, since the sent copy is
/// indexed by notmuch like any other message and notmuch threads on these
/// headers.
void TestMessageBuilder::inReplyToAndReferencesAreCarried()
{
    OutgoingMessage m = baseMessage();
    m.inReplyTo = QStringLiteral("<orig@example.org>");
    m.references = QStringList{QStringLiteral("<older@example.org>"),
                               QStringLiteral("<orig@example.org>")};

    const MessageBuilder::Result r = MessageBuilder::build(m, m_account);
    QVERIFY2(r.ok(), qPrintable(r.error));

    const QString text = QString::fromUtf8(r.bytes);
    QVERIFY2(text.contains(QStringLiteral("In-Reply-To: <orig@example.org>")), qPrintable(text));
    QVERIFY2(text.contains(QStringLiteral("References:")), qPrintable(text));
    QVERIFY2(text.contains(QStringLiteral("<older@example.org>")), qPrintable(text));
}

/// The attachment wrapper must NEST the body, not sit beside it: multipart/mixed
/// outermost, with the multipart/alternative as its first part. Beside it, a
/// client would show the alternatives as attachments and the body would be
/// unreadable. Position in the byte stream is what distinguishes the two, so the
/// test asserts mixed appears BEFORE alternative.
void TestMessageBuilder::attachmentsProduceMultipartMixed()
{
    QTemporaryDir dir;
    QVERIFY(dir.isValid());
    const QString path = dir.filePath(QStringLiteral("notes.txt"));
    QFile f(path);
    QVERIFY(f.open(QIODevice::WriteOnly));
    f.write("some attached bytes\n");
    f.close();

    OutgoingMessage m = baseMessage();
    m.sendHtml = true;
    m.attachments = QStringList{path};

    const MessageBuilder::Result r = MessageBuilder::build(m, m_account);
    QVERIFY2(r.ok(), qPrintable(r.error));

    const QString text = QString::fromUtf8(r.bytes);
    const int mixed = text.indexOf(QStringLiteral("multipart/mixed"));
    const int alternative = text.indexOf(QStringLiteral("multipart/alternative"));
    QVERIFY2(mixed >= 0, qPrintable(text));
    QVERIFY2(alternative >= 0, qPrintable(text));
    QVERIFY2(mixed < alternative, "multipart/mixed must wrap the body, not sit beside it");
    QVERIFY2(text.contains(QStringLiteral("notes.txt")), qPrintable(text));
    QVERIFY2(text.contains(QStringLiteral("Content-Disposition: attachment")), qPrintable(text));
}

/// A file can vanish between being attached and being sent, so existence is
/// checked at BUILD time. The build must produce NOTHING sendable: an empty
/// `bytes` is what stops a caller that only checks for content from shipping a
/// message missing the thing it was written to carry.
void TestMessageBuilder::aMissingAttachmentFailsTheBuild()
{
    OutgoingMessage m = baseMessage();
    m.attachments = QStringList{QStringLiteral("/nonexistent/path/to/report.pdf")};

    const MessageBuilder::Result r = MessageBuilder::build(m, m_account);
    QVERIFY(!r.ok());
    QVERIFY(r.bytes.isEmpty());
    QVERIFY2(r.error.contains(QStringLiteral("report.pdf")), qPrintable(r.error));
}

/// Measured 2026-08-20: GMime generates neither header unless asked. A message
/// without a Message-ID cannot be threaded by anything that receives it,
/// including this application's own notmuch index once the sent copy lands.
void TestMessageBuilder::everyMessageCarriesADateAndMessageId()
{
    const MessageBuilder::Result r = MessageBuilder::build(baseMessage(), m_account);
    QVERIFY2(r.ok(), qPrintable(r.error));

    const QString text = QString::fromUtf8(r.bytes);
    QVERIFY2(text.contains(QStringLiteral("Date: ")), qPrintable(text));
    QVERIFY2(text.contains(QStringLiteral("Message-Id: "), Qt::CaseInsensitive), qPrintable(text));
    QVERIFY(!r.messageId.isEmpty());
}

/// Bcc must be PRESENT in the bytes. The documented send command is `msmtp -t`,
/// which reads its recipients FROM the headers and strips Bcc itself before
/// transmission. Removing it here would mean blind recipients never receive the
/// message at all, silently.
///
/// If a later change passes recipients as command arguments instead of relying
/// on -t, this test must change with it: under that scheme leaving Bcc in the
/// bytes discloses the blind recipients to everyone.
void TestMessageBuilder::recipientsAppearInTheirOwnHeaders()
{
    OutgoingMessage m = baseMessage();
    m.to = QStringList{QStringLiteral("to@example.org")};
    m.cc = QStringList{QStringLiteral("cc@example.org")};
    m.bcc = QStringList{QStringLiteral("bcc@example.org")};

    const MessageBuilder::Result r = MessageBuilder::build(m, m_account);
    QVERIFY2(r.ok(), qPrintable(r.error));

    const QString text = QString::fromUtf8(r.bytes);
    QVERIFY2(text.contains(QStringLiteral("From: ")), qPrintable(text));
    QVERIFY2(text.contains(QStringLiteral("user@example.org")), qPrintable(text));

    const QRegularExpression to(QStringLiteral("^To:.*to@example\\.org"),
                                QRegularExpression::MultilineOption);
    const QRegularExpression cc(QStringLiteral("^Cc:.*cc@example\\.org"),
                                QRegularExpression::MultilineOption);
    const QRegularExpression bcc(QStringLiteral("^Bcc:.*bcc@example\\.org"),
                                 QRegularExpression::MultilineOption);
    QVERIFY2(to.match(text).hasMatch(), qPrintable(text));
    QVERIFY2(cc.match(text).hasMatch(), qPrintable(text));
    QVERIFY2(bcc.match(text).hasMatch(), qPrintable(text));
}

/// Config::account() returns a DEFAULT-CONSTRUCTED Account for an unknown key
/// rather than failing, so without this guard a bad key would build a message
/// with an empty From: silently malformed mail rather than a refusal, handed to
/// the send command as though it were fine.
void TestMessageBuilder::anAccountWithNoAddressFailsRatherThanBuildingHeaderlessMail()
{
    const Account empty;
    const MessageBuilder::Result r = MessageBuilder::build(baseMessage(), empty);
    QVERIFY(!r.ok());
    QVERIFY(r.bytes.isEmpty());
}

QTEST_MAIN(TestMessageBuilder)
#include "test_messagebuilder.moc"