Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mock mailer service #3711

Merged
merged 2 commits into from
Jul 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 21 additions & 30 deletions packages/cli/test/integration/passwordReset.api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand All @@ -33,9 +32,7 @@ beforeAll(async () => {

utils.initTestTelemetry();
utils.initTestLogger();

isSmtpAvailable = await utils.isTestSmtpServiceAvailable();
}, SMTP_TEST_TIMEOUT);
});

beforeEach(async () => {
await testDb.truncate(['User'], testDbName);
Expand All @@ -50,36 +47,30 @@ afterAll(async () => {
await testDb.terminate(testDbName);
});

test(
'POST /forgot-password should send password reset email',
async () => {
if (!isSmtpAvailable) utils.skipSmtpTest(expect);

const owner = await testDb.createUser({ globalRole: globalOwnerRole });
test('POST /forgot-password should send password reset email', async () => {
const owner = await testDb.createUser({ globalRole: globalOwnerRole });

const authlessAgent = utils.createAgent(app);
const member = await testDb.createUser({
email: '[email protected]',
globalRole: globalMemberRole,
});
const authlessAgent = utils.createAgent(app);
const member = await testDb.createUser({
email: '[email protected]',
globalRole: globalMemberRole,
});

await utils.configureSmtp();
config.set('userManagement.emails.mode', 'smtp');

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(
[{ email: owner.email }, { email: member.email.toUpperCase() }].map(async (payload) => {
const response = await authlessAgent.post('/forgot-password').send(payload);

expect(response.statusCode).toBe(200);
expect(response.body).toEqual({});
expect(response.statusCode).toBe(200);
expect(response.body).toEqual({});

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,
);
const user = await Db.collections.User.findOneOrFail({ email: payload.email });
expect(user.resetPasswordToken).toBeDefined();
expect(user.resetPasswordTokenExpiration).toBeGreaterThan(Math.ceil(Date.now() / 1000));
}),
);
});

test('POST /forgot-password should fail if emailing is not set up', async () => {
const owner = await testDb.createUser({ globalRole: globalOwnerRole });
Expand Down
5 changes: 0 additions & 5 deletions packages/cli/test/integration/shared/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down
19 changes: 8 additions & 11 deletions packages/cli/test/integration/shared/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
51 changes: 1 addition & 50 deletions packages/cli/test/integration/shared/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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.
*
Expand Down Expand Up @@ -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
// ----------------------------------
Expand Down
Loading