All files / src/dev/lib core.ts

99.19% Statements 246/248
66.66% Branches 8/12
100% Functions 74/74
99.17% Lines 239/241

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392                    1x 1x 1x 1x 1x 1x   1x 1x   1x 1x   1x 1x   1x 1x       1x       2x 2x   2x 2x   2x 2x   2x 2x   2x 2x   2x 2x 2x   2x     2x 2x 2x     2x   2x 2x 2x     2x       1x 1x 1x 1x 1x 1x 1x       1x           2x   2x 2x     2x 2x 2x 2x 2x   1x     2x 2x 2x 2x 2x   1x     2x 2x 2x 2x 2x   1x     2x 2x 2x 2x 2x   1x     2x 2x   2x 2x     2x 2x     2x 2x 1x   1x           1x 1x 1x             1x 1x   1x 1x             1x 1x 1x   1x 1x             1x 1x 1x   1x 1x             1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x   1x 1x 1x   1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x   1x   1x   1x   1x     1x 1x 1x     1x 1x 1x 1x 1x       1x 1x   1x 1x 1x   1x 1x 1x 1x   1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x   1x 1x 1x 1x   1x 1x 1x 1x 1x       1x 1x 1x 1x 1x   1x 1x 1x     1x 1x 1x 1x   1x 1x       1x 1x 1x   1x 1x 1x 1x 1x   1x 1x 1x   1x 1x 1x   1x 1x 1x   1x 1x 1x     1x   1x 1x 1x            
import { describe, test, expect } from 'vitest';
import type { ICoreAnyModule, ICoreKernelModule, ILogChannel } from '../../lib';
import TestService from '../testClass/service/TestService';
import { CoreCache, CoreLogChannel, CoreLogger, LogLevel } from '../../classes';
import { CoreCryptoClient, DefaultLogger, generateSeed } from '../../modules';
import { CoreDb } from '../../database';
import TestContext from '../TestContext';
import { Type, XUtil } from '../../utils';
 
export default function jestCore() {
  describe('core', () => {
    const testText = 'hello_world';
    const [kernel] = TestContext.getEntity();
    describe('kernel extend', () => {
      test('getChild empty', () => {
        expect(() => kernel.getChildModule('invaldimodname')).toThrow();
      });
      test('getOffline', async () => {
        expect(kernel.getOffline()).toBeFalsy();
      });
      test('getAppCode', async () => {
        expect(kernel.getAppCode()).not.toBe('');
      });
      test('getActionList', async () => {
        expect(kernel.getActionList().length).toBeGreaterThan(0);
      });
      test('getServiceList', async () => {
        expect(kernel.getServiceList().length).toBeGreaterThan(0);
      });
    });
 
    describe.each([
      ['kernel', kernel],
      ['module', kernel.getModule() as ILogChannel],
    ])('Default logger:(%s):', (name: string, log: ILogChannel) => {
      test('log', async () => {
        log.log('log');
      });
      test('debug', async () => {
        log.debug('debug');
      });
      test('warn', async () => {
        log.warn('warn');
      });
      test('error', async () => {
        log.error('error');
      });
      test('verbose', async () => {
        log.verbose('verbose');
      });
      test('lError', () => {
        try {
          throw log.lError('TestError');
        } catch (e) {
          expect(false).toBe(false);
        }
      });
      test('log - object', async () => {
        const logger = kernel.getLogger();
        Iif (logger instanceof DefaultLogger) {
          logger.setPrintObject(false);
        }
        log.log({ test: 'test' }, { test: 'test' });
      });
      test('log - object', async () => {
        const logger = kernel.getLogger();
        Iif (logger instanceof DefaultLogger) {
          logger.setPrintObject(true);
        }
        log.log({ test: 'test' }, { test: 'test' });
      });
    });
 
    describe('DevMode', () => {
      test('switch', async () => {
        expect(kernel.getDevMode()).toBeFalsy();
        kernel.setDevMode(true);
        expect(kernel.getDevMode()).toBeTruthy();
        kernel.setDevMode(false);
        expect(kernel.getDevMode()).toBeFalsy();
      });
    });
 
    describe.each([
      ['testModule', false, 0, [null]],
      ['bridgeModule', true, 1, ['testModule']],
    ])(
      'Module: (%s):',
      (name: string, failing: boolean, br: number, mods: (string | null)[]) => {
        const module = kernel.getChildModule(name) as ICoreAnyModule;
 
        test('exist', () => {
          expect(module).not.toBeNull();
        });
 
        test('hasPresenter', () => {
          try {
            expect(module.hasPresenter()).toBeTruthy();
            expect(module.getPresenter()).not.toBeNull();
            expect(failing).toBeFalsy();
          } catch (e) {
            expect(failing).toBeTruthy();
          }
        });
        test('hasDb', () => {
          try {
            expect(module.hasDb()).toBeTruthy();
            expect(module.getDb()).not.toBeNull();
            expect(failing).toBeFalsy();
          } catch (e) {
            expect(failing).toBeTruthy();
          }
        });
        test('hasCache', () => {
          try {
            expect(module.hasCache()).toBeTruthy();
            expect(module.getCache()).not.toBeNull();
            expect(failing).toBeFalsy();
          } catch (e) {
            expect(failing).toBeTruthy();
          }
        });
        test('hasClient', () => {
          try {
            expect(module.hasClient()).toBeTruthy();
            expect(module.getClient()).not.toBeNull();
            expect(failing).toBeFalsy();
          } catch (e) {
            expect(failing).toBeTruthy();
          }
        });
        test('hasServiceList', () => {
          expect(module.getServiceList()).toHaveLength(failing ? 0 : 2);
        });
        test('test_trigger', async () => {
          expect(await kernel.triggerEvent('test_trigger')).toBeTruthy();
        });
 
        test('hasBridges', () => {
          expect(module.getBridges()).toHaveLength(br);
        });
 
        test.each(mods)('Bridge: (%s):', (mName: string | null) => {
          if (mName) {
            expect(module.getBridgeModule(mName)).not.toBeUndefined();
          } else {
            expect(() => module.getBridgeModule('modnotexist')).toThrow();
          }
        });
      },
    );
 
    describe('Cache', () => {
      test('set', async () => {
        const mod = kernel.getChildModule('testModule') as ICoreKernelModule<
          any,
          any,
          any,
          any,
          any
        >;
        const cache = mod.getCache() as CoreCache;
        await cache.set('test', 'test');
      });
      test('exist', async () => {
        const mod = kernel.getChildModule('testModule') as ICoreKernelModule<
          any,
          any,
          any,
          any,
          any
        >;
        const cache = mod.getCache() as CoreCache;
        const conf = await cache.exist('test');
        expect(conf).toBeTruthy();
      });
      test('get', async () => {
        const mod = kernel.getChildModule('testModule') as ICoreKernelModule<
          any,
          any,
          any,
          any,
          any
        >;
        const cache = mod.getCache() as CoreCache;
        const conf = await cache.get('test');
        expect(conf).toBe('test');
      });
      test('del', async () => {
        const mod = kernel.getChildModule('testModule') as ICoreKernelModule<
          any,
          any,
          any,
          any,
          any
        >;
        const cache = mod.getCache() as CoreCache;
        await cache.delete('test');
        const conf = await cache.exist('test');
        expect(conf).toBeFalsy();
      });
    });
    describe('Crypto', () => {
      test('encrypt/decrypt', async () => {
        const cc = kernel.getCryptoClient();
        expect(cc).not.toBeNull();
        expect(kernel.hasCryptoClient()).toBeTruthy();
        const enc = cc?.encrypt(testText);
        expect(enc).not.toBeUndefined();
        Eif (enc) {
          const dev = cc?.decrypt(enc.enc, enc.iv, enc.auth);
          expect(dev).toBe(testText);
        }
      });
 
      test('seeded hash', async () => {
        const cc = kernel.getCryptoClient();
        expect(cc).not.toBeNull();
 
        const seed = generateSeed();
        expect(seed).not.toBe('');
        expect(cc?.getHash(seed, testText)).not.toBeNull();
      });
      test('token gen', async () => {
        const cc = kernel.getCryptoClient();
        expect(cc).not.toBeNull();
        expect(await cc?.generateSecureToken(48)).not.toBe('');
      });
 
      test('keystore', async () => {
        const text = testText;
        const cc = kernel.getCryptoClient();
        const db = kernel.getDb() as CoreDb;
        expect(cc).not.toBeNull();
        Eif (cc) {
          const keyID = await cc.keyStoreSave(text);
          expect(keyID).not.toBeNull();
          expect(keyID).not.toBeUndefined();
          const keyreturn = await cc.keyStoreLoad(keyID);
          expect(keyreturn).not.toBeNull();
          expect(keyreturn).not.toBeUndefined();
          expect(keyreturn).toBe(text);
          await db.deleteKey(keyID);
          expect(await db.getKey(keyID)).toBeNull();
        }
      });
    });
 
    describe('Service', () => {
      test('test tates', async () => {
        const mod = kernel.getModule();
        const service = new TestService('hello', 30000, mod);
        expect(service.state).toBe('INIT');
        service.setRunning();
        expect(service.state).toBe('RUNNING');
        service.setSleeping();
        expect(service.state).toBe('SLEEPING');
        service.forceStop = true;
        service.setRunning();
        expect(service.state).toBe('SLEEPING');
      });
      test('loop service cycle', async () => {
        const mod = kernel.getModule();
        const service = new TestService('hello', 30000, mod);
        mod.addService(service);
        await service.start();
 
        await XUtil.sleep(10);
 
        expect(service.state).toBe('RUNNING');
 
        await service.stop();
 
        expect(service.state).toBe('SLEEPING');
      });
    });
    describe('CoreLogger', () => {
      test('getLogLevelFromString - all valid levels', () => {
        expect(CoreLogger.getLogLevelFromString('verbose')).toBe(
          LogLevel.VERBOSE,
        );
        expect(CoreLogger.getLogLevelFromString('debug')).toBe(LogLevel.DEBUG);
        expect(CoreLogger.getLogLevelFromString('warn')).toBe(LogLevel.WARN);
        expect(CoreLogger.getLogLevelFromString('info')).toBe(LogLevel.INFO);
        expect(CoreLogger.getLogLevelFromString('error')).toBe(LogLevel.ERROR);
        expect(CoreLogger.getLogLevelFromString('silent')).toBe(
          LogLevel.SILENT,
        );
      });
      test('getLogLevelFromString - unknown level throws', () => {
        expect(() => CoreLogger.getLogLevelFromString('invalid')).toThrow();
      });
      test('constructor with logLevel string', () => {
        const logger = new DefaultLogger('debug');
        expect(logger.getLogLevel()).toBe(LogLevel.DEBUG);
      });
      test('setLogLevel with string', () => {
        const logger = new DefaultLogger();
        logger.setLogLevel('error');
        expect(logger.getLogLevel()).toBe(LogLevel.ERROR);
      });
      test('setLogLevel with numeric LogLevel', () => {
        const logger = new DefaultLogger();
        logger.setLogLevel(LogLevel.VERBOSE);
        expect(logger.getLogLevel()).toBe(LogLevel.VERBOSE);
      });
      test('isOnLevel', () => {
        const logger = new DefaultLogger();
        logger.setLogLevel(LogLevel.WARN);
        expect(logger.isOnLevel(LogLevel.ERROR)).toBe(true);
        expect(logger.isOnLevel(LogLevel.WARN)).toBe(true);
        expect(logger.isOnLevel(LogLevel.DEBUG)).toBe(false);
        expect(logger.isOnLevel(LogLevel.VERBOSE)).toBe(false);
      });
      test('setNoColor disables ANSI codes in output', () => {
        const logger = new DefaultLogger();
        logger.setNoColor(true);
        expect(() => logger.error('ch', 'msg')).not.toThrow();
        expect(() => logger.warn('ch', 'msg')).not.toThrow();
      });
      test('setPrintTimestamp false omits timestamp', () => {
        const logger = new DefaultLogger();
        logger.setPrintTimestamp(false);
        expect(() => logger.log('ch', 'msg')).not.toThrow();
      });
      test('printObject=true with primitive arg hits non-object branch', () => {
        const logger = new DefaultLogger();
        logger.setPrintObject(true);
        expect(() =>
          logger.log('ch', 'primitive string arg', 42),
        ).not.toThrow();
      });
    });
    describe('CoreLogChannel', () => {
      test('constructor with CoreLogger instance sets logger directly', () => {
        const logger = new DefaultLogger();
        const ch = new CoreLogChannel('coverage-test', logger);
        expect(ch.logger).toBe(logger);
      });
      test('constructor with null sets logger to null', () => {
        const ch = new CoreLogChannel('coverage-test', null);
        expect(ch.logger).toBeNull();
      });
    });
    describe('CoreCryptoClient', () => {
      test('fromPW derives a 32-char key', () => {
        const key = CoreCryptoClient.fromPW('my-secret-password');
        expect(key).toHaveLength(32);
      });
      test('constructor with invalid key length throws', () => {
        expect(() => new CoreCryptoClient(kernel as any, 'short')).toThrow(
          'INVALID KEY LENGTH',
        );
      });
      test('isValid returns true for valid 32-char key', () => {
        const cc = kernel.getCryptoClient();
        expect(cc?.isValid()).toBe(true);
      });
      test('getUUID generates a valid UUID string', () => {
        const cc = kernel.getCryptoClient();
        const uuid = cc?.getUUID();
        expect(typeof uuid).toBe('string');
        expect(Type.isUUID(uuid!)).toBe(true);
      });
      test('timeSavePWValidation - equal strings returns true', () => {
        const cc = kernel.getCryptoClient();
        expect(cc?.timeSavePWValidation('password', 'password')).toBe(true);
      });
      test('timeSavePWValidation - same length but different returns false', () => {
        const cc = kernel.getCryptoClient();
        expect(cc?.timeSavePWValidation('hello', 'world')).toBe(false);
      });
      test('timeSavePWValidation - different lengths returns false', () => {
        const cc = kernel.getCryptoClient();
        expect(cc?.timeSavePWValidation('hi', 'hello world')).toBe(false);
      });
      test('keyStoreLoad with non-existent id returns null', async () => {
        const cc = kernel.getCryptoClient();
        const result = await cc?.keyStoreLoad(
          '00000000-0000-0000-0000-000000000000',
        );
        expect(result).toBeNull();
      });
      test('clientFromPW throws because sha512 hex is 128 chars not 32', () => {
        expect(() =>
          CoreCryptoClient.clientFromPW(kernel as any, 'any-password'),
        ).toThrow('INVALID KEY LENGTH');
      });
    });
  });
}