Skip to content

Commit

Permalink
UI: Fix flaky time-related tests (#19521)
Browse files Browse the repository at this point in the history
  • Loading branch information
hashishaw authored Mar 22, 2023
1 parent 3dbe946 commit bf2f1a8
Show file tree
Hide file tree
Showing 65 changed files with 645 additions and 527 deletions.
3 changes: 2 additions & 1 deletion ui/app/components/calendar-widget.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { action } from '@ember/object';
import { tracked } from '@glimmer/tracking';
import { ARRAY_OF_MONTHS, parseAPITimestamp } from 'core/utils/date-formatters';
import { addYears, isSameYear, subYears } from 'date-fns';
import timestamp from 'core/utils/timestamp';
/**
* @module CalendarWidget
* CalendarWidget component is used in the client counts dashboard to select a month/year to query the /activity endpoint.
Expand All @@ -24,7 +25,7 @@ import { addYears, isSameYear, subYears } from 'date-fns';
* ```
*/
export default class CalendarWidget extends Component {
currentDate = new Date();
currentDate = timestamp.now();
@tracked calendarDisplayDate = this.currentDate; // init to current date, updates when user clicks on calendar chevrons
@tracked showCalendar = false;
@tracked tooltipTarget = null;
Expand Down
3 changes: 2 additions & 1 deletion ui/app/components/date-dropdown.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import Component from '@glimmer/component';
import { action } from '@ember/object';
import { tracked } from '@glimmer/tracking';
import { ARRAY_OF_MONTHS } from 'core/utils/date-formatters';
import timestamp from 'core/utils/timestamp';
/**
* @module DateDropdown
* DateDropdown components are used to display a dropdown of months and years to handle date selection. Future dates are disabled (current month and year are selectable).
Expand All @@ -23,7 +24,7 @@ import { ARRAY_OF_MONTHS } from 'core/utils/date-formatters';
* @param {function} [validateDate] - parent function to validate date selection, receives date object and returns an error message that's passed to the inline alert
*/
export default class DateDropdown extends Component {
currentDate = new Date();
currentDate = timestamp.now();
currentYear = this.currentDate.getFullYear(); // integer of year
currentMonthIdx = this.currentDate.getMonth(); // integer of month, 0 indexed
dropdownMonths = ARRAY_OF_MONTHS.map((m, i) => ({ name: m, index: i }));
Expand Down
5 changes: 3 additions & 2 deletions ui/app/components/license-banners.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { inject as service } from '@ember/service';
import isAfter from 'date-fns/isAfter';
import differenceInDays from 'date-fns/differenceInDays';
import localStorage from 'vault/lib/local-storage';
import timestamp from 'core/utils/timestamp';

/**
* @module LicenseBanners
Expand Down Expand Up @@ -41,13 +42,13 @@ export default class LicenseBanners extends Component {

get licenseExpired() {
if (!this.args.expiry) return false;
return isAfter(new Date(), new Date(this.args.expiry));
return isAfter(timestamp.now(), new Date(this.args.expiry));
}

get licenseExpiringInDays() {
// Anything more than 30 does not render a warning
if (!this.args.expiry) return 99;
return differenceInDays(new Date(this.args.expiry), new Date());
return differenceInDays(new Date(this.args.expiry), timestamp.now());
}

@action
Expand Down
3 changes: 2 additions & 1 deletion ui/app/models/secret-v2-version.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
*/

import { belongsTo, attr } from '@ember-data/model';
import timestamp from 'core/utils/timestamp';
import SecretModel from './secret';

export default class SecretV2VersionModel extends SecretModel {
Expand All @@ -20,7 +21,7 @@ export default class SecretV2VersionModel extends SecretModel {

get deleted() {
const deletionTime = new Date(this.deletionTime);
const now = new Date();
const now = timestamp.now();
return deletionTime <= now;
}
}
3 changes: 2 additions & 1 deletion ui/app/routes/vault/cluster/clients/dashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@
import Route from '@ember/routing/route';
import getStorage from 'vault/lib/token-storage';
import { inject as service } from '@ember/service';
import timestamp from 'core/utils/timestamp';

export default class DashboardRoute extends Route {
@service store;
currentDate = new Date().toISOString();
currentDate = timestamp.now().toISOString();

async getActivity(start_time) {
// on init ONLY make network request if we have a start_time
Expand Down
5 changes: 3 additions & 2 deletions ui/app/serializers/clients/activity.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@
import ApplicationSerializer from '../application';
import { formatISO } from 'date-fns';
import { formatByMonths, formatByNamespace, homogenizeClientNaming } from 'core/utils/client-count-utils';
import timestamp from 'core/utils/timestamp';
export default class ActivitySerializer extends ApplicationSerializer {
normalizeResponse(store, primaryModelClass, payload, id, requestType) {
if (payload.id === 'no-data') {
return super.normalizeResponse(store, primaryModelClass, payload, id, requestType);
}
const response_timestamp = formatISO(new Date());
const response_timestamp = formatISO(timestamp.now());
const transformedPayload = {
...payload,
response_timestamp,
Expand All @@ -25,7 +26,7 @@ export default class ActivitySerializer extends ApplicationSerializer {
return super.normalizeResponse(store, primaryModelClass, transformedPayload, id, requestType);
}
}
/*
/*
SAMPLE PAYLOAD BEFORE/AFTER:
payload.data.by_namespace = [
Expand Down
3 changes: 2 additions & 1 deletion ui/app/services/download.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
*/

import Service from '@ember/service';
import timestamp from 'core/utils/timestamp';

interface Extensions {
csv: string;
Expand All @@ -29,7 +30,7 @@ export default class DownloadService extends Service {
// replace spaces with hyphens, append extension to filename
const formattedFilename =
`${filename?.replace(/\s+/g, '-')}.${extension}` ||
`vault-data-${new Date().toISOString()}.${extension}`;
`vault-data-${timestamp.now().toISOString()}.${extension}`;

// map extension to MIME type or use default
const mimetype = EXTENSION_TO_MIME[extension as keyof Extensions] || 'text/plain';
Expand Down
5 changes: 3 additions & 2 deletions ui/lib/core/addon/components/download-button.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import Component from '@glimmer/component';
import { action } from '@ember/object';
import { inject as service } from '@ember/service';
import errorMessage from 'vault/utils/error-message';
import timestamp from 'vault/utils/timestamp';
/**
* @module DownloadButton
* DownloadButton components are an action button used to download data. Both the action text and icon are yielded.
Expand Down Expand Up @@ -37,8 +38,8 @@ export default class DownloadButton extends Component {
@service flashMessages;

get filename() {
const timestamp = new Date().toISOString();
return this.args.filename ? this.args.filename + '-' + timestamp : timestamp;
const ts = timestamp.now().toISOString();
return this.args.filename ? this.args.filename + '-' + ts : ts;
}

get content() {
Expand Down
15 changes: 15 additions & 0 deletions ui/lib/core/addon/utils/timestamp.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* Use this instead of new Date() throughout the app so that time-related logic is easier to test.
*/
const timestamp = {
// Method defined within an object so it can be stubbed
/**
* * Use timestamp.now to create a date for the current moment. In testing context, stub this method so it returns an expected value
* @returns Date object
*/
now: () => {
return new Date();
},
};

export default timestamp;
1 change: 1 addition & 0 deletions ui/lib/core/app/utils/timestamp.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from 'core/utils/timestamp';
4 changes: 2 additions & 2 deletions ui/lib/kubernetes/addon/components/page/credentials.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { task } from 'ember-concurrency';
import { waitFor } from '@ember/test-waiters';
import { add } from 'date-fns';
import errorMessage from 'vault/utils/error-message';

import timestamp from 'vault/utils/timestamp';
/**
* @module Credentials
* CredentialsPage component is a child component to show the generate and view
Expand All @@ -33,7 +33,7 @@ export default class CredentialsPageComponent extends Component {
@tracked credentials;
get leaseExpiry() {
return add(new Date(), { seconds: this.credentials.lease_duration });
return add(timestamp.now(), { seconds: this.credentials.lease_duration });
}
@action
Expand Down
3 changes: 2 additions & 1 deletion ui/mirage/handlers/clients.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import {
} from 'date-fns';
import { parseAPITimestamp } from 'core/utils/date-formatters';

const CURRENT_DATE = new Date();
// Matches mocked date in client-dashboard-test file
const CURRENT_DATE = new Date('2023-01-13T14:15:00');
const COUNTS_START = subMonths(CURRENT_DATE, 12); // pretend vault user started cluster 6 months ago
// for testing, we're in the middle of a license/billing period
const LICENSE_START = startOfMonth(subMonths(CURRENT_DATE, 6));
Expand Down
6 changes: 4 additions & 2 deletions ui/tests/acceptance/auth-list-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import {
} from '@ember/test-helpers';
import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import { v4 as uuidv4 } from 'uuid';

import authPage from 'vault/tests/pages/auth';
import logout from 'vault/tests/pages/logout';
import enablePage from 'vault/tests/pages/settings/auth/enable';
Expand Down Expand Up @@ -107,14 +109,14 @@ module('Acceptance | auth backend list', function (hooks) {

test('auth methods are linkable and link to correct view', async function (assert) {
assert.expect(16);
const timestamp = new Date().getTime();
const uid = uuidv4();
await visit('/vault/access');

const supportManaged = supportedManagedAuthBackends();
const backends = supportedAuthBackends();
for (const backend of backends) {
const { type } = backend;
const path = `${type}-${timestamp}`;
const path = `auth-list-${type}-${uid}`;
if (type !== 'token') {
await enablePage.enable(type, path);
}
Expand Down
6 changes: 4 additions & 2 deletions ui/tests/acceptance/aws-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import { click, fillIn, findAll, currentURL, find, settled, waitUntil } from '@ember/test-helpers';
import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import { v4 as uuidv4 } from 'uuid';

import authPage from 'vault/tests/pages/auth';
import logout from 'vault/tests/pages/logout';
import enablePage from 'vault/tests/pages/settings/mount-secret-backend';
Expand All @@ -14,6 +16,7 @@ module('Acceptance | aws secret backend', function (hooks) {
setupApplicationTest(hooks);

hooks.beforeEach(function () {
this.uid = uuidv4();
return authPage.login();
});

Expand All @@ -33,8 +36,7 @@ module('Acceptance | aws secret backend', function (hooks) {
};
test('aws backend', async function (assert) {
assert.expect(12);
const now = new Date().getTime();
const path = `aws-${now}`;
const path = `aws-${this.uid}`;
const roleName = 'awsrole';

await enablePage.enable('aws', path);
Expand Down
Loading

0 comments on commit bf2f1a8

Please sign in to comment.