n8n/packages/nodes-base/nodes/Code/test/Code.node.test.ts
Iván Ovejero 6d6e2488c6
refactor(core): Generalize binary data manager interface (no-changelog) (#7164)
Depends on: #7092 | Story:
[PAY-768](https://linear.app/n8n/issue/PAY-768)

This PR: 
- Generalizes the `IBinaryDataManager` interface.
- Adjusts `Filesystem.ts` to satisfy the interface.
- Sets up an S3 client stub to be filled in in the next PR.
- Turns `BinaryDataManager` into an injectable service.
- Adjusts the config schema and adds new validators.

Note that the PR looks large but all the main changes are in
`packages/core/src/binaryData`.

Out of scope:
- `BinaryDataManager` (now `BinaryDataService`) and `Filesystem.ts` (now
`fs.client.ts`) were slightly refactored for maintainability, but fully
overhauling them is **not** the focus of this PR, which is meant to
clear the way for the S3 implementation. Future improvements for these
two should include setting up a backwards-compatible dir structure that
makes it easier to locate binary data files to delete, removing
duplication, simplifying cloning methods, using integers for binary data
size instead of `prettyBytes()`, writing tests for existing binary data
logic, etc.

---------

Co-authored-by: कारतोफ्फेलस्क्रिप्ट™ <aditya@netroy.in>
2023-09-22 17:22:12 +02:00

144 lines
4.3 KiB
TypeScript

import { anyNumber, mock } from 'jest-mock-extended';
import { NodeVM } from '@n8n/vm2';
import type { IExecuteFunctions, IWorkflowDataProxyData } from 'n8n-workflow';
import { NodeHelpers } from 'n8n-workflow';
import { normalizeItems } from 'n8n-core';
import { testWorkflows, getWorkflowFilenames, initBinaryDataService } from '@test/nodes/Helpers';
import { Code } from '../Code.node';
import { ValidationError } from '../ValidationError';
describe('Test Code Node', () => {
const workflows = getWorkflowFilenames(__dirname);
beforeAll(async () => {
await initBinaryDataService();
});
testWorkflows(workflows);
});
describe('Code Node unit test', () => {
const node = new Code();
const thisArg = mock<IExecuteFunctions>({
getNode: () => mock(),
helpers: { normalizeItems },
prepareOutputData: NodeHelpers.prepareOutputData,
});
const workflowDataProxy = mock<IWorkflowDataProxyData>({ $input: mock() });
thisArg.getWorkflowDataProxy.mockReturnValue(workflowDataProxy);
describe('runOnceForAllItems', () => {
beforeEach(() => {
thisArg.getNodeParameter.calledWith('mode', 0).mockReturnValueOnce('runOnceForAllItems');
});
describe('valid return data', () => {
const tests: Record<string, [object | null, object]> = {
'should handle null': [null, []],
'should handle pre-normalized result': [
[{ json: { count: 42 } }],
[{ json: { count: 42 } }],
],
'should handle when returned data is not an array': [
{ json: { count: 42 } },
[{ json: { count: 42 } }],
],
'should handle when returned data is an array with items missing `json` key': [
[{ count: 42 }],
[{ json: { count: 42 } }],
],
'should handle when returned data missing `json` key': [
{ count: 42 },
[{ json: { count: 42 } }],
],
};
Object.entries(tests).forEach(([title, [input, expected]]) =>
test(title, async () => {
jest.spyOn(NodeVM.prototype, 'run').mockResolvedValueOnce(input);
const output = await node.execute.call(thisArg);
expect(output).toEqual([expected]);
}),
);
});
describe('invalid return data', () => {
const tests = {
undefined,
null: null,
date: new Date(),
string: 'string',
boolean: true,
array: [],
};
Object.entries(tests).forEach(([title, returnData]) =>
test(`return error if \`.json\` is ${title}`, async () => {
jest.spyOn(NodeVM.prototype, 'run').mockResolvedValueOnce([{ json: returnData }]);
try {
await node.execute.call(thisArg);
throw new Error("Validation error wasn't thrown");
} catch (error) {
expect(error).toBeInstanceOf(ValidationError);
expect(error.message).toEqual("A 'json' property isn't an object [item 0]");
}
}),
);
});
});
describe('runOnceForEachItem', () => {
beforeEach(() => {
thisArg.getNodeParameter.calledWith('mode', 0).mockReturnValueOnce('runOnceForEachItem');
thisArg.getNodeParameter.calledWith('jsCode', anyNumber()).mockReturnValueOnce('');
thisArg.getInputData.mockReturnValueOnce([{ json: {} }]);
});
describe('valid return data', () => {
const tests: Record<string, [object | null, { json: any } | null]> = {
'should handle pre-normalized result': [{ json: { count: 42 } }, { json: { count: 42 } }],
'should handle when returned data missing `json` key': [
{ count: 42 },
{ json: { count: 42 } },
],
};
Object.entries(tests).forEach(([title, [input, expected]]) =>
test(title, async () => {
jest.spyOn(NodeVM.prototype, 'run').mockResolvedValueOnce(input);
const output = await node.execute.call(thisArg);
expect(output).toEqual([[{ json: expected?.json, pairedItem: { item: 0 } }]]);
}),
);
});
describe('invalid return data', () => {
const tests = {
undefined,
null: null,
date: new Date(),
string: 'string',
boolean: true,
array: [],
};
Object.entries(tests).forEach(([title, returnData]) =>
test(`return error if \`.json\` is ${title}`, async () => {
jest.spyOn(NodeVM.prototype, 'run').mockResolvedValueOnce({ json: returnData });
try {
await node.execute.call(thisArg);
throw new Error("Validation error wasn't thrown");
} catch (error) {
expect(error).toBeInstanceOf(ValidationError);
expect(error.message).toEqual("A 'json' property isn't an object [item 0]");
}
}),
);
});
});
});