test: Mock mailer service (#3711)

* 🧪 Mock mailer service

* 🔥 Remove unneeded imports
This commit is contained in:
Iván Ovejero 2022-07-14 22:07:07 +02:00 committed by GitHub
parent c9b7b6d30f
commit eefd594074
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 96 additions and 187 deletions

View file

@ -13,15 +13,14 @@ import {
} from './shared/random'; } from './shared/random';
import * as testDb from './shared/testDb'; import * as testDb from './shared/testDb';
import type { Role } from '../../src/databases/entities/Role'; import type { Role } from '../../src/databases/entities/Role';
import { SMTP_TEST_TIMEOUT } from './shared/constants';
jest.mock('../../src/telemetry'); jest.mock('../../src/telemetry');
jest.mock('../../src/UserManagement/email/NodeMailer');
let app: express.Application; let app: express.Application;
let testDbName = ''; let testDbName = '';
let globalOwnerRole: Role; let globalOwnerRole: Role;
let globalMemberRole: Role; let globalMemberRole: Role;
let isSmtpAvailable = false;
beforeAll(async () => { beforeAll(async () => {
app = await utils.initTestServer({ endpointGroups: ['passwordReset'], applyAuth: true }); app = await utils.initTestServer({ endpointGroups: ['passwordReset'], applyAuth: true });
@ -33,9 +32,7 @@ beforeAll(async () => {
utils.initTestTelemetry(); utils.initTestTelemetry();
utils.initTestLogger(); utils.initTestLogger();
});
isSmtpAvailable = await utils.isTestSmtpServiceAvailable();
}, SMTP_TEST_TIMEOUT);
beforeEach(async () => { beforeEach(async () => {
await testDb.truncate(['User'], testDbName); await testDb.truncate(['User'], testDbName);
@ -50,36 +47,30 @@ afterAll(async () => {
await testDb.terminate(testDbName); await testDb.terminate(testDbName);
}); });
test( test('POST /forgot-password should send password reset email', async () => {
'POST /forgot-password should send password reset email', const owner = await testDb.createUser({ globalRole: globalOwnerRole });
async () => {
if (!isSmtpAvailable) utils.skipSmtpTest(expect);
const owner = await testDb.createUser({ globalRole: globalOwnerRole }); const authlessAgent = utils.createAgent(app);
const member = await testDb.createUser({
email: 'test@test.com',
globalRole: globalMemberRole,
});
const authlessAgent = utils.createAgent(app); config.set('userManagement.emails.mode', 'smtp');
const member = await testDb.createUser({
email: 'test@test.com',
globalRole: globalMemberRole,
});
await utils.configureSmtp(); await Promise.all(
[{ email: owner.email }, { email: member.email.toUpperCase() }].map(async (payload) => {
const response = await authlessAgent.post('/forgot-password').send(payload);
await Promise.all( expect(response.statusCode).toBe(200);
[{ email: owner.email }, { email: member.email.toUpperCase() }].map(async (payload) => { expect(response.body).toEqual({});
const response = await authlessAgent.post('/forgot-password').send(payload);
expect(response.statusCode).toBe(200); const user = await Db.collections.User.findOneOrFail({ email: payload.email });
expect(response.body).toEqual({}); expect(user.resetPasswordToken).toBeDefined();
expect(user.resetPasswordTokenExpiration).toBeGreaterThan(Math.ceil(Date.now() / 1000));
const user = await Db.collections.User.findOneOrFail({ email: payload.email }); }),
expect(user.resetPasswordToken).toBeDefined(); );
expect(user.resetPasswordTokenExpiration).toBeGreaterThan(Math.ceil(Date.now() / 1000)); });
}),
);
},
SMTP_TEST_TIMEOUT,
);
test('POST /forgot-password should fail if emailing is not set up', async () => { test('POST /forgot-password should fail if emailing is not set up', async () => {
const owner = await testDb.createUser({ globalRole: globalOwnerRole }); const owner = await testDb.createUser({ globalRole: globalOwnerRole });

View file

@ -71,11 +71,6 @@ export const BOOTSTRAP_POSTGRES_CONNECTION_NAME: Readonly<string> = 'n8n_bs_post
*/ */
export const BOOTSTRAP_MYSQL_CONNECTION_NAME: Readonly<string> = 'n8n_bs_mysql'; export const BOOTSTRAP_MYSQL_CONNECTION_NAME: Readonly<string> = 'n8n_bs_mysql';
/**
* Timeout (in milliseconds) to account for fake SMTP service being slow to respond.
*/
export const SMTP_TEST_TIMEOUT = 30_000;
/** /**
* Timeout (in milliseconds) to account for DB being slow to initialize. * Timeout (in milliseconds) to account for DB being slow to initialize.
*/ */

View file

@ -8,19 +8,16 @@ export type CollectionName = keyof IDatabaseCollections;
export type MappingName = keyof typeof MAPPING_TABLES; export type MappingName = keyof typeof MAPPING_TABLES;
export type SmtpTestAccount = {
user: string;
pass: string;
smtp: {
host: string;
port: number;
secure: boolean;
};
};
export type ApiPath = 'internal' | 'public'; export type ApiPath = 'internal' | 'public';
type EndpointGroup = 'me' | 'users' | 'auth' | 'owner' | 'passwordReset' | 'credentials' | 'publicApi'; type EndpointGroup =
| 'me'
| 'users'
| 'auth'
| 'owner'
| 'passwordReset'
| 'credentials'
| 'publicApi';
export type CredentialPayload = { export type CredentialPayload = {
name: string; name: string;

View file

@ -6,8 +6,6 @@ import superagent from 'superagent';
import request from 'supertest'; import request from 'supertest';
import { URL } from 'url'; import { URL } from 'url';
import bodyParser from 'body-parser'; import bodyParser from 'body-parser';
import util from 'util';
import { createTestAccount } from 'nodemailer';
import { set } from 'lodash'; import { set } from 'lodash';
import { CronJob } from 'cron'; import { CronJob } from 'cron';
import { BinaryDataManager, UserSettings } from 'n8n-core'; import { BinaryDataManager, UserSettings } from 'n8n-core';
@ -45,18 +43,10 @@ import { issueJWT } from '../../../src/UserManagement/auth/jwt';
import { getLogger } from '../../../src/Logger'; import { getLogger } from '../../../src/Logger';
import { credentialsController } from '../../../src/api/credentials.api'; import { credentialsController } from '../../../src/api/credentials.api';
import { loadPublicApiVersions } from '../../../src/PublicApi/'; import { loadPublicApiVersions } from '../../../src/PublicApi/';
import * as UserManagementMailer from '../../../src/UserManagement/email/UserManagementMailer';
import type { User } from '../../../src/databases/entities/User'; import type { User } from '../../../src/databases/entities/User';
import type { import type { ApiPath, EndpointGroup, PostgresSchemaSection, TriggerTime } from './types';
ApiPath,
EndpointGroup,
PostgresSchemaSection,
SmtpTestAccount,
TriggerTime,
} from './types';
import type { N8nApp } from '../../../src/UserManagement/Interfaces'; import type { N8nApp } from '../../../src/UserManagement/Interfaces';
/** /**
* Initialize a test server. * Initialize a test server.
* *
@ -860,45 +850,6 @@ export async function isInstanceOwnerSetUp() {
return Boolean(value); return Boolean(value);
} }
// ----------------------------------
// SMTP
// ----------------------------------
/**
* Get an SMTP test account from https://ethereal.email to test sending emails.
*/
const getSmtpTestAccount = util.promisify<SmtpTestAccount>(createTestAccount);
export async function configureSmtp() {
const {
user,
pass,
smtp: { host, port, secure },
} = await getSmtpTestAccount();
config.set('userManagement.emails.mode', 'smtp');
config.set('userManagement.emails.smtp.host', host);
config.set('userManagement.emails.smtp.port', port);
config.set('userManagement.emails.smtp.secure', secure);
config.set('userManagement.emails.smtp.auth.user', user);
config.set('userManagement.emails.smtp.auth.pass', pass);
}
export async function isTestSmtpServiceAvailable() {
try {
await configureSmtp();
await UserManagementMailer.getInstance();
return true;
} catch (_) {
return false;
}
}
export function skipSmtpTest(expect: jest.Expect) {
console.warn(`SMTP service unavailable - Skipping test ${expect.getState().currentTestName}`);
return;
}
// ---------------------------------- // ----------------------------------
// misc // misc
// ---------------------------------- // ----------------------------------

View file

@ -4,7 +4,7 @@ import { v4 as uuid } from 'uuid';
import { Db } from '../../src'; import { Db } from '../../src';
import config from '../../config'; import config from '../../config';
import { SMTP_TEST_TIMEOUT, SUCCESS_RESPONSE_BODY } from './shared/constants'; import { SUCCESS_RESPONSE_BODY } from './shared/constants';
import { import {
randomEmail, randomEmail,
randomValidPassword, randomValidPassword,
@ -20,6 +20,7 @@ import * as testDb from './shared/testDb';
import { compareHash } from '../../src/UserManagement/UserManagementHelper'; import { compareHash } from '../../src/UserManagement/UserManagementHelper';
jest.mock('../../src/telemetry'); jest.mock('../../src/telemetry');
jest.mock('../../src/UserManagement/email/NodeMailer');
let app: express.Application; let app: express.Application;
let testDbName = ''; let testDbName = '';
@ -27,7 +28,6 @@ let globalMemberRole: Role;
let globalOwnerRole: Role; let globalOwnerRole: Role;
let workflowOwnerRole: Role; let workflowOwnerRole: Role;
let credentialOwnerRole: Role; let credentialOwnerRole: Role;
let isSmtpAvailable = false;
beforeAll(async () => { beforeAll(async () => {
app = await utils.initTestServer({ endpointGroups: ['users'], applyAuth: true }); app = await utils.initTestServer({ endpointGroups: ['users'], applyAuth: true });
@ -48,9 +48,7 @@ beforeAll(async () => {
utils.initTestTelemetry(); utils.initTestTelemetry();
utils.initTestLogger(); utils.initTestLogger();
});
isSmtpAvailable = await utils.isTestSmtpServiceAvailable();
}, SMTP_TEST_TIMEOUT);
beforeEach(async () => { beforeEach(async () => {
await testDb.truncate( await testDb.truncate(
@ -487,114 +485,91 @@ test('POST /users should fail if user management is disabled', async () => {
expect(response.statusCode).toBe(500); expect(response.statusCode).toBe(500);
}); });
test( test('POST /users should email invites and create user shells but ignore existing', async () => {
'POST /users should email invites and create user shells but ignore existing', const owner = await testDb.createUser({ globalRole: globalOwnerRole });
async () => { const member = await testDb.createUser({ globalRole: globalMemberRole });
if (!isSmtpAvailable) utils.skipSmtpTest(expect); const memberShell = await testDb.createUserShell(globalMemberRole);
const authOwnerAgent = utils.createAgent(app, { auth: true, user: owner });
const owner = await testDb.createUser({ globalRole: globalOwnerRole }); config.set('userManagement.emails.mode', 'smtp');
const member = await testDb.createUser({ globalRole: globalMemberRole });
const memberShell = await testDb.createUserShell(globalMemberRole);
const authOwnerAgent = utils.createAgent(app, { auth: true, user: owner });
await utils.configureSmtp(); const testEmails = [randomEmail(), randomEmail().toUpperCase(), memberShell.email, member.email];
const testEmails = [ const payload = testEmails.map((e) => ({ email: e }));
randomEmail(),
randomEmail().toUpperCase(),
memberShell.email,
member.email,
];
const payload = testEmails.map((e) => ({ email: e })); const response = await authOwnerAgent.post('/users').send(payload);
const response = await authOwnerAgent.post('/users').send(payload); expect(response.statusCode).toBe(200);
expect(response.statusCode).toBe(200); for (const {
user: { id, email: receivedEmail },
error,
} of response.body.data) {
expect(validator.isUUID(id)).toBe(true);
expect(id).not.toBe(member.id);
for (const { const lowerCasedEmail = receivedEmail.toLowerCase();
user: { id, email: receivedEmail }, expect(receivedEmail).toBe(lowerCasedEmail);
error, expect(payload.some(({ email }) => email.toLowerCase() === lowerCasedEmail)).toBe(true);
} of response.body.data) {
expect(validator.isUUID(id)).toBe(true);
expect(id).not.toBe(member.id);
const lowerCasedEmail = receivedEmail.toLowerCase(); if (error) {
expect(receivedEmail).toBe(lowerCasedEmail); expect(error).toBe('Email could not be sent');
expect(payload.some(({ email }) => email.toLowerCase() === lowerCasedEmail)).toBe(true);
if (error) {
expect(error).toBe('Email could not be sent');
}
const storedUser = await Db.collections.User.findOneOrFail(id);
const { firstName, lastName, personalizationAnswers, password, resetPasswordToken } =
storedUser;
expect(firstName).toBeNull();
expect(lastName).toBeNull();
expect(personalizationAnswers).toBeNull();
expect(password).toBeNull();
expect(resetPasswordToken).toBeNull();
} }
},
SMTP_TEST_TIMEOUT,
);
test( const storedUser = await Db.collections.User.findOneOrFail(id);
'POST /users should fail with invalid inputs', const { firstName, lastName, personalizationAnswers, password, resetPasswordToken } =
async () => { storedUser;
if (!isSmtpAvailable) utils.skipSmtpTest(expect);
const owner = await testDb.createUser({ globalRole: globalOwnerRole }); expect(firstName).toBeNull();
const authOwnerAgent = utils.createAgent(app, { auth: true, user: owner }); expect(lastName).toBeNull();
expect(personalizationAnswers).toBeNull();
expect(password).toBeNull();
expect(resetPasswordToken).toBeNull();
}
});
await utils.configureSmtp(); test('POST /users should fail with invalid inputs', async () => {
const owner = await testDb.createUser({ globalRole: globalOwnerRole });
const authOwnerAgent = utils.createAgent(app, { auth: true, user: owner });
const invalidPayloads = [ config.set('userManagement.emails.mode', 'smtp');
randomEmail(),
[randomEmail()],
{},
[{ name: randomName() }],
[{ email: randomName() }],
];
await Promise.all( const invalidPayloads = [
invalidPayloads.map(async (invalidPayload) => { randomEmail(),
const response = await authOwnerAgent.post('/users').send(invalidPayload); [randomEmail()],
expect(response.statusCode).toBe(400); {},
[{ name: randomName() }],
[{ email: randomName() }],
];
const users = await Db.collections.User.find(); await Promise.all(
expect(users.length).toBe(1); // DB unaffected invalidPayloads.map(async (invalidPayload) => {
}), const response = await authOwnerAgent.post('/users').send(invalidPayload);
); expect(response.statusCode).toBe(400);
},
SMTP_TEST_TIMEOUT,
);
test( const users = await Db.collections.User.find();
'POST /users should ignore an empty payload', expect(users.length).toBe(1); // DB unaffected
async () => { }),
if (!isSmtpAvailable) utils.skipSmtpTest(expect); );
});
const owner = await testDb.createUser({ globalRole: globalOwnerRole }); test('POST /users should ignore an empty payload', async () => {
const authOwnerAgent = utils.createAgent(app, { auth: true, user: owner }); const owner = await testDb.createUser({ globalRole: globalOwnerRole });
const authOwnerAgent = utils.createAgent(app, { auth: true, user: owner });
await utils.configureSmtp(); config.set('userManagement.emails.mode', 'smtp');
const response = await authOwnerAgent.post('/users').send([]); const response = await authOwnerAgent.post('/users').send([]);
const { data } = response.body; const { data } = response.body;
expect(response.statusCode).toBe(200); expect(response.statusCode).toBe(200);
expect(Array.isArray(data)).toBe(true); expect(Array.isArray(data)).toBe(true);
expect(data.length).toBe(0); expect(data.length).toBe(0);
const users = await Db.collections.User.find(); const users = await Db.collections.User.find();
expect(users.length).toBe(1); expect(users.length).toBe(1);
}, });
SMTP_TEST_TIMEOUT,
);
// TODO: /users/:id/reinvite route tests missing // TODO: /users/:id/reinvite route tests missing