Skip to content

Commit

Permalink
write, fix and extend test and fix code
Browse files Browse the repository at this point in the history
  • Loading branch information
CordlessWool committed Jan 14, 2024
1 parent 384e6e1 commit 7e07e2d
Show file tree
Hide file tree
Showing 13 changed files with 460 additions and 98 deletions.
36 changes: 26 additions & 10 deletions src/core/dir.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,18 @@ import { Directory } from './dir.js';
import { TestFilesystemHelper } from '../../test/helpers/testFilesystemHelper.js';
import { File } from './file.js';

class DirectoryTest extends Directory {

getPath() {
return this.path;
}
}


describe('Test Directory Service', () => {
test('Create Instance and set path', () => {
const path = './test/data';
const dir = new DirectoryTest(path);
const dir = new Directory(path);
expect(dir).toBeInstanceOf(Directory);
expect(dir.getPath()).toBe(path);
expect(dir.path).toBe(path);
});

test('relativePath', () => {
const dir = new Directory('./test/');
const dir2 = new Directory('./test/data');
expect(dir.relativePath(dir2)).toBe('data');
});


Expand All @@ -35,6 +33,7 @@ describe('Test Directory Service', () => {
});



describe('list methode', () => {


Expand Down Expand Up @@ -117,6 +116,23 @@ describe('Test Directory Service', () => {

});

test('get files recursive', async () => {
await testHelper.createDirs();
await testHelper.createFile('lorem', {path: 'dorem/tt.txt'});
await testHelper.createFile('lorem');
await testHelper.createFile('lorem');

const dir = new Directory(testHelper.getBasePath());

const files = await dir.files(true);
expect(files).toHaveLength(3);

for(const f of files) {
expect(f).toBeInstanceOf;
expect(await (f as File).text()).toBe('lorem');
}
});

});


Expand Down
8 changes: 4 additions & 4 deletions src/core/dir.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,14 @@ export class Directory {
}


file(name: string): File {
file(name: string) {
return new File(path.join(this.path, name));
}

protected async filesRecursion(list: List): Promise<List> {

const dirList = list.filterByDirent('isDirectory');
const fileList = list.filterByDirent('isFile');
const dirList = list.filterByType('isDirectory');
const fileList = list.filterByType('isFile');

for(const el of dirList) {
if(el instanceof Directory) {
Expand All @@ -58,7 +58,7 @@ export class Directory {
if(recursive) {
return this.filesRecursion(list);
} else {
const fileList = list.filterByDirent('isFile');
const fileList = list.filterByType('isFile');
return fileList;
}

Expand Down
6 changes: 6 additions & 0 deletions src/core/exceptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,10 @@ export class PluginNotFoundException extends Error {
constructor(path: string) {
super(`No plugin found for ${path}`);
}
}

export class FileConvertException extends Error {
constructor(path: string, message: string) {
super(`Error converting file ${path}: ${message}`);
}
}
69 changes: 39 additions & 30 deletions src/core/file.spec.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,24 @@
import { expect, test, describe, beforeEach, afterEach, beforeAll, afterAll } from 'vitest';
import { File } from './file.js';
import { FileDoesNotExistException, PluginNotFoundException } from './exceptions.js';
import { FileConvertException, FileDoesNotExistException, PluginNotFoundException } from './exceptions.js';
import { TestFilesystemHelper } from '../../test/helpers/testFilesystemHelper.js';


import jsonConverter from '../plugins/jsonConverter.js';
import yamlConverter from '../plugins/yamlConverter.js';


class FileTest extends File {

getPath() {
return this.path;
}

static getPlugins() {
return File.plugins;
static getConvertPlugins() {
return Array.from(new Set(File.converterPlugins.values()));
}

static emptyPlugins() {
File.plugins = [];
File.converterPlugins = new Map();
}
}

Expand All @@ -46,33 +45,14 @@ describe('Test File Service', () => {

test('Create Instance with invalid path', () => {
const path = './test/data/test2.txt';
expect(() => new File(path)).toThrow(FileDoesNotExistException as ErrorConstructor);
expect(() => new File(path)).toThrow(FileDoesNotExistException);
});

test('Register plugins', async () => {
new File('./test/data/test.json');
const plugins = FileTest.getPlugins();
const plugins = FileTest.getConvertPlugins();
expect(plugins).toHaveLength(2);
});

test('Create from Array', async () => {

const paths = ['./test/data/test.json', './test/data/test.yaml'];
const files = await File.fromArray(paths);
const fileArray = files.asArray();
expect(fileArray).toHaveLength(2);
expect(fileArray[0]).toBeInstanceOf(File);
expect(fileArray[1]).toBeInstanceOf(File);

for(let x = 0; x < 3; x++) {
let loopCount = 0;
for (const file of files) {
expect(file).toBeInstanceOf(File);
loopCount++;
}
expect(loopCount).toBe(2);
}
});


describe('Test with generaed file', () => {
Expand All @@ -93,6 +73,13 @@ describe('Test File Service', () => {
expect(content).toBe(testFile.getContent());
});

test.each(['json', 'yaml', 'yml', 'log', 'txt'])('Get extenction %s', async (extention) => {
const testFile = await testHelper.createFile('', { extention });
const file = new File(testFile.includeBasePath().getPath());
expect(file.extention).toBe(extention);

});

test('Read json file', async () => {

const testContent = {test: true};
Expand Down Expand Up @@ -123,13 +110,24 @@ describe('Test File Service', () => {
expect(content.test).toBe(true);
});

test('Read file plain', async () => {
const testContent = '1234k2hk3jh1fasdasfc%';
const testFile = await testHelper.createFile(testContent, { extention: 'rtx' });
const path = testFile.includeBasePath().getPath();

const file = new File(path);
const content = await file.plain();
expect(content).toBeInstanceOf(Buffer);
expect(content.toString()).toBe(testContent);
});



});
});


describe.todo('Test with missing plugins' , () => {
describe('Test Error handling' , () => {

let testHelper: TestFilesystemHelper;

Expand All @@ -151,15 +149,26 @@ describe.todo('Test with missing plugins' , () => {
const testFile = await testHelper.createFile(testContent, { extention: 'json' });

const file = new File(testFile.includeBasePath().getPath());
expect(() => file.json()).toThrow(PluginNotFoundException);
expect(() => file.json()).rejects.toThrow(PluginNotFoundException);
});

test('Plugin not registered for path', async () => {

const testFile = testHelper.createFile('test', { extention: 'md' });
const path = (await testFile).includeBasePath().getPath();

const file = new File(path);
expect(() => file.json()).rejects.toThrow(PluginNotFoundException);
});

test('No file extenstion', async () => {

const testFile = testHelper.createFile('{test: true}', { path: 'test/test' });
const path = (await testFile).includeBasePath().getPath();

const file = new File((await testFile).includeBasePath().getPath());
expect(() => file.json()).toThrow(PluginNotFoundException);
const file = new File(path);
expect(file.text()).resolves.toBe('{test: true}');
expect(file.json()).rejects.toThrow(FileConvertException);
});
});

Expand Down
70 changes: 44 additions & 26 deletions src/core/file.ts
Original file line number Diff line number Diff line change
@@ -1,50 +1,68 @@
import * as fs from 'node:fs/promises';
import { existsSync } from 'node:fs';
import type { LoomFSFileConverter } from './types.js';
import { FileDoesNotExistException, PluginNotFoundException } from './exceptions.js';
import { PLUGIN_TYPE, type LoomFSFileConverter } from './types.js';
import { FileConvertException, FileDoesNotExistException, PluginNotFoundException } from './exceptions.js';

export class File {

protected static plugins: LoomFSFileConverter[] = [];
protected static converterPlugins: Map<string, LoomFSFileConverter> = new Map();
protected _extention: string | undefined;

constructor(
protected path: string
protected _path: string
) {
if(!existsSync(path)) {
throw new FileDoesNotExistException(path);
if(!existsSync(_path)) {
throw new FileDoesNotExistException(_path);
}
}

get path() {
return this._path;
}

get name(): string {
return <string>this.path.split('/').pop();
}

get extention() {
if(this._extention === undefined) {
const split = this.name.split('.');
this._extention = split.length > 1 ? split.pop() : undefined;
}
return this._extention;
}

async json<T>() {
const text = await this.text();
for(const plugin of File.plugins) {
if(plugin.extentions.includes(this.path.split('.').pop()!)) {
return plugin.parse(text) as T;
}

if(this.extention === undefined) {
throw new FileConvertException(this.path, 'File has no extension');
}

const plugin = File.converterPlugins.get(this.extention);

if(plugin === undefined) {
throw new PluginNotFoundException(this.path);
}

throw new PluginNotFoundException(this.path);
return plugin.parse<T>(text);

}

async plain() {
return await fs.readFile(this.path);
}

async text(encoding: BufferEncoding = 'utf8') {
return fs.readFile(this.path, encoding);
return await fs.readFile(this.path, encoding);
}

static register(plugin: LoomFSFileConverter) {
File.plugins.push(plugin);
}

static async fromArray (paths: string[]) {
return {
asArray() {
return paths.map((path) => new File(path));
},
[Symbol.iterator]: function* () {
for(const path of paths) {
yield new File(path);
}
}
};
if(plugin.type === PLUGIN_TYPE.FILE_CONVERTER) {
plugin.extentions.forEach(ext => {
File.converterPlugins.set(ext, plugin);
});
}
}

}
Loading

0 comments on commit 7e07e2d

Please sign in to comment.