Skip to content

Modular logistics and supply chain operating system (LSOS)

test(console): cover the auth/login and console controllers

Ronald A. Richardson11ab597a16ff
diff --git a/console/tests/unit/controllers/auth/login-test.js b/console/tests/unit/controllers/auth/login-test.js
index 194279f6..781447c2 100644
--- a/console/tests/unit/controllers/auth/login-test.js
+++ b/console/tests/unit/controllers/auth/login-test.js
@@ -2,51 +2,256 @@ import { module, test } from 'qunit';
import { setupTest } from '@fleetbase/console/tests/helpers';
import Service from '@ember/service';
+class IntlStub extends Service {
+ t(key) {
+ return key;
+ }
+}
+
+class NotificationsStub extends Service {
+ warnings = [];
+ errors = [];
+ warning(m) {
+ this.warnings.push(m);
+ }
+ error(m) {
+ this.errors.push(m);
+ }
+ serverError(e) {
+ this.errors.push(e);
+ }
+}
+
module('Unit | Controller | auth/login', function (hooks) {
setupTest(hooks);
- test("reset('success') clears the form and loading flags", function (assert) {
- const controller = this.owner.lookup('controller:auth/login');
- controller.isLoading = true;
- controller.isSlowConnection = true;
- controller.identity = '[email protected]';
- controller.password = 'secret';
- controller.isValidating = true;
+ hooks.beforeEach(function () {
+ const self = this;
+ this.persisted = [];
+ this.authenticateCalls = [];
+ this.redirects = [];
+ this.posted = [];
- controller.reset('success');
+ // Defaults: no 2FA, authentication succeeds.
+ this.twoFactor = () => Promise.resolve({ isTwoFaEnabled: false });
+ this.authenticateResult = () => Promise.resolve();
+ this.isAuthenticated = true;
- assert.false(controller.isLoading);
- assert.false(controller.isSlowConnection);
- assert.strictEqual(controller.identity, null);
- assert.strictEqual(controller.password, null);
- assert.false(controller.isValidating);
+ class SessionStub extends Service {
+ store = {
+ persist(data) {
+ self.persisted.push(data);
+ return Promise.resolve();
+ },
+ };
+ get isAuthenticated() {
+ return self.isAuthenticated;
+ }
+ checkForTwoFactor(identity) {
+ return self.twoFactor(identity);
+ }
+ authenticate(...args) {
+ self.authenticateCalls.push(args);
+ return self.authenticateResult();
+ }
+ setRedirect(route) {
+ self.redirects.push(route);
+ }
+ }
+ class UrlSearchParamsStub extends Service {
+ params = {};
+ get(key) {
+ return this.params[key];
+ }
+ }
+ class FetchStub extends Service {
+ post(path, payload) {
+ self.posted.push({ path, payload });
+ return Promise.resolve({ token: 'verify-token', session: 'sess_1' });
+ }
+ }
+
+ this.owner.register('service:intl', IntlStub);
+ this.owner.register('service:notifications', NotificationsStub);
+ this.owner.register('service:session', SessionStub);
+ this.owner.register('service:url-search-params', UrlSearchParamsStub);
+ this.owner.register('service:fetch', FetchStub);
+
+ this.controller = this.owner.lookup('controller:auth/login');
+ this.notifications = this.owner.lookup('service:notifications');
+ this.urlParams = this.owner.lookup('service:url-search-params');
+
+ this.transitions = [];
+ Object.defineProperty(this.controller.router, 'transitionTo', {
+ configurable: true,
+ value: (...args) => {
+ this.transitions.push(args);
+ return Promise.resolve();
+ },
+ });
+
+ this.submit = () => this.controller.login({ preventDefault() {} });
});
- test("reset('error') clears only the password and keeps the identity", function (assert) {
- const controller = this.owner.lookup('controller:auth/login');
- controller.identity = '[email protected]';
- controller.password = 'secret';
+ test('login refuses to submit without an identity or password', async function (assert) {
+ await this.submit();
+ assert.strictEqual(this.notifications.warnings.length, 1, 'a missing identity is refused');
- controller.reset('error');
+ this.controller.identity = '[email protected]';
+ await this.submit();
+ assert.strictEqual(this.notifications.warnings.length, 2, 'a missing password is refused');
- assert.strictEqual(controller.password, null);
- assert.strictEqual(controller.identity, '[email protected]', 'identity is preserved on error');
+ assert.deepEqual(this.authenticateCalls, [], 'nothing is submitted');
});
- test('login warns and stops when no identity is provided', async function (assert) {
- class NotificationsStub extends Service {
- warning() {
- this.warned = true;
- }
- }
- this.owner.register('service:notifications', NotificationsStub);
+ test('login authenticates and clears the form on success', async function (assert) {
+ this.controller.identity = '[email protected]';
+ this.controller.password = 'hunter2';
+ this.controller.rememberMe = true;
+
+ await this.submit();
+
+ assert.deepEqual(this.authenticateCalls.at(-1), ['authenticator:fleetbase', { identity: '[email protected]', password: 'hunter2' }, true]);
+ assert.strictEqual(this.controller.identity, null, 'the form is cleared on success');
+ assert.strictEqual(this.controller.password, null);
+ assert.false(this.controller.isLoading);
+ });
- const controller = this.owner.lookup('controller:auth/login');
- controller.identity = null;
+ test('login leaves the form alone when the session does not become authenticated', async function (assert) {
+ this.isAuthenticated = false;
+ this.controller.identity = '[email protected]';
+ this.controller.password = 'hunter2';
+
+ await this.submit();
+
+ assert.strictEqual(this.controller.identity, '[email protected]', 'no success reset');
+ });
+
+ test('login diverts to two-factor when the identity requires it', async function (assert) {
+ this.twoFactor = () => Promise.resolve({ isTwoFaEnabled: true, twoFaSession: 'two-fa-token' });
+ this.controller.identity = '[email protected]';
+ this.controller.password = 'hunter2';
+
+ await this.submit();
+
+ assert.deepEqual(this.persisted.at(-1), { identity: '[email protected]' }, 'the identity is persisted for the 2FA step');
+ assert.deepEqual(this.transitions.at(-1), ['auth.two-fa', { queryParams: { token: 'two-fa-token' } }]);
+ assert.deepEqual(this.authenticateCalls, [], 'the password is never submitted when 2FA is required');
+ });
+
+ test('a failure during the two-factor handoff is reported', async function (assert) {
+ this.twoFactor = () => Promise.resolve({ isTwoFaEnabled: true, twoFaSession: 'two-fa-token' });
+ Object.defineProperty(this.controller.router, 'transitionTo', {
+ configurable: true,
+ value: () => Promise.reject(new Error('cannot route')),
+ });
+ this.controller.identity = '[email protected]';
+ this.controller.password = 'hunter2';
+
+ await assert.rejects(this.submit(), /cannot route/, 'the error propagates after being reported');
+ assert.strictEqual(this.notifications.errors.length, 1);
+ assert.strictEqual(this.controller.password, null, 'the password is cleared on error');
+ });
+
+ test('a failing two-factor check is reported and stops the login', async function (assert) {
+ this.twoFactor = () => Promise.reject(new Error('2fa lookup failed'));
+ this.controller.identity = '[email protected]';
+ this.controller.password = 'hunter2';
+
+ await this.submit();
+
+ assert.strictEqual(this.notifications.errors.length, 1);
+ assert.deepEqual(this.authenticateCalls, [], 'authentication is not attempted');
+ });
+
+ test('an unverified account is sent to email verification', async function (assert) {
+ this.authenticateResult = () => Promise.reject(new Error('account not verified'));
+ this.controller.identity = '[email protected]';
+ this.controller.password = 'hunter2';
+
+ await this.submit();
+
+ assert.strictEqual(this.controller.failedAttempts, 1, 'the attempt is counted');
+ assert.deepEqual(this.posted.at(-1), { path: 'auth/create-verification-session', payload: { email: '[email protected]', send: true } });
+ assert.deepEqual(this.transitions.at(-1), ['auth.verification', { queryParams: { token: 'verify-token', hello: 'sess_1' } }]);
+ });
+
+ test('an account needing a reset is sent to forgot-password', async function (assert) {
+ this.authenticateResult = () => Promise.reject(new Error('password reset required'));
+ this.controller.identity = '[email protected]';
+ this.controller.password = 'hunter2';
+
+ await this.submit();
+
+ assert.deepEqual(this.transitions.at(-1), ['auth.forgot-password', { queryParams: { email: '[email protected]' } }]);
+ assert.strictEqual(this.notifications.warnings.at(-1), 'auth.login.password-reset-required');
+ });
+
+ test('any other authentication error is surfaced and clears the password', async function (assert) {
+ this.authenticateResult = () => Promise.reject(new Error('bad credentials'));
+ this.controller.identity = '[email protected]';
+ this.controller.password = 'hunter2';
+
+ await this.submit();
+
+ assert.strictEqual(this.notifications.errors.length, 1);
+ assert.strictEqual(this.controller.password, null);
+ assert.strictEqual(this.controller.identity, '[email protected]', 'the identity is kept so the user can retry');
+ });
+
+ test('setRedirect stores a redirect only when a shift param is present', async function (assert) {
+ this.controller.setRedirect();
+ assert.deepEqual(this.redirects, [], 'no shift means no redirect');
+
+ this.urlParams.params = { shift: '/console/orders' };
+ this.controller.setRedirect();
+ assert.strictEqual(this.redirects.length, 1, 'the shift path is converted to a route');
+ });
+
+ test('transitionToOnboard and forgotPassword route away', async function (assert) {
+ await this.controller.transitionToOnboard();
+ assert.deepEqual(this.transitions.at(-1), ['onboard']);
+
+ await this.controller.forgotPassword();
+ assert.deepEqual(this.transitions.at(-1), ['auth.forgot-password']);
+ });
+
+ test('forgotPassword carries a known email across to that controller', async function (assert) {
+ this.controller.email = '[email protected]';
+
+ await this.controller.forgotPassword();
+
+ assert.strictEqual(this.controller.forgotPasswordController.email, '[email protected]');
+ });
+
+ test('slowConnection reports the slow connection message', function (assert) {
+ this.controller.slowConnection();
+
+ assert.deepEqual(this.notifications.errors, ['auth.login.slow-connection-message']);
+ });
+
+ test('reset clears loading always, and the form according to the outcome', function (assert) {
+ const controller = this.controller;
+
+ Object.assign(controller, { isLoading: true, isSlowConnection: true, identity: 'a', password: 'b', isValidating: true });
+ controller.reset('success');
+ assert.false(controller.isLoading);
+ assert.false(controller.isSlowConnection);
+ assert.strictEqual(controller.identity, null);
+ assert.strictEqual(controller.password, null);
+ assert.false(controller.isValidating);
+
+ Object.assign(controller, { identity: 'a', password: 'b' });
+ controller.reset('error');
+ assert.strictEqual(controller.password, null, 'errors clear only the password');
+ assert.strictEqual(controller.identity, 'a');
- await controller.login({ preventDefault() {} });
+ Object.assign(controller, { password: 'b' });
+ controller.reset('fail');
+ assert.strictEqual(controller.password, null, 'fail behaves like error');
- assert.true(this.owner.lookup('service:notifications').warned, 'warns about the missing identity');
- assert.false(controller.isLoading, 'never enters the loading state');
+ Object.assign(controller, { identity: 'a', password: 'b' });
+ controller.reset('anything-else');
+ assert.strictEqual(controller.password, 'b', 'an unknown outcome leaves the form alone');
});
});
diff --git a/console/tests/unit/controllers/console-test.js b/console/tests/unit/controllers/console-test.js
index 421aefb9..18c1cb9f 100644
--- a/console/tests/unit/controllers/console-test.js
+++ b/console/tests/unit/controllers/console-test.js
@@ -1,31 +1,254 @@
import { module, test } from 'qunit';
import { setupTest } from '@fleetbase/console/tests/helpers';
+import Service from '@ember/service';
+import { cancel } from '@ember/runloop';
+
+class IntlStub extends Service {
+ t(key) {
+ return key;
+ }
+}
+
+class NotificationsStub extends Service {
+ successes = [];
+ errors = [];
+ success(m) {
+ this.successes.push(m);
+ }
+ serverError(e) {
+ this.errors.push(e);
+ }
+}
+
+class ModalsManagerStub extends Service {
+ lastOptions = null;
+ shown = [];
+ show(name, options) {
+ this.shown.push(name);
+ this.lastOptions = options;
+ return Promise.resolve();
+ }
+ confirm(options) {
+ this.shown.push('confirm');
+ this.lastOptions = options;
+ return Promise.resolve();
+ }
+ setOption(key, value) {
+ this.lastOptions[key] = value;
+ }
+ getOptions() {
+ return this.lastOptions;
+ }
+}
+
+function fakeModal(options = {}) {
+ return {
+ loading: false,
+ startLoading() {
+ this.loading = true;
+ },
+ stopLoading() {
+ this.loading = false;
+ },
+ getOptions() {
+ return options;
+ },
+ getOption(key) {
+ return options[key];
+ },
+ };
+}
module('Unit | Controller | console', function (hooks) {
setupTest(hooks);
- test('onAction dispatches to a matching method with its params', function (assert) {
- const controller = this.owner.lookup('controller:console');
- const calls = [];
- controller.ping = (...args) => calls.push(args);
+ hooks.beforeEach(function () {
+ const self = this;
+ this.posted = [];
+ this.shouldReject = false;
+
+ class FetchStub extends Service {
+ post(path, payload) {
+ self.posted.push({ path, payload });
+ return self.shouldReject ? Promise.reject(new Error('nope')) : Promise.resolve({});
+ }
+ flushRequestCache(path) {
+ self.posted.push({ flushed: path });
+ }
+ }
+ class SessionStub extends Service {
+ invalidated = 0;
+ invalidateWithLoader() {
+ this.invalidated++;
+ return Promise.resolve();
+ }
+ }
+
+ this.owner.register('service:intl', IntlStub);
+ this.owner.register('service:notifications', NotificationsStub);
+ this.owner.register('service:modals-manager', ModalsManagerStub);
+ this.owner.register('service:fetch', FetchStub);
+ this.owner.register('service:session', SessionStub);
+
+ this.controller = this.owner.lookup('controller:console');
+ this.notifications = this.owner.lookup('service:notifications');
+ this.modals = this.owner.lookup('service:modals-manager');
+ this.session = this.owner.lookup('service:session');
- controller.onAction('ping', 1, 'two');
+ // currentUser.currency/country/timezone are all getters over whois(), so the stub
+ // has to answer per key rather than returning one value for everything.
+ this.whoisData = { timezone: 'Asia/Singapore' };
+ Object.defineProperty(this.controller.currentUser, 'whois', {
+ configurable: true,
+ value: (key) => this.whoisData[key],
+ });
+ });
+
+ test('currentRouteClass dasherizes the current route name', function (assert) {
+ Object.defineProperty(this.controller.router, 'currentRouteName', { configurable: true, value: 'console.admin.organizations' });
- assert.deepEqual(calls, [[1, 'two']], 'the named method receives the params');
+ assert.strictEqual(this.controller.currentRouteClass, 'console-admin-organizations');
});
- test('onAction ignores an unknown action name', function (assert) {
- const controller = this.owner.lookup('controller:console');
+ test('onAction dispatches to a matching controller method and ignores unknown ones', function (assert) {
+ // viewChangelog is an @action, exposed as a getter — shadow it with a value.
+ const called = [];
+ Object.defineProperty(this.controller, 'viewChangelog', {
+ configurable: true,
+ value: (...args) => called.push(args),
+ });
- controller.onAction('doesNotExist');
+ this.controller.onAction('viewChangelog', 'a', 'b');
+ assert.deepEqual(called, [['a', 'b']], 'the named action runs with its params');
- assert.ok(true, 'no error is thrown for a missing method');
+ this.controller.onAction('notAFunction');
+ assert.deepEqual(called, [['a', 'b']], 'an unknown action is a no-op');
});
- test('currentRouteClass dasherizes the current route name', function (assert) {
- const controller = this.owner.lookup('controller:console');
- Object.defineProperty(controller.router, 'currentRouteName', { value: 'console.admin.index', configurable: true });
+ test('invalidateSession stops the event and invalidates with the loader', async function (assert) {
+ let prevented = false;
+
+ await this.controller.invalidateSession(null, { preventDefault: () => (prevented = true) });
+
+ assert.true(prevented, 'the link default is suppressed');
+ assert.strictEqual(this.session.invalidated, 1);
+ });
+
+ test('viewChangelog opens the changelog modal without a decline button', function (assert) {
+ this.controller.viewChangelog();
+
+ assert.strictEqual(this.modals.shown.at(-1), 'modals/changelog');
+ assert.true(this.modals.lastOptions.hideDeclineButton);
+ });
+
+ test('createOrJoinOrg seeds the modal from the current company', function (assert) {
+ this.controller.currentUser.company = { currency: 'SGD', country: 'SG', timezone: 'Asia/Singapore' };
+
+ this.controller.createOrJoinOrg();
+
+ const options = this.modals.lastOptions;
+ assert.strictEqual(this.modals.shown.at(-1), 'modals/create-or-join-org');
+ assert.strictEqual(options.action, 'join', 'it opens on the join tab');
+ assert.strictEqual(options.currency, 'SGD');
+ assert.strictEqual(options.country, 'SG');
+ assert.strictEqual(options.timezone, 'Asia/Singapore');
+ });
+
+ test('createOrJoinOrg falls back to USD and the whois timezone without a company', function (assert) {
+ this.controller.currentUser.company = null;
+
+ this.controller.createOrJoinOrg();
+
+ const options = this.modals.lastOptions;
+ assert.strictEqual(options.currency, 'USD', 'currency falls back to USD');
+ assert.strictEqual(options.timezone, 'Asia/Singapore', 'the timezone comes from whois');
+ });
+
+ test('changeAction switches the modal between join and create', function (assert) {
+ this.controller.createOrJoinOrg();
+
+ this.modals.lastOptions.changeAction('create');
+
+ assert.strictEqual(this.modals.lastOptions.action, 'create');
+ });
+
+ test('confirming a join posts the selected organization', async function (assert) {
+ this.controller.createOrJoinOrg();
+
+ const timer = await this.modals.lastOptions.confirm(fakeModal({ action: 'join', next: 'org_2' }));
+ cancel(timer);
+
+ assert.deepEqual(this.posted[0], { path: 'auth/join-organization', payload: { next: 'org_2' } });
+ assert.deepEqual(this.posted[1], { flushed: 'auth/organizations' });
+ assert.strictEqual(this.notifications.successes.length, 1);
+ });
+
+ test('a failed join is reported and stops the modal loading', async function (assert) {
+ this.shouldReject = true;
+ this.controller.createOrJoinOrg();
+
+ const modal = fakeModal({ action: 'join', next: 'org_2' });
+ await this.modals.lastOptions.confirm(modal);
+
+ assert.strictEqual(this.notifications.errors.length, 1);
+ assert.false(modal.loading);
+ });
+
+ test('confirming a create posts the new organization details', async function (assert) {
+ this.controller.createOrJoinOrg();
+
+ const timer = await this.modals.lastOptions.confirm(
+ fakeModal({ action: 'create', name: 'New Co', description: 'movers', phone: '+1', currency: 'USD', country: 'US', timezone: 'UTC' })
+ );
+ cancel(timer);
+
+ assert.strictEqual(this.posted[0].path, 'auth/create-organization');
+ assert.strictEqual(this.posted[0].payload.name, 'New Co');
+ assert.strictEqual(this.posted[0].payload.timezone, 'UTC');
+ assert.deepEqual(this.posted[1], { flushed: 'auth/organizations' });
+ });
+
+ test('a failed create is reported and stops the modal loading', async function (assert) {
+ this.shouldReject = true;
+ this.controller.createOrJoinOrg();
+
+ const modal = fakeModal({ action: 'create', name: 'New Co' });
+ await this.modals.lastOptions.confirm(modal);
+
+ assert.strictEqual(this.notifications.errors.length, 1);
+ assert.false(modal.loading);
+ });
+
+ test('switchOrganization confirms then posts the switch', async function (assert) {
+ this.controller.switchOrganization({ uuid: 'org_9', name: 'Acme' });
+
+ // The success path returns the later() timer that reloads the page — cancel it so
+ // the pending reload never fires against the test runner.
+ const timer = await this.modals.lastOptions.confirm(fakeModal());
+ cancel(timer);
+
+ assert.deepEqual(this.posted[0], { path: 'auth/switch-organization', payload: { next: 'org_9' } });
+ assert.deepEqual(this.posted[1], { flushed: 'auth/organizations' });
+ assert.strictEqual(this.notifications.successes.length, 1);
+ });
+
+ test('switchOrganization unwraps an array of organizations', async function (assert) {
+ this.controller.switchOrganization([{ uuid: 'org_first', name: 'First' }, { uuid: 'org_second' }]);
+
+ const timer = await this.modals.lastOptions.confirm(fakeModal());
+ cancel(timer);
+
+ assert.strictEqual(this.posted[0].payload.next, 'org_first', 'the first organization is used');
+ });
+
+ test('a failed switch is reported without reloading', async function (assert) {
+ this.shouldReject = true;
+ this.controller.switchOrganization({ uuid: 'org_9', name: 'Acme' });
+
+ const modal = fakeModal();
+ await this.modals.lastOptions.confirm(modal);
- assert.strictEqual(controller.currentRouteClass, 'console-admin-index');
+ assert.strictEqual(this.notifications.errors.length, 1);
+ assert.false(modal.loading);
});
});