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';
import * as testDb from './shared/testDb';
import type { Role } from '../../src/databases/entities/Role';
import { SMTP_TEST_TIMEOUT } from './shared/constants';
jest.mock('../../src/telemetry');
jest.mock('../../src/UserManagement/email/NodeMailer');
let app: express.Application;
let testDbName = '';
let globalOwnerRole: Role;
let globalMemberRole: Role;
let isSmtpAvailable = false;
beforeAll(async () => {
app = await utils.initTestServer({ endpointGroups: ['passwordReset'], applyAuth: true });
@ -33,9 +32,7 @@ beforeAll(async () => {
utils.initTestTelemetry();
utils.initTestLogger();
isSmtpAvailable = await utils.isTestSmtpServiceAvailable();
}, SMTP_TEST_TIMEOUT);
});
beforeEach(async () => {
await testDb.truncate(['User'], testDbName);
@ -50,11 +47,7 @@ afterAll(async () => {
await testDb.terminate(testDbName);
});
test(
'POST /forgot-password should send password reset email',
async () => {
if (!isSmtpAvailable) utils.skipSmtpTest(expect);
test('POST /forgot-password should send password reset email', async () => {
const owner = await testDb.createUser({ globalRole: globalOwnerRole });
const authlessAgent = utils.createAgent(app);
@ -63,7 +56,7 @@ test(
globalRole: globalMemberRole,
});
await utils.configureSmtp();
config.set('userManagement.emails.mode', 'smtp');
await Promise.all(
[{ email: owner.email }, { email: member.email.toUpperCase() }].map(async (payload) => {
@ -77,9 +70,7 @@ test(
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 () => {
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';
/**
* 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.
*/

View file

@ -8,19 +8,16 @@ export type CollectionName = keyof IDatabaseCollections;
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';
type EndpointGroup = 'me' | 'users' | 'auth' | 'owner' | 'passwordReset' | 'credentials' | 'publicApi';
type EndpointGroup =
| 'me'
| 'users'
| 'auth'
| 'owner'
| 'passwordReset'
| 'credentials'
| 'publicApi';
export type CredentialPayload = {
name: string;

View file

@ -6,8 +6,6 @@ import superagent from 'superagent';
import request from 'supertest';
import { URL } from 'url';
import bodyParser from 'body-parser';
import util from 'util';
import { createTestAccount } from 'nodemailer';
import { set } from 'lodash';
import { CronJob } from 'cron';
import { BinaryDataManager, UserSettings } from 'n8n-core';
@ -45,18 +43,10 @@ import { issueJWT } from '../../../src/UserManagement/auth/jwt';
import { getLogger } from '../../../src/Logger';
import { credentialsController } from '../../../src/api/credentials.api';
import { loadPublicApiVersions } from '../../../src/PublicApi/';
import * as UserManagementMailer from '../../../src/UserManagement/email/UserManagementMailer';
import type { User } from '../../../src/databases/entities/User';
import type {
ApiPath,
EndpointGroup,
PostgresSchemaSection,
SmtpTestAccount,
TriggerTime,
} from './types';
import type { ApiPath, EndpointGroup, PostgresSchemaSection, TriggerTime } from './types';
import type { N8nApp } from '../../../src/UserManagement/Interfaces';
/**
* Initialize a test server.
*
@ -860,45 +850,6 @@ export async function isInstanceOwnerSetUp() {
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
// ----------------------------------

View file

@ -4,7 +4,7 @@ import { v4 as uuid } from 'uuid';
import { Db } from '../../src';
import config from '../../config';
import { SMTP_TEST_TIMEOUT, SUCCESS_RESPONSE_BODY } from './shared/constants';
import { SUCCESS_RESPONSE_BODY } from './shared/constants';
import {
randomEmail,
randomValidPassword,
@ -20,6 +20,7 @@ import * as testDb from './shared/testDb';
import { compareHash } from '../../src/UserManagement/UserManagementHelper';
jest.mock('../../src/telemetry');
jest.mock('../../src/UserManagement/email/NodeMailer');
let app: express.Application;
let testDbName = '';
@ -27,7 +28,6 @@ let globalMemberRole: Role;
let globalOwnerRole: Role;
let workflowOwnerRole: Role;
let credentialOwnerRole: Role;
let isSmtpAvailable = false;
beforeAll(async () => {
app = await utils.initTestServer({ endpointGroups: ['users'], applyAuth: true });
@ -48,9 +48,7 @@ beforeAll(async () => {
utils.initTestTelemetry();
utils.initTestLogger();
isSmtpAvailable = await utils.isTestSmtpServiceAvailable();
}, SMTP_TEST_TIMEOUT);
});
beforeEach(async () => {
await testDb.truncate(
@ -487,24 +485,15 @@ test('POST /users should fail if user management is disabled', async () => {
expect(response.statusCode).toBe(500);
});
test(
'POST /users should email invites and create user shells but ignore existing',
async () => {
if (!isSmtpAvailable) utils.skipSmtpTest(expect);
test('POST /users should email invites and create user shells but ignore existing', async () => {
const owner = await testDb.createUser({ globalRole: globalOwnerRole });
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();
config.set('userManagement.emails.mode', 'smtp');
const testEmails = [
randomEmail(),
randomEmail().toUpperCase(),
memberShell.email,
member.email,
];
const testEmails = [randomEmail(), randomEmail().toUpperCase(), memberShell.email, member.email];
const payload = testEmails.map((e) => ({ email: e }));
@ -537,19 +526,13 @@ test(
expect(password).toBeNull();
expect(resetPasswordToken).toBeNull();
}
},
SMTP_TEST_TIMEOUT,
);
test(
'POST /users should fail with invalid inputs',
async () => {
if (!isSmtpAvailable) utils.skipSmtpTest(expect);
});
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 });
await utils.configureSmtp();
config.set('userManagement.emails.mode', 'smtp');
const invalidPayloads = [
randomEmail(),
@ -568,19 +551,13 @@ test(
expect(users.length).toBe(1); // DB unaffected
}),
);
},
SMTP_TEST_TIMEOUT,
);
test(
'POST /users should ignore an empty payload',
async () => {
if (!isSmtpAvailable) utils.skipSmtpTest(expect);
});
test('POST /users should ignore an empty payload', async () => {
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([]);
@ -592,9 +569,7 @@ test(
const users = await Db.collections.User.find();
expect(users.length).toBe(1);
},
SMTP_TEST_TIMEOUT,
);
});
// TODO: /users/:id/reinvite route tests missing