Modular logistics and supply chain operating system (LSOS)
JavaScript driver-appfleet-managementfreight-managementinfrastructureinventory-managementlast-mile-deliverylogisticsondemandopen-sourceorder-managementroute-optimizationsupply-chain-managementtracking-and-monitoringtransport-management-systemtransportationwarehouse-management
test(console): cover the application route, auth boot loader and runtime config
Ronald A. Richardsone3e06a4e226c
diff --git a/console/tests/unit/routes/application-test.js b/console/tests/unit/routes/application-test.jsindex e5e93009..43f34759 100644--- a/console/tests/unit/routes/application-test.js+++ b/console/tests/unit/routes/application-test.js@@ -2,9 +2,57 @@ import { module, test } from 'qunit';import Service from '@ember/service';import { setupTest } from '@fleetbase/console/tests/helpers';+/**+ * Every hook on the application route delegates straight to one of its nine injected+ * services, so each test patches only the members under test on the instances the route+ * actually holds. Going through the instance is deliberate: `universe/hook-service`,+ * `session` and `intl` are resolved before the route is built (so owner.register no+ * longer swaps them), and the hooks themselves are `@action` getters, which cannot be+ * assigned over. defineProperty shadows both cases.+ */+function patch(target, name, value) {+ Object.defineProperty(target, name, { configurable: true, value });+}++/**+ * Records every hookService.execute() call so tests can assert both the hook name and the+ * context the route forwards to extensions.+ */+function captureHooks(route) {+ const calls = [];+ patch(route.hookService, 'execute', (...args) => calls.push(args));++ return calls;+}++/**+ * Drives the real UrlSearchParamsService.get()/getParam() path by swapping the underlying+ * URLSearchParams rather than stubbing the lookup methods.+ */+function withSearch(route, search) {+ Object.defineProperty(route.urlSearchParams, 'urlParams', {+ configurable: true,+ get() {+ return new URLSearchParams(search);+ },+ });+}++function addBootLoader() {+ const element = document.createElement('div');+ element.id = 'boot-loader';+ document.body.appendChild(element);++ return element;+}+module('Unit | Route | application', function (hooks) {setupTest(hooks);+ hooks.afterEach(function () {+ document.getElementById('boot-loader')?.remove();+ });+test('it exists', function (assert) {let route = this.owner.lookup('route:application');assert.ok(route);@@ -51,4 +99,196 @@ module('Unit | Route | application', function (hooks) {assert.true(result);});++ test('willTransition hands the transition to the application:will-transition hook', function (assert) {+ const route = this.owner.lookup('route:application');+ const calls = captureHooks(route);+ const transition = { to: { name: 'console.home' } };++ route.willTransition(transition);++ assert.strictEqual(calls.length, 1, 'the hook fires exactly once');++ const [name, session, router, forwarded] = calls[0];+ assert.strictEqual(name, 'application:will-transition');+ assert.strictEqual(session, route.session, 'extensions receive the session');+ assert.strictEqual(router, route.router, 'extensions receive the router');+ assert.strictEqual(forwarded, transition, 'extensions receive the in-flight transition');+ });++ test('loading hands the transition to the application:loading hook', function (assert) {+ const route = this.owner.lookup('route:application');+ const calls = captureHooks(route);+ const transition = { to: { name: 'console.home' } };++ route.loading(transition);++ assert.strictEqual(calls.length, 1);++ const [name, session, router, forwarded] = calls[0];+ assert.strictEqual(name, 'application:loading');+ assert.strictEqual(session, route.session);+ assert.strictEqual(router, route.router);+ assert.strictEqual(forwarded, transition);+ });++ test('activate initializes the theme before the locale', function (assert) {+ const route = this.owner.lookup('route:application');+ const order = [];++ patch(route, 'initializeTheme', () => order.push('theme'));+ patch(route, 'initializeLocale', () => order.push('locale'));++ route.activate();++ assert.deepEqual(order, ['theme', 'locale']);+ });++ test('initializeTheme applies no extra body classes in a browser', function (assert) {+ const route = this.owner.lookup('route:application');+ let options;++ patch(route.theme, 'initialize', (value) => (options = value));++ route.initializeTheme();++ assert.deepEqual(options, { bodyClassNames: [] }, 'the theme is initialized with an empty class list');+ });++ test('initializeTheme adds the is-electron body class inside an Electron renderer', function (assert) {+ const route = this.owner.lookup('route:application');+ let options;++ patch(route.theme, 'initialize', (value) => (options = value));++ // isElectron() checks window.process.type first, which a browser never has.+ const hadProcess = 'process' in window;+ const previousProcess = window.process;+ window.process = { type: 'renderer' };++ try {+ route.initializeTheme();+ } finally {+ if (hadProcess) {+ window.process = previousProcess;+ } else {+ delete window.process;+ }+ }++ // The route uses pushObject() with an array literal, so the entry arrives nested;+ // classList.add() stringifies a single-element array to the same token. Assert the+ // effective class names rather than pinning that shape.+ assert.deepEqual(options.bodyClassNames.flat(), ['is-electron']);+ });++ test('initializeLocale applies the locale stored on the current user', function (assert) {+ const route = this.owner.lookup('route:application');+ let locales;++ patch(route.intl, 'setLocale', (value) => (locales = value));+ patch(route.currentUser, 'getOption', (key, fallback) => (key === 'locale' ? 'fr-fr' : fallback));++ route.initializeLocale();++ assert.deepEqual(locales, ['fr-fr']);+ });++ test('initializeLocale falls back to en-US when the user has no locale option', function (assert) {+ const route = this.owner.lookup('route:application');+ let locales;+ let requestedFallback;++ patch(route.intl, 'setLocale', (value) => (locales = value));+ patch(route.currentUser, 'getOption', (key, fallback) => {+ requestedFallback = fallback;+ return fallback;+ });++ route.initializeLocale();++ assert.strictEqual(requestedFallback, 'en-US', 'en-US is passed as the default');+ assert.deepEqual(locales, ['en-US']);+ });++ test('beforeModel sets up the session, waits for extensions, then runs the before-model hook', async function (assert) {+ const route = this.owner.lookup('route:application');+ const calls = captureHooks(route);+ const order = [];++ patch(route.session, 'setup', async () => order.push('session'));+ patch(route.session, 'isAuthenticated', false);+ patch(route.extensionManager, 'waitForBoot', async () => order.push('extensions'));+ withSearch(route, '');++ const transition = {};+ const result = await route.beforeModel(transition);++ assert.deepEqual(order, ['session', 'extensions'], 'the session is set up before extensions are awaited');+ assert.strictEqual(calls.length, 1);+ assert.strictEqual(calls[0][0], 'application:before-model');+ assert.strictEqual(calls[0][3], transition);+ assert.strictEqual(result, undefined, 'no shift param means no redirect');+ });++ test('beforeModel redirects an authenticated session to the shift target', async function (assert) {+ const route = this.owner.lookup('route:application');+ let transitionedTo;++ captureHooks(route);+ patch(route.session, 'setup', async () => {});+ patch(route.session, 'isAuthenticated', true);+ patch(route.extensionManager, 'waitForBoot', async () => {});+ withSearch(route, '?shift=fleet-ops/orders');+ patch(route.router, 'transitionTo', (routeName) => {+ transitionedTo = routeName;+ return 'shift-transition';+ });++ const result = await route.beforeModel({});++ // pathToRoute() prefixes 'console.' and turns slashes into dots.+ assert.strictEqual(transitionedTo, 'console.fleet-ops.orders');+ assert.strictEqual(result, 'shift-transition', 'the transition is returned so Ember waits on it');+ });++ test('beforeModel ignores the shift param when the session is not authenticated', async function (assert) {+ const route = this.owner.lookup('route:application');+ let transitioned = false;++ captureHooks(route);+ patch(route.session, 'setup', async () => {});+ patch(route.session, 'isAuthenticated', false);+ patch(route.extensionManager, 'waitForBoot', async () => {});+ withSearch(route, '?shift=fleet-ops/orders');+ patch(route.router, 'transitionTo', () => (transitioned = true));++ const result = await route.beforeModel({});++ assert.false(transitioned, 'an anonymous visitor is not shifted into the console');+ assert.strictEqual(result, undefined);+ });++ test('afterModel removes the boot loader for an unauthenticated session', function (assert) {+ const route = this.owner.lookup('route:application');++ patch(route.session, 'isAuthenticated', false);+ addBootLoader();+ assert.ok(document.getElementById('boot-loader'), 'precondition: the boot loader is present');++ route.afterModel();++ assert.strictEqual(document.getElementById('boot-loader'), null, 'the boot loader is torn down');+ });++ test('afterModel leaves the boot loader in place for an authenticated session', function (assert) {+ const route = this.owner.lookup('route:application');++ patch(route.session, 'isAuthenticated', true);+ addBootLoader();++ route.afterModel();++ assert.ok(document.getElementById('boot-loader'), 'the loader stays up while the console boots');+ });});diff --git a/console/tests/unit/routes/auth/boot-loader-test.js b/console/tests/unit/routes/auth/boot-loader-test.jsnew file mode 100644index 00000000..69d53e69--- /dev/null+++ b/console/tests/unit/routes/auth/boot-loader-test.js@@ -0,0 +1,31 @@+import { module, test } from 'qunit';+import { setupTest } from '@fleetbase/console/tests/helpers';++/**+ * Every route under /auth is a landing point reached straight from a cold boot, so each+ * one tears down the index.html boot loader on activate(). The hook is identical across+ * them, so assert it once per route from a single table rather than copying the same test+ * into five files.+ */+const ROUTES_THAT_CLEAR_THE_BOOT_LOADER = ['route:auth/login', 'route:auth/reset-password', 'route:auth/confirm-email-change', 'route:auth/two-fa', 'route:auth/verification'];++module('Unit | Route | auth boot loader teardown', function (hooks) {+ setupTest(hooks);++ hooks.afterEach(function () {+ document.getElementById('boot-loader')?.remove();+ });++ ROUTES_THAT_CLEAR_THE_BOOT_LOADER.forEach((routeName) => {+ test(`${routeName} removes the boot loader on activate`, function (assert) {+ const element = document.createElement('div');+ element.id = 'boot-loader';+ document.body.appendChild(element);+ assert.ok(document.getElementById('boot-loader'), 'precondition: the boot loader is present');++ this.owner.lookup(routeName).activate();++ assert.strictEqual(document.getElementById('boot-loader'), null, 'the boot loader is removed so the auth screen is visible');+ });+ });+});diff --git a/console/tests/unit/utils/runtime-config-test.js b/console/tests/unit/utils/runtime-config-test.jsindex 8c76795a..987c5431 100644--- a/console/tests/unit/utils/runtime-config-test.js+++ b/console/tests/unit/utils/runtime-config-test.js@@ -1,11 +1,48 @@import { module, test } from 'qunit';import { setupTest } from '@fleetbase/console/tests/helpers';-import { applyRuntimeConfig, clearRuntimeConfigCache } from '@fleetbase/console/utils/runtime-config';+import loadRuntimeConfig, { applyRuntimeConfig, clearRuntimeConfigCache } from '@fleetbase/console/utils/runtime-config';import config from '@fleetbase/console/config/environment';import { get, set } from '@ember/object';const TOUCHED_PATHS = ['API.host', 'API.namespace', 'socket.path', 'socket.hostname', 'socket.secure', 'socket.port', 'osrm.host', 'APP.extensions'];+const CACHE_KEY = 'fleetbase_runtime_config';+const CACHE_VERSION_KEY = 'fleetbase_runtime_config_version';+const CACHE_TTL = 1000 * 60 * 60;++/**+ * loadRuntimeConfig() only consults the cache in production, so the cache branches can+ * only be reached by standing the environment up as production for the duration of a test.+ */+function asProduction() {+ set(config, 'APP.disableRuntimeConfig', false);+ set(config, 'environment', 'production');+}++function writeCache(runtimeConfig, { version = config.APP.version, age = 0 } = {}) {+ window.localStorage.setItem(CACHE_KEY, JSON.stringify({ config: runtimeConfig, timestamp: Date.now() - age }));++ if (version !== null) {+ window.localStorage.setItem(CACHE_VERSION_KEY, version);+ }+}++/**+ * Replaces a localStorage method with one that throws, so the defensive try/catch blocks+ * can be driven the way a private-mode or quota-exhausted browser would drive them.+ * Storage methods live on Storage.prototype; an own property on the instance shadows them.+ */+function breakStorage(method) {+ Object.defineProperty(window.localStorage, method, {+ configurable: true,+ value() {+ throw new Error('QuotaExceededError');+ },+ });++ return () => delete window.localStorage[method];+}+module('Unit | Utility | runtime-config', function (hooks) {setupTest(hooks);@@ -13,10 +50,29 @@ module('Unit | Utility | runtime-config', function (hooks) {// applyRuntimeConfig writes straight into the shared environment config, so// snapshot everything it can touch and put it back afterwards.this.snapshot = TOUCHED_PATHS.map((path) => [path, get(config, path)]);+ this.environment = config.environment;+ this.disableRuntimeConfig = config.APP.disableRuntimeConfig;+ this.fetch = window.fetch;++ // Nothing in these tests should reach the network; each one opts into a response.+ this.requests = [];+ window.fetch = (...args) => {+ this.requests.push(args);+ return Promise.reject(new Error('unexpected request'));+ };+ this.respondWith = (response) => {+ window.fetch = (...args) => {+ this.requests.push(args);+ return Promise.resolve(response);+ };+ };});hooks.afterEach(function () {this.snapshot.forEach(([path, value]) => set(config, path, value));+ set(config, 'environment', this.environment);+ set(config, 'APP.disableRuntimeConfig', this.disableRuntimeConfig);+ window.fetch = this.fetch;});test('it maps the runtime keys onto their config paths', function (assert) {@@ -83,4 +139,133 @@ module('Unit | Utility | runtime-config', function (hooks) {assert.strictEqual(window.localStorage.getItem('fleetbase_runtime_config'), null);assert.strictEqual(window.localStorage.getItem('fleetbase_runtime_config_version'), null);});++ test('clearRuntimeConfigCache swallows a storage failure', function (assert) {+ window.localStorage.setItem(CACHE_KEY, 'cached-payload');+ const restore = breakStorage('removeItem');++ try {+ clearRuntimeConfigCache();+ } finally {+ restore();+ }++ assert.strictEqual(window.localStorage.getItem(CACHE_KEY), 'cached-payload', 'the entry survives because removal threw, but the error did not escape');+ });++ test('loadRuntimeConfig does nothing when runtime config is disabled', async function (assert) {+ set(config, 'APP.disableRuntimeConfig', true);+ const before = get(config, 'API.host');++ await loadRuntimeConfig();++ assert.deepEqual(this.requests, [], 'no request is made');+ assert.strictEqual(get(config, 'API.host'), before, 'the built-in config is left alone');+ });++ test('loadRuntimeConfig applies a fresh cached config in production without a request', async function (assert) {+ asProduction();+ writeCache({ API_HOST: 'https://cached.example.com' });++ await loadRuntimeConfig();++ assert.strictEqual(get(config, 'API.host'), 'https://cached.example.com', 'the cached override is applied');+ assert.deepEqual(this.requests, [], 'a cache hit skips the network entirely');+ });++ test('loadRuntimeConfig falls through to the server when the cache is empty', async function (assert) {+ asProduction();+ this.respondWith({ ok: true, json: () => Promise.resolve({ API_NAMESPACE: 'from-server' }) });++ await loadRuntimeConfig();++ assert.strictEqual(get(config, 'API.namespace'), 'from-server');+ assert.strictEqual(this.requests.length, 1, 'the config file is requested');+ assert.strictEqual(this.requests[0][0], '/fleetbase.config.json');+ assert.deepEqual(this.requests[0][1], { cache: 'default' });+ assert.deepEqual(JSON.parse(window.localStorage.getItem(CACHE_KEY)).config, { API_NAMESPACE: 'from-server' }, 'the response is cached for the next boot');+ assert.strictEqual(window.localStorage.getItem(CACHE_VERSION_KEY), config.APP.version, 'the cache is stamped with the app version');+ });++ test('loadRuntimeConfig ignores a cached config that has no version stamp', async function (assert) {+ asProduction();+ writeCache({ API_HOST: 'https://stale.example.com' }, { version: null });+ this.respondWith({ ok: true, json: () => Promise.resolve({ API_HOST: 'https://server.example.com' }) });++ await loadRuntimeConfig();++ assert.strictEqual(get(config, 'API.host'), 'https://server.example.com', 'an unstamped cache is not trusted');+ assert.strictEqual(this.requests.length, 1);+ });++ test('loadRuntimeConfig discards a cache written by a different app version', async function (assert) {+ asProduction();+ writeCache({ API_HOST: 'https://stale.example.com' }, { version: 'some-other-version' });+ this.respondWith({ ok: true, json: () => Promise.resolve({ API_HOST: 'https://server.example.com' }) });++ await loadRuntimeConfig();++ assert.strictEqual(get(config, 'API.host'), 'https://server.example.com', 'a version mismatch invalidates the cache');+ assert.strictEqual(this.requests.length, 1);+ });++ test('loadRuntimeConfig discards a cache older than the TTL', async function (assert) {+ asProduction();+ writeCache({ API_HOST: 'https://stale.example.com' }, { age: CACHE_TTL + 1000 });+ this.respondWith({ ok: true, json: () => Promise.resolve({ API_HOST: 'https://server.example.com' }) });++ await loadRuntimeConfig();++ assert.strictEqual(get(config, 'API.host'), 'https://server.example.com', 'an expired cache is refetched');+ assert.strictEqual(this.requests.length, 1);+ });++ test('loadRuntimeConfig discards cache data it cannot parse', async function (assert) {+ asProduction();+ window.localStorage.setItem(CACHE_KEY, 'not-json');+ window.localStorage.setItem(CACHE_VERSION_KEY, config.APP.version);+ this.respondWith({ ok: true, json: () => Promise.resolve({ API_HOST: 'https://server.example.com' }) });++ await loadRuntimeConfig();++ assert.strictEqual(get(config, 'API.host'), 'https://server.example.com', 'corrupt cache data falls back to the server');+ assert.strictEqual(this.requests.length, 1);+ });++ test('loadRuntimeConfig keeps the built-in defaults when there is no config file', async function (assert) {+ set(config, 'APP.disableRuntimeConfig', false);+ const before = get(config, 'API.host');+ this.respondWith({ ok: false, status: 404 });++ await loadRuntimeConfig();++ assert.strictEqual(get(config, 'API.host'), before, 'a 404 leaves the built-in config in place');+ assert.strictEqual(window.localStorage.getItem(CACHE_KEY), null, 'nothing is cached for a missing file');+ });++ test('loadRuntimeConfig swallows a failed request', async function (assert) {+ set(config, 'APP.disableRuntimeConfig', false);+ const before = get(config, 'API.host');++ // The default beforeEach stub rejects, standing in for an offline browser.+ await loadRuntimeConfig();++ assert.strictEqual(this.requests.length, 1, 'the request was attempted');+ assert.strictEqual(get(config, 'API.host'), before, 'boot continues on the built-in config');+ });++ test('loadRuntimeConfig still applies a config it cannot cache', async function (assert) {+ set(config, 'APP.disableRuntimeConfig', false);+ this.respondWith({ ok: true, json: () => Promise.resolve({ API_HOST: 'https://uncacheable.example.com' }) });+ const restore = breakStorage('setItem');++ try {+ await loadRuntimeConfig();+ } finally {+ restore();+ }++ assert.strictEqual(get(config, 'API.host'), 'https://uncacheable.example.com', 'a storage failure does not stop the config being applied');+ assert.strictEqual(window.localStorage.getItem(CACHE_KEY), null, 'and nothing was written');+ });});