kua-money-trace/test/gmailApi.test.js

83 lines
2.4 KiB
JavaScript

import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import {
buildGmailQuery,
decodeBase64Url,
downloadGmailApiAccount,
listGmailMessageRefs,
} from '../src/gmailApi.js';
const sample = await fs.readFile('test/fixtures/sample-bank-email.eml');
test('builds gmail after query from ISO date', () => {
assert.equal(buildGmailQuery({ since: '2025-01-01' }), 'after:2025/01/01');
});
test('decodes gmail base64url raw message', () => {
const encoded = sample.toString('base64').replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');
assert.equal(decodeBase64Url(encoded).toString(), sample.toString());
});
test('lists gmail message refs across pages', async () => {
const calls = [];
const gmail = {
users: {
messages: {
async list(params) {
calls.push(params);
if (!params.pageToken) {
return { data: { messages: [{ id: 'a' }], nextPageToken: 'next' } };
}
return { data: { messages: [{ id: 'b' }] } };
},
},
},
};
const refs = await listGmailMessageRefs({ gmail, q: 'after:2025/01/01', limit: 2 });
assert.deepEqual(refs.map((ref) => ref.id), ['a', 'b']);
assert.equal(calls[1].pageToken, 'next');
});
test('downloads gmail raw messages into archive', async () => {
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'kua-gmail-api-'));
const encoded = sample.toString('base64').replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');
const gmail = {
users: {
messages: {
async list() {
return { data: { messages: [{ id: 'gmail-message-1', threadId: 'thread-1' }] } };
},
async get(params) {
assert.equal(params.format, 'raw');
return {
data: {
id: params.id,
threadId: 'thread-1',
historyId: 'history-1',
internalDate: '1764547200000',
labelIds: ['INBOX'],
raw: encoded,
},
};
},
},
},
};
const result = await downloadGmailApiAccount({
account: { id: 'vjoati-gmail', email: 'vjoati@gmail.com' },
gmail,
archiveRoot: tmp,
since: '2025-01-01',
limit: 1,
});
assert.equal(result.imported, 1);
assert.equal(result.records[0].gmail.id, 'gmail-message-1');
assert.equal(result.records[0].attachments.length, 1);
});