Skip to content

Commit

Permalink
feat: utils test
Browse files Browse the repository at this point in the history
  • Loading branch information
AbigailDeng authored and AbigailDeng committed Jun 25, 2024
1 parent f4de27b commit 8a2913a
Show file tree
Hide file tree
Showing 9 changed files with 778 additions and 7 deletions.
12 changes: 7 additions & 5 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -143,10 +143,12 @@ export default {
// testLocationInResults: false,

// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
testMatch: [
'**/test/command/dappServer/socket-sign.test.js',
'**/test/**/*.[jt]s?(x)'
// "**/?(*.)+(spec|test).[tj]s?(x)"
],
testTimeout: 5000,

// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
Expand Down Expand Up @@ -176,7 +178,7 @@ export default {
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
transformIgnorePatterns: [
// "/node_modules/(?!chalk|update-notifier|configstore|xdg-basedir|unique-string|crypto-random-string|semver-diff|latest-version|package-json|got|@sindresorhus|p-cancelable|@szmarczak/http-timer|cacheable-request|normalize-url|responselike|lowercase-keys|mimic-response|form-data-encoder)"
],
]

// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
Expand Down
3 changes: 1 addition & 2 deletions src/utils/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,6 @@ async function getParams(method) {
} catch (e) {}
let paramValue;
// todo: use recursion

if (
rule !== 'repeated' &&
innerType &&
Expand Down Expand Up @@ -366,7 +365,7 @@ async function deserializeLogs(aelf, logs = []) {
let results = await Promise.all(logs.map(v => getProto(aelf, v.Address)));
results = results.map((proto, index) => {
const { Name, NonIndexed, Indexed = [] } = logs[index];
const serializedData = [...(Indexed || [])];
const serializedData = [...Indexed];
if (NonIndexed) {
serializedData.push(NonIndexed);
}
Expand Down
5 changes: 5 additions & 0 deletions test/dataDir/aelf/.aelfrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# THIS IS AN AUTOGENERATED FILE FOR AELF-COMMAND OPTIONS. DO NOT EDIT THIS FILE DIRECTLY.



endpoint https://tdvw-test-node.aelf.io/
79 changes: 79 additions & 0 deletions test/rc/index.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import fs from 'fs';
import path from 'path';
import Registry from '../../src/rc/index';
import { userHomeDir } from '../../src/utils/userHomeDir';
import { endpoint, account, password, dataDir } from '../constants.js';

jest.mock('../../src/utils/userHomeDir', () => {
const path = require('path');
return {
userHomeDir: path.resolve(__dirname)
};
});

describe('Registry', () => {
afterEach(() => {
jest.clearAllMocks();
delete process.env.AELF_CLI_ENDPOINT;
});
afterAll(() => {
fs.unlinkSync(path.resolve(userHomeDir, 'aelf/.aelfrc'));
fs.rmdirSync(path.resolve(userHomeDir, 'aelf'));
});
test('should get file or not', () => {
const result = Registry.getFileOrNot(path.resolve(__dirname, '../datadir/aelf/.aelfrc'));
expect(result).toBe(`# THIS IS AN AUTOGENERATED FILE FOR AELF-COMMAND OPTIONS. DO NOT EDIT THIS FILE DIRECTLY.
endpoint https://tdvw-test-node.aelf.io/
`);
});
test('should load config', () => {
const result = Registry.loadConfig();
expect(result).toEqual({});
});
test('should get config from env', () => {
// mock
process.env.AELF_CLI_ENDPOINT = 'http://localhost:1234';
const result = Registry.getConfigFromEnv();
expect(result).toEqual({ endpoint: 'http://localhost:1234' });
});
test('should stringify', () => {
const result = Registry.stringify();
expect(result).toEqual([
'# THIS IS AN AUTOGENERATED FILE FOR AELF-COMMAND OPTIONS. DO NOT EDIT THIS FILE DIRECTLY.',
'',
'',
''
]);
});
test('should get and set options correctly', () => {
const registry = new Registry();
registry.setOption('endpoint', endpoint);
expect(registry.getOption('endpoint')).toBe(endpoint);
});
test('should save options to file', () => {
const registry = new Registry();
registry.saveOption('endpoint', endpoint);
expect(fs.readFileSync(registry.globalConfigLoc).toString()).toContain(`endpoint ${endpoint}`);
});
test('should delete config key from file', () => {
const registry = new Registry();
registry.saveOption('endpoint', endpoint);
registry.deleteConfig('endpoint');
expect(fs.readFileSync(registry.globalConfigLoc).toString()).not.toContain(`endpoint ${endpoint}`);
});
test('should get file configs correctly', () => {
const registry = new Registry();
registry.saveOption('endpoint', endpoint);
const fileConfigs = registry.getFileConfigs();
expect(fileConfigs.endpoint).toBe(endpoint);
});
test('should get configs correctly', () => {
const registry = new Registry();
registry.saveOption('endpoint', endpoint);
const configs = registry.getConfigs();
expect(configs.endpoint).toBe(endpoint);
});
});
52 changes: 52 additions & 0 deletions test/utils/Logger.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import chalk from 'chalk';
import Logger from '../../src/utils/Logger';

describe('Logger', () => {
let consoleLogSpy;
const fnName = 'trace',
level = 'Trace';
beforeEach(() => {
consoleLogSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
});

afterEach(() => {
consoleLogSpy.mockRestore();
});

test(`should log correctly formatted message`, () => {
const logger = new Logger({ log: true, onlyWords: false, name: 'TestLogger' });
const message = 'Test message';
logger[fnName](message);
const expectedPrefix = `[${level}]: `;
const expectedLog = chalk.gray(`TestLogger ${expectedPrefix}${message}`);
// second params: add spaces
expect(consoleLogSpy).toHaveBeenCalledWith(expectedLog, '');
});
test(`should return correctly formatted chalk message`, () => {
const logger = new Logger({ log: false, onlyWords: false, name: 'TestLogger' });
const message = 'Test message';
const result = logger[fnName](message);
const expectedPrefix = `TestLogger [${level}]: `;
const expectedChalk = chalk(chalk.gray(`${expectedPrefix}${message}`));
expect(result.trim()).toEqual(expectedChalk);
});
test(`should log correctly formatted object message`, () => {
const logger = new Logger({ log: true, onlyWords: false, name: 'TestLogger' });
const message = { key: 'value' };
logger[fnName](message);
const expectedPrefix = `TestLogger [${level}]: \n`;
const expectedLog = chalk.gray(`${expectedPrefix}`).trim();
expect(consoleLogSpy).toHaveBeenCalledWith(expectedLog, message);
});
test(`should log correctly formatted object message (onlyWords: true)`, () => {
const logger = new Logger({ onlyWords: true, name: 'TestLogger' });
logger.symbol = '*';
const message = { key: 'value' };
logger[fnName](message);

const expectedPrefix = `* [${level}]: \n`;
const expectedLog = chalk.gray(`${expectedPrefix}`).trim();

expect(consoleLogSpy).toHaveBeenCalledWith(expectedLog, message);
});
});
51 changes: 51 additions & 0 deletions test/utils/fs.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import fs from 'fs';
import os from 'os';
import { writeFilePreservingEol } from '../../src/utils/fs.js';
import { promisify } from '../../src/utils/utils';

jest.mock('fs');
jest.mock('../../src/utils/utils', () => {
return {
promisify: fn => fn
};
});

describe('File System Operators', () => {
afterEach(() => {
jest.restoreAllMocks();
});

describe('writeFilePreservingEol', () => {
// cannot test /r/n because it depends on Windows
test('should write data with preserved EOL', async () => {
const path = '/path/to/existing/file.txt';
const existingData = 'Line 1\nLine 2\nLine 3\n';
const newData = 'New Line 1\nNew Line 2\nNew Line 3\n';
const expectedData = 'New Line 1\nNew Line 2\nNew Line 3\n';

const mockBuffer = Buffer.from(existingData, 'utf-8');
fs.existsSync.mockReturnValue(true);
fs.readFile.mockReturnValue(mockBuffer);

let writtenData = '';
fs.writeFile.mockImplementation((filePath, data) => {
writtenData = data.toString();
});

await writeFilePreservingEol(path, newData);
expect(writtenData).toBe(expectedData);
});

test('should write data with default EOL if file does not exist', async () => {
const path = '/path/to/nonexistent/file.txt';
const newData = 'Line 1\nLine 2\nLine 3\n';
fs.existsSync.mockReturnValue(false);
let writtenData = '';
fs.writeFile.mockImplementation((filePath, data) => {
writtenData = data.toString();
});
await writeFilePreservingEol(path, newData);
expect(writtenData).toBe(newData);
});
});
});
111 changes: 111 additions & 0 deletions test/utils/userHomeDir.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import path from 'path';
import { homedir } from 'os';
import { userHomeDir, home, isFakeRoot, isRootUser, ROOT_USER } from '../../src/utils/userHomeDir';

jest.mock('os', () => ({
homedir: jest.fn(() => {
const mockHomeDir = '/mock/home';
return mockHomeDir;
})
}));
describe('userHomeDir', () => {
let originalPlatform;
let originalEnv;
const mockHomeDir = '/mock/home';
beforeAll(() => {
originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform');
originalEnv = { ...process.env };
});

afterAll(() => {
Object.defineProperty(process, 'platform', originalPlatform);
process.env = originalEnv;
});

beforeEach(() => {
jest.clearAllMocks();
jest.resetModules();
});

test('home should be the user home directory', () => {
expect(home).toBe(mockHomeDir);
});

test('isFakeRoot should return true if FAKEROOTKEY is set', () => {
process.env.FAKEROOTKEY = 'true';
expect(isFakeRoot()).toBe(true);
});

test('isFakeRoot should return false if FAKEROOTKEY is not set', () => {
delete process.env.FAKEROOTKEY;
expect(isFakeRoot()).toBe(false);
});

test('isRootUser should return true if uid is 0', () => {
expect(isRootUser(0)).toBe(true);
});

test('isRootUser should return false if uid is not 0', () => {
expect(isRootUser(1000)).toBe(false);
});

test('isWindows should return true if platform is win32', () => {
Object.defineProperty(process, 'platform', {
value: 'win32'
});
expect(process.platform).toBe('win32');
});

test('isWindows should return false if platform is not win32', () => {
Object.defineProperty(process, 'platform', {
value: 'linux'
});
expect(process.platform).toBe('linux');
});

test('userHomeDir should be correct for Windows platform', () => {
Object.defineProperty(process, 'platform', {
value: 'win32'
});

jest.resetModules();
const { userHomeDir } = require('../../src/utils/userHomeDir');
expect(userHomeDir).toBe(path.resolve(mockHomeDir, './AppData/Local'));
});

test('userHomeDir should be correct for non-Windows platform', () => {
Object.defineProperty(process, 'platform', {
value: 'linux'
});

jest.resetModules();
const { userHomeDir } = require('../../src/utils/userHomeDir');
expect(userHomeDir).toBe(path.resolve(mockHomeDir, './.local/share'));
});

test('ROOT_USER should be true if user is root and not fake root', () => {
jest.spyOn(process, 'getuid').mockReturnValue(0);
delete process.env.FAKEROOTKEY;

jest.resetModules();
const { ROOT_USER } = require('../../src/utils/userHomeDir');
expect(ROOT_USER).toBe(true);
});

test('ROOT_USER should be false if user is not root', () => {
jest.spyOn(process, 'getuid').mockReturnValue(1000);

jest.resetModules();
const { ROOT_USER } = require('../../src/utils/userHomeDir');
expect(ROOT_USER).toBe(false);
});

test('ROOT_USER should be false if user is root but is fake root', () => {
jest.spyOn(process, 'getuid').mockReturnValue(0);
process.env.FAKEROOTKEY = 'true';

jest.resetModules();
const { ROOT_USER } = require('../../src/utils/userHomeDir');
expect(ROOT_USER).toBe(false);
});
});
Loading

0 comments on commit 8a2913a

Please sign in to comment.