Skip to content

Modular logistics and supply chain operating system (LSOS)

test(console): cover blog cache, admin registry fallbacks and permission guards

Ronald A. Richardson878d5593c419
diff --git a/console/app/initializers/load-intl-polyfills.js b/console/app/initializers/load-intl-polyfills.js
index d0fe1e07..947a8a8d 100644
--- a/console/app/initializers/load-intl-polyfills.js
+++ b/console/app/initializers/load-intl-polyfills.js
@@ -4,6 +4,9 @@ import { all } from 'rsvp';
const isBrowser = typeof window !== 'undefined';
const isValidLang = (lang) => typeof lang === 'string' && /^[a-z]{2,3}$/i.test(lang);
+// The only caller maps over ember-intl's translation manifest, so a tag is always
+// present; the default exists purely as a guard.
+/* istanbul ignore next -- unreachable default argument */
function langOf(tag = 'en') {
return String(tag).toLowerCase().split('-')[0];
}
@@ -16,6 +19,9 @@ async function loadBasePolyfills() {
}
async function loadLocaleData(lang) {
+ // initialize() already filters the language list through isValidLang, so this is a
+ // second line of defence that the initializer itself can never trigger.
+ /* istanbul ignore next -- unreachable via initialize() */
if (!isValidLang(lang)) return;
return all([
@@ -27,6 +33,9 @@ async function loadLocaleData(lang) {
}
export function initialize(application) {
+ // There is no window to polyfill outside a browser. The test suite only ever runs in
+ // one, so this arm cannot be exercised.
+ /* istanbul ignore next -- no browser, nothing to polyfill */
if (!isBrowser) return;
const locales = translations.map(([locale]) => String(locale));
diff --git a/console/app/models/permission.js b/console/app/models/permission.js
index fdab72d4..046a88c5 100644
--- a/console/app/models/permission.js
+++ b/console/app/models/permission.js
@@ -27,7 +27,7 @@ export const getPermissionResource = function (permissionName) {
return parserPermissionName(permissionName, 2);
};
-const titleize = function (string = '') {
+const titleize = function (string) {
if (typeof string !== 'string') {
return '';
}
@@ -37,7 +37,7 @@ const titleize = function (string = '') {
.join(' ');
};
-const smartTitleize = function (string = '') {
+const smartTitleize = function (string) {
if (typeof string !== 'string') {
return '';
}
diff --git a/console/tests/integration/components/fleetbase-blog-test.js b/console/tests/integration/components/fleetbase-blog-test.js
index f9f6b13c..5e9321a2 100644
--- a/console/tests/integration/components/fleetbase-blog-test.js
+++ b/console/tests/integration/components/fleetbase-blog-test.js
@@ -140,3 +140,101 @@ module('Integration | Component | fleetbase-blog | loading', function (hooks) {
assert.strictEqual(formatted[0].title, 'Dated', 'the rest of the post is preserved');
});
});
+
+/**
+ * The blog caches its feed for six hours. These drive the cache-hit arm and the teardown
+ * guard, neither of which the loading module above ever reaches.
+ */
+module('Integration | Component | fleetbase-blog | cache', function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ _resetStorages();
+ window.localStorage.clear();
+
+ this.getResponse = [{ title: 'Cached Post', pubDate: '2026-01-15T00:00:00Z' }];
+ this.requests = 0;
+ this.release = null;
+ this.park = false;
+ const context = this;
+
+ class FetchStub extends Service {
+ get() {
+ context.requests++;
+
+ if (context.park) {
+ return new Promise((resolve) => (context.release = () => resolve(context.getResponse)));
+ }
+
+ return Promise.resolve(context.getResponse);
+ }
+ }
+ this.owner.register('service:fetch', FetchStub);
+
+ const captured = captureComponent(this.owner, 'fleetbase-blog', FleetbaseBlogComponent);
+ this.build = async () => {
+ await render(hbs`<FleetbaseBlog />`);
+ return captured.instance;
+ };
+ });
+
+ hooks.afterEach(function () {
+ _resetStorages();
+ window.localStorage.clear();
+ });
+
+ test('a second mount is served entirely from the cache', async function (assert) {
+ const first = await this.build();
+ assert.strictEqual(this.requests, 1, 'the first mount goes to the network');
+
+ this.getResponse = [{ title: 'Should not be requested' }];
+ const second = await this.build();
+
+ assert.strictEqual(this.requests, 1, 'the second mount never calls the endpoint');
+ assert.deepEqual(second.posts, first.localCache.get('fleetbase-blog-data'), 'it renders what was cached');
+ assert.strictEqual(second.posts[0].title, 'Cached Post');
+ });
+
+ test('an expired cache is refetched', async function (assert) {
+ const first = await this.build();
+ first.localCache.set('fleetbase-blog-data-expiration', new Date('2020-01-01T00:00:00Z'));
+
+ this.getResponse = [{ title: 'Fresh Post' }];
+ const second = await this.build();
+
+ assert.strictEqual(this.requests, 2, 'a stale stamp sends it back to the network');
+ assert.strictEqual(second.posts[0].title, 'Fresh Post');
+ });
+
+ test('a cache holding something other than a list is refetched', async function (assert) {
+ const first = await this.build();
+ first.localCache.set('fleetbase-blog-data', { error: 'corrupted' });
+
+ const second = await this.build();
+
+ assert.strictEqual(this.requests, 2, 'a non-list cache entry is not trusted');
+ assert.deepEqual(second.posts, this.getResponse);
+ });
+
+ test('an empty response is not cached', async function (assert) {
+ this.getResponse = null;
+ const component = await this.build();
+
+ assert.deepEqual(component.posts, [], 'there is nothing to show');
+ assert.strictEqual(component.localCache.get('fleetbase-blog-data'), undefined, 'and nothing is written to the cache');
+ });
+
+ test('a response arriving after teardown is dropped', async function (assert) {
+ this.park = true;
+ const component = await this.build();
+
+ // Racing clearRender() does not work: it waits on settled(), which the parked
+ // request blocks. Mark the component destroying instead, then let the response land.
+ Object.defineProperty(component, 'isDestroying', { configurable: true, value: true });
+ this.release();
+ await component.loadBlogPosts.last;
+
+ assert.deepEqual(component.posts, [], 'the tracked state is left alone');
+ assert.strictEqual(component.localCache.get('fleetbase-blog-data'), undefined, 'and nothing is cached');
+ });
+});
diff --git a/console/tests/integration/components/onboarding/verify-email-test.js b/console/tests/integration/components/onboarding/verify-email-test.js
index 532589e5..03b84a1a 100644
--- a/console/tests/integration/components/onboarding/verify-email-test.js
+++ b/console/tests/integration/components/onboarding/verify-email-test.js
@@ -4,6 +4,8 @@ import { render } from '@ember/test-helpers';
import { hbs } from 'ember-cli-htmlbars';
import Service from '@ember/service';
import { tracked } from '@glimmer/tracking';
+import OnboardingVerifyEmailComponent from '@fleetbase/console/components/onboarding/verify-email';
+import { captureComponent } from '@fleetbase/console/tests/helpers/capture-component';
module('Integration | Component | onboarding/verify-email', function (hooks) {
setupRenderingTest(hooks);
@@ -60,3 +62,148 @@ module('Integration | Component | onboarding/verify-email', function (hooks) {
assert.dom('form').exists();
});
});
+
+/**
+ * The verify task is submitted from the rendered form, but its outcomes are easier to drive
+ * on the captured instance than through the DOM.
+ */
+module('Integration | Component | onboarding/verify-email | verify', function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.owner.lookup('service:intl').setLocale('en-us');
+
+ this.posted = [];
+ this.postResponse = { status: 'ok', token: 'auth-token' };
+ this.postRejectsWith = null;
+ const context = this;
+
+ class VerificationStub extends Service {
+ @tracked ready = false;
+ @tracked waiting = false;
+ start() {}
+ validateInput() {}
+ didntReceiveCode() {}
+ resendBySms() {}
+ resendEmail() {}
+ }
+ class UrlSearchParamsStub extends Service {
+ params = { code: '123456', session: 'sess_from_url' };
+ get(key) {
+ return this.params[key];
+ }
+ }
+ class FetchStub extends Service {
+ post(path, payload) {
+ context.posted.push({ path, payload });
+ return context.postRejectsWith ? Promise.reject(context.postRejectsWith) : Promise.resolve(context.postResponse);
+ }
+ }
+ class NotificationsStub extends Service {
+ successes = [];
+ infos = [];
+ serverErrors = [];
+ success(message) {
+ this.successes.push(message);
+ }
+ info(message) {
+ this.infos.push(message);
+ }
+ serverError(error) {
+ this.serverErrors.push(error);
+ }
+ }
+ this.owner.register('service:user-verification', VerificationStub);
+ this.owner.register('service:url-search-params', UrlSearchParamsStub);
+ this.owner.register('service:fetch', FetchStub);
+ this.owner.register('service:notifications', NotificationsStub);
+
+ const captured = captureComponent(this.owner, 'onboarding/verify-email', OnboardingVerifyEmailComponent);
+ this.set('context', { get: () => undefined });
+ this.build = async () => {
+ await render(hbs`<Onboarding::VerifyEmail @context={{this.context}} />`);
+ const component = captured.instance;
+
+ // The session service is not replaceable: the application adapter reads
+ // session.data.authenticated while building request headers, so a stub in its
+ // place breaks every container lookup in the test.
+ this.authenticated = [];
+ Object.defineProperty(component.authSession, 'manuallyAuthenticate', {
+ configurable: true,
+ value: (token) => this.authenticated.push(token),
+ });
+
+ this.transitions = [];
+ Object.defineProperty(component.router, 'transitionTo', {
+ configurable: true,
+ value: (routeName) => {
+ this.transitions.push(routeName);
+ return routeName;
+ },
+ });
+
+ return component;
+ };
+ this.notifications = () => this.owner.lookup('service:notifications');
+ });
+
+ test('verify posts the session and code, then signs the user into the console', async function (assert) {
+ const component = await this.build();
+
+ await component.verify.perform();
+
+ assert.deepEqual(this.posted, [{ path: 'onboard/verify-email', payload: { session: 'sess_from_url', code: '123456' } }]);
+ assert.deepEqual(this.authenticated, ['auth-token']);
+ assert.deepEqual(this.transitions, ['console']);
+ assert.deepEqual(this.notifications().successes, ['Email successfully verified!']);
+ assert.deepEqual(this.notifications().infos, ['Welcome to Fleetbase!']);
+ });
+
+ test('verify sends the user to login when no token comes back', async function (assert) {
+ this.postResponse = { status: 'ok' };
+ const component = await this.build();
+
+ await component.verify.perform();
+
+ assert.deepEqual(this.transitions, ['auth.login']);
+ assert.deepEqual(this.authenticated, [], 'there is nothing to authenticate with');
+ assert.deepEqual(this.notifications().infos, [], 'and no welcome is shown');
+ });
+
+ test('verify stays put on a status that is not ok', async function (assert) {
+ this.postResponse = { status: 'invalid' };
+ const component = await this.build();
+
+ assert.strictEqual(await component.verify.perform(), undefined);
+ assert.deepEqual(this.transitions, []);
+ assert.deepEqual(this.notifications().successes, [], 'nothing is reported as verified');
+ });
+
+ test('verify prevents the form from submitting itself', async function (assert) {
+ const component = await this.build();
+ let prevented = false;
+
+ await component.verify.perform({ preventDefault: () => (prevented = true) });
+
+ assert.true(prevented);
+ });
+
+ test('verify tolerates being invoked without an event', async function (assert) {
+ const component = await this.build();
+
+ await component.verify.perform(undefined);
+
+ assert.strictEqual(this.posted.length, 1, 'the code is still submitted');
+ });
+
+ test('a failed verification is reported as a server error', async function (assert) {
+ const failure = new Error('verification service down');
+ this.postRejectsWith = failure;
+ const component = await this.build();
+
+ await component.verify.perform();
+
+ assert.deepEqual(this.notifications().serverErrors, [failure]);
+ assert.deepEqual(this.transitions, [], 'the user stays on the form');
+ });
+});
diff --git a/console/tests/unit/controllers/console/admin-test.js b/console/tests/unit/controllers/console/admin-test.js
index ab0124e7..1e34083f 100644
--- a/console/tests/unit/controllers/console/admin-test.js
+++ b/console/tests/unit/controllers/console/admin-test.js
@@ -231,3 +231,53 @@ module('Unit | Controller | console/admin', function (hooks) {
);
});
});
+
+/**
+ * Registry-supplied menus are third-party data: panels and items arrive with whatever keys
+ * the extension chose to set, so every read has a fallback. This drives those fallbacks.
+ */
+module('Unit | Controller | console/admin | registry fallbacks', function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.owner.register('service:intl', IntlStub);
+
+ this.seed = (adminMenuItems, adminMenuPanels) => {
+ const apply = (service) => {
+ Object.defineProperty(service, 'adminMenuItems', { configurable: true, value: adminMenuItems });
+ Object.defineProperty(service, 'adminMenuPanels', { configurable: true, value: adminMenuPanels });
+ };
+ apply(this.owner.lookup('service:universe/menu-service'));
+ apply(this.owner.lookup('service:universe'));
+
+ return this.owner.lookup('controller:console/admin');
+ };
+ });
+
+ test('an extension registry that has registered nothing yields no registry entries', function (assert) {
+ const controller = this.seed(undefined, undefined);
+
+ assert.deepEqual(controller.registryNavigationItems, [], 'no navigation items');
+ assert.deepEqual(controller.registryPanelItems, [], 'no panels');
+ });
+
+ test('a panel with only a title and slug is given a description and an icon', function (assert) {
+ const controller = this.seed([], [{ title: 'Billing Config', slug: 'billing' }]);
+
+ const [panel] = controller.registryPanelItems;
+ assert.strictEqual(panel.id, 'billing');
+ assert.strictEqual(panel.label, 'Billing Config');
+ assert.strictEqual(panel.description, 'Billing Config admin controls.', 'a description is generated from the title');
+ assert.strictEqual(panel.icon, 'folder', 'and a neutral icon stands in');
+ assert.deepEqual(panel.keywords, ['billing', 'Billing Config'], 'the absent description is filtered out of the keywords');
+ assert.deepEqual(panel.children, [], 'a panel with no items has no children');
+ });
+
+ test('a panel item with no slug is identified by its title', function (assert) {
+ const controller = this.seed([], [{ title: 'Billing Config', slug: 'billing', items: [{ title: 'Invoices' }] }]);
+
+ const [child] = controller.registryPanelItems[0].children;
+ assert.strictEqual(child.id, 'billing:Invoices:index', 'the title stands in for the slug, and the view defaults to index');
+ assert.strictEqual(child.label, 'Invoices', 'the title also stands in for the label');
+ });
+});
diff --git a/console/tests/unit/models/permission-test.js b/console/tests/unit/models/permission-test.js
index 3db65efa..2e42fdfb 100644
--- a/console/tests/unit/models/permission-test.js
+++ b/console/tests/unit/models/permission-test.js
@@ -77,3 +77,33 @@ module('Unit | Model | permission', function (hooks) {
assert.strictEqual(typeof permission.updatedAgo, 'string');
});
});
+
+module('Unit | Model | permission | incomplete names', function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.permission = (attrs = {}) => this.owner.lookup('service:store').createRecord('permission', attrs);
+ });
+
+ test('actionName is empty when the name carries no action segment', function (assert) {
+ // getPermissionAction returns null here, and titleize has to survive that rather
+ // than blowing up while a permission list renders.
+ assert.strictEqual(this.permission({ name: 'fleet-ops' }).actionName, '');
+ });
+
+ test('description drops the resource when the name has only two segments', function (assert) {
+ const description = this.permission({ name: 'fleet-ops view' }).description;
+
+ assert.ok(description.startsWith('Permission to View'), description);
+ assert.ok(/on Fleet.?Ops$/i.test(description), 'the extension still closes the sentence');
+ assert.ok(description.includes('View on'), 'the resource and its preposition are both blank');
+ });
+
+ test('a wildcard action with no resource does not take the "with" preposition', function (assert) {
+ const description = this.permission({ name: 'iam *' }).description;
+
+ assert.notOk(description.includes('with'), `there is nothing to be "with": ${description}`);
+ assert.ok(description.includes('do anything'));
+ assert.ok(description.includes('IAM'));
+ });
+});
diff --git a/console/tests/unit/models/schedule-template-test.js b/console/tests/unit/models/schedule-template-test.js
index 0d9029aa..a9c8615b 100644
--- a/console/tests/unit/models/schedule-template-test.js
+++ b/console/tests/unit/models/schedule-template-test.js
@@ -19,3 +19,32 @@ module('Unit | Model | schedule-template', function (hooks) {
assert.strictEqual(store.createRecord('schedule-template', {}).recurrenceSummary, null);
});
});
+
+module('Unit | Model | schedule-template | recurrence edge cases', function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.template = (attrs) => this.owner.lookup('service:store').createRecord('schedule-template', attrs);
+ });
+
+ test('an unrecognised day code is passed through as written', function (assert) {
+ const summary = this.template({ rrule: 'FREQ=WEEKLY;BYDAY=MO,XX', start_time: '09:00', end_time: '17:00' }).recurrenceSummary;
+
+ assert.strictEqual(summary, 'Weekly on Mon, XX · 09:00–17:00', 'MO maps to Mon, XX has no mapping and survives verbatim');
+ });
+
+ test('an rrule with neither a frequency nor days summarizes to almost nothing', function (assert) {
+ // A malformed or partial rule should still render rather than throw — every part of
+ // the summary is optional.
+ assert.strictEqual(this.template({ rrule: 'INTERVAL=2' }).recurrenceSummary, ' on ');
+ });
+
+ test('the times are omitted unless both ends are known', function (assert) {
+ assert.strictEqual(this.template({ rrule: 'FREQ=DAILY', start_time: '08:00' }).recurrenceSummary, 'Daily on ', 'a start with no end is dropped');
+ assert.strictEqual(this.template({ rrule: 'FREQ=DAILY', end_time: '16:00' }).recurrenceSummary, 'Daily on ', 'an end with no start is dropped');
+ });
+
+ test('the frequency is title-cased from the rrule', function (assert) {
+ assert.ok(this.template({ rrule: 'FREQ=MONTHLY;BYDAY=TU,WE,TH,FR,SA,SU' }).recurrenceSummary.startsWith('Monthly on Tue, Wed, Thu, Fri, Sat, Sun'));
+ });
+});
diff --git a/console/tests/unit/models/user-test.js b/console/tests/unit/models/user-test.js
index eeb48bf4..9863ceb4 100644
--- a/console/tests/unit/models/user-test.js
+++ b/console/tests/unit/models/user-test.js
@@ -2,6 +2,7 @@ import { module, test } from 'qunit';
import { setupTest } from '@fleetbase/console/tests/helpers';
import { format, formatDistanceToNow } from 'date-fns';
import Service from '@ember/service';
+import UserModel from '@fleetbase/console/models/user';
module('Unit | Model | user', function (hooks) {
setupTest(hooks);
@@ -183,3 +184,40 @@ module('Unit | Model | user | timestamps', function (hooks) {
assert.strictEqual(user.createdAgo, formatDistanceToNow(created));
});
});
+
+/**
+ * getPermissions guards every relationship it reads before walking it. Ember Data always
+ * hands back a ManyArray — empty or not — so a saved record can never take those guards'
+ * false arms; the only way to assert they actually guard is to run the method against a
+ * minimal `get`-shaped stand-in, which is exactly the shape it consumes.
+ */
+module('Unit | Model | user | getPermissions guards', function () {
+ const runOn = (values) => UserModel.prototype.getPermissions.call({ get: (key) => values[key] });
+ // Relationships are consumed via toArray(), so a stand-in policy has to offer one.
+ const policyWith = (...names) => ({ get: () => (names.length ? { toArray: () => names } : null) });
+
+ test('a user with nothing attached collects no permissions', function (assert) {
+ assert.deepEqual(runOn({}), [], 'no direct permissions, no role and no policies');
+ });
+
+ test('a role carrying neither permissions nor policies contributes nothing', function (assert) {
+ assert.deepEqual(runOn({ role: { id: 'role_1' } }), [], 'the role is entered but has nothing to give');
+ });
+
+ test('a role policy with no permissions is skipped', function (assert) {
+ const permissions = runOn({
+ role: { id: 'role_1' },
+ 'role.policies': { length: 2, objectAt: (i) => [policyWith(), policyWith('granted')][i] },
+ });
+
+ assert.deepEqual(permissions, ['granted'], 'only the policy that has permissions contributes');
+ });
+
+ test('a directly attached policy with no permissions is skipped', function (assert) {
+ const permissions = runOn({
+ policies: { length: 2, objectAt: (i) => [policyWith(), policyWith('direct-grant')][i] },
+ });
+
+ assert.deepEqual(permissions, ['direct-grant']);
+ });
+});