Skip to content

Commit

Permalink
[FTR] Update getAttribute method return (#179715)
Browse files Browse the repository at this point in the history
  • Loading branch information
nickofthyme authored Apr 10, 2024
1 parent a6a6823 commit 2b344d2
Show file tree
Hide file tree
Showing 59 changed files with 157 additions and 127 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ interface SetValueOptions {
typeCharByChar?: boolean;
}

export function nonNullable<T>(v: T): v is NonNullable<T> {
return v != null;
}

export class TestSubjects extends FtrService {
public readonly log = this.ctx.getService('log');
public readonly retry = this.ctx.getService('retry');
Expand Down Expand Up @@ -226,9 +230,11 @@ export class TestSubjects extends FtrService {

public async getAttributeAll(selector: string, attribute: string): Promise<string[]> {
this.log.debug(`TestSubjects.getAttributeAll(${selector}, ${attribute})`);
return await this._mapAll(selector, async (element: WebElementWrapper) => {
return await element.getAttribute(attribute);
});
return (
await this._mapAll(selector, async (element: WebElementWrapper) => {
return await element.getAttribute(attribute);
})
).filter(nonNullable);
}

public async getAttribute(
Expand All @@ -240,7 +246,7 @@ export class TestSubjects extends FtrService {
findTimeout?: number;
tryTimeout?: number;
}
): Promise<string> {
): Promise<string | null> {
const findTimeout =
(typeof options === 'number' ? options : options?.findTimeout) ??
this.config.get('timeouts.find');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ export class WebElementWrapper {
* @return {Promise<boolean>}
*/
public async elementHasClass(className: string): Promise<boolean> {
const classes: string = await this._webElement.getAttribute('class');
const classes = (await this._webElement.getAttribute('class')) ?? '';

return classes.includes(className);
}
Expand Down Expand Up @@ -262,7 +262,7 @@ export class WebElementWrapper {
*/
async clearValueWithKeyboard(options: TypeOptions = { charByChar: false }) {
const value = await this.getAttribute('value');
if (!value.length) {
if (!value?.length) {
return;
}

Expand Down Expand Up @@ -344,10 +344,11 @@ export class WebElementWrapper {
* https://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/webdriver_exports_WebElement.html#getAttribute
*
* @param {string} name
* @return {Promise<string|null>}
*/
public async getAttribute(name: string) {
return await this.retryCall(async function getAttribute(wrapper) {
return await wrapper._webElement.getAttribute(name);
public async getAttribute(name: string): Promise<string | null> {
return await this.retryCall(async function getAttribute(wrapper): Promise<string | null> {
return await wrapper._webElement.getAttribute(name); // this returns null if not found
});
}

Expand Down
4 changes: 2 additions & 2 deletions test/examples/state_sync/todo_app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export default function ({ getService, getPageObjects }: PluginFunctionalProvide

it('links are rendered correctly and state is preserved in links', async () => {
const getHrefByLinkTestSubj = async (linkTestSubj: string) =>
(await testSubjects.find(linkTestSubj)).getAttribute('href');
(await (await testSubjects.find(linkTestSubj)).getAttribute('href')) ?? '';

await expectPathname(await getHrefByLinkTestSubj('filterLinkCompleted'), '/completed');
await expectPathname(
Expand Down Expand Up @@ -115,7 +115,7 @@ export default function ({ getService, getPageObjects }: PluginFunctionalProvide

it('Links are rendered correctly and state is preserved in links', async () => {
const getHrefByLinkTestSubj = async (linkTestSubj: string) =>
(await testSubjects.find(linkTestSubj)).getAttribute('href');
(await (await testSubjects.find(linkTestSubj)).getAttribute('href')) ?? '';
await expectHashPathname(await getHrefByLinkTestSubj('filterLinkCompleted'), '/completed');
await expectHashPathname(
await getHrefByLinkTestSubj('filterLinkNotCompleted'),
Expand Down
4 changes: 2 additions & 2 deletions test/functional/apps/dashboard/group3/dashboard_state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {

it('when removing a panel', async function () {
await PageObjects.dashboard.waitForRenderComplete();
const currentUrl = await getUrlFromShare();
const currentUrl = (await getUrlFromShare()) ?? '';
const newUrl = updateAppStateQueryParam(
currentUrl,
(appState: Partial<SharedDashboardState>) => {
Expand All @@ -319,7 +319,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
await queryBar.clearQuery();
await dashboardAddPanel.addVisualization(PIE_CHART_VIS_NAME);
await enableNewChartLibraryDebug();
originalPieSliceStyle = await pieChart.getPieSliceStyle(`80,000`);
originalPieSliceStyle = (await pieChart.getPieSliceStyle(`80,000`)) ?? '';
});

it('updates a pie slice color on a hard refresh', async function () {
Expand Down
3 changes: 1 addition & 2 deletions test/functional/apps/dashboard/group5/share.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
if (mode === 'savedObject') {
await PageObjects.share.exportAsSavedObject();
}
const sharedUrl = await PageObjects.share.getSharedUrl();
return sharedUrl;
return PageObjects.share.getSharedUrl();
};

describe('share dashboard', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
});

describe('time slider selections', () => {
let valueBefore: string;
let valueBefore: string | null;

before(async () => {
valueBefore = await dashboardControls.getTimeSliceFromTimeSlider();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,14 +92,16 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {

const getRange = async () => {
await dashboardControls.rangeSliderWaitForLoading(rangeSliderId);
const lower = await dashboardControls.rangeSliderGetLowerBoundAttribute(
rangeSliderId,
'placeholder'
);
const upper = await dashboardControls.rangeSliderGetUpperBoundAttribute(
rangeSliderId,
'placeholder'
);
const lower =
(await dashboardControls.rangeSliderGetLowerBoundAttribute(
rangeSliderId,
'placeholder'
)) ?? '0';
const upper =
(await dashboardControls.rangeSliderGetUpperBoundAttribute(
rangeSliderId,
'placeholder'
)) ?? '0';
return parseInt(upper, 10) - parseInt(lower, 10);
};

Expand Down
9 changes: 4 additions & 5 deletions test/functional/apps/discover/group1/_discover_histogram.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,10 +304,8 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
await PageObjects.discover.saveSearch(savedSearch);
await PageObjects.discover.chooseBreakdownField('extension.keyword');
await PageObjects.discover.setChartInterval('Second');
let requestData = await testSubjects.getAttribute(
'unifiedHistogramChart',
'data-request-data'
);
let requestData =
(await testSubjects.getAttribute('unifiedHistogramChart', 'data-request-data')) ?? '';
expect(JSON.parse(requestData)).to.eql({
dataViewId: 'long-window-logstash-*',
timeField: '@timestamp',
Expand All @@ -318,7 +316,8 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
await PageObjects.discover.waitUntilSearchingHasFinished();
await PageObjects.discover.revertUnsavedChanges();
await PageObjects.discover.waitUntilSearchingHasFinished();
requestData = await testSubjects.getAttribute('unifiedHistogramChart', 'data-request-data');
requestData =
(await testSubjects.getAttribute('unifiedHistogramChart', 'data-request-data')) ?? '';
expect(JSON.parse(requestData)).to.eql({
dataViewId: 'long-window-logstash-*',
timeField: '@timestamp',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
const fieldIcons = await element.findAllByCssSelector('.kbnFieldIcon svg');

firstFieldIcons = await Promise.all(
fieldIcons.slice(0, 10).map((fieldIcon) => fieldIcon.getAttribute('aria-label'))
fieldIcons.slice(0, 10).map(async (fieldIcon) => {
return (await fieldIcon.getAttribute('aria-label')) ?? '';
})
).catch((error) => {
log.debug(`error in findFirstFieldIcons: ${error.message}`);
return undefined;
Expand Down
2 changes: 1 addition & 1 deletion test/functional/apps/kibana_overview/_analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {

const verifyImageUrl = async (el: WebElementWrapper, imgName: string) => {
const image = await el.findByCssSelector('img');
const imageUrl = await image.getAttribute('src');
const imageUrl = (await image.getAttribute('src')) ?? '';
expect(imageUrl.includes(imgName)).to.be(true);
};

Expand Down
2 changes: 1 addition & 1 deletion test/functional/apps/kibana_overview/_solutions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
for (let i = 0; i < solutionCards.length; i++) {
const solutionCard = solutionCards[i];
const image = await solutionCard.findByCssSelector('img');
const imageSrc = await image.getAttribute('src');
const imageSrc = (await image.getAttribute('src')) ?? '';
const match = myRegexp.exec(imageSrc);
myRegexp.lastIndex = 0;
if (match && match.length > 1) {
Expand Down
12 changes: 6 additions & 6 deletions test/functional/page_objects/console_page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ export class ConsolePageObject extends FtrService {
if (!element) return false;

const attribute = await element.getAttribute('style');
return !attribute.includes('display: none;');
return !attribute?.includes('display: none;');
}

public async getAutocompleteSuggestion(index: number = 0) {
Expand Down Expand Up @@ -321,7 +321,7 @@ export class ConsolePageObject extends FtrService {
await blocks[blockNumber].click();
await this.retry.waitFor('json block to be collapsed', async () => {
return blocks[blockNumber].getAttribute('class').then((classes) => {
return classes.includes('ace_closed');
return classes?.includes('ace_closed') ?? false;
});
});
}
Expand All @@ -336,7 +336,7 @@ export class ConsolePageObject extends FtrService {
await blocks[blockNumber].click();
await this.retry.waitFor('json block to be expanded', async () => {
return blocks[blockNumber].getAttribute('class').then((classes) => {
return classes.includes('ace_open');
return classes?.includes('ace_open') ?? false;
});
});
}
Expand All @@ -349,7 +349,7 @@ export class ConsolePageObject extends FtrService {
}

const classes = await blocks[blockNumber].getAttribute('class');
return classes.includes('ace_open');
return classes?.includes('ace_open') ?? false;
}

public async selectCurrentRequest() {
Expand Down Expand Up @@ -385,7 +385,7 @@ export class ConsolePageObject extends FtrService {
});

// style attribute looks like this: "top: 0px; height: 18.5px;" height is the line height
const styleAttribute = await line.getAttribute('style');
const styleAttribute = (await line.getAttribute('style')) ?? '';
const height = parseFloat(styleAttribute.replace(/.*height: ([+-]?\d+(\.\d+)?).*/, '$1'));
const top = parseFloat(styleAttribute.replace(/.*top: ([+-]?\d+(\.\d+)?).*/, '$1'));
// calculate the line number by dividing the top position by the line height
Expand Down Expand Up @@ -490,7 +490,7 @@ export class ConsolePageObject extends FtrService {
const path = [];
for (const pathPart of requestPath) {
const className = await pathPart.getAttribute('class');
if (className.includes('ace_param')) {
if (className?.includes('ace_param') ?? false) {
// This is a parameter, we don't want to include it in the path
break;
}
Expand Down
6 changes: 5 additions & 1 deletion test/functional/page_objects/dashboard_page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -696,7 +696,11 @@ export class DashboardPageObject extends FtrService {
const attributeName = 'data-shared-items-count';
const element = await this.find.byCssSelector(`[${attributeName}]`);
if (element) {
return await element.getAttribute(attributeName);
const attribute = await element.getAttribute(attributeName);

if (!attribute) throw new Error(`no attribute found for [${attributeName}]`);

return attribute;
}

throw new Error('no element');
Expand Down
11 changes: 7 additions & 4 deletions test/functional/page_objects/dashboard_page_controls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,9 @@ export class DashboardPageControls extends FtrService {
public async getAllControlIds() {
const controlFrames = await this.testSubjects.findAll('control-frame');
const ids = await Promise.all(
controlFrames.map(async (controlFrame) => await controlFrame.getAttribute('data-control-id'))
controlFrames.map(
async (controlFrame) => (await controlFrame.getAttribute('data-control-id')) ?? ''
)
);
this.log.debug('Got all control ids:', ids);
return ids;
Expand Down Expand Up @@ -93,7 +95,7 @@ export class DashboardPageControls extends FtrService {
public async clearAllControls() {
const controlIds = await this.getAllControlIds();
for (const controlId of controlIds) {
await this.removeExistingControl(controlId);
if (controlId) await this.removeExistingControl(controlId);
}
}

Expand Down Expand Up @@ -162,7 +164,8 @@ export class DashboardPageControls extends FtrService {
false: 'NONE',
};

const switchState = await this.testSubjects.getAttribute('control-group-chaining', 'checked');
const switchState =
(await this.testSubjects.getAttribute('control-group-chaining', 'checked')) ?? '';
if (chainingSystem !== switchStateToChainingSystem[switchState]) {
await this.testSubjects.click('control-group-chaining');
}
Expand Down Expand Up @@ -432,7 +435,7 @@ export class DashboardPageControls extends FtrService {
this.log.debug(`getting available options count from options list`);
await this.optionsListPopoverWaitForLoading();
const availableOptions = await this.testSubjects.find(`optionsList-control-available-options`);
return +(await availableOptions.getAttribute('data-option-count'));
return +((await availableOptions.getAttribute('data-option-count')) ?? '0');
}

public async optionsListPopoverGetAvailableOptions() {
Expand Down
2 changes: 1 addition & 1 deletion test/functional/page_objects/discover_page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,7 @@ export class DiscoverPageObject extends FtrService {
return await cell.getVisibleText();
} else {
const textContent = await cell.getAttribute('textContent');
return textContent.trim();
return textContent?.trim();
}
})
);
Expand Down
6 changes: 3 additions & 3 deletions test/functional/page_objects/home_page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,15 @@ export class HomePageObject extends FtrService {

async openSampleDataAccordion() {
const accordionButton = await this.testSubjects.find('showSampleDataButton');
let expandedAttribute = await accordionButton.getAttribute('aria-expanded');
let expandedAttribute = (await accordionButton.getAttribute('aria-expanded')) ?? '';
let expanded = expandedAttribute.toLocaleLowerCase().includes('true');
this.log.debug(`Sample data accordion expanded: ${expanded}`);

if (!expanded) {
await this.retry.waitFor('sample data according to be expanded', async () => {
this.log.debug(`Opening sample data accordion`);
await accordionButton.click();
expandedAttribute = await accordionButton.getAttribute('aria-expanded');
expandedAttribute = (await accordionButton.getAttribute('aria-expanded')) ?? '';
expanded = expandedAttribute.toLocaleLowerCase().includes('true');
return expanded;
});
Expand Down Expand Up @@ -75,7 +75,7 @@ export class HomePageObject extends FtrService {
const panelAttributes = await Promise.all(
solutionPanels.map((panel) => panel.getAttribute('data-test-subj'))
);
return panelAttributes.map((attributeValue) => attributeValue.split('homSolutionPanel_')[1]);
return panelAttributes.map((attributeValue) => attributeValue?.split('homSolutionPanel_')[1]);
}

async goToSampleDataPage() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ export class SavedObjectsPageObject extends FtrService {
let copySaveObjectsElement = null;
const actions = await row.findByClassName('euiTableRowCell--hasActions');
// getting the innerHTML and checking if it 'includes' a string is faster than a timeout looking for each element
const actionsHTML = await actions.getAttribute('innerHTML');
const actionsHTML = (await actions.getAttribute('innerHTML')) ?? '';
if (actionsHTML.includes('euiCollapsedItemActionsButton')) {
menuElement = await row.findByTestSubject('euiCollapsedItemActionsButton');
}
Expand Down
4 changes: 2 additions & 2 deletions test/functional/page_objects/settings_page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ export class SettingsPageObject extends FtrService {
}

async toggleAdvancedSettingCheckbox(propertyName: string, value?: boolean) {
let curValue: string | undefined;
let curValue: string | null;
if (value !== undefined) {
curValue = await this.getAdvancedSettingAriaCheckbox(propertyName);

Expand Down Expand Up @@ -669,7 +669,7 @@ export class SettingsPageObject extends FtrService {
// case where we don't want the * appended so we'll remove it if it was added
await field.type(indexPatternName, { charByChar: true });
const tempName = await field.getAttribute('value');
if (tempName.length > indexPatternName.length) {
if (tempName?.length ?? 0 > indexPatternName.length) {
await field.type(this.browser.keys.DELETE, { charByChar: true });
}
}
Expand Down
2 changes: 1 addition & 1 deletion test/functional/page_objects/share_page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export class SharePageObject extends FtrService {

async getSharedUrl() {
await this.openPermaLinks();
return await this.testSubjects.getAttribute('copyShareUrlButton', 'data-share-url');
return (await this.testSubjects.getAttribute('copyShareUrlButton', 'data-share-url')) ?? '';
}

async createShortUrlExistOrFail() {
Expand Down
2 changes: 1 addition & 1 deletion test/functional/page_objects/tag_cloud_page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export class TagCloudPageObject extends FtrService {
const tags = await this.find.allByCssSelector('text');
async function returnTagSize(tag: WebElementWrapper) {
const style = await tag.getAttribute('style');
const fontSize = style.match(/font-size: ([^;]*);/);
const fontSize = style?.match(/font-size: ([^;]*);/);
return fontSize ? fontSize[1] : '';
}
return await Promise.all(tags.map(returnTagSize));
Expand Down
Loading

0 comments on commit 2b344d2

Please sign in to comment.