export function setAlmPersonalAccessToken(
almSetting: string,
pat: string,
- username?: string
+ username?: string,
): Promise<void> {
return post('/api/alm_integrations/set_pat', { almSetting, pat, username }).catch(
- throwGlobalError
+ throwGlobalError,
);
}
export function checkPersonalAccessTokenIsValid(
- almSetting: string
+ almSetting: string,
): Promise<{ status: boolean; error?: string }> {
return get('/api/alm_integrations/check_pat', { almSetting })
.then(() => ({ status: true }))
export function getAzureProjects(almSetting: string): Promise<{ projects: AzureProject[] }> {
return getJSON('/api/alm_integrations/list_azure_projects', { almSetting }).catch(
- throwGlobalError
+ throwGlobalError,
);
}
export function getAzureRepositories(
almSetting: string,
- projectName: string
+ projectName: string,
): Promise<{ repositories: AzureRepository[] }> {
return getJSON('/api/alm_integrations/search_azure_repos', { almSetting, projectName }).catch(
- throwGlobalError
+ throwGlobalError,
);
}
export function searchAzureRepositories(
almSetting: string,
- searchQuery: string
+ searchQuery: string,
): Promise<{ repositories: AzureRepository[] }> {
return getJSON('/api/alm_integrations/search_azure_repos', { almSetting, searchQuery }).catch(
- throwGlobalError
+ throwGlobalError,
);
}
}
export function getBitbucketServerProjects(
- almSetting: string
+ almSetting: string,
): Promise<{ projects: BitbucketProject[] }> {
return getJSON('/api/alm_integrations/list_bitbucketserver_projects', { almSetting });
}
export function getBitbucketServerRepositories(
almSetting: string,
- projectName: string
+ projectName: string,
): Promise<{
isLastPage: boolean;
repositories: BitbucketRepository[];
newCodeDefinitionValue?: string;
}): Promise<{ project: ProjectBase }> {
return postJSON('/api/alm_integrations/import_bitbucketserver_project', data).catch(
- throwGlobalError
+ throwGlobalError,
);
}
export function searchForBitbucketServerRepositories(
almSetting: string,
- repositoryName: string
+ repositoryName: string,
): Promise<{
isLastPage: boolean;
repositories: BitbucketRepository[];
almSetting: string,
repositoryName: string,
pageSize: number,
- page?: number
+ page?: number,
): Promise<{
isLastPage: boolean;
repositories: BitbucketCloudRepository[];
export function getGithubOrganizations(
almSetting: string,
- token: string
+ token: string,
): Promise<{ organizations: GithubOrganization[] }> {
return getJSON('/api/alm_integrations/list_github_organizations', {
almSetting,
}
export function updateBitbucketServerConfiguration(
- data: BitbucketServerBindingDefinition & { newKey: string }
+ data: BitbucketServerBindingDefinition & { newKey: string },
) {
return post('/api/alm_settings/update_bitbucket', data).catch(throwGlobalError);
}
}
export function updateBitbucketCloudConfiguration(
- data: BitbucketCloudBindingDefinition & { newKey: string }
+ data: BitbucketCloudBindingDefinition & { newKey: string },
) {
return post('/api/alm_settings/update_bitbucketcloud', data).catch(throwGlobalError);
}
}
export function validateProjectAlmBinding(
- projectKey: string
+ projectKey: string,
): Promise<ProjectAlmBindingConfigurationErrors | undefined> {
return get('/api/alm_settings/validate_binding', { project: projectKey })
.then(() => undefined)
export function getApplicationLeak(
application: string,
- branch?: string
+ branch?: string,
): Promise<ApplicationPeriod[]> {
return getJSON('/api/applications/show_leak', { application, branch }).then(
(r) => r.leaks,
- throwGlobalError
+ throwGlobalError,
);
}
export function getApplicationDetails(application: string, branch?: string): Promise<Application> {
return getJSON('/api/applications/show', { application, branch }).then(
(r) => r.application,
- throwGlobalError
+ throwGlobalError,
);
}
name: string,
description: string,
key: string | undefined,
- visibility: string
+ visibility: string,
): Promise<{
application: {
description?: string;
};
}> {
return postJSON('/api/applications/create', { description, key, name, visibility }).catch(
- throwGlobalError
+ throwGlobalError,
);
}
export function getBranches(project: string): Promise<Branch[]> {
return getJSON('/api/project_branches/list', { project }).then(
(r) => r.branches,
- throwGlobalError
+ throwGlobalError,
);
}
export function getPullRequests(project: string): Promise<PullRequest[]> {
return getJSON('/api/project_pull_requests/list', { project }).then(
(r) => r.pullRequests,
- throwGlobalError
+ throwGlobalError,
);
}
}
export function getActivity(
- data: ActivityRequestParameters
+ data: ActivityRequestParameters,
): Promise<{ tasks: Task[]; paging: Paging }> {
return getJSON('/api/ce/activity', data);
}
export function getStatus(
- component?: string
+ component?: string,
): Promise<{ failing: number; inProgress: number; pending: number; pendingTime?: number }> {
return getJSON('/api/ce/activity_status', { component });
}
export function cancelTask(id: string): Promise<any> {
return post('/api/ce/cancel', { id }).then(
() => getTask(id),
- () => getTask(id)
+ () => getTask(id),
);
}
}
export function getTasksForComponent(
- component: string
+ component: string,
): Promise<{ queue: Task[]; current?: Task }> {
return getJSON('/api/ce/component', { component }).catch(throwGlobalError);
}
export function getReportStatus(
componentKey: string,
- branchKey?: string
+ branchKey?: string,
): Promise<ComponentReportStatus> {
return getJSON('/api/governance_reports/status', { componentKey, branchKey }).catch(
- throwGlobalError
+ throwGlobalError,
);
}
export function getReportUrl(componentKey: string, branchKey?: string): string {
let url = `${getBaseUrl()}/api/governance_reports/download?componentKey=${encodeURIComponent(
- componentKey
+ componentKey,
)}`;
if (branchKey) {
export function subscribeToEmailReport(
componentKey: string,
- branchKey?: string
+ branchKey?: string,
): Promise<void | Response> {
return post('/api/governance_reports/subscribe', { componentKey, branchKey }).catch(
- throwGlobalError
+ throwGlobalError,
);
}
export function unsubscribeFromEmailReport(
componentKey: string,
- branchKey?: string
+ branchKey?: string,
): Promise<void | Response> {
return post('/api/governance_reports/unsubscribe', { componentKey, branchKey }).catch(
- throwGlobalError
+ throwGlobalError,
);
}
strategy: string,
component: string,
metrics: string[] = [],
- additional: RequestData = {}
+ additional: RequestData = {},
): Promise<{
baseComponent: ComponentMeasure;
components: ComponentMeasure[];
export function getChildren(
component: string,
metrics: string[] = [],
- additional: RequestData = {}
+ additional: RequestData = {},
) {
return getComponentTree('children', component, metrics, additional);
}
export function getComponentLeaves(
component: string,
metrics: string[] = [],
- additional: RequestData = {}
+ additional: RequestData = {},
) {
return getComponentTree('leaves', component, metrics, additional);
}
export function getComponent(
- data: { component: string; metricKeys: string } & BranchParameters
+ data: { component: string; metricKeys: string } & BranchParameters,
): Promise<{ component: ComponentMeasure }> {
return getJSON('/api/measures/component', data);
}
} & BranchParameters;
export function getTree<T = TreeComponent>(
- data: GetTreeParams & { qualifiers?: string }
+ data: GetTreeParams & { qualifiers?: string },
): Promise<{ baseComponent: TreeComponent; components: T[]; paging: Paging }> {
return getJSON('/api/components/tree', data).catch(throwGlobalError);
}
}
export function doesComponentExists(
- data: { component: string } & BranchParameters
+ data: { component: string } & BranchParameters,
): Promise<boolean> {
return getComponentData(data).then(
({ component }) => component !== undefined,
- () => false
+ () => false,
);
}
}
export function getBreadcrumbs(
- data: { component: string } & BranchParameters
+ data: { component: string } & BranchParameters,
): Promise<Array<Omit<ComponentRaw, 'tags'>>> {
return getComponentShow(data).then((r) => {
const reversedAncestors = [...r.ancestors].reverse();
export function getSuggestions(
query?: string,
recentlyBrowsed?: string[],
- more?: string
+ more?: string,
): Promise<SuggestionsResponse> {
const data: RequestData = {};
if (query) {
}
export function getComponentForSourceViewer(
- data: { component: string } & BranchParameters
+ data: { component: string } & BranchParameters,
): Promise<SourceViewerFile> {
return getJSON('/api/components/app', data);
}
export function getSources(
- data: { key: string; from?: number; to?: number } & BranchParameters
+ data: { key: string; from?: number; to?: number } & BranchParameters,
): Promise<SourceLine[]> {
return getJSON('/api/sources/lines', data).then((r) => r.sources);
}
export function getDuplications(
- data: { key: string } & BranchParameters
+ data: { key: string } & BranchParameters,
): Promise<{ duplications: Duplication[]; files: Dict<DuplicatedFile> }> {
return getJSON('/api/duplications/show', data).catch(throwGlobalError);
}
export function getTests(
- data: { sourceFileKey: string; sourceFileLineNumber: number | string } & BranchParameters
+ data: { sourceFileKey: string; sourceFileLineNumber: number | string } & BranchParameters,
): Promise<any> {
return getJSON('/api/tests/list', data).then((r) => r.tests);
}
export function getFacets(
query: RequestData,
- facets: FacetName[]
+ facets: FacetName[],
): Promise<{
facets: Array<{ property: string; values: FacetValue[] }>;
response: RawIssuesResponse;
export function getFacet(
query: RequestData,
- facet: FacetName
+ facet: FacetName,
): Promise<{ facet: { count: number; val: string }[]; response: RawIssuesResponse }> {
return getFacets(query, [facet]).then((r) => {
return { facet: r.facets[0].values, response: r.response };
lineMap[line.line] = line;
return lineMap;
},
- {}
+ {},
);
}
});
import { L10nBundleRequestParams, L10nBundleRequestResponse } from '../types/l10nBundle';
export function fetchL10nBundle(
- params: L10nBundleRequestParams
+ params: L10nBundleRequestParams,
): Promise<L10nBundleRequestResponse> {
return getJSON('/api/l10n/index', params);
}
const COMPONENT_URL = '/api/measures/component';
export function getMeasures(
- data: { component: string; metricKeys: string } & BranchParameters
+ data: { component: string; metricKeys: string } & BranchParameters,
): Promise<Measure[]> {
return getJSON(COMPONENT_URL, data).then((r) => r.component.measures, throwGlobalError);
}
export function getMeasuresWithMetrics(
component: string,
metrics: string[],
- branchParameters?: BranchParameters
+ branchParameters?: BranchParameters,
): Promise<MeasuresAndMetaWithMetrics> {
return getJSON(COMPONENT_URL, {
additionalFields: 'metrics',
export function getMeasuresWithPeriod(
component: string,
metrics: string[],
- branchParameters?: BranchParameters
+ branchParameters?: BranchParameters,
): Promise<MeasuresAndMetaWithPeriod> {
return getJSON(COMPONENT_URL, {
additionalFields: 'period',
export function getMeasuresWithPeriodAndMetrics(
component: string,
metrics: string[],
- branchParameters?: BranchParameters
+ branchParameters?: BranchParameters,
): Promise<MeasuresAndMetaWithPeriod & MeasuresAndMetaWithMetrics> {
return getJSON(COMPONENT_URL, {
additionalFields: 'period,metrics',
export function getMeasuresForProjects(
projectKeys: string[],
- metricKeys: string[]
+ metricKeys: string[],
): Promise<MeasuresForProjects[]> {
return getJSON('/api/measures/search', {
projectKeys: projectKeys.join(),
function inner(
data: { p?: number; ps?: number } = { ps: 500 },
- prev?: MetricsResponse
+ prev?: MetricsResponse,
): Promise<Metric[]> {
return getMetrics(data).then((r) => {
const result = prev ? prev.metrics.concat(r.metrics) : r.metrics;
GitlabBindingDefinition[],
AzureBindingDefinition[],
BitbucketCloudBindingDefinition[],
- BitbucketServerBindingDefinition[]
+ BitbucketServerBindingDefinition[],
]) {
const foundIndex = definitionsGroup.findIndex((definition) => definition.key === key);
if (foundIndex !== -1) {
removeFromAlmSettings = (almKey: string) => {
this.#almSettings = cloneDeep(defaultAlmSettings).filter(
- (almSetting) => almSetting.alm !== almKey
+ (almSetting) => almSetting.alm !== almKey,
);
};
handleUpdateGithubConfiguration = (data: GithubBindingDefinition & { newKey: string }) => {
const definition = this.#almDefinitions[AlmKeys.GitHub].find(
- (item) => item.key === data.key
+ (item) => item.key === data.key,
) as GithubBindingDefinition;
Object.assign(definition, { ...data, key: data.newKey });
handleUpdateGitlabConfiguration = (data: GitlabBindingDefinition & { newKey: string }) => {
const definition = this.#almDefinitions[AlmKeys.GitLab].find(
- (item) => item.key === data.key
+ (item) => item.key === data.key,
) as GitlabBindingDefinition;
Object.assign(definition, { ...data, key: data.newKey });
handleUpdateAzureConfiguration = (data: AzureBindingDefinition & { newKey: string }) => {
const definition = this.#almDefinitions[AlmKeys.Azure].find(
- (item) => item.key === data.key
+ (item) => item.key === data.key,
) as AzureBindingDefinition;
Object.assign(definition, { ...data, key: data.newKey });
};
handleUpdateBitbucketServerConfiguration = (
- data: BitbucketServerBindingDefinition & { newKey: string }
+ data: BitbucketServerBindingDefinition & { newKey: string },
) => {
const definition = this.#almDefinitions[AlmKeys.BitbucketServer].find(
- (item) => item.key === data.key
+ (item) => item.key === data.key,
) as BitbucketServerBindingDefinition;
Object.assign(definition, { ...data, key: data.newKey });
};
handleUpdateBitbucketCloudConfiguration = (
- data: BitbucketCloudBindingDefinition & { newKey: string }
+ data: BitbucketCloudBindingDefinition & { newKey: string },
) => {
const definition = this.#almDefinitions[AlmKeys.BitbucketCloud].find(
- (item) => item.key === data.key
+ (item) => item.key === data.key,
) as BitbucketCloudBindingDefinition;
Object.assign(definition, { ...data, key: data.newKey });
return Promise.reject(
new Response('', {
status: 404,
- })
+ }),
);
}
id: Math.random().toString(),
type: TaskTypes.GithubProvisioning,
...overrides,
- })
+ }),
);
};
}
const nextSync = this.tasks.find((t: Task) =>
- [TaskStatuses.InProgress, TaskStatuses.Pending].includes(t.status)
+ [TaskStatuses.InProgress, TaskStatuses.Pending].includes(t.status),
);
const lastSync = this.tasks.find(
- (t: Task) => ![TaskStatuses.InProgress, TaskStatuses.Pending].includes(t.status)
+ (t: Task) => ![TaskStatuses.InProgress, TaskStatuses.Pending].includes(t.status),
);
return Promise.resolve({
excludeBranchFromPurgeHandler: typeof excludeBranchFromPurge = (_, name, value) => {
this.branches = this.branches.map((b) =>
- b.name === name ? { ...b, excludedFromPurge: value } : b
+ b.name === name ? { ...b, excludedFromPurge: value } : b,
);
return this.reply(null);
};
'cleanCodeAttributeCategory',
'cleanCodeAttribute',
'impacts',
- ])
+ ]),
);
}
filteredRules = filteredRules.filter(
(r) =>
r.cleanCodeAttributeCategory &&
- cleanCodeAttributeCategories.includes(r.cleanCodeAttributeCategory)
+ cleanCodeAttributeCategories.includes(r.cleanCodeAttributeCategory),
);
}
if (impactSoftwareQualities) {
filteredRules = filteredRules.filter(
(r) =>
r.impacts &&
- r.impacts.some(({ softwareQuality }) => impactSoftwareQualities.includes(softwareQuality))
+ r.impacts.some(({ softwareQuality }) =>
+ impactSoftwareQualities.includes(softwareQuality),
+ ),
);
}
if (impactSeverities) {
filteredRules = filteredRules.filter(
- (r) => r.impacts && r.impacts.some(({ severity }) => impactSeverities.includes(severity))
+ (r) => r.impacts && r.impacts.some(({ severity }) => impactSeverities.includes(severity)),
);
}
if (types) {
}
if (available_since) {
filteredRules = filteredRules.filter(
- (r) => r.createdAt && new Date(r.createdAt) > new Date(available_since)
+ (r) => r.createdAt && new Date(r.createdAt) > new Date(available_since),
);
}
if (is_template !== undefined) {
handleDeactivateRule = (data: { key: string; rule: string }) => {
this.rulesActivations[data.rule] = this.rulesActivations[data.rule]?.filter(
- (activation) => activation.qProfile !== data.key
+ (activation) => activation.qProfile !== data.key,
);
return this.reply(undefined);
};
dismissedNotices: {
educationPrinciples: this.dismissedNoticesEP,
},
- })
+ }),
);
};
measures ||
this.defaultComponents.reduce(
(acc, tree) => ({ ...acc, ...mockFullMeasureData(tree, issueList) }),
- {}
+ {},
);
this.components = cloneDeep(this.defaultComponents);
}
return acc;
},
- { sourceFile: undefined, size: -Infinity }
+ { sourceFile: undefined, size: -Infinity },
);
if (sourceFile) {
return sourceFile.component.key;
handleGetChildren = (
component: string,
metrics: string[] = [],
- data: RequestData = {}
+ data: RequestData = {},
): Promise<{
baseComponent: ComponentMeasure;
components: ComponentMeasure[];
strategy: string,
key: string,
metricKeys: string[] = [],
- { p = 1, ps = 100 }: RequestData = {}
+ { p = 1, ps = 100 }: RequestData = {},
): Promise<{
baseComponent: ComponentMeasure;
components: ComponentMeasure[];
handleGetComponentLeaves = (
component: string,
metrics: string[] = [],
- data: RequestData = {}
+ data: RequestData = {},
): Promise<{
baseComponent: ComponentMeasure;
components: ComponentMeasure[];
Math.max(
+new Date(t.submittedAt),
+new Date(t.startedAt ?? 0),
- +new Date(t.executedAt ?? 0)
+ +new Date(t.executedAt ?? 0),
);
return getMaxDate(b) - getMaxDate(a);
case TaskStatuses.Pending:
stats.pendingTime = Math.max(
stats.pendingTime,
- differenceInMilliseconds(parseDate(task.submittedAt), Date.now())
+ differenceInMilliseconds(parseDate(task.submittedAt), Date.now()),
);
stats.pending += 1;
break;
return stats;
},
- { failing: 0, inProgress: 0, pending: 0, pendingTime: 0 }
- )
+ { failing: 0, inProgress: 0, pending: 0, pendingTime: 0 },
+ ),
);
};
const tasks = this.tasks.filter((t) => t.componentKey === componentKey);
return Promise.resolve({
queue: tasks.filter(
- (t) => t.status === TaskStatuses.InProgress || t.status === TaskStatuses.Pending
+ (t) => t.status === TaskStatuses.InProgress || t.status === TaskStatuses.Pending,
),
current: tasks.find(
- (t) => t.status === TaskStatuses.Success || t.status === TaskStatuses.Failed
+ (t) => t.status === TaskStatuses.Success || t.status === TaskStatuses.Failed,
),
});
};
mockTask({
id,
...overrides,
- })
+ }),
);
};
'External Users and Groups Provisioning': this.provider,
},
}
- : {}
- )
+ : {},
+ ),
);
};
if (name === 'codeVariants') {
return {
property: 'codeVariants',
- values: this.list.reduce((acc, { issue }) => {
- if (issue.codeVariants?.length) {
- issue.codeVariants.forEach((codeVariant) => {
- const item = acc.find(({ val }) => val === codeVariant);
- if (item) {
- item.count++;
- } else {
- acc.push({
- val: codeVariant,
- count: 1,
- });
- }
- });
- }
- return acc;
- }, [] as RawFacet['values']),
+ values: this.list.reduce(
+ (acc, { issue }) => {
+ if (issue.codeVariants?.length) {
+ issue.codeVariants.forEach((codeVariant) => {
+ const item = acc.find(({ val }) => val === codeVariant);
+ if (item) {
+ item.count++;
+ } else {
+ acc.push({
+ val: codeVariant,
+ count: 1,
+ });
+ }
+ });
+ }
+ return acc;
+ },
+ [] as RawFacet['values'],
+ ),
};
}
val: 'java',
count: cleanCodeCategories.reduce<number>(
(acc, category) => acc + counters[category].java,
- 0
+ 0,
),
},
{
val: 'ts',
count: cleanCodeCategories.reduce<number>(
(acc, category) => acc + counters[category].ts,
- 0
+ 0,
),
},
],
.filter((item) => !query.types || query.types.split(',').includes(item.issue.type))
.filter(
(item) =>
- !query.inNewCodePeriod || new Date(item.issue.creationDate) > new Date('2023-01-10')
+ !query.inNewCodePeriod || new Date(item.issue.creationDate) > new Date('2023-01-10'),
);
// Splice list items according to paging using a fixed page size
}
return item.issue.impacts.some(({ softwareQuality }) =>
- query.impactSoftwareQualities.split(',').includes(softwareQuality)
+ query.impactSoftwareQualities.split(',').includes(softwareQuality),
);
})
.filter((item) => {
}
return item.issue.impacts.some(({ severity }) =>
- query.impactSeverities.split(',').includes(severity)
+ query.impactSeverities.split(',').includes(severity),
);
})
.filter((item) => {
})
.filter(
(item) =>
- !query.createdBefore || new Date(item.issue.creationDate) <= new Date(query.createdBefore)
+ !query.createdBefore ||
+ new Date(item.issue.creationDate) <= new Date(query.createdBefore),
)
.filter(
(item) =>
- !query.createdAfter || new Date(item.issue.creationDate) >= new Date(query.createdAfter)
+ !query.createdAfter || new Date(item.issue.creationDate) >= new Date(query.createdAfter),
)
.filter((item) => !query.types || query.types.split(',').includes(item.issue.type))
.filter(
- (item) => !query.severities || query.severities.split(',').includes(item.issue.severity)
+ (item) => !query.severities || query.severities.split(',').includes(item.issue.severity),
)
.filter((item) => !query.scopes || query.scopes.split(',').includes(item.issue.scope))
.filter((item) => !query.statuses || query.statuses.split(',').includes(item.issue.status))
.filter((item) => !query.projects || query.projects.split(',').includes(item.issue.project))
.filter((item) => !query.rules || query.rules.split(',').includes(item.issue.rule))
.filter(
- (item) => !query.resolutions || query.resolutions.split(',').includes(item.issue.resolution)
+ (item) =>
+ !query.resolutions || query.resolutions.split(',').includes(item.issue.resolution),
)
.filter(
(item) =>
- !query.inNewCodePeriod || new Date(item.issue.creationDate) > new Date('2023-01-10')
+ !query.inNewCodePeriod || new Date(item.issue.creationDate) > new Date('2023-01-10'),
)
.filter((item) => {
if (!query.codeVariants) {
if (!item.issue.codeVariants) {
return false;
}
- return item.issue.codeVariants.some((codeVariant) =>
- query.codeVariants?.split(',').includes(codeVariant)
+ return item.issue.codeVariants.some(
+ (codeVariant) => query.codeVariants?.split(',').includes(codeVariant),
);
});
handleSetIssueAssignee = (data: { issue: string; assignee?: string }) => {
return this.getActionsResponse(
{ assignee: data.assignee === '_me' ? this.currentUser.login : data.assignee },
- data.issue
+ data.issue,
);
};
transitions: transitionMap[statusMap[data.transition]],
resolution: resolutionMap[data.transition],
},
- data.issue
+ data.issue,
);
};
},
],
},
- data.issue
+ data.issue,
);
};
},
],
},
- issueKey
+ issueKey,
);
};
handleDeleteComment = (data: { comment: string }) => {
- const issue = this.list.find((i) =>
- i.issue.comments?.some((c) => c.key === data.comment)
- )?.issue;
+ const issue = this.list.find((i) => i.issue.comments?.some((c) => c.key === data.comment))
+ ?.issue;
if (!issue) {
throw new Error(`Couldn't find issue for comment ${data.comment}`);
}
{
comments: issue.comments?.filter((c) => c.key !== data.comment),
},
- issue.key
+ issue.key,
);
};
filterMeasures = (componentKey: string, metricKeys: string[]) => {
return this.#measures[componentKey]
? Object.values(this.#measures[componentKey]).filter(({ metric }) =>
- metricKeys.includes(metric)
+ metricKeys.includes(metric),
)
: [];
};
handleGetMeasuresWithPeriod = (
component: string,
metrics: string[],
- _branchParameters?: BranchParameters
+ _branchParameters?: BranchParameters,
) => {
const entry = this.findComponentTree(component);
const measures = this.filterMeasures(entry.component.key, metrics);
handleGetNewCodePeriod = (data?: { branch?: string; project?: string }) => {
if (data?.branch !== undefined) {
return this.reply(
- this.#listBranchesNewCode.find((b) => b.branchKey === data?.branch) as NewCodeDefinition
+ this.#listBranchesNewCode.find((b) => b.branchKey === data?.branch) as NewCodeDefinition,
);
}
if (project !== undefined && branch !== undefined) {
this.#listBranchesNewCode = this.#listBranchesNewCode.filter((b) => b.branchKey !== branch);
this.#listBranchesNewCode.push(
- mockNewCodePeriodBranch({ type, value, branchKey: branch, projectKey: project })
+ mockNewCodePeriodBranch({ type, value, branchKey: branch, projectKey: project }),
);
} else {
this.#newCodePeriod = mockNewCodePeriod({ projectKey: project, type, value });
handleRemoveNotification = (params: AddRemoveNotificationParameters) => {
const index = this.notifications.findIndex(
- (n) => n.project === params.project && n.type === params.type && n.channel === params.channel
+ (n) => n.project === params.project && n.type === params.type && n.channel === params.channel,
);
if (index < 0) {
groupsCount: defaultGroups.filter((g) => g.permissions.includes(key)).length,
usersCount: defaultUsers.filter((g) => g.permissions.includes(key)).length,
withProjectCreator: false,
- })
+ }),
),
}),
mockPermissionTemplate({
groupsCount: 0,
usersCount: 0,
withProjectCreator: [Permissions.Browse, Permissions.CodeViewer].includes(key),
- })
+ }),
),
}),
];
constructor() {
this.#permissionTemplates = cloneDeep(defaultTemplates);
this.#permissions = PERMISSIONS_ORDER_FOR_PROJECT_TEMPLATE.map((key) =>
- mockPermission({ key, name: key })
+ mockPermission({ key, name: key }),
);
this.#groups = cloneDeep(defaultGroups);
this.#users = cloneDeep(defaultUsers);
params.projects.split(',').length > MAX_PROJECTS_TO_APPLY_PERMISSION_TEMPLATE
) {
const response = new Response(
- JSON.stringify({ errors: [{ msg: 'bulk apply permission template error message' }] })
+ JSON.stringify({ errors: [{ msg: 'bulk apply permission template error message' }] }),
);
return Promise.reject(response);
}
? this.#users.filter(
(user) =>
user.name.toLowerCase().includes(q.toLowerCase()) ||
- user.login.toLowerCase().includes(q.toLowerCase())
+ user.login.toLowerCase().includes(q.toLowerCase()),
)
: this.#users;
const usersChunked = chunk(
permission ? users.filter((u) => u.permissions.includes(permission)) : users,
- ps
+ ps,
);
return this.reply({
const groupsChunked = chunk(
permission ? groups.filter((g) => g.permissions.includes(permission)) : groups,
- ps
+ ps,
);
return this.reply({
handleGetPluginUpdates = () => {
return this.reply(
- this.#installed.filter((plugin) => plugin.updates && plugin.updates.length > 0)
+ this.#installed.filter((plugin) => plugin.updates && plugin.updates.length > 0),
);
};
'sonarLintSupported',
'hash',
'filename',
- 'documentationPath'
+ 'documentationPath',
),
implementationBuild: '20210101-000000',
});
'sonarLintSupported',
'hash',
'filename',
- 'documentationPath'
+ 'documentationPath',
),
version: plugin.updates[plugin.updates.length - 1].release?.version ?? '',
implementationBuild: '20210101-000000',
from?: string;
p?: number;
ps?: number;
- } & BranchParameters
+ } & BranchParameters,
) => {
const { project, ps = PAGE_SIZE, p = DEFAULT_PAGE, category, from } = data;
analysisKey: string,
name: string,
category = ProjectAnalysisEventCategory.Other,
- description?: string
+ description?: string,
) => {
const analysis = this.findAnalysis(analysisKey);
name,
visibility,
lastAnalysisDate: undefined,
- })
+ }),
);
return this.reply({ project: this.#projects[0] });
};
showHandler = ({ name }: { name: string }) => {
const qualityGate = omit(
this.list.find((q) => q.name === name),
- 'isDefault'
+ 'isDefault',
);
return this.reply({ ...qualityGate, actions: this.computeActions(qualityGate) });
};
isDefault: false,
isBuiltIn: false,
caycStatus: CaycStatus.Compliant,
- })
+ }),
);
return this.reply({
name,
createConditionHandler = (
data: {
gateName: string;
- } & Omit<Condition, 'id'>
+ } & Omit<Condition, 'id'>,
) => {
const { metric, gateName, op, error } = data;
const qg = this.list.find((q) => q.name === gateName);
};
handleGetProfileProjects = (
- data: RequestData
+ data: RequestData,
): Promise<{
more: boolean;
paging: Paging;
const results = (this.profileProjects[data.key] ?? []).filter(
(project) =>
project.selected ===
- (data.selected !== undefined ? Boolean(data.selected === 'selected') : true)
+ (data.selected !== undefined ? Boolean(data.selected === 'selected') : true),
);
return this.reply({
}
const ancestors = this.listQualityProfile.filter(
- (p) => p.key === profile.parentKey
+ (p) => p.key === profile.parentKey,
) as ProfileInheritanceDetails[];
const children = this.listQualityProfile.filter(
- (p) => p.parentKey === profile.key
+ (p) => p.parentKey === profile.key,
) as ProfileInheritanceDetails[];
return this.reply({
};
handleSearchQualityProfiles = (
- parameters: SearchQualityProfilesParameters = {}
+ parameters: SearchQualityProfilesParameters = {},
): Promise<SearchQualityProfilesResponse> => {
const { language } = parameters;
let profiles = this.listQualityProfile;
const keyFilter = profile.name === this.comparisonResult.left.name ? 'inRight' : 'inLeft';
this.comparisonResult[keyFilter] = this.comparisonResult[keyFilter].filter(
- ({ key }) => key !== data.rule
+ ({ key }) => key !== data.rule,
);
return this.reply(undefined);
// delete Children
const qualityProfileToDelete = this.listQualityProfile.find((profile) => profile.name === name);
this.listQualityProfile = this.listQualityProfile.filter(
- (profile) => profile.parentKey !== qualityProfileToDelete?.key
+ (profile) => profile.parentKey !== qualityProfileToDelete?.key,
);
// delete profile
mockSourceLine({
line: n,
code: ' <span class="sym-35 sym">symbole</span>',
- })
- )
+ }),
+ ),
);
jest.mocked(commentSecurityHotspot).mockImplementation(this.handleCommentSecurityHotspot);
jest
data: {
projectKey: string;
branch?: string;
- }
+ },
) => {
if (data?.branch === 'normal-branch') {
return this.reply({
return this.reply({
paging: mockPaging(),
hotspots: this.mockRawHotspots(false).filter(
- (h) => hotspotKeys.includes(h.key) || hotspotKeys.length === 0
+ (h) => hotspotKeys.includes(h.key) || hotspotKeys.length === 0,
),
components: [
{
handleResetSettingValue = (data: { keys: string; component?: string } & BranchParameters) => {
const setting = this.#settingValues.find((s) => s.key === data.keys) as SettingValue;
const definition = this.#definitions.find(
- (d) => d.key === data.keys
+ (d) => d.key === data.keys,
) as ExtendedSettingDefinition;
if (data.keys === 'sonar.auth.github.userConsentForPermissionProvisioningRequired') {
this.#settingValues = this.#settingValues.filter(
- (s) => s.key !== 'sonar.auth.github.userConsentForPermissionProvisioningRequired'
+ (s) => s.key !== 'sonar.auth.github.userConsentForPermissionProvisioningRequired',
);
} else if (definition.type === SettingType.PROPERTY_SET) {
setting.fieldValues = [];
p?: number;
ps?: number;
to?: string;
- } & BranchParameters
+ } & BranchParameters,
) => {
const { ps = PAGE_SIZE, p = DEFAULT_PAGE } = data;
p?: number;
to?: string;
} & BranchParameters,
- _prev?: TimeMachineResponse
+ _prev?: TimeMachineResponse,
) => {
const { p = DEFAULT_PAGE } = data;
return this.reply({
(user.sonarQubeLastConnectionDate === null ||
isBefore(
new Date(user.sonarQubeLastConnectionDate),
- new Date(sonarQubeLastConnectionDateFrom)
+ new Date(sonarQubeLastConnectionDateFrom),
))
) {
return false;
(user.sonarLintLastConnectionDate === null ||
isBefore(
new Date(user.sonarLintLastConnectionDate),
- new Date(sonarLintLastConnectionDateFrom)
+ new Date(sonarLintLastConnectionDateFrom),
))
) {
return false;
'External Users and Groups Provisioning': 'GitHub',
},
}
- : {}
- )
+ : {},
+ ),
);
};
handleSearchWebhooks = ({ project }: { project?: string }) => {
if (project !== this.project) {
throw new Error(
- 'You are asking for webhooks of a project that is not mocked. Reset first the mock with the correct project'
+ 'You are asking for webhooks of a project that is not mocked. Reset first the mock with the correct project',
);
}
return this.response({
breadcrumbs: [
{ key: PARENT_COMPONENT_KEY, name: 'Foo', qualifier: ComponentQualifier.Project },
],
- })
+ }),
): ComponentTree {
const folderComponent = mockComponent({
key: `${baseComponent.key}:${FOLDER1_KEY}`,
mockSourceLine({
line: n,
code: 'function Test() {}',
- })
+ }),
),
},
{
mockSourceLine({
line: n,
code: 'function Test() {}',
- })
+ }),
),
},
{
mockSourceLine({
line: n,
code: 'function Test() {}',
- })
+ }),
),
},
{
mockSourceLine({
line: n,
code: `\u003cspan class\u003d"cd"\u003eLine ${n}\u003c/span\u003e`,
- })
+ }),
),
},
{
mockSourceLine({
line: n,
code: `\u003cspan class\u003d"cd"\u003eLine ${n}\u003c/span\u003e`,
- })
+ }),
),
},
{
mockSourceLine({
line: n,
code: ' <span class="sym-35 sym">symbole</span>',
- })
+ }),
),
},
] as SourceFile[];
mockSnippetsByComponent(
ISSUE_TO_FILES[ISSUE_101][0],
baseComponentKey,
- times(40, (i) => i + 1)
+ times(40, (i) => i + 1),
),
mockSnippetsByComponent(
ISSUE_TO_FILES[ISSUE_101][1],
baseComponentKey,
- times(40, (i) => i + 1)
+ times(40, (i) => i + 1),
),
],
- 'component.key'
+ 'component.key',
),
},
{
mockSnippetsByComponent(
ISSUE_TO_FILES[ISSUE_11][0],
baseComponentKey,
- times(40, (i) => i + 1)
+ times(40, (i) => i + 1),
),
mockSnippetsByComponent(
ISSUE_TO_FILES[ISSUE_11][1],
baseComponentKey,
- times(40, (i) => i + 1)
+ times(40, (i) => i + 1),
),
],
- 'component.key'
+ 'component.key',
),
},
{
mockSnippetsByComponent(
ISSUE_TO_FILES[ISSUE_1][0],
baseComponentKey,
- times(80, (i) => i + 1)
+ times(80, (i) => i + 1),
),
mockSnippetsByComponent(
ISSUE_TO_FILES[ISSUE_1][0],
baseComponentKey,
- times(80, (i) => i + 1)
+ times(80, (i) => i + 1),
),
],
- 'component.key'
+ 'component.key',
),
},
{
mockSnippetsByComponent(
ISSUE_TO_FILES[ISSUE_2][0],
baseComponentKey,
- times(40, (i) => i + 20)
+ times(40, (i) => i + 20),
),
],
- 'component.key'
+ 'component.key',
),
},
{
mockSnippetsByComponent(
ISSUE_TO_FILES[ISSUE_3][0],
baseComponentKey,
- times(40, (i) => i + 20)
+ times(40, (i) => i + 20),
),
],
- 'component.key'
+ 'component.key',
),
},
{
mockSnippetsByComponent(
ISSUE_TO_FILES[ISSUE_4][0],
baseComponentKey,
- times(40, (i) => i + 20)
+ times(40, (i) => i + 20),
),
],
- 'component.key'
+ 'component.key',
),
},
{
listAllComponentTrees(tree).forEach((tree) => {
measures[tree.component.key] = keyBy(
Object.values(MetricKey).map((metricKey) => mockComponentMeasure(tree, issueList, metricKey)),
- 'metric'
+ 'metric',
);
});
return measures;
.filter(({ component }) => componentKeys.includes(component))
.filter(({ status }) =>
[IssueStatus.Open, IssueStatus.Reopened, IssueStatus.Confirmed].includes(
- status as IssueStatus
- )
+ status as IssueStatus,
+ ),
);
if (isIssueType(metricKey)) {
httpStatus: i % 2 === 0 ? 200 : undefined,
success: i % 2 === 0,
durationMs: 1000 + i * 100,
- })
+ }),
),
];
import { Extension, NavigationComponent } from '../types/types';
export function getComponentNavigation(
- data: { component: string } & BranchParameters
+ data: { component: string } & BranchParameters,
): Promise<NavigationComponent> {
return getJSON('/api/navigation/component', data);
}
export function removeProjectCreatorFromTemplate(
templateId: string,
- permission: string
+ permission: string,
): Promise<void> {
return post('/api/permissions/remove_project_creator_from_template', { templateId, permission });
}
export function changeProjectVisibility(
project: string,
- visibility: Visibility
+ visibility: Visibility,
): Promise<void | Response> {
return post('/api/projects/update_visibility', { project, visibility }).catch(throwGlobalError);
}
export function getInstalledPlugins(type = PluginType.External): Promise<InstalledPlugin[]> {
return getJSON('/api/plugins/installed', { f: 'category', type }).then(
({ plugins }) => plugins,
- throwGlobalError
+ throwGlobalError,
);
}
}
export function bulkDeleteProjects(
- parameters: BaseSearchProjectsParameters
+ parameters: BaseSearchProjectsParameters,
): Promise<void | Response> {
return post('/api/projects/bulk_delete', parameters).catch(throwGlobalError);
}
}
export function changeProjectDefaultVisibility(
- projectVisibility: Visibility
+ projectVisibility: Visibility,
): Promise<void | Response> {
return post('/api/projects/update_default_visibility', { projectVisibility }).catch(
- throwGlobalError
+ throwGlobalError,
);
}
from?: string;
p?: number;
ps?: number;
- } & BranchParameters
+ } & BranchParameters,
): Promise<{ analyses: Analysis[]; paging: Paging }> {
return getJSON('/api/project_analyses/search', data).catch(throwGlobalError);
}
analysis: string,
name: string,
category?: string,
- description?: string
+ description?: string,
): Promise<CreateEventResponse> {
const data: RequestData = { analysis, name };
if (category) {
}
return postJSON('/api/project_analyses/create_event', data).then(
(r) => r.event,
- throwGlobalError
+ throwGlobalError,
);
}
export function changeEvent(
event: string,
name?: string,
- description?: string
+ description?: string,
): Promise<CreateEventResponse> {
const data: RequestData = { event };
if (name) {
}
return postJSON('/api/project_analyses/update_event', data).then(
(r) => r.event,
- throwGlobalError
+ throwGlobalError,
);
}
export function getProjectLinks(projectKey: string): Promise<ProjectLink[]> {
return getJSON('/api/project_links/search', { projectKey }).then(
(r) => r.links,
- throwGlobalError
+ throwGlobalError,
);
}
export function createCondition(
data: {
gateName: string;
- } & Omit<Condition, 'id'>
+ } & Omit<Condition, 'id'>,
): Promise<Condition> {
return postJSON('/api/qualitygates/create_condition', data).catch(throwGlobalError);
}
...qualityGate,
isDefault: qualityGate.default,
}),
- throwGlobalError
+ throwGlobalError,
);
}
data: {
projectKey?: string;
projectId?: string;
- } & BranchParameters
+ } & BranchParameters,
): Promise<QualityGateProjectStatus> {
return getJSON('/api/qualitygates/project_status', data)
.then((r) => r.projectStatus)
}
export function searchQualityProfiles(
- parameters?: SearchQualityProfilesParameters
+ parameters?: SearchQualityProfilesParameters,
): Promise<SearchQualityProfilesResponse> {
return getJSON('/api/qualityprofiles/search', parameters).catch(throwGlobalError);
}
}
export function getProfileProjects(
- data: RequestData
+ data: RequestData,
): Promise<{ more: boolean; paging: Paging; results: ProfileProject[] }> {
return getJSON('/api/qualityprofiles/projects', data).catch(throwGlobalError);
}
export function changeProfileParent(
{ language, name: qualityProfile }: Profile,
- parentProfile?: Profile
+ parentProfile?: Profile,
) {
return post('/api/qualityprofiles/change_parent', {
language,
export function getQualityProfileExporterUrl(
{ key: exporterKey }: Exporter,
- { language, name: qualityProfile }: Profile
+ { language, name: qualityProfile }: Profile,
) {
const queryParams = Object.entries({ exporterKey, language, qualityProfile })
.map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
since: any,
to: any,
{ language, name: qualityProfile }: Profile,
- page?: number
+ page?: number,
): Promise<ChangelogResponse> {
return getJSON('/api/qualityprofiles/changelog', {
since,
}
export function searchGroups(
- parameters: SearchUsersGroupsParameters
+ parameters: SearchUsersGroupsParameters,
): Promise<SearchGroupsResponse> {
return getJSON('/api/qualityprofiles/search_groups', parameters).catch(throwGlobalError);
}
}): Promise<Array<{ key: string; language: string; name: string }>> {
return getJSON('/api/rules/repositories', parameters).then(
({ repositories }) => repositories,
- throwGlobalError
+ throwGlobalError,
);
}
} else {
return throwGlobalError(response);
}
- }
+ },
);
}
export function assignSecurityHotspot(
hotspotKey: string,
- data: HotspotAssignRequest
+ data: HotspotAssignRequest,
): Promise<void> {
return post('/api/hotspots/assign', { hotspot: hotspotKey, ...data }).catch(throwGlobalError);
}
export function setSecurityHotspotStatus(
hotspotKey: string,
- data: HotspotSetStatusRequest
+ data: HotspotSetStatusRequest,
): Promise<void> {
return post('/api/hotspots/change_status', { hotspot: hotspotKey, ...data }).catch(
- throwGlobalError
+ throwGlobalError,
);
}
export function commentSecurityHotspot(hotspotKey: string, comment: string): Promise<void> {
return post('/api/hotspots/add_comment', { hotspot: hotspotKey, comment }).catch(
- throwGlobalError
+ throwGlobalError,
);
}
export function editSecurityHotspotComment(
commentKey: string,
- comment: string
+ comment: string,
): Promise<HotspotComment> {
return post('/api/hotspots/edit_comment', { comment: commentKey, text: comment }).catch(
- throwGlobalError
+ throwGlobalError,
);
}
resolution?: HotspotResolution;
status?: HotspotStatus;
} & BranchParameters,
- projectIsIndexing = false
+ projectIsIndexing = false,
): Promise<HotspotSearchResponse> {
return getJSON(
projectIsIndexing ? HOTSPOTS_LIST_URL : HOTSPOTS_SEARCH_URL,
- projectIsIndexing ? { ...data, project: data.projectKey } : data
+ projectIsIndexing ? { ...data, project: data.projectKey } : data,
).catch(throwGlobalError);
}
data: {
projectKey: string;
} & BranchParameters,
- projectIsIndexing = false
+ projectIsIndexing = false,
): Promise<HotspotSearchResponse> {
return getJSON(projectIsIndexing ? HOTSPOTS_LIST_URL : HOTSPOTS_SEARCH_URL, {
...data,
export function getDefinitions(component?: string): Promise<ExtendedSettingDefinition[]> {
return getJSON('/api/settings/list_definitions', { component }).then(
(r) => r.definitions,
- throwGlobalError
+ throwGlobalError,
);
}
export function getValue(
- data: { key: string; component?: string } & BranchParameters
+ data: { key: string; component?: string } & BranchParameters,
): Promise<SettingValue> {
return getValues({ keys: [data.key], component: data.component }).then(([result]) => result);
}
export function getValues(
- data: { keys: string[]; component?: string } & BranchParameters
+ data: { keys: string[]; component?: string } & BranchParameters,
): Promise<SettingValue[]> {
return getJSON('/api/settings/values', {
keys: data.keys.join(','),
}
export function getAllValues(
- data: { component?: string } & BranchParameters = {}
+ data: { component?: string } & BranchParameters = {},
): Promise<SettingValue[]> {
return getJSON('/api/settings/values', data).then((r: SettingValueResponse) => [
...r.settings,
export function setSettingValue(
definition: SettingDefinition,
value: any,
- component?: string
+ component?: string,
): Promise<void> {
const { key } = definition;
const data: RequestData = { key, component };
}
export function setSimpleSettingValue(
- data: { component?: string; value: string; key: string } & BranchParameters
+ data: { component?: string; value: string; key: string } & BranchParameters,
): Promise<void | Response> {
return post('/api/settings/set', data).catch(throwGlobalError);
}
export function resetSettingValue(
- data: { keys: string; component?: string } & BranchParameters
+ data: { keys: string; component?: string } & BranchParameters,
): Promise<void> {
return post('/api/settings/reset', data);
}
return requestTryAndRepeatUntil(
getSystemStatus,
{ max: -1, slowThreshold: -15 },
- ({ status }) => status === 'UP'
+ ({ status }) => status === 'UP',
);
}
p?: number;
ps?: number;
to?: string;
- } & BranchParameters
+ } & BranchParameters,
): Promise<TimeMachineResponse> {
return getJSON('/api/measures/search_history', data).catch(throwGlobalError);
}
p?: number;
to?: string;
} & BranchParameters,
- prev?: TimeMachineResponse
+ prev?: TimeMachineResponse,
): Promise<TimeMachineResponse> {
return getTimeMachineData({ ...data, ps: 1000 }).then((r) => {
const result = prev
export function fetchResponseExample(domain: string, action: string): Promise<WebApi.Example> {
return getJSON('/api/webservices/response_example', { controller: domain, action }).catch(
- throwGlobalError
+ throwGlobalError,
);
}
fetchNavigationSettings = () => {
getSettingsNavigation().then(
(r) => this.setState({ adminPages: r.extensions }),
- () => {}
+ () => {},
);
};
this.setState({ pendingPlugins });
}
},
- () => {}
+ () => {},
);
};
}
}
},
- () => {}
+ () => {},
);
};
window.location.reload();
}
},
- () => {}
+ () => {},
);
};
defer={false}
titleTemplate={translateWithParameters(
'page_title.template.with_category',
- translate('layout.settings')
+ translate('layout.settings'),
)}
/>
<SettingsNav
if (shouldRedirectToDashboard && this.props.location.pathname.includes('tutorials')) {
this.props.router.replace(getProjectUrl(key));
}
- }
+ },
);
this.fetchStatus(componentWithQualifier.key);
newTasksInProgress,
currentTask,
newCurrentTask,
- component
+ component,
);
shouldRedirectToDashboard =
this.watchStatusTimer = window.setTimeout(
() => this.fetchStatus(componentKey),
- FETCH_STATUS_WAIT_TIME
+ FETCH_STATUS_WAIT_TIME,
);
}
if (shouldFetchComponent) {
this.fetchComponent(shouldRedirectToDashboard);
}
- }
+ },
);
}
},
- () => {}
+ () => {},
);
};
this.props.hasFeature(Feature.BranchSupport)
) {
const projectBindingErrors = await validateProjectAlmBinding(component.key).catch(
- () => undefined
+ () => undefined,
);
if (this.mounted) {
newTasksInProgress: Task[],
currentTask: Task | undefined,
newCurrentTask: Task | undefined,
- component: Component | undefined
+ component: Component | undefined,
) => {
const progressHasChanged = Boolean(
tasksInProgress &&
(newTasksInProgress.length !== tasksInProgress.length ||
- differenceBy(newTasksInProgress, tasksInProgress, 'id').length > 0)
+ differenceBy(newTasksInProgress, tasksInProgress, 'id').length > 0),
);
const currentTaskHasChanged = Boolean(
(!currentTask && newCurrentTask) ||
- (currentTask && newCurrentTask && currentTask.id !== newCurrentTask.id)
+ (currentTask && newCurrentTask && currentTask.id !== newCurrentTask.id),
);
if (progressHasChanged) {
needsAnotherCheck = (
shouldFetchComponent: boolean,
component: Component | undefined,
- newTasksInProgress: Task[]
+ newTasksInProgress: Task[],
) => {
return (
!shouldFetchComponent &&
defer={false}
titleTemplate={translateWithParameters(
'page_title.template.with_instance',
- component?.name ?? ''
+ component?.name ?? '',
)}
/>
{component &&
isPending={isPending}
projectBindingErrors={projectBindingErrors}
/>,
- this.portalAnchor
+ this.portalAnchor,
)}
{loading ? (
<div className="page page-limited">
<FormattedMessage
id="settings.authentication.github.synchronization_successful.with_warning"
defaultMessage={translate(
- 'settings.authentication.github.synchronization_successful.with_warning'
+ 'settings.authentication.github.synchronization_successful.with_warning',
)}
values={{
date: formattedDate,
) : (
translateWithParameters(
'settings.authentication.github.synchronization_successful',
- formattedDate
+ formattedDate,
)
)}
</i>
<>
{translateWithParameters(
'settings.authentication.github.synchronization_successful',
- formattedDate
+ formattedDate,
)}
<br />
{summary ?? ''}
<div>
{translateWithParameters(
'settings.authentication.github.synchronization_failed',
- formattedDate
+ formattedDate,
)}
</div>
<br />
translate(
data.nextSync.status === TaskStatuses.Pending
? 'settings.authentication.github.synchronization_pending'
- : 'settings.authentication.github.synchronization_in_progress'
+ : 'settings.authentication.github.synchronization_in_progress',
)}
</Alert>
className={classNames('page-wrapper', {
'new-background': TEMP_PAGELIST_WITH_NEW_BACKGROUND.includes(location.pathname),
'white-background': TEMP_PAGELIST_WITH_NEW_BACKGROUND_WHITE.includes(
- location.pathname
+ location.pathname,
),
})}
id="container"
<code key={k} className="little-spacer-right">
{k}
</code>
- )
+ ),
)}
</td>
<td>{translate('keyboard_shortcuts', category, action)}</td>
const newTokenName = await getNextAvailableTokenName(login, `${TOKEN_PREFIX}-${ideName}`);
const expirationDate = await computeExpirationDate();
const token = await generateToken({ name: newTokenName, login, expirationDate }).catch(
- () => undefined
+ () => undefined,
);
if (!token) {
},
})}
{...props}
- />
+ />,
);
}
expect(await ui.portfolioTitle.find()).toHaveAttribute('href', '/portfolio?id=portfolioKey');
expect(ui.issuesPageLink.get()).toHaveAttribute(
'href',
- '/project/issues?id=portfolioKey&resolved=false'
+ '/project/issues?id=portfolioKey&resolved=false',
);
expect(ui.measuresPageLink.get()).toHaveAttribute('href', '/component_measures?id=portfolioKey');
expect(ui.activityPageLink.get()).toHaveAttribute('href', '/project/activity?id=portfolioKey');
expect(ui.overviewPageLink.get()).toHaveAttribute('href', '/dashboard?id=project-key');
expect(ui.issuesPageLink.get()).toHaveAttribute(
'href',
- '/project/issues?id=project-key&resolved=false'
+ '/project/issues?id=project-key&resolved=false',
);
expect(ui.hotspotsPageLink.get()).toHaveAttribute('href', '/security_hotspots?id=project-key');
expect(ui.measuresPageLink.get()).toHaveAttribute('href', '/component_measures?id=project-key');
renderComponentContainerAsComponent({ hasFeature: jest.fn().mockReturnValue(true) });
expect(
- await screen.findByText('component_navigation.pr_deco.error_detected_X', { exact: false })
+ await screen.findByText('component_navigation.pr_deco.error_detected_X', { exact: false }),
).toBeInTheDocument();
});
});
await waitFor(() => {
expect(validateProjectAlmBinding).not.toHaveBeenCalled();
});
- }
+ },
);
function renderComponentContainerAsComponent(props: Partial<Props> = {}) {
router={mockRouter()}
{...props}
/>
- </>
+ </>,
);
}
breadcrumbs: [
{ key: 'portfolioKey', name: 'portfolio', qualifier: ComponentQualifier.Portfolio },
],
- })
+ }),
)
}
type="button"
expect(await screen.findByRole('link')).toHaveAttribute(
'href',
- 'https://docs.sonarsource.com/sonarqube/10.0/land'
+ 'https://docs.sonarsource.com/sonarqube/10.0/land',
);
});
expect(await screen.findByRole('link')).toHaveAttribute(
'href',
- 'https://docs.sonarsource.com/sonarqube/latest/land'
+ 'https://docs.sonarsource.com/sonarqube/latest/land',
);
});
renderAppRoutes(
`documentation/${navigate}`,
() => <Route path="/documentation/*" element={<DocumentationRedirect />} />,
- { appState: mockAppState({ version }) }
+ { appState: mockAppState({ version }) },
);
}
function renderGlobalFooter(
props: Partial<FCProps<typeof GlobalFooter>> = {},
- appStateOverride: Partial<AppState> = {}
+ appStateOverride: Partial<AppState> = {},
) {
return renderComponent(<GlobalFooter {...props} />, '/', {
appState: mockAppState({
<>
<KeyboardShortcutsModal />
<input type="text" />
- </>
+ </>,
);
}
renderMigrationContainer();
expect(
- byText('/maintenance?return_to=%2Fprojects%3Fquery%3Dtoto%23hash').get()
+ byText('/maintenance?return_to=%2Fprojects%3Fquery%3Dtoto%23hash').get(),
).toBeInTheDocument();
});
it('should render correctly for an user that does not have access to all children', () => {
renderNonAdminPagesContainer(
- mockComponent({ qualifier: ComponentQualifier.Application, canBrowseAllChildProjects: false })
+ mockComponent({ qualifier: ComponentQualifier.Application, canBrowseAllChildProjects: false }),
);
expect(screen.getByText('application.cannot_access_all_child_projects1')).toBeInTheDocument();
});
</Route>
</Routes>
</MemoryRouter>
- </ComponentContext.Provider>
+ </ComponentContext.Provider>,
);
}
currentUser={mockLoggedInUser({ permissions: { global: ['admin'] } })}
router={mockRouter()}
{...props}
- />
+ />,
);
}
RecentHistory.add('bar', 'Bar', 'VW');
expect(save).toHaveBeenCalledWith(
'sonar_recent_history',
- JSON.stringify([{ key: 'bar', name: 'Bar', icon: 'VW' }, ...history])
+ JSON.stringify([{ key: 'bar', name: 'Bar', icon: 'VW' }, ...history]),
);
});
RecentHistory.add('bar', 'Bar', 'VW');
expect(save).toHaveBeenCalledWith(
'sonar_recent_history',
- JSON.stringify([{ key: 'bar', name: 'Bar', icon: 'VW' }, ...history.slice(0, 9)])
+ JSON.stringify([{ key: 'bar', name: 'Bar', icon: 'VW' }, ...history.slice(0, 9)]),
);
});
RecentHistory.remove('key-5');
expect(save).toHaveBeenCalledWith(
'sonar_recent_history',
- JSON.stringify([...history.slice(0, 5), ...history.slice(6)])
+ JSON.stringify([...history.slice(0, 5), ...history.slice(6)]),
);
});
renderSonarLintConnection();
expect(
- await screen.findByRole('heading', { name: 'sonarlint-connection.request.title' })
+ await screen.findByRole('heading', { name: 'sonarlint-connection.request.title' }),
).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'sonarlint-connection.request.action' }));
expect(
- await screen.findByText('sonarlint-connection.success.description', { exact: false })
+ await screen.findByText('sonarlint-connection.success.description', { exact: false }),
).toBeInTheDocument();
});
renderSonarLintConnection();
await user.click(
- await screen.findByRole('button', { name: 'sonarlint-connection.request.action' })
+ await screen.findByRole('button', { name: 'sonarlint-connection.request.action' }),
);
expect(
- await screen.findByText('sonarlint-connection.token-error.description')
+ await screen.findByText('sonarlint-connection.token-error.description'),
).toBeInTheDocument();
});
renderSonarLintConnection();
await user.click(
- await screen.findByRole('button', { name: 'sonarlint-connection.request.action' })
+ await screen.findByRole('button', { name: 'sonarlint-connection.request.action' }),
);
expect(
- await screen.findByText('sonarlint-connection.connection-error.description')
+ await screen.findByText('sonarlint-connection.connection-error.description'),
).toBeInTheDocument();
const tokenValue = tokenMock.getLastToken()?.token ?? '';
renderSonarLintConnection({ port: '' });
await user.click(
- await screen.findByRole('button', { name: 'sonarlint-connection.request.action' })
+ await screen.findByRole('button', { name: 'sonarlint-connection.request.action' }),
);
expect(
- await screen.findByText('sonarlint-connection.connection-error.description')
+ await screen.findByText('sonarlint-connection.connection-error.description'),
).toBeInTheDocument();
});
{...props}
>
<div />
- </StartupModal>
+ </StartupModal>,
);
}
return renderComponent(
<AvailableFeaturesContext.Provider value={[Feature.Announcement]}>
<SystemAnnouncement />
- </AvailableFeaturesContext.Provider>
+ </AvailableFeaturesContext.Provider>,
);
}
import { AdminPagesContext } from '../../../types/admin';
export default function withAdminPagesOutletContext(
- WrappedComponent: React.ComponentType<AdminPagesContext>
+ WrappedComponent: React.ComponentType<AdminPagesContext>,
) {
return function WithAdminPagesOutletContext() {
const { adminPages } = useOutletContext<AdminPagesContext>();
}
export default function withAppStateContext<P>(
- WrappedComponent: React.ComponentType<P & WithAppStateContextProps>
+ WrappedComponent: React.ComponentType<P & WithAppStateContextProps>,
) {
return class WithAppStateContext extends React.PureComponent<
Omit<P, keyof WithAppStateContextProps>
}
export default function withAvailableFeatures<P>(
- WrappedComponent: React.ComponentType<P & WithAvailableFeaturesProps>
+ WrappedComponent: React.ComponentType<P & WithAvailableFeaturesProps>,
) {
return class WithAvailableFeatures extends React.PureComponent<
Omit<P, keyof WithAvailableFeaturesProps>
import { ComponentContext } from './ComponentContext';
export default function withComponentContext<P extends Partial<ComponentContextShape>>(
- WrappedComponent: React.ComponentType<P>
+ WrappedComponent: React.ComponentType<P>,
) {
return class WithComponentContext extends React.PureComponent<
Omit<P, keyof ComponentContextShape>
import { CurrentUserContext, CurrentUserContextInterface } from './CurrentUserContext';
export default function withCurrentUserContext<P>(
- WrappedComponent: React.ComponentType<P & Pick<CurrentUserContextInterface, 'currentUser'>>
+ WrappedComponent: React.ComponentType<P & Pick<CurrentUserContextInterface, 'currentUser'>>,
) {
return class WithCurrentUserContext extends React.PureComponent<
Omit<P, 'currentUser' | 'updateCurrentUserHomepage' | 'updateDismissedNotices'>
}
export default injectIntl(
- withRouter(withTheme(withAppStateContext(withCurrentUserContext(withQueryClient(Extension)))))
+ withRouter(withTheme(withAppStateContext(withCurrentUserContext(withQueryClient(Extension))))),
);
component &&
component.configuration &&
(component.configuration.extensions || []).find(
- (p) => p.key === `${pluginKey}/${extensionKey}`
+ (p) => p.key === `${pluginKey}/${extensionKey}`,
);
return extension ? (
</button>
</div>
);
- }
+ },
);
getEnhancedWindow().registerExtension(
el.innerHTML = '';
};
}
- }
+ },
);
getEnhancedWindow().registerExtension('second-extension', () => {
await user.click(screen.getByRole('button', { name: 'Click first react' }));
expect(
- await screen.findByRole('button', { name: 'Click first react change' })
+ await screen.findByRole('button', { name: 'Click first react change' }),
).toBeInTheDocument();
});
function renderGlobalPageExtension(
navigateTo: string,
globalPages: Extension[] = [],
- params?: GlobalPageExtensionProps['params']
+ params?: GlobalPageExtensionProps['params'],
) {
renderApp(`extension/:pluginKey/:extensionKey`, <GlobalPageExtension params={params} />, {
appState: mockAppState({ globalPages }),
mockComponent({
configuration: { extensions: [{ key: 'pluginId/extensionId', name: 'name' }] },
}),
- { pluginKey: 'pluginId', extensionKey: 'extensionId' }
+ { pluginKey: 'pluginId', extensionKey: 'extensionId' },
);
expect(getExtensionStart).toHaveBeenCalledWith('pluginId/extensionId');
});
it('should render correctly when the extension is not found', () => {
renderProjectAdminPageExtension(
mockComponent({ extensions: [{ key: 'pluginId/extensionId', name: 'name' }] }),
- { pluginKey: 'not-found-plugin', extensionKey: 'not-found-extension' }
+ { pluginKey: 'not-found-plugin', extensionKey: 'not-found-extension' },
);
expect(screen.getByText('page_not_found')).toBeInTheDocument();
});
params: {
extensionKey: string;
pluginKey: string;
- }
+ },
) {
const { pluginKey, extensionKey } = params;
const queryClient = new QueryClient();
</ComponentContext.Provider>
</IntlProvider>
</HelmetProvider>
- </QueryClientProvider>
+ </QueryClientProvider>,
);
}
it('should render correctly when the extension is found', async () => {
renderProjectPageExtension(
mockComponent({ extensions: [{ key: 'pluginId/extensionId', name: 'name' }] }),
- { params: { pluginKey: 'pluginId', extensionKey: 'extensionId' } }
+ { params: { pluginKey: 'pluginId', extensionKey: 'extensionId' } },
);
await waitFor(() => expect(getExtensionStart).toHaveBeenCalledWith('pluginId/extensionId'));
});
it('should render correctly when the extension is not found', async () => {
renderProjectPageExtension(
mockComponent({ extensions: [{ key: 'pluginId/extensionId', name: 'name' }] }),
- { params: { pluginKey: 'not-found-plugin', extensionKey: 'not-found-extension' } }
+ { params: { pluginKey: 'not-found-plugin', extensionKey: 'not-found-extension' } },
);
expect(await screen.findByText('page_not_found')).toBeInTheDocument();
});
function renderProjectPageExtension(
component?: Component,
- props?: Partial<ProjectPageExtensionProps>
+ props?: Partial<ProjectPageExtensionProps>,
) {
const queryClient = new QueryClient();
return render(
</ComponentContext.Provider>
</IntlProvider>
</HelmetProvider>
- </QueryClientProvider>
+ </QueryClientProvider>,
);
}
)}
<ItemDivider />
</ul>
- </li>
+ </li>,
);
}
});
static shouldDisplayCompletedNotification() {
return JSON.parse(
- get(LS_INDEXATION_COMPLETED_NOTIFICATION_SHOULD_BE_DISPLAYED) || false.toString()
+ get(LS_INDEXATION_COMPLETED_NOTIFICATION_SHOULD_BE_DISPLAYED) || false.toString(),
);
}
}
values={{
link: renderBackgroundTasksPageLink(
true,
- translate('indexation.completed_with_error.link')
+ translate('indexation.completed_with_error.link'),
),
}}
/>
{translateWithParameters(
'indexation.progression',
completedCount.toString(),
- total.toString()
+ total.toString(),
)}
</span>
defaultMessage={translateWithParameters(
'indexation.progression_with_error',
completedCount.toString(),
- total.toString()
+ total.toString(),
)}
values={{
link: renderBackgroundTasksPageLink(
true,
- translate('indexation.progression_with_error.link')
+ translate('indexation.progression_with_error.link'),
),
}}
/>
<span className="sw-ml-1">
<FormattedMessage
defaultMessage={translate(
- 'indexation.page_unavailable.description.additional_information'
+ 'indexation.page_unavailable.description.additional_information',
)}
id="indexation.page_unavailable.description.additional_information"
values={{
return renderComponent(
<IndexationContextProvider appState={mockAppState({ needIssueSync: true, ...props?.appState })}>
<TestComponent />
- </IndexationContextProvider>
+ </IndexationContextProvider>,
);
}
indexationContext={{
status: { completedCount: 23, hasFailures: false, isCompleted: true, total: 42 },
}}
- />
+ />,
);
expect(IndexationNotificationHelper.shouldDisplayCompletedNotification).toHaveBeenCalled();
indexationContext={{
status: { completedCount: 23, hasFailures: true, isCompleted: false, total: 42 },
}}
- />
+ />,
);
expect(byText('indexation.progression_with_error').get()).toBeInTheDocument();
indexationContext={{
status: { completedCount: 23, hasFailures: true, isCompleted: true, total: 42 },
}}
- />
+ />,
);
expect(byText('indexation.completed_with_error').get()).toBeInTheDocument();
});
indexationContext={{
status: { completedCount: 23, hasFailures: false, isCompleted: true, total: 42 },
}}
- />
+ />,
);
expect(IndexationNotificationHelper.shouldDisplayCompletedNotification).toHaveBeenCalled();
});
status: { completedCount: 23, hasFailures: false, isCompleted: false, total: 42 },
}}
{...props}
- />
+ />,
);
}
indexationContext={{
status: { hasFailures: true, isCompleted: true },
}}
- />
+ />,
);
expect(reload).not.toHaveBeenCalled();
indexationContext={{
status: { hasFailures: false, isCompleted: true },
}}
- />
+ />,
);
expect(reload).toHaveBeenCalled();
indexationContext={{
status: { completedCount: 23, hasFailures: false, isCompleted: false, total: 42 },
}}
- />
+ />,
);
}
return renderComponent(
<LanguagesContextProvider>
<Consumer />
- </LanguagesContextProvider>
+ </LanguagesContextProvider>,
);
}
}
export default function withLanguagesContext<P>(
- WrappedComponent: React.ComponentType<P & WithLanguagesContextProps>
+ WrappedComponent: React.ComponentType<P & WithLanguagesContextProps>,
) {
return class WithLanguagesContext extends React.PureComponent<
Omit<P, keyof WithLanguagesContextProps>
return renderComponent(
<MetricsContextProvider>
<Consumer />
- </MetricsContextProvider>
+ </MetricsContextProvider>,
);
}
}
export default function withMetricsContext<P>(
- WrappedComponent: React.ComponentType<P & WithMetricsContextProps>
+ WrappedComponent: React.ComponentType<P & WithMetricsContextProps>,
) {
return class WithMetricsContext extends React.PureComponent<
Omit<P, keyof WithMetricsContextProps>
<>
{translateWithParameters(
'component_navigation.status.last_blocked_due_to_bad_license_X',
- translate('qualifier', currentTask.componentQualifier ?? ComponentQualifier.Project)
+ translate('qualifier', currentTask.componentQualifier ?? ComponentQualifier.Project),
)}
</>
);
}
export default function ComponentNavProjectBindingErrorNotif(
- props: ComponentNavProjectBindingErrorNotifProps
+ props: ComponentNavProjectBindingErrorNotifProps,
) {
const { component } = props;
let action;
};
const isGovernanceEnabled = extensions.some((extension) =>
- extension.key.startsWith('governance/')
+ extension.key.startsWith('governance/'),
);
const getQuery = (): Query => {
<Tooltip
overlay={translateWithParameters(
'layout.all_project_must_be_accessible',
- translate('qualifier', qualifier)
+ translate('qualifier', qualifier),
)}
>
<a aria-disabled="true" className="disabled-link">
}
const hasSecurityReportsEnabled = extensions.some((extension) =>
- extension.key.startsWith('securityreport/')
+ extension.key.startsWith('securityreport/'),
);
if (!hasSecurityReportsEnabled) {
query,
isProject(qualifier),
isApplication(qualifier),
- isPortfolioLike(qualifier)
+ isPortfolioLike(qualifier),
);
if (!adminLinks.some((link) => link != null)) {
return null;
query: Query,
isProject: boolean,
isApplication: boolean,
- isPortfolio: boolean
+ isPortfolio: boolean,
) => {
return [
renderSettingsLink(query, isApplication, isPortfolio),
const query = getQuery();
const withoutSecurityExtension = extensions.filter(
(extension) =>
- !extension.key.startsWith('securityreport/') && !extension.key.startsWith('governance/')
+ !extension.key.startsWith('securityreport/') && !extension.key.startsWith('governance/'),
);
if (withoutSecurityExtension.length === 0) {
currentTask: mockTask({ pullRequest: '01', pullRequestTitle: 'Fix stuff' }),
},
undefined,
- 'pullRequest=01&id=my-project'
+ 'pullRequest=01&id=my-project',
);
expect(await screen.findByText(/component_navigation.status.failed_X/)).toBeInTheDocument();
{
component: mockComponent({ configuration: { showBackgroundTasks: true } }),
},
- 'project/background_tasks'
+ 'project/background_tasks',
);
expect(screen.getByText(/component_navigation.status.failed_X.admin.help/)).toBeInTheDocument();
function renderAnalysisErrorMessage(
overrides: Partial<Parameters<typeof AnalysisErrorMessage>[0]> = {},
location = '/',
- params?: string
+ params?: string,
) {
return renderApp(
location,
onLeave={jest.fn()}
{...overrides}
/>,
- { navigateTo: params ? `/?${params}` : undefined, featureList: [Feature.BranchSupport] }
+ { navigateTo: params ? `/?${params}` : undefined, featureList: [Feature.BranchSupport] },
);
}
expect(
await screen.findByText(
- 'component_navigation.status.last_blocked_due_to_bad_license_X.qualifier.TRK'
- )
+ 'component_navigation.status.last_blocked_due_to_bad_license_X.qualifier.TRK',
+ ),
).toBeInTheDocument();
});
{
currentTask: mockTask({ errorMessage, errorType: 'error-type' }),
},
- true
+ true,
);
expect(
- await screen.findByText('license.component_navigation.button.error-type.')
+ await screen.findByText('license.component_navigation.button.error-type.'),
).toBeInTheDocument();
expect(screen.getByText(errorMessage)).toBeInTheDocument();
});
function renderAnalysisLicenseError(
overrides: Partial<Parameters<typeof AnalysisLicenseError>[0]> = {},
- canAdmin = false
+ canAdmin = false,
) {
return renderApp('/', <AnalysisLicenseError currentTask={mockTask()} {...overrides} />, {
appState: mockAppState({ canAdmin }),
it('renders correctly when there is a background task in progress', () => {
renderComponentNav({ isInProgress: true });
expect(
- screen.getByText('project_navigation.analysis_status.in_progress', { exact: false })
+ screen.getByText('project_navigation.analysis_status.in_progress', { exact: false }),
).toBeInTheDocument();
});
it('renders correctly when there is a background task pending', () => {
renderComponentNav({ isPending: true });
expect(
- screen.getByText('project_navigation.analysis_status.pending', { exact: false })
+ screen.getByText('project_navigation.analysis_status.pending', { exact: false }),
).toBeInTheDocument();
});
it('renders correctly when there is a failing background task', () => {
renderComponentNav({ currentTask: mockTask({ status: TaskStatuses.Failed }) });
expect(
- screen.getByText('project_navigation.analysis_status.failed', { exact: false })
+ screen.getByText('project_navigation.analysis_status.failed', { exact: false }),
).toBeInTheDocument();
});
projectBindingErrors: mockProjectAlmBindingConfigurationErrors(),
});
expect(
- screen.getByText('component_navigation.pr_deco.error_detected_X', { exact: false })
+ screen.getByText('component_navigation.pr_deco.error_detected_X', { exact: false }),
).toBeInTheDocument();
});
isInProgress={false}
isPending={false}
{...props}
- />
+ />,
);
}
expect(
screen.queryByRole('link', {
name: 'component_navigation.pr_deco.action.check_project_settings',
- })
+ }),
).not.toBeInTheDocument();
});
component: mockComponent({ configuration: { showSettings: true } }),
});
expect(
- screen.getByRole('link', { name: 'component_navigation.pr_deco.action.check_project_settings' })
+ screen.getByRole('link', {
+ name: 'component_navigation.pr_deco.action.check_project_settings',
+ }),
).toBeInTheDocument();
});
function renderComponentNavProjectBindingErrorNotif(
- props: Partial<ComponentNavProjectBindingErrorNotifProps> = {}
+ props: Partial<ComponentNavProjectBindingErrorNotifProps> = {},
) {
return renderComponent(
- <ComponentNavProjectBindingErrorNotif component={mockComponent()} {...props} />
+ <ComponentNavProjectBindingErrorNotif component={mockComponent()} {...props} />,
);
}
expect(await screen.findByLabelText('help-tooltip')).toBeInTheDocument();
expect(screen.getByText('project')).toBeInTheDocument();
expect(
- await screen.findByRole('button', { name: 'master overview.quality_gate_x.OK' })
+ await screen.findByRole('button', { name: 'master overview.quality_gate_x.OK' }),
).toBeDisabled();
});
renderHeader();
expect(
- await screen.findByRole('button', { name: 'main overview.quality_gate_x.OK' })
+ await screen.findByRole('button', { name: 'main overview.quality_gate_x.OK' }),
).toBeEnabled();
expect(screen.queryByLabelText('help-tooltip')).not.toBeInTheDocument();
expect(
screen.getByRole('menuitem', {
name: '03 – TEST-193 dumb commit overview.quality_gate_x.ERROR ERROR',
- })
+ }),
).toBeInTheDocument();
expect(
screen.getByRole('menuitem', {
name: '01 – TEST-191 update master overview.quality_gate_x.OK OK',
- })
+ }),
).toBeInTheDocument();
expect(
- screen.getByRole('menuitem', { name: 'normal-branch overview.quality_gate_x.ERROR ERROR' })
+ screen.getByRole('menuitem', { name: 'normal-branch overview.quality_gate_x.ERROR ERROR' }),
).toBeInTheDocument();
await user.click(
- screen.getByRole('menuitem', { name: 'normal-branch overview.quality_gate_x.ERROR ERROR' })
+ screen.getByRole('menuitem', { name: 'normal-branch overview.quality_gate_x.ERROR ERROR' }),
);
expect(screen.getByText('/dashboard?branch=normal-branch&id=header-project')).toBeInTheDocument();
});
expect(screen.getByRole('link', { name: 'branch_like_navigation.manage' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'branch_like_navigation.manage' })).toHaveAttribute(
'href',
- '/project/branches?id=header-project'
+ '/project/branches?id=header-project',
);
});
await user.click(screen.getByRole('button', { name: 'favorite.action.TRK.add' }));
expect(
- await screen.findByRole('button', { name: 'favorite.action.TRK.remove' })
+ await screen.findByRole('button', { name: 'favorite.action.TRK.remove' }),
).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'favorite.action.TRK.remove' }));
currentUser: mockLoggedInUser(),
},
undefined,
- 'pullRequest=1001&id=compa'
+ 'pullRequest=1001&id=compa',
);
const image = await screen.findByAltText(alm);
expect(image).toBeInTheDocument();
expect(image).toHaveAttribute('src', `/images/alm/${alm}.svg`);
- }
+ },
);
it('should show the correct help tooltip for applications', async () => {
{
currentUser: mockLoggedInUser(),
},
- []
+ [],
);
expect(
- await screen.findByText('branch_like_navigation.no_branch_support.title.mr')
+ await screen.findByText('branch_like_navigation.no_branch_support.title.mr'),
).toBeInTheDocument();
expect(
- screen.getByText('branch_like_navigation.no_branch_support.content_x.mr.alm.gitlab')
+ screen.getByText('branch_like_navigation.no_branch_support.content_x.mr.alm.gitlab'),
).toBeInTheDocument();
});
function renderHeader(
props?: Partial<HeaderProps>,
featureList = [Feature.BranchSupport],
- params?: string
+ params?: string,
) {
return renderApp(
'/',
currentUser={mockCurrentUser()}
{...props}
/>,
- { featureList, navigateTo: params ? `/?id=header-project&${params}` : '/?id=header-project' }
+ { featureList, navigateTo: params ? `/?id=header-project&${params}` : '/?id=header-project' },
);
}
expect(await screen.findByText('version_x.0.0.1')).toBeInTheDocument();
expect(
- await screen.findByText('project_navigation.analysis_status.warnings')
+ await screen.findByText('project_navigation.analysis_status.warnings'),
).toBeInTheDocument();
await user.click(screen.getByText('project_navigation.analysis_status.details_link'));
renderHeaderMeta({}, undefined, 'pullRequest=01&id=my-project');
expect(
- await screen.findByText('branch_like_navigation.for_merge_into_x_from_y')
+ await screen.findByText('branch_like_navigation.for_merge_into_x_from_y'),
).toBeInTheDocument();
expect(screen.queryByText('version_x.0.0.1')).not.toBeInTheDocument();
});
function renderHeaderMeta(
props: Partial<HeaderMetaProps> = {},
currentUser: CurrentUser = mockLoggedInUser(),
- params?: string
+ params?: string,
) {
return renderApp('/', <HeaderMeta component={mockComponent({ version: '0.0.1' })} {...props} />, {
currentUser,
extensions: [{ key: 'component-foo', name: 'ComponentFoo' }],
},
},
- 'branch=normal-branch'
+ 'branch=normal-branch',
);
expect(await screen.findByRole('link', { name: 'overview.page' })).toBeInTheDocument();
extensions: [{ key: 'component-foo', name: 'ComponentFoo' }],
},
},
- 'pullRequest=01'
+ 'pullRequest=01',
);
expect(await screen.findByRole('link', { name: 'overview.page' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'layout.measures' })).toBeInTheDocument();
expect(
- screen.queryByRole('link', { name: `layout.settings.${ComponentQualifier.Project}` })
+ screen.queryByRole('link', { name: `layout.settings.${ComponentQualifier.Project}` }),
).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'project.info.title' })).not.toBeInTheDocument();
});
{...props}
/>,
params ? `/?${params}` : '/',
- { featureList: [Feature.BranchSupport] }
+ { featureList: [Feature.BranchSupport] },
);
}
expect(
getCurrentPage(
mockComponent({ key: 'foo', qualifier: ComponentQualifier.Portfolio }),
- undefined
- )
+ undefined,
+ ),
).toEqual({
type: 'PORTFOLIO',
component: 'foo',
expect(
getCurrentPage(
mockComponent({ key: 'foo', qualifier: ComponentQualifier.SubPortfolio }),
- undefined
- )
+ undefined,
+ ),
).toEqual({
type: 'PORTFOLIO',
component: 'foo',
expect(
getCurrentPage(
mockComponent({ key: 'foo', qualifier: ComponentQualifier.Application }),
- mockBranch({ name: 'develop' })
- )
+ mockBranch({ name: 'develop' }),
+ ),
).toEqual({ type: 'APPLICATION', component: 'foo', branch: 'develop' });
});
projectBinding != null
? translateWithParameters(
`branch_like_navigation.no_branch_support.content_x.${isGitLab ? 'mr' : 'pr'}`,
- translate('alm', projectBinding.alm)
+ translate('alm', projectBinding.alm),
)
: translate('branch_like_navigation.no_branch_support.content')
}
title={translateWithParameters(
'branch_like_navigation.for_merge_into_x_from_y.title',
currentBranchLike.target,
- currentBranchLike.branch
+ currentBranchLike.branch,
)}
>
<FormattedMessage
highlightSiblingBranchlike = (indexDelta: number) => {
const selectBranchLikeIndex = this.state.branchLikesToDisplay.findIndex((b) =>
- isSameBranchLike(b, this.state.selectedBranchLike)
+ isSameBranchLike(b, this.state.selectedBranchLike),
);
const newIndex = selectBranchLikeIndex + indexDelta;
isPullRequest(pr) && (pr.title.toLowerCase().includes(q) || pr.key.toLowerCase().includes(q));
const filteredBranchLikes = this.props.branchLikes.filter(
- (bl) => filterBranch(bl) || filterPullRequest(bl)
+ (bl) => filterBranch(bl) || filterPullRequest(bl),
);
this.setState({
render() {
const governanceInstalled = this.props.appState.qualifiers.includes(
- ComponentQualifier.Portfolio
+ ComponentQualifier.Portfolio,
);
return (
renderConfigurationTab() {
const extensionsWithoutSupport = this.props.extensions.filter(
- (extension) => extension.key !== 'license/support'
+ (extension) => extension.key !== 'license/support',
);
return (
<Dropdown
const { extensions, pendingPlugins } = this.props;
const hasSupportExtension = extensions.find((extension) => extension.key === 'license/support');
const hasGovernanceExtension = extensions.find(
- (e) => e.key === AdminPageExtension.GovernanceConsole
+ (e) => e.key === AdminPageExtension.GovernanceConsole,
);
const totalPendingPlugins =
pendingPlugins.installing.length +
refreshPending={() => {}}
systemStatus="UP"
{...props}
- />
+ />,
);
}
expect(
shallowRender({
extensions: [{ key: AdminPageExtension.GovernanceConsole, name: 'governance' }],
- })
+ }),
).toMatchSnapshot();
});
pendingPlugins={{ installing: [], removing: [], updating: [] }}
systemStatus="UP"
{...props}
- />
+ />,
);
}
expect(
shallowRender({
currentUser: mockLoggedInUser({ dismissedNotices: { [NoticeType.SONARLINT_AD]: true } }),
- })
+ }),
).toMatchSnapshot('adAlreadySeen');
expect(shallowRender({ currentUser: mockLoggedInUser() })).toMatchSnapshot('loggedIn');
});
updateDismissedNotices={jest.fn()}
updateCurrentUserHomepage={jest.fn()}
{...props}
- />
+ />,
);
}
isPreviousLTSUpdate(
parsedVersion: number[],
latestLTS: string,
- systemUpgrades: GroupedSystemUpdate
+ systemUpgrades: GroupedSystemUpdate,
) {
const [ltsMajor, ltsMinor] = latestLTS.split('.').map(Number);
let ltsOlderThan6Month = false;
groupBy(upgrades, (upgrade) => {
const [, minor] = upgrade.version.split('.');
return minor;
- })
+ }),
);
let useCase = UpdateUseCase.NewMinorVersion;
const latest = [...upgrades].sort(
(upgrade1, upgrade2) =>
new Date(upgrade2.releaseDate || '').getTime() -
- new Date(upgrade1.releaseDate || '').getTime()
+ new Date(upgrade1.releaseDate || '').getTime(),
)[0];
const dismissKey = useCase + latest.version;
appState={mockAppState()}
currentUser={mockCurrentUser()}
{...props}
- />
+ />,
);
}
border: 1px solid #ccc;
border-radius: 3px;
background-image: linear-gradient(to bottom, #f5f5f5, #eee);
- box-shadow: inset 0 1px 0 #fff, 0 1px 0 #ccc;
+ box-shadow:
+ inset 0 1px 0 #fff,
+ 0 1px 0 #ccc;
color: var(--secondFontColor);
font-size: 11px;
text-align: center;
cursor: pointer;
outline: none;
text-decoration: none;
- transition: border-bottom-color 0.2s ease, color 0.2s ease;
+ transition:
+ border-bottom-color 0.2s ease,
+ color 0.2s ease;
}
a:hover,
/>
<Route path="*" element={<CatchAll />} />
</Routes>
- </MemoryRouter>
+ </MemoryRouter>,
);
}
it('should not render for anonymous user', () => {
handleRequiredAuthorization();
expect(replace).toHaveBeenCalledWith(
- '/sessions/new?return_to=%2Fpath%3Fid%3D12%23tag&authorizationError=true'
+ '/sessions/new?return_to=%2Fpath%3Fid%3D12%23tag&authorizationError=true',
);
});
l10nBundle: IntlShape,
currentUser?: CurrentUser,
appState?: AppState,
- availableFeatures?: Feature[]
+ availableFeatures?: Feature[],
) {
exportModulesAsGlobals();
</AvailableFeaturesContext.Provider>
</AppStateContextProvider>
</HelmetProvider>,
- el
+ el,
);
}
defer={false}
titleTemplate={translateWithParameters(
'page_title.template.with_category',
- translate('my_account.page')
+ translate('my_account.page'),
)}
/>
<A11ySkipTarget anchor="account_main" />
renderAccountApp(loggedInUser);
expect(
- await screen.findByText(`${loggedInUser.externalProvider}: ${loggedInUser.externalIdentity}`)
+ await screen.findByText(`${loggedInUser.externalProvider}: ${loggedInUser.externalIdentity}`),
).toBeInTheDocument();
});
renderAccountApp(
mockLoggedInUser({ permissions: { global: [Permissions.Scan] } }),
- securityPagePath
+ securityPagePath,
);
expect(await screen.findByText('users.tokens')).toBeInTheDocument();
await user.click(generateButton);
expect(
- await screen.findByText(`users.tokens.new_token_created.${newTokenName}`)
+ await screen.findByText(`users.tokens.new_token_created.${newTokenName}`),
).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'copy_to_clipboard' })).toBeInTheDocument();
// eslint-disable-next-line jest/no-conditional-in-test
expect(screen.getByLabelText('users.new_token')).toHaveTextContent(
// eslint-disable-next-line jest/no-conditional-in-test
- lastTokenCreated.token ?? ''
+ lastTokenCreated.token ?? '',
);
expect(screen.getAllByRole('row')).toHaveLength(4); // 3 tokens + header
await user.click(revokeButtons);
expect(
- screen.getByRole('heading', { name: 'users.tokens.revoke_label.importantToken' })
+ screen.getByRole('heading', { name: 'users.tokens.revoke_label.importantToken' }),
).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'yes' }));
await waitFor(() => expect(screen.getAllByRole('row')).toHaveLength(3)); // 2 tokens + header
- }
+ },
);
it('should flag expired tokens as such', async () => {
name: 'expired token',
isExpired: true,
expirationDate: '2021-01-23T19:25:19+0000',
- })
+ }),
);
renderAccountApp(
mockLoggedInUser({ permissions: { global: [Permissions.Scan] } }),
- securityPagePath
+ securityPagePath,
);
expect(await screen.findByText('users.tokens')).toBeInTheDocument();
// unexpired token is not flagged
const unexpiredTokenRow = screen.getAllByRole('row')[0];
expect(
- within(unexpiredTokenRow).queryByText('my_account.tokens.expired')
+ within(unexpiredTokenRow).queryByText('my_account.tokens.expired'),
).not.toBeInTheDocument();
});
});
renderAccountApp(
mockLoggedInUser({ permissions: { global: [Permissions.Scan] } }),
- securityPagePath
+ securityPagePath,
);
selectEvent.openMenu(screen.getByRole('combobox', { name: 'users.tokens.type' }));
});
renderAccountApp(
mockLoggedInUser({ permissions: { global: [Permissions.Scan] } }),
- securityPagePath
+ securityPagePath,
);
await selectEvent.select(screen.getByRole('combobox', { name: 'users.tokens.type' }), [
renderAccountApp(mockLoggedInUser({ local: true }), securityPagePath);
expect(
- await screen.findByRole('heading', { name: 'my_profile.password.title' })
+ await screen.findByRole('heading', { name: 'my_profile.password.title' }),
).toBeInTheDocument();
const oldPasswordField = screen.getByLabelText('my_profile.password.old', {
expect(projectUI.sonarQubeProject.get()).toBeInTheDocument();
expect(
- projectUI.checkbox(NotificationProjectType.NewFalsePositiveIssue).get()
+ projectUI.checkbox(NotificationProjectType.NewFalsePositiveIssue).get(),
).toBeInTheDocument();
await user.click(projectUI.checkbox(NotificationProjectType.NewAlerts).get());
renderAccountApp(mockLoggedInUser(), notificationsPagePath);
await user.click(
- await screen.findByRole('button', { name: 'my_profile.per_project_notifications.add' })
+ await screen.findByRole('button', { name: 'my_profile.per_project_notifications.add' }),
);
expect(screen.getByLabelText('search.placeholder', { selector: 'input' })).toBeInTheDocument();
await user.keyboard('sonarqube');
export default class NotificationsList extends React.PureComponent<Props> {
isEnabled(type: string, channel: string) {
return !!this.props.notifications.find(
- (notification) => notification.type === type && notification.channel === channel
+ (notification) => notification.type === type && notification.channel === channel,
);
}
<Checkbox
label={translateWithParameters(
'notification.dispatcher.descrption_x',
- this.getDispatcherLabel(type)
+ this.getDispatcherLabel(type),
)}
checked={this.isEnabled(type, channel)}
id={checkboxId(type, channel)}
if (this.mounted) {
this.setState({ loading: false, open: false });
}
- }
+ },
);
};
const { addedProjects, search } = this.state;
const projects = uniqBy(notifications, ({ project }) => project).filter(
- isNotificationProject
+ isNotificationProject,
) as NotificationProject[];
const notificationsByProject = groupBy(notifications, (n) => n.project);
const allProjects = uniqBy([...addedProjects, ...projects], (project) => project.project);
const filteredProjects = sortBy(allProjects, 'projectName').filter((p) =>
- this.filterSearch(p, search)
+ this.filterSearch(p, search),
);
const shouldBeCollapsed = Object.keys(notificationsByProject).length > THRESHOLD_COLLAPSED;
export function Preferences() {
const [shortcutsPreferenceValue, setShortcutsPreferenceValue] = React.useState(
- getKeyboardShortcutEnabled()
+ getKeyboardShortcutEnabled(),
);
const handleToggleKeyboardShortcut = React.useCallback(
setKeyboardShortcutEnabled(value);
setShortcutsPreferenceValue(value);
},
- [setShortcutsPreferenceValue]
+ [setShortcutsPreferenceValue],
);
return (
<FormattedMessage
id="my_account.preferences.keyboard_shortcuts.description"
defaultMessage={translate(
- 'my_account.preferences.keyboard_shortcuts.description'
+ 'my_account.preferences.keyboard_shortcuts.description',
)}
values={{
questionMark: (
.then((providers) => {
if (this.mounted) {
const identityProvider = providers.find(
- (provider) => provider.key === this.props.user.externalProvider
+ (provider) => provider.key === this.props.user.externalProvider,
);
this.setState({ loading: false, identityProvider });
}
type,
url: href,
};
- })
+ }),
);
const { lastAnalysisDate } = project;
hasGovernanceExtension = () => {
return Boolean(
- this.props.adminPages?.find((e) => e.key === AdminPageExtension.GovernanceConsole)
+ this.props.adminPages?.find((e) => e.key === AdminPageExtension.GovernanceConsole),
);
};
expect(downloadButton).toBeInTheDocument();
expect(downloadButton).toHaveAttribute(
'href',
- '/api/audit_logs/download?from=2020-07-21T12%3A00%3A00.000Z&to=2020-07-21T12%3A00%3A00.000Z'
+ '/api/audit_logs/download?from=2020-07-21T12%3A00%3A00.000Z&to=2020-07-21T12%3A00%3A00.000Z',
);
await user.click(ui.weekRadio.get());
expect(downloadButton).toHaveAttribute(
'href',
- '/api/audit_logs/download?from=2020-07-14T12%3A00%3A00.000Z&to=2020-07-21T12%3A00%3A00.000Z'
+ '/api/audit_logs/download?from=2020-07-14T12%3A00%3A00.000Z&to=2020-07-21T12%3A00%3A00.000Z',
);
await user.click(ui.monthRadio.get());
expect(downloadButton).toHaveAttribute(
'href',
- '/api/audit_logs/download?from=2020-06-21T12%3A00%3A00.000Z&to=2020-07-21T12%3A00%3A00.000Z'
+ '/api/audit_logs/download?from=2020-06-21T12%3A00%3A00.000Z&to=2020-07-21T12%3A00%3A00.000Z',
);
await user.click(ui.trimesterRadio.get());
expect(downloadButton).toHaveAttribute(
'href',
- '/api/audit_logs/download?from=2020-04-22T12%3A00%3A00.000Z&to=2020-07-21T12%3A00%3A00.000Z'
+ '/api/audit_logs/download?from=2020-04-22T12%3A00%3A00.000Z&to=2020-07-21T12%3A00%3A00.000Z',
);
await user.click(downloadButton);
const modal = screen.getByRole('dialog');
expect(
- within(modal).getByRole('heading', { name: 'background_tasks.change_number_of_workers' })
+ within(modal).getByRole('heading', { name: 'background_tasks.change_number_of_workers' }),
).toBeInTheDocument();
await user.click(
within(modal).getByLabelText('background_tasks.change_number_of_workers', {
selector: 'input',
- })
+ }),
);
await user.keyboard('[ArrowDown][ArrowDown][Enter]');
expect(screen.queryByText('background_tasks.table.nodeName')).not.toBeInTheDocument();
expect(screen.queryByText('best_node_ever')).not.toBeInTheDocument();
- }
+ },
);
it('DCE edition should display node name', async () => {
this.setState({ types });
this.loadTasks();
},
- () => {}
+ () => {},
);
}
}));
}
},
- this.stopLoading
+ this.stopLoading,
);
};
const newValue = value ? CURRENTS.ONLY_CURRENTS : CURRENTS.ALL;
onChange(newValue);
},
- [onChange]
+ [onChange],
);
return (
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
}
({ value }: LabelValueSelectOption) => {
onChange(value);
},
- [onChange]
+ [onChange],
);
return (
<ActionsDropdownItem className="js-task-filter" onClick={this.handleFilterClick}>
{translateWithParameters(
'background_tasks.filter_by_component_x',
- task.componentName
+ task.componentName,
)}
</ActionsDropdownItem>
)}
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
};
if (this.mounted) {
this.setState({ submitting: false });
}
- }
+ },
);
};
password: passwordValue,
}).then(
() => true,
- () => false
+ () => false,
);
if (this.mounted) {
this.setState({ submitting: false, success });
}),
unauthorizedMessage: byText('unauthorized.message'),
defaultPasswordWarningMessage: byText(
- 'users.change_admin_password.form.cannot_use_default_password'
+ 'users.change_admin_password.form.cannot_use_default_password',
),
};
it('should allow changing password when using the default admin password', async () => {
const user = userEvent.setup();
renderChangeAdminPasswordApp(
- mockAppState({ instanceUsesDefaultAdminCredentials: true, canAdmin: true })
+ mockAppState({ instanceUsesDefaultAdminCredentials: true, canAdmin: true }),
);
expect(ui.updateButton.get()).toBeDisabled();
await user.type(ui.passwordInput.get(), 'password');
it('should not allow to submit the default password', async () => {
const user = userEvent.setup();
renderChangeAdminPasswordApp(
- mockAppState({ instanceUsesDefaultAdminCredentials: true, canAdmin: true })
+ mockAppState({ instanceUsesDefaultAdminCredentials: true, canAdmin: true }),
);
await user.type(ui.passwordInput.get(), DEFAULT_ADMIN_PASSWORD);
});
expect(await ui.notAccessToAllChildrenTxt.find()).toBeInTheDocument();
- }
+ },
);
it('should correctly show measures for a project', async () => {
overallCodeBtn: byRole('radio', { name: 'projects.view.overall_code' }),
measureRow: (name: string | RegExp) => byRole('row', { name, exact: false }),
measureValueCell: (row: ReactTestingQuery, name: string, value: string) => {
- const i = Array.from(screen.getAllByRole('columnheader')).findIndex((c) =>
- c.textContent?.includes(name)
+ const i = Array.from(screen.getAllByRole('columnheader')).findIndex(
+ (c) => c.textContent?.includes(name),
);
if (i < 0) {
// eslint-disable-next-line testing-library/no-debugging-utils
].map((metric) =>
isDiffMetric(metric)
? mockMeasure({ metric, period: { index: 1, value: newValue } })
- : mockMeasure({ metric, value: overallValue, period: undefined })
+ : mockMeasure({ metric, value: overallValue, period: undefined }),
),
mockMeasure({
metric: MetricKey.alert_status,
period: undefined,
}),
],
- 'metric'
+ 'metric',
);
}
expect(getCodeMetrics('VW')).toMatchSnapshot();
expect(getCodeMetrics('VW', undefined, { includeQGStatus: true })).toMatchSnapshot();
expect(
- getCodeMetrics('VW', undefined, { includeQGStatus: true, newCode: true })
+ getCodeMetrics('VW', undefined, { includeQGStatus: true, newCode: true }),
).toMatchSnapshot();
expect(
- getCodeMetrics('VW', undefined, { includeQGStatus: true, newCode: false })
+ getCodeMetrics('VW', undefined, { includeQGStatus: true, newCode: false }),
).toMatchSnapshot();
});
componentKey: string,
children: ComponentMeasure[],
total: number,
- page: number
+ page: number,
): void {
const previous = getComponentChildren(componentKey);
if (previous) {
componentKey,
this.props.component.qualifier,
this,
- this.props.branchLike
+ this.props.branchLike,
).then((r) => {
if (this.mounted) {
if (
[ComponentQualifier.File, ComponentQualifier.TestFile].includes(
- r.component.qualifier as ComponentQualifier
+ r.component.qualifier as ComponentQualifier,
)
) {
this.setState({
page + 1,
this.props.component.qualifier,
this,
- this.props.branchLike
+ this.props.branchLike,
).then((r) => {
if (this.mounted && r.components.length) {
this.setState({
const metricKeys = intersection(
getCodeMetrics(component.qualifier, branchLike, { newCode: newCodeSelected }),
- Object.keys(metrics)
+ Object.keys(metrics),
);
const filteredMetrics = metricKeys.map((metric) => metrics[metric]);
<LightLabel>
{translate(
'code_viewer.no_source_code_displayed_due_to_empty_analysis',
- component.qualifier
+ component.qualifier,
)}
</LightLabel>
</div>
if (
[ComponentQualifier.Application, ComponentQualifier.Portfolio].includes(
- rootComponent.qualifier as ComponentQualifier
+ rootComponent.qualifier as ComponentQualifier,
) &&
[ComponentQualifier.Application, ComponentQualifier.Project].includes(
- component.qualifier as ComponentQualifier
+ component.qualifier as ComponentQualifier,
)
) {
return (
showIcon,
unclickable,
canBrowse,
- newCodeSelected
+ newCodeSelected,
)}
</div>
{component.branch ? (
rootComponent,
showIcon,
unclickable,
- canBrowse
+ canBrowse,
)}
</span>
);
showIcon: boolean,
unclickable = false,
canBrowse = false,
- newCodeSelected = true
+ newCodeSelected = true,
) {
const name = renderName(component, previous);
const codeType = newCodeSelected ? CodeScope.New : CodeScope.Overall;
isProject(component.qualifier))
) {
const branch = [ComponentQualifier.Application, ComponentQualifier.Portfolio].includes(
- rootComponent.qualifier as ComponentQualifier
+ rootComponent.qualifier as ComponentQualifier,
)
? component.branch
: undefined;
component.refKey ?? component.key,
component.qualifier,
{ branch },
- codeType
+ codeType,
)}
>
{name}
components,
(c) => c.qualifier,
(c) => c.name.toLowerCase(),
- (c) => (c.branch ? c.branch.toLowerCase() : '')
+ (c) => (c.branch ? c.branch.toLowerCase() : ''),
).map((component, index, list) => (
<Component
branchLike={branchLike}
translate(
'metric',
metric,
- SHORT_NAME_METRICS.includes(metric as MetricKey) ? 'short_name' : 'name'
- )
+ SHORT_NAME_METRICS.includes(metric as MetricKey) ? 'short_name' : 'name',
+ ),
);
Cell = NumericalCell;
componentMeasures={[]}
location={mockLocation({ query: { line: '2' } })}
{...props}
- />
+ />,
);
}
export function getCodeMetrics(
qualifier: string,
branchLike?: BranchLike,
- options: { includeQGStatus?: boolean; newCode?: boolean } = {}
+ options: { includeQGStatus?: boolean; newCode?: boolean } = {},
) {
if (isPortfolioLike(qualifier)) {
let metrics: MetricKey[] = [];
componentKey: string,
qualifier: string,
instance: { mounted: boolean },
- branchLike?: BranchLike
+ branchLike?: BranchLike,
) {
const existing = getComponentFromBucket(componentKey);
if (existing) {
componentKey: string,
qualifier: string,
instance: { mounted: boolean },
- branchLike?: BranchLike
+ branchLike?: BranchLike,
): Promise<{ components: ComponentMeasure[]; page: number; total: number }> {
const existing = getComponentChildren(componentKey);
if (existing) {
if (instance.mounted && isPortfolioLike(qualifier)) {
await Promise.all(
- result.components.map((c) => getComponentData({ component: c.refKey || c.key }))
+ result.components.map((c) => getComponentData({ component: c.refKey || c.key })),
).then(
(data) => {
data.forEach(({ component: { analysisDate } }, i) => {
},
() => {
// noop
- }
+ },
);
}
function retrieveComponentBreadcrumbs(
component: string,
instance: { mounted: boolean },
- branchLike?: BranchLike
+ branchLike?: BranchLike,
): Promise<Breadcrumb[]> {
const existing = getComponentBreadcrumbs(component);
if (existing) {
componentKey: string,
qualifier: string,
instance: { mounted: boolean },
- branchLike?: BranchLike
+ branchLike?: BranchLike,
): Promise<{
breadcrumbs: Breadcrumb[];
component: ComponentMeasure;
page: number,
qualifier: string,
instance: { mounted: boolean },
- branchLike?: BranchLike
+ branchLike?: BranchLike,
): Promise<Children> {
const metrics = getCodeMetrics(qualifier, branchLike, {
includeQGStatus: true,
// Render clean code attributes.
expect(
- ui.ruleCleanCodeAttributeCategory(CleanCodeAttributeCategory.Adaptable).getAll().length
+ ui.ruleCleanCodeAttributeCategory(CleanCodeAttributeCategory.Adaptable).getAll().length,
).toBeGreaterThan(1);
expect(ui.ruleSoftwareQuality(SoftwareQuality.Maintainability).getAll().length).toBeGreaterThan(
- 1
+ 1,
);
// Renders clean code categories and software qualities facets
CLEAN_CODE_CATEGORIES.map(
- (category) => `issue.clean_code_attribute_category.${category}`
+ (category) => `issue.clean_code_attribute_category.${category}`,
).forEach((name) => expect(ui.facetItem(name).get()).toBeInTheDocument());
SOFTWARE_QUALITIES.map((quality) => `issue.software_quality.${quality}`).forEach((name) =>
- expect(ui.facetItem(name).get()).toBeInTheDocument()
+ expect(ui.facetItem(name).get()).toBeInTheDocument(),
);
// Renders language facets
['JavaScript', 'Java', 'C'].forEach((name) =>
- expect(ui.facetItem(name).get()).toBeInTheDocument()
+ expect(ui.facetItem(name).get()).toBeInTheDocument(),
);
// Other facets are collapsed
await act(async () => {
await user.type(ui.facetSearchInput('search.search_for_cwe').get(), 'Certificate');
await user.click(
- ui.facetItem('CWE-297 - Improper Validation of Certificate with Host Mismatch').get()
+ ui.facetItem('CWE-297 - Improper Validation of Certificate with Host Mismatch').get(),
);
});
expect(ui.ruleListItem.getAll(ui.rulesList.get())).toHaveLength(2);
await ui.bulkActivate(rulesCount, selectQPSuccess);
expect(
- ui.bulkSuccessMessage(selectQPSuccess.name, selectQPSuccess.languageName, rulesCount).get()
+ ui.bulkSuccessMessage(selectQPSuccess.name, selectQPSuccess.languageName, rulesCount).get(),
).toBeInTheDocument();
await user.click(ui.bulkClose.get());
expect(
ui
.bulkWarningMessage(selectQPWarning.name, selectQPWarning.languageName, rulesCount - 1)
- .get()
+ .get(),
).toBeInTheDocument();
});
await ui.bulkDeactivate(rulesCount, selectQP);
expect(
- ui.bulkSuccessMessage(selectQP.name, selectQP.languageName, rulesCount).get()
+ ui.bulkSuccessMessage(selectQP.name, selectQP.languageName, rulesCount).get(),
).toBeInTheDocument();
});
});
await ui.appLoaded();
expect(
- ui.ruleListItemLink('Awsome java rule').get(ui.currentListItem.get())
+ ui.ruleListItemLink('Awsome java rule').get(ui.currentListItem.get()),
).toBeInTheDocument();
await act(async () => {
await user.keyboard('{ArrowUp}');
});
expect(
- ui.ruleListItemLink('Awsome java rule').get(ui.currentListItem.get())
+ ui.ruleListItemLink('Awsome java rule').get(ui.currentListItem.get()),
).toBeInTheDocument();
await act(async () => {
await user.keyboard('{ArrowLeft}');
});
expect(
- ui.ruleListItemLink('Awsome java rule').get(ui.currentListItem.get())
+ ui.ruleListItemLink('Awsome java rule').get(ui.currentListItem.get()),
).toBeInTheDocument();
});
});
await ui.appLoaded();
expect(ui.ruleTitle('Awsome java rule').get()).toBeInTheDocument();
expect(
- ui.ruleCleanCodeAttributeCategory(CleanCodeAttributeCategory.Adaptable).get()
+ ui.ruleCleanCodeAttributeCategory(CleanCodeAttributeCategory.Adaptable).get(),
).toBeInTheDocument();
expect(ui.ruleCleanCodeAttribute(CleanCodeAttribute.Clear).get()).toBeInTheDocument();
// 1 In Rule details + 1 in facet
renderCodingRulesApp(
mockLoggedInUser(),
- 'coding_rules#languages=c,js|types=BUG|cleanCodeAttributeCategories=ADAPTABLE'
+ 'coding_rules#languages=c,js|types=BUG|cleanCodeAttributeCategories=ADAPTABLE',
);
expect(await screen.findByText('x_selected.2')).toBeInTheDocument();
expect(screen.getByTitle('issue.type.BUG')).toBeInTheDocument();
!profile.isBuiltIn &&
profile.actions &&
profile.actions.edit &&
- profile.language === this.props.rule.lang
- )
+ profile.language === this.props.rule.lang,
+ ),
).map((profile) => ({
...profile,
// Decrease depth by 1, so the top level starts at 0
if (this.mounted) {
this.setState({ submitting: false });
}
- }
+ },
);
};
export default function AttributeCategoryFacet(props: BasicProps) {
const renderName = React.useCallback(
(attribute: string) => translate('issue.clean_code_attribute_category', attribute),
- []
+ [],
);
return (
render() {
// show "Bulk Change" button only if user is admin of at least one QP
const canBulkChange = Object.values(this.props.referencedProfiles).some((profile) =>
- Boolean(profile.actions && profile.actions.edit)
+ Boolean(profile.actions && profile.actions.edit),
);
if (!canBulkChange) {
return (
const { activation } = this.props.query;
const profile = this.getSelectedProfile();
const canChangeProfile = Boolean(
- profile && !profile.isBuiltIn && profile.actions && profile.actions.edit
+ profile && !profile.isBuiltIn && profile.actions && profile.actions.edit,
);
const allowActivateOnProfile = canChangeProfile && activation === false;
const allowDeactivateOnProfile = canChangeProfile && activation === true;
method({
...data,
targetKey: profile,
- })
+ }),
)
.then((response) => this.processResponse(profile, response));
}
if (this.mounted) {
this.setState({ submitting: false });
}
- }
+ },
);
};
profile.name,
language,
result.succeeded,
- result.failed
+ result.failed,
)
: translateWithParameters(
'coding_rules.bulk_change.success',
profile.name,
language,
- result.succeeded
+ result.succeeded,
)}
</Alert>
);
action === 'activate'
? `${translate('coding_rules.activate_in_quality_profile')} (${formatMeasure(
total,
- 'INT'
+ 'INT',
)} ${translate('coding_rules._rules')})`
: `${translate('coding_rules.deactivate_in_quality_profile')} (${formatMeasure(
total,
- 'INT'
+ 'INT',
)} ${translate('coding_rules._rules')})`;
return (
'owaspTop10-2021': shouldOpenStandardsChildFacet(
{},
query,
- SecurityStandard.OWASP_TOP10_2021
+ SecurityStandard.OWASP_TOP10_2021,
),
sonarsourceSecurity: shouldOpenSonarSourceSecurityFacet({}, query),
standards: shouldOpenStandardsFacet({}, query),
});
this.fetchFirstRules();
},
- this.stopLoading
+ this.stopLoading,
);
};
const actives = rawActives && parseActives(rawActives);
const facets = rawFacets && parseFacets(rawFacets);
return { actives, facets, paging, rules };
- }
+ },
);
fetchFirstRules = (query?: RawQuery) => {
}));
}
},
- this.stopLoading
+ this.stopLoading,
);
}
};
if (willOpenProperty && property === STANDARDS) {
newState.openFacets.sonarsourceSecurity = shouldOpenSonarSourceSecurityFacet(
newState.openFacets,
- parseQuery(this.props.location.query)
+ parseQuery(this.props.location.query),
);
// Force loading of sonarsource security facet data
property = newState.openFacets.sonarsourceSecurity ? 'sonarsourceSecurity' : property;
title={translateWithParameters('coding_rule.page', openRule.langName, openRule.name)}
titleTemplate={translateWithParameters(
'page_title.template.with_category',
- translate('coding_rules.page')
+ translate('coding_rules.page'),
)}
/>
) : (
if (this.mounted) {
this.setState({ reactivating: response.status === 409, submitting: false });
}
- }
+ },
);
};
newValue = itemValue === value ? undefined : itemValue;
} else if (multiple) {
newValue = orderBy(
- values.includes(itemValue) ? without(values, itemValue) : [...values, itemValue]
+ values.includes(itemValue) ? without(values, itemValue) : [...values, itemValue],
);
} else {
newValue = values.includes(itemValue) && values.length < 2 ? [] : [itemValue];
sortBy(
Object.keys(stats),
(key) => -stats[key],
- (key) => renderTextName(key).toLowerCase()
+ (key) => renderTextName(key).toLowerCase(),
));
const headerId = `facet_${property}`;
handleSearch = (query: string) => {
const options = this.getAllPossibleOptions();
const results = options.filter((language) =>
- language.name.toLowerCase().includes(query.toLowerCase())
+ language.name.toLowerCase().includes(query.toLowerCase()),
);
const paging = { pageIndex: 1, pageSize: results.length, total: results.length };
return Promise.resolve({ paging, results });
// and make sure we reference each language only once
return uniqBy<Language>(
[...Object.values(languages), ...Object.keys(stats).map((key) => ({ key, name: key }))],
- (language: Language) => language.key
+ (language: Language) => language.key,
);
};
profiles = sortBy(
profiles,
(profile) => profile.name.toLowerCase(),
- (profile) => profile.languageName
+ (profile) => profile.languageName,
);
const property = 'profile';
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
};
// optimistic update
const oldTags = this.state.ruleDetails && this.state.ruleDetails.tags;
this.setState((state) =>
- state.ruleDetails ? { ruleDetails: { ...state.ruleDetails, tags } } : null
+ state.ruleDetails ? { ruleDetails: { ...state.ruleDetails, tags } } : null,
);
updateRule({
key: this.props.ruleKey,
}).catch(() => {
if (this.mounted) {
this.setState((state) =>
- state.ruleDetails ? { ruleDetails: { ...state.ruleDetails, tags: oldTags } } : null
+ state.ruleDetails ? { ruleDetails: { ...state.ruleDetails, tags: oldTags } } : null,
);
}
});
handleDelete = () => {
return deleteRule({ key: this.props.ruleKey }).then(() =>
- this.props.onDelete(this.props.ruleKey)
+ this.props.onDelete(this.props.ruleKey),
);
};
isDestructive
modalBody={translateWithParameters(
'coding_rules.delete.custom.confirm',
- ruleDetails.name
+ ruleDetails.name,
)}
modalHeader={translate('coding_rules.delete_rule')}
onConfirm={this.handleDelete}
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
};
if (this.mounted) {
this.setState({ submitting: false });
}
- }
+ },
);
};
: undefined;
const introductionSection = ruleDetails.descriptionSections?.find(
- (section) => section.key === RuleDescriptionSections.INTRODUCTION
+ (section) => section.key === RuleDescriptionSections.INTRODUCTION,
)?.content;
return (
resolved: 'false',
rules: key,
},
- 'projects'
+ 'projects',
).then(
({ facet, response }) => {
if (this.mounted) {
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
};
confirmData={profile.key}
modalBody={translateWithParameters(
'coding_rules.revert_to_parent_definition.confirm',
- profile.parentName
+ profile.parentName,
)}
modalHeader={translate('coding_rules.revert_to_parent_definition')}
onConfirm={this.handleRevert}
className="coding-rules-detail-quality-profile-deactivate button-red spacer-left"
aria-label={translateWithParameters(
'coding_rules.deactivate_in_quality_profile_x',
- profile.name
+ profile.name,
)}
onClick={onClick}
>
render() {
const { activations = [], referencedProfiles, ruleDetails } = this.props;
const canActivate = Object.values(referencedProfiles).some((profile) =>
- Boolean(profile.actions && profile.actions.edit && profile.language === ruleDetails.lang)
+ Boolean(profile.actions && profile.actions.edit && profile.language === ruleDetails.lang),
);
return (
onDone={this.handleActivate}
profiles={filter(
this.props.referencedProfiles,
- (profile) => !activations.find((activation) => activation.qProfile === profile.key)
+ (profile) => !activations.find((activation) => activation.qProfile === profile.key),
)}
rule={ruleDetails}
/>
this.setState({ searchResult: without(tags, ...this.props.sysTags) });
}
},
- () => {}
+ () => {},
);
};
};
deactivateRule(data).then(
() => this.props.onDeactivate(data.key, data.rule),
- () => {}
+ () => {},
);
}
};
overlay={translateWithParameters(
'coding_rules.overrides',
selectedProfile.name,
- selectedProfile.parentName
+ selectedProfile.parentName,
)}
>
<RuleInheritanceIcon
overlay={translateWithParameters(
'coding_rules.inherits',
selectedProfile.name,
- selectedProfile.parentName
+ selectedProfile.parentName,
)}
>
<RuleInheritanceIcon
<span className="sw-ml-1">{translate('severity', severity)}</span>
</div>
),
- []
+ [],
);
const renderTextName = React.useCallback(
(severity: string) => translate('severity', severity),
- []
+ [],
);
return (
export default function SoftwareQualityFacet(props: BasicProps) {
const renderName = React.useCallback(
(quality: string) => translate('issue.software_quality', quality),
- []
+ [],
);
return (
});
}
},
- () => {}
+ () => {},
);
};
getValues = () => {
return [
...this.props.sonarsourceSecurity.map((item) =>
- renderSonarSourceSecurityCategory(this.state.standards, item, true)
+ renderSonarSourceSecurityCategory(this.state.standards, item, true),
),
...this.props.owaspTop10.map((item) =>
- renderOwaspTop10Category(this.state.standards, item, true)
+ renderOwaspTop10Category(this.state.standards, item, true),
),
...this.props['owaspTop10-2021'].map((item) =>
- renderOwaspTop102021Category(this.state.standards, item, true)
+ renderOwaspTop102021Category(this.state.standards, item, true),
),
...this.props.cwe.map((item) => renderCWECategory(this.state.standards, item)),
if (multiple) {
const newValue = sortBy(
- items.includes(itemValue) ? without(items, itemValue) : [...items, itemValue]
+ items.includes(itemValue) ? without(items, itemValue) : [...items, itemValue],
);
this.props.onChange({ [prop]: newValue });
handleCWESearch = (query: string) => {
return Promise.resolve({
results: Object.keys(this.state.standards.cwe).filter((cwe) =>
- renderCWECategory(this.state.standards, cwe).toLowerCase().includes(query.toLowerCase())
+ renderCWECategory(this.state.standards, cwe).toLowerCase().includes(query.toLowerCase()),
),
});
};
statsProp: StatsProp,
valuesProp: ValuesProp,
renderName: (standards: Standards, category: string) => string,
- onClick: (x: string, multiple?: boolean) => void
+ onClick: (x: string, multiple?: boolean) => void,
) => {
const stats = this.props[statsProp];
const values = this.props[valuesProp];
valuesProp,
renderName,
renderName,
- onClick
+ onClick,
);
};
listKey: ValuesProp,
renderName: (standards: Standards, category: string) => React.ReactNode,
renderTooltip: (standards: Standards, category: string) => string,
- onClick: (x: string, multiple?: boolean) => void
+ onClick: (x: string, multiple?: boolean) => void,
) => {
if (!categories.length) {
return (
'owaspTop10Stats',
SecurityStandard.OWASP_TOP10,
renderOwaspTop10Category,
- this.handleOwaspTop10ItemClick
+ this.handleOwaspTop10ItemClick,
);
}
'owaspTop10-2021Stats',
SecurityStandard.OWASP_TOP10_2021,
renderOwaspTop102021Category,
- this.handleOwaspTop102021ItemClick
+ this.handleOwaspTop102021ItemClick,
);
}
const sortedItems = sortBy(
Object.keys(stats),
(key) => -stats[key],
- (key) => renderSonarSourceSecurityCategory(this.state.standards, key)
+ (key) => renderSonarSourceSecurityCategory(this.state.standards, key),
);
const limitedList = this.state.showFullSonarSourceList
onClick={() => this.props.onToggle('sonarsourceSecurity')}
open={sonarsourceSecurityOpen}
values={sonarsourceSecurity.map((item) =>
- renderSonarSourceSecurityCategory(this.state.standards, item)
+ renderSonarSourceSecurityCategory(this.state.standards, item),
)}
/>
onClick={() => this.props.onToggle('owaspTop10-2021')}
open={owaspTop102021Open}
values={owaspTop102021.map((item) =>
- renderOwaspTop102021Category(this.state.standards, item)
+ renderOwaspTop102021Category(this.state.standards, item),
)}
/>
availableSince: parseAsDate(query.available_since),
cleanCodeAttributeCategories: parseAsArray<CleanCodeAttributeCategory>(
query.cleanCodeAttributeCategories,
- parseAsString
+ parseAsString,
),
compareToProfile: parseAsOptionalString(query.compareToProfile),
cwe: parseAsArray(query.cwe, parseAsString),
impactSeverities: parseAsArray<SoftwareImpactSeverity>(query.impactSeverities, parseAsString),
impactSoftwareQualities: parseAsArray<SoftwareQuality>(
query.impactSoftwareQualities,
- parseAsString
+ parseAsString,
),
inheritance: parseAsInheritance(query.inheritance),
languages: parseAsArray(query.languages, parseAsString),
};
navigate(
{ pathname: location.pathname, search: new URLSearchParams(normalizedQuery).toString() },
- { replace: true }
+ { replace: true },
);
}
}, [location, navigate]);
jest.mock('../../../api/metrics', () => {
const { DEFAULT_METRICS } = jest.requireActual('../../../helpers/mocks/metrics');
const metrics = Object.values(MetricKey).map(
- (key) => DEFAULT_METRICS[key] ?? mockMetric({ key })
+ (key) => DEFAULT_METRICS[key] ?? mockMetric({ key }),
);
return {
getAllMetrics: jest.fn().mockResolvedValue(metrics),
await ui.appLoaded();
expect(
- within(ui.noAccessWarning.get()).getByText('component_measures.not_all_measures_are_shown')
+ within(ui.noAccessWarning.get()).getByText('component_measures.not_all_measures_are_shown'),
).toBeInTheDocument();
});
}),
ancestors: [tree.component],
children: [],
- }))
+ })),
);
componentsHandler.registerComponentTree(tree);
measuresHandler.registerComponentMeasures(
}),
};
return acc;
- }, measures)
+ }, measures),
);
const { ui, user } = getPageObject();
await user.click(ui.measureBtn('Code Smells 8').get());
expect(ui.goToActivityLink.get()).toHaveAttribute(
'href',
- '/project/activity?id=foo&graph=custom&custom_metrics=code_smells'
+ '/project/activity?id=foo&graph=custom&custom_metrics=code_smells',
);
});
await user.click(ui.measureBtn('Code Smells 8').get());
expect(
- within(ui.measuresRow('folderA').get()).getByRole('cell', { name: '3' })
+ within(ui.measuresRow('folderA').get()).getByRole('cell', { name: '3' }),
).toBeInTheDocument();
expect(
- within(ui.measuresRow('test1.js').get()).getByRole('cell', { name: '2' })
+ within(ui.measuresRow('test1.js').get()).getByRole('cell', { name: '2' }),
).toBeInTheDocument();
await user.click(ui.fileLink('folderA').get());
expect(
- within(ui.measuresRow('out.tsx').get()).getByRole('cell', { name: '1' })
+ within(ui.measuresRow('out.tsx').get()).getByRole('cell', { name: '1' }),
).toBeInTheDocument();
expect(
- within(ui.measuresRow('in.tsx').get()).getByRole('cell', { name: '2' })
+ within(ui.measuresRow('in.tsx').get()).getByRole('cell', { name: '2' }),
).toBeInTheDocument();
await user.click(ui.fileLink('out.tsx').get());
await ui.changeViewToList();
expect(
- within(ui.measuresRow('out.tsx').get()).getByRole('cell', { name: '1' })
+ within(ui.measuresRow('out.tsx').get()).getByRole('cell', { name: '1' }),
).toBeInTheDocument();
expect(
- within(ui.measuresRow('test1.js').get()).getByRole('cell', { name: '2' })
+ within(ui.measuresRow('test1.js').get()).getByRole('cell', { name: '2' }),
).toBeInTheDocument();
await user.click(ui.fileLink('out.tsx').get());
});
expect(
- within(ui.measuresRow('out.tsx').get()).getByRole('cell', { name: '1' })
+ within(ui.measuresRow('out.tsx').get()).getByRole('cell', { name: '1' }),
).toBeInTheDocument();
expect(
- within(ui.measuresRow('in.tsx').get()).getByRole('cell', { name: '2' })
+ within(ui.measuresRow('in.tsx').get()).getByRole('cell', { name: '2' }),
).toBeInTheDocument();
// Move back to project.
});
expect(
- within(ui.measuresRow('folderA').get()).getByRole('cell', { name: '3' })
+ within(ui.measuresRow('folderA').get()).getByRole('cell', { name: '3' }),
).toBeInTheDocument();
await act(async () => {
it('should redirect old history route', () => {
renderMeasuresApp('component_measures/metric/bugs/history?id=foo');
expect(
- screen.getByText('/project/activity?id=foo&graph=custom&custom_metrics=bugs')
+ screen.getByText('/project/activity?id=foo&graph=custom&custom_metrics=bugs'),
).toBeInTheDocument();
});
}),
ancestors: [tree.component],
children: [],
- }))
+ })),
);
componentsHandler.registerComponentTree(tree);
'component_measures',
routes,
{ navigateTo, featureList: [Feature.BranchSupport] },
- { component: mockComponent({ key: 'foo' }), ...componentContext }
+ { component: mockComponent({ key: 'foo' }), ...componentContext },
);
}
type: 'INT',
},
},
- ])
+ ]),
).toHaveLength(1);
});
});
{ metric: { id: '3', key: MetricKey.new_bugs, name: 'new_bugs', type: 'INT' } },
{ metric: { id: '4', key: MetricKey.bugs, name: 'bugs', type: 'INT' } },
'overall_category',
- ])
+ ]),
).toMatchSnapshot();
});
});
view: utils.DEFAULT_VIEW,
});
expect(
- utils.parseQuery({ metric: 'foo', selected: 'bar', view: 'tree', asc: 'false' })
+ utils.parseQuery({ metric: 'foo', selected: 'bar', view: 'tree', asc: 'false' }),
).toEqual({
metric: 'foo',
selected: 'bar',
view: 'list',
});
expect(
- utils.serializeQuery({ metric: 'foo', selected: 'bar', view: MeasurePageView.tree })
+ utils.serializeQuery({ metric: 'foo', selected: 'bar', view: MeasurePageView.tree }),
).toEqual({
metric: 'foo',
selected: 'bar',
this.setState({ metrics: byKey });
this.fetchMeasures(byKey);
},
- () => {}
+ () => {},
);
}
({ component, period }) => {
if (this.mounted) {
const measures = banQualityGateMeasure(component).map((measure) =>
- enhanceMeasure(measure, metrics)
+ enhanceMeasure(measure, metrics),
);
const leakPeriod =
loading: false,
leakPeriod,
measures: measures.filter(
- (measure) => measure.value !== undefined || measure.leak !== undefined
+ (measure) => measure.value !== undefined || measure.leak !== undefined,
),
});
}
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
}
const leakPeriodLabel = getNewCodePeriodLabel(
period,
- period.mode === 'manual_baseline' ? this.formatDateTime : this.formatDate
+ period.mode === 'manual_baseline' ? this.formatDateTime : this.formatDate,
);
const label = (
}
const components = tree.components.map((component) =>
- enhanceComponent(component, metric, metrics)
+ enhanceComponent(component, metric, metrics),
);
const measure = measures.find((m) => m.metric === requestedMetric.key);
components.find(
(c) =>
getComponentMeasureUniqueKey(c) ===
- getComponentMeasureUniqueKey(selectedComponent)
+ getComponentMeasureUniqueKey(selectedComponent),
)
? selectedComponent
: undefined,
},
() => {
/* noop */
- }
+ },
);
};
if (this.mounted) {
this.setState({ loadingMoreComponents: false });
}
- }
+ },
);
};
getComponentRequestParams(
view: MeasurePageView,
metric: Pick<Metric, 'key' | 'direction'>,
- options: Object = {}
+ options: Object = {},
) {
const strategy = view === MeasurePageView.list ? 'leaves' : 'children';
const metricKeys = [metric.key];
const comp = this.state.components.find(
(c) =>
c.refKey === component.key ||
- getComponentMeasureUniqueKey(c) === getComponentMeasureUniqueKey(component)
+ getComponentMeasureUniqueKey(c) === getComponentMeasureUniqueKey(component),
);
if (comp) {
? getComponentMeasureUniqueKey(this.state.baseComponent)
: getComponentMeasureUniqueKey(this.state.selectedComponent);
const index = this.state.components.findIndex(
- (component) => getComponentMeasureUniqueKey(component) === componentKey
+ (component) => getComponentMeasureUniqueKey(component) === componentKey,
);
return index !== -1 ? index : undefined;
};
measureValue
? translateWithParameters(
'metric.has_rating_X',
- formatMeasure(measureValue, MetricType.Rating)
+ formatMeasure(measureValue, MetricType.Rating),
)
: translate('metric.no_rating')
}
this.props.updateLoading({ bubbles: false });
}
},
- () => this.props.updateLoading({ bubbles: false })
+ () => this.props.updateLoading({ bubbles: false }),
);
};
this.updateLoading({ component: false });
}
},
- () => this.updateLoading({ component: false })
+ () => this.updateLoading({ component: false }),
);
};
this.setState({ breadcrumbs });
}
},
- () => {}
+ () => {},
);
};
function renderLeakPeriodLegend(overrides: Partial<LeakPeriodLegendProps> = {}) {
return renderComponent(
- <LeakPeriodLegend component={mockComponentMeasure()} period={PERIOD} {...overrides} />
+ <LeakPeriodLegend component={mockComponentMeasure()} period={PERIOD} {...overrides} />,
);
}
getTooltip(
component: ComponentMeasureEnhanced,
values: { x: number; y: number; size: number; colors?: Array<number | undefined> },
- metrics: { x: Metric; y: Metric; size: Metric; colors?: Metric[] }
+ metrics: { x: Metric; y: Metric; size: Metric; colors?: Metric[] },
) {
const inner = [
[component.name, isProject(component.qualifier) ? component.branch : undefined]
? translate('component_measures.overview', domain, 'title')
: translateWithParameters(
'component_measures.domain_x_overview',
- getLocalizedMetricDomain(domain)
+ getLocalizedMetricDomain(domain),
);
return (
{colorsMetric.length > 1
? translateWithParameters(
'component_measures.legend.worse_of_x_y',
- ...colorsMetric.map((metric) => getLocalizedMetricName(metric))
+ ...colorsMetric.map((metric) => getLocalizedMetricName(metric)),
)
: getLocalizedMetricName(colorsMetric[0])}
</span>
selectionKey,
metric.key,
component.branch ? fillBranchLike(component.branch) : branchLike,
- view
+ view,
);
// This metric doesn't exist for project
'component_measures.hidden_best_score_metrics',
formatMeasure(
this.props.paging.total - filteredComponents.length,
- MetricType.Integer
+ MetricType.Integer,
),
- formatMeasure(this.props.metric.bestValue, this.props.metric.type)
+ formatMeasure(this.props.metric.bestValue, this.props.metric.type),
)}
<ButtonSecondary
onClick={this.handleShowBestMeasures}
value
? translateWithParameters(
'metric.has_rating_X',
- formatMeasure(value, MetricType.Rating)
+ formatMeasure(value, MetricType.Rating),
)
: translate('metric.no_rating')
}
return components
.map((component) => {
const colorMeasure = component.measures.find(
- (measure) => measure.metric.key === metric.key
+ (measure) => measure.metric.key === metric.key,
);
const sizeMeasure = component.measures.find((measure) => measure.metric.key !== metric.key);
if (!sizeMeasure) {
{translate(
'metric',
sizeMeasure && sizeMeasure.metric ? sizeMeasure.metric.key : MetricKey.ncloc,
- 'name'
+ 'name',
)}
</span>
<span>{this.renderLegend()}</span>
id: searchParams.get('id') ?? undefined,
graph: 'custom',
custom_metrics: params.metricKey,
- })
+ }),
).toString(),
};
return <Navigate to={to} replace />;
...searchParamsToQuery(searchParams),
metric: params.metricKey,
view: params.view,
- })
+ }),
).toString(),
};
return <Navigate to={to} replace />;
onChange={onChange}
selected={selected}
/>
- )
+ ),
)}
</SubnavigationAccordion>
);
(metric: string) => {
updateQuery({ metric });
},
- [updateQuery]
+ [updateQuery],
);
const handleProjectOverviewClick = () => {
export function sortMeasures(
domainName: string,
- measures: Array<MeasureEnhanced | string>
+ measures: Array<MeasureEnhanced | string>,
): Array<MeasureEnhanced | string> {
const config = domains[domainName] || {};
const configOrder = config.order || [];
export function enhanceComponent(
component: ComponentMeasure,
metric: Pick<Metric, 'key'> | undefined,
- metrics: Dict<Metric>
+ metrics: Dict<Metric>,
): ComponentMeasureEnhanced {
if (!component.measures) {
return { ...component, measures: [] };
export function hasList(metric: string): boolean {
return ![MetricKey.releasability_rating, MetricKey.releasability_effort].includes(
- metric as MetricKey
+ metric as MetricKey,
);
}
const searchResults: AzureRepository[] = await searchAzureRepositories(
selectedAlmInstance.key,
- searchQuery
+ searchQuery,
)
.then(({ repositories }) => repositories)
.catch(() => []);
almSetting: selectedAlmInstance.key,
projectName: selectedRepository.projectName,
repositoryName: selectedRepository.name,
- })
+ }),
);
}
};
this.fetchData().catch(() => {
/* noop */
});
- }
+ },
);
};
name: r.projectName,
description: translateWithParameters(
'onboarding.create_project.azure.search_results_for_project_X',
- r.projectName
+ r.projectName,
),
}
);
}),
- 'name'
+ 'name',
);
} else {
filteredProjects = projects;
<FormattedMessage
id="onboarding.create_project.enter_password.instructions.bitbucket_cloud"
defaultMessage={translate(
- 'onboarding.create_project.enter_password.instructions.bitbucket_cloud'
+ 'onboarding.create_project.enter_password.instructions.bitbucket_cloud',
)}
values={{
link: (
<Link to="https://bitbucket.org/account/settings/app-passwords/new">
{translate(
- 'onboarding.create_project.enter_password.instructions.bitbucket_cloud.link'
+ 'onboarding.create_project.enter_password.instructions.bitbucket_cloud.link',
)}
</Link>
),
selectedAlmInstance.key,
searchQuery,
pageSize,
- pageIndex
+ pageIndex,
).catch(() => {
this.handleError();
return { isLastPage: undefined, repositories: undefined };
},
() => {
/* noop */
- }
+ },
);
- }
+ },
);
};
},
() => {
/* noop */
- }
+ },
);
- }
+ },
);
};
setupBitbucketCloudProjectCreation({
almSetting: selectedAlmInstance.key,
repositorySlug,
- })
+ }),
);
}
};
}
export default function BitbucketCloudProjectCreateRenderer(
- props: BitbucketCloudProjectCreateRendererProps
+ props: BitbucketCloudProjectCreateRendererProps,
) {
const {
almInstances,
<FlagMessage variant="warning">
{translateWithParameters(
'onboarding.create_project.only_showing_X_first_repos',
- repositoryCount
+ repositoryCount,
)}
</FlagMessage>
)}
let projectRepositories;
if (projects && projects.length > 0) {
projectRepositories = await this.fetchBitbucketRepositories(projects).catch(
- () => undefined
+ () => undefined,
);
}
};
fetchBitbucketRepositories = (
- projects: BitbucketProject[]
+ projects: BitbucketProject[],
): Promise<BitbucketProjectRepositories | undefined> => {
const { selectedAlmInstance } = this.state;
isLastPage: realIsLastPage,
projectKey: p.key,
};
- }
+ },
);
- })
+ }),
).then((results) => {
return results.reduce(
(acc: BitbucketProjectRepositories, { isLastPage, projectKey, repositories }) => {
return { ...acc, [projectKey]: { allShown: isLastPage, repositories } };
},
- {}
+ {},
);
});
};
almSetting: selectedAlmInstance.key,
projectKey: selectedRepository.projectKey,
repositorySlug: selectedRepository.slug,
- })
+ }),
);
}
};
const { projects, projectRepositories } = props;
const [openProjectKeys, setOpenProjectKeys] = React.useState(
- projects.length > 0 ? [projects[0].key] : []
+ projects.length > 0 ? [projects[0].key] : [],
);
const handleClick = (isOpen: boolean, projectKey: string) => {
setOpenProjectKeys(
- isOpen ? without(openProjectKeys, projectKey) : uniq([...openProjectKeys, projectKey])
+ isOpen ? without(openProjectKeys, projectKey) : uniq([...openProjectKeys, projectKey]),
);
};
}
const filteredProjects = projects.filter((p) =>
- searchResults.some((r) => r.projectKey === p.key)
+ searchResults.some((r) => r.projectKey === p.key),
);
const filteredProjectKeys = filteredProjects.map((p) => p.key);
const filteredSearchResults = searchResults.filter(
- (r) => !filteredProjectKeys.includes(r.projectKey)
+ (r) => !filteredProjectKeys.includes(r.projectKey),
);
return (
<FormattedMessage
id="onboarding.create_project.pat_help.instructions.bitbucket_server"
defaultMessage={translate(
- 'onboarding.create_project.pat_help.instructions.bitbucket_server'
+ 'onboarding.create_project.pat_help.instructions.bitbucket_server',
)}
values={{
link: url ? (
<Link to={`${url.replace(/\/$/, '')}/account`}>
{translate(
- 'onboarding.create_project.pat_help.instructions.bitbucket_server.link'
+ 'onboarding.create_project.pat_help.instructions.bitbucket_server.link',
)}
</Link>
) : (
function renderAlmOption(
props: CreateProjectModeSelectionProps,
alm: AlmKeys,
- mode: CreateProjectModes
+ mode: CreateProjectModes,
) {
const {
almCounts,
const availableOptions: almList = [];
const unavailableOptions: almList = [];
almList.forEach(({ key, mode }) =>
- (almCounts[key] > 0 ? availableOptions : unavailableOptions).push({ key, mode })
+ (almCounts[key] > 0 ? availableOptions : unavailableOptions).push({ key, mode }),
);
return {
availableOptions,
almInstances,
} = this.props;
const selectedAlmInstance = almInstances.find(
- (instance) => instance.key === selectedAlmInstanceKey
+ (instance) => instance.key === selectedAlmInstanceKey,
);
if (selectedAlmInstance) {
return selectedAlmInstance;
value: encodeURIComponent(
`${getHostUrl()}/projects/create?mode=${AlmKeys.GitHub}&almInstance=${
selectedAlmInstance.key
- }`
+ }`,
),
},
]
almSetting: selectedAlmInstance.key,
organization: selectedOrganization.key,
repositoryKey: repoKey,
- })
+ }),
);
}
};
this.initialize().catch(() => {
/* noop */
});
- }
+ },
);
};
link: (
<Link to="/admin/settings?category=almintegration">
{translate(
- 'onboarding.create_project.github.warning.message_admin.link'
+ 'onboarding.create_project.github.warning.message_admin.link',
)}
</Link>
),
if (selectedAlmInstance) {
this.props.onProjectSetupDone(
- setupGitlabProjectCreation({ almSetting: selectedAlmInstance.key, gitlabProjectId })
+ setupGitlabProjectCreation({ almSetting: selectedAlmInstance.key, gitlabProjectId }),
);
}
};
expect(
screen.getByRole('row', {
name: 'Azure repo 1 onboarding.create_project.repository_imported',
- })
+ }),
).toBeInTheDocument();
expect(
screen.getByRole('row', {
name: 'Azure repo 2 onboarding.create_project.import',
- })
+ }),
).toBeInTheDocument();
const importButton = screen.getByText('onboarding.create_project.import');
await user.click(importButton);
expect(
- screen.getByRole('heading', { name: 'onboarding.create_project.new_code_definition.title' })
+ screen.getByRole('heading', { name: 'onboarding.create_project.new_code_definition.title' }),
).toBeInTheDocument();
await user.click(screen.getByRole('radio', { name: 'new_code_definition.global_setting' }));
await user.click(
screen.getByRole('button', {
name: 'onboarding.create_project.new_code_definition.create_project',
- })
+ }),
);
expect(await screen.findByText('/dashboard?id=key')).toBeInTheDocument();
// Should search with positive results
const inputSearch = screen.getByPlaceholderText(
- 'onboarding.create_project.search_projects_repositories'
+ 'onboarding.create_project.search_projects_repositories',
);
await user.click(inputSearch);
await user.keyboard('s');
await user.click(
screen.getByRole('textbox', {
name: /onboarding.create_project.enter_pat/,
- })
+ }),
);
await user.keyboard('password');
const projectItem = screen.getByRole('region', { name: /Bitbucket Project 1/ });
expect(
- within(projectItem).getByText('onboarding.create_project.repository_imported')
+ within(projectItem).getByText('onboarding.create_project.repository_imported'),
).toBeInTheDocument();
expect(within(projectItem).getByRole('link', { name: /Bitbucket Repo 1/ })).toBeInTheDocument();
expect(within(projectItem).getByRole('link', { name: /Bitbucket Repo 1/ })).toHaveAttribute(
'href',
- '/dashboard?id=key'
+ '/dashboard?id=key',
);
await user.click(projectItem);
expect(
screen.getByRole('row', {
name: 'Bitbucket Repo 1 onboarding.create_project.repository_imported',
- })
+ }),
).toBeInTheDocument();
expect(
screen.getByRole('row', {
name: 'Bitbucket Repo 2 onboarding.create_project.import',
- })
+ }),
).toBeInTheDocument();
const importButton = screen.getByText('onboarding.create_project.import');
await user.click(importButton);
expect(
- screen.getByRole('heading', { name: 'onboarding.create_project.new_code_definition.title' })
+ screen.getByRole('heading', { name: 'onboarding.create_project.new_code_definition.title' }),
).toBeInTheDocument();
await user.click(screen.getByRole('radio', { name: 'new_code_definition.global_setting' }));
await user.click(
screen.getByRole('button', {
name: 'onboarding.create_project.new_code_definition.create_project',
- })
+ }),
);
expect(await screen.findByText('/dashboard?id=key')).toBeInTheDocument();
expect(searchForBitbucketServerRepositories).toHaveBeenLastCalledWith(
'conf-bitbucketserver-2',
- 'search'
+ 'search',
);
});
const ui = {
bitbucketCloudCreateProjectButton: byText(
- 'onboarding.create_project.select_method.bitbucketcloud'
+ 'onboarding.create_project.select_method.bitbucketcloud',
),
personalAccessTokenInput: byRole('textbox', {
name: /onboarding.create_project.enter_pat/,
expect(await ui.instanceSelector.find()).toBeInTheDocument();
expect(
- screen.getByText('onboarding.create_project.bitbucket_cloud.enter_password')
+ screen.getByText('onboarding.create_project.bitbucket_cloud.enter_password'),
).toBeInTheDocument();
expect(
- screen.getByText('onboarding.create_project.enter_password.instructions.bitbucket_cloud')
+ screen.getByText('onboarding.create_project.enter_password.instructions.bitbucket_cloud'),
).toBeInTheDocument();
expect(
screen.getByText(
- 'onboarding.create_project.pat.expired.info_message onboarding.create_project.pat.expired.info_message_contact'
- )
+ 'onboarding.create_project.pat.expired.info_message onboarding.create_project.pat.expired.info_message_contact',
+ ),
).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'save' })).toBeDisabled();
await user.click(
screen.getByRole('textbox', {
name: /onboarding.create_project.bitbucket_cloud.enter_username/,
- })
+ }),
);
await user.keyboard('username');
await user.click(
screen.getByRole('textbox', {
name: /onboarding.create_project.bitbucket_cloud.enter_password/,
- })
+ }),
);
await user.keyboard('password');
projectItem = screen.getByRole('row', { name: /BitbucketCloud Repo 1/ });
expect(
- within(projectItem).getByText('onboarding.create_project.repository_imported')
+ within(projectItem).getByText('onboarding.create_project.repository_imported'),
).toBeInTheDocument();
expect(
- within(projectItem).getByRole('link', { name: /BitbucketCloud Repo 1/ })
+ within(projectItem).getByRole('link', { name: /BitbucketCloud Repo 1/ }),
).toBeInTheDocument();
expect(within(projectItem).getByRole('link', { name: /BitbucketCloud Repo 1/ })).toHaveAttribute(
'href',
- '/dashboard?id=key'
+ '/dashboard?id=key',
);
projectItem = screen.getByRole('row', { name: /BitbucketCloud Repo 2/ });
await user.click(setupButton);
expect(
- screen.getByRole('heading', { name: 'onboarding.create_project.new_code_definition.title' })
+ screen.getByRole('heading', { name: 'onboarding.create_project.new_code_definition.title' }),
).toBeInTheDocument();
await user.click(screen.getByRole('radio', { name: 'new_code_definition.global_setting' }));
await user.click(
screen.getByRole('button', {
name: 'onboarding.create_project.new_code_definition.create_project',
- })
+ }),
);
expect(await screen.findByText('/dashboard?id=key')).toBeInTheDocument();
'conf-bitbucketcloud-2',
'',
BITBUCKET_CLOUD_PROJECTS_PAGESIZE,
- 1
+ 1,
);
const inputSearch = screen.getByRole('searchbox', {
'conf-bitbucketcloud-2',
'search',
BITBUCKET_CLOUD_PROJECTS_PAGESIZE,
- 1
+ 1,
);
});
});
expect(
- screen.getByText('onboarding.create_project.bitbucketcloud.no_projects')
+ screen.getByText('onboarding.create_project.bitbucketcloud.no_projects'),
).toBeInTheDocument();
});
const user = userEvent.setup();
almIntegrationHandler.createRandomBitbucketCloudProjectsWithLoadMore(
BITBUCKET_CLOUD_PROJECTS_PAGESIZE,
- BITBUCKET_CLOUD_PROJECTS_PAGESIZE + 1
+ BITBUCKET_CLOUD_PROJECTS_PAGESIZE + 1,
);
renderCreateProject();
*/
almIntegrationHandler.createRandomBitbucketCloudProjectsWithLoadMore(
BITBUCKET_CLOUD_PROJECTS_PAGESIZE + 1,
- BITBUCKET_CLOUD_PROJECTS_PAGESIZE + 1
+ BITBUCKET_CLOUD_PROJECTS_PAGESIZE + 1,
);
await user.click(screen.getByRole('button', { name: 'show_more' }));
'conf-bitbucketcloud-2',
'',
BITBUCKET_CLOUD_PROJECTS_PAGESIZE,
- 2
+ 2,
);
await waitFor(() => {
expect(await screen.findByText('onboarding.create_project.select_method')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'setup' })).not.toBeInTheDocument();
await expect(screen.getByLabelText('help-tooltip')).toHaveATooltipWithContent(
- 'onboarding.create_project.alm_not_configured'
+ 'onboarding.create_project.alm_not_configured',
);
});
renderCreateProject();
expect(await screen.findByText('onboarding.create_project.select_method')).toBeInTheDocument();
expect(
- screen.getByRole('link', { name: 'onboarding.create_project.import_select_method.bitbucket' })
+ screen.getByRole('link', { name: 'onboarding.create_project.import_select_method.bitbucket' }),
).toBeInTheDocument();
});
});
expect(
- within(repoItem).getByText('onboarding.create_project.repository_imported')
+ within(repoItem).getByText('onboarding.create_project.repository_imported'),
).toBeInTheDocument();
expect(within(repoItem).getByRole('link', { name: /Github repo 1/ })).toBeInTheDocument();
expect(within(repoItem).getByRole('link', { name: /Github repo 1/ })).toHaveAttribute(
'href',
- '/dashboard?id=key123'
+ '/dashboard?id=key123',
);
repoItem = screen.getByRole('row', {
await user.click(importButton);
expect(
- screen.getByRole('heading', { name: 'onboarding.create_project.new_code_definition.title' })
+ screen.getByRole('heading', { name: 'onboarding.create_project.new_code_definition.title' }),
).toBeInTheDocument();
await user.click(screen.getByRole('radio', { name: 'new_code_definition.global_setting' }));
await user.click(
screen.getByRole('button', {
name: 'onboarding.create_project.new_code_definition.create_project',
- })
+ }),
);
expect(await screen.findByText('/dashboard?id=key')).toBeInTheDocument();
expect(screen.getByText('onboarding.create_project.enter_pat')).toBeInTheDocument();
expect(
- screen.getByText('onboarding.create_project.pat_help.instructions.gitlab')
+ screen.getByText('onboarding.create_project.pat_help.instructions.gitlab'),
).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'save' })).toBeInTheDocument();
await act(async () => {
projectItem = screen.getByRole('row', { name: /Gitlab project 1/ });
expect(
- within(projectItem).getByText('onboarding.create_project.repository_imported')
+ within(projectItem).getByText('onboarding.create_project.repository_imported'),
).toBeInTheDocument();
expect(within(projectItem).getByRole('link', { name: /Gitlab project 1/ })).toBeInTheDocument();
expect(within(projectItem).getByRole('link', { name: /Gitlab project 1/ })).toHaveAttribute(
'href',
- '/dashboard?id=key'
+ '/dashboard?id=key',
);
projectItem = screen.getByRole('row', { name: /Gitlab project 2/ });
await user.click(importButton);
expect(
- screen.getByRole('heading', { name: 'onboarding.create_project.new_code_definition.title' })
+ screen.getByRole('heading', { name: 'onboarding.create_project.new_code_definition.title' }),
).toBeInTheDocument();
await user.click(screen.getByRole('radio', { name: 'new_code_definition.global_setting' }));
await user.click(
screen.getByRole('button', {
name: 'onboarding.create_project.new_code_definition.create_project',
- })
+ }),
);
expect(await screen.findByText('/dashboard?id=key')).toBeInTheDocument();
it('should show branch information', async () => {
renderManualProjectCreate({ branchesEnabled: true });
expect(
- await screen.findByText('onboarding.create_project.pr_decoration.information')
+ await screen.findByText('onboarding.create_project.pr_decoration.information'),
).toBeInTheDocument();
});
await user.click(
await screen.findByRole('textbox', {
name: /onboarding.create_project.display_name/,
- })
+ }),
);
await user.keyboard('test');
expect(
- screen.getByRole('textbox', { name: /onboarding.create_project.project_key/ })
+ screen.getByRole('textbox', { name: /onboarding.create_project.project_key/ }),
).toHaveValue('test');
expect(ui.nextButton.get()).toBeEnabled();
await user.click(
await screen.findByRole('textbox', {
name: /onboarding.create_project.display_name/,
- })
+ }),
);
await user.keyboard('{Control>}a{/Control}This is not a key%^$');
expect(
- screen.getByRole('textbox', { name: /onboarding.create_project.project_key/ })
+ screen.getByRole('textbox', { name: /onboarding.create_project.project_key/ }),
).toHaveValue('This-is-not-a-key-');
// Clear name
await user.clear(
screen.getByRole('textbox', {
name: /onboarding.create_project.display_name/,
- })
+ }),
);
expect(
- screen.getByRole('textbox', { name: /onboarding.create_project.project_key/ })
+ screen.getByRole('textbox', { name: /onboarding.create_project.project_key/ }),
).toHaveValue('');
expect(ui.nextButton.get()).toBeDisabled();
await user.click(
await screen.findByRole('textbox', {
name: /onboarding.create_project.project_key/,
- })
+ }),
);
await user.keyboard('awsome-key');
expect(
- screen.getByRole('textbox', { name: /onboarding.create_project.display_name/ })
+ screen.getByRole('textbox', { name: /onboarding.create_project.display_name/ }),
).toHaveValue('');
expect(ui.nextButton.get()).toBeDisabled();
await user.click(
await screen.findByRole('textbox', {
name: /onboarding.create_project.project_key/,
- })
+ }),
);
await user.keyboard('{Control>}a{/Control}123');
expect(ui.nextButton.get()).toBeDisabled();
await user.clear(
screen.getByRole('textbox', {
name: /onboarding.create_project.main_branch_name/,
- })
+ }),
);
expect(ui.nextButton.get()).toBeDisabled();
});
await user.click(
await screen.findByRole('textbox', {
name: /onboarding.create_project.display_name/,
- })
+ }),
);
await user.keyboard('test');
await user.click(ui.nextButton.get());
await user.click(
await screen.findByRole('textbox', {
name: /onboarding.create_project.display_name/,
- })
+ }),
);
await user.keyboard('test');
expect(
- screen.getByRole('textbox', { name: /onboarding.create_project.display_name/ })
+ screen.getByRole('textbox', { name: /onboarding.create_project.display_name/ }),
).toHaveValue('test');
});
function renderManualProjectCreate(props: Partial<ManualProjectCreate['props']> = {}) {
renderComponent(
- <ManualProjectCreate branchesEnabled={false} onProjectSetupDone={jest.fn()} {...props} />
+ <ManualProjectCreate branchesEnabled={false} onProjectSetupDone={jest.fn()} {...props} />,
);
}
setSubmitting(true);
const { project } = await createProjectFnRef(
selectedDefinition.type,
- selectedDefinition.value
+ selectedDefinition.value,
);
setSubmitting(false);
router.push(getProjectUrl(project.key));
expect(screen.getByText('test1')).toBeInTheDocument();
expect(screen.getByText('url text')).toHaveAttribute('href', '/url');
expect(
- screen.getByRole('button', { name: 'onboarding.create_project.import' })
+ screen.getByRole('button', { name: 'onboarding.create_project.import' }),
).toBeInTheDocument();
});
expect(screen.getByText('url text')).toHaveAttribute('href', '/url');
expect(screen.getByText('onboarding.create_project.repository_imported')).toBeInTheDocument();
expect(
- screen.queryByRole('button', { name: 'onboarding.create_project.import' })
+ screen.queryByRole('button', { name: 'onboarding.create_project.import' }),
).not.toBeInTheDocument();
});
almIconSrc="src"
onImport={jest.fn()}
{...props}
- />
+ />,
);
}
projectNameError === undefined &&
!isEmpty(projectKey) &&
!isEmpty(projectName) &&
- !isEmpty(mainBranchName)
+ !isEmpty(mainBranchName),
);
}
project: projectKey,
name: (projectName || projectKey).trim(),
mainBranch: mainBranchName,
- })
+ }),
);
}
};
.replace(PROJECT_KEY_INVALID_CHARACTERS, '-');
this.handleProjectKeyChange(sanitizedProjectKey);
}
- }
+ },
);
};
export type CreateProjectApiCallback = (
newCodeDefinitionType?: NewCodeDefinitionType,
- newCodeDefinitionValue?: string
+ newCodeDefinitionValue?: string,
) => Promise<{ project: ProjectBase }>;
export const usePersonalAccessToken = (
almSetting: AlmSettingsInstance,
resetPat: boolean,
- onPersonalAccessTokenCreated: () => void
+ onPersonalAccessTokenCreated: () => void,
): PATType => {
const [checkingPat, setCheckingPat] = useState(false);
const [touched, setTouched] = useState(false);
});
expect(
- within(ui.githubManagedGroupRow.get()).getByRole('img', { name: 'github' })
+ within(ui.githubManagedGroupRow.get()).getByRole('img', { name: 'github' }),
).toBeInTheDocument();
});
});
<ButtonIcon
aria-label={translateWithParameters(
isManaged || group.default ? 'groups.users.view' : 'groups.users.edit',
- group.name
+ group.name,
)}
className="button-small little-spacer-left little-padded"
onClick={this.handleMembersClick}
externalRuleEngine: 'eslint',
},
},
- { eslint: 'eslint' }
+ { eslint: 'eslint' },
);
// Title
expect(byRole('heading', { name: issue.message }).get()).toBeInTheDocument();
expect(byRole('button', { name: 'permalink' }).get()).toHaveAttribute(
'data-clipboard-text',
- 'http://localhost/project/issues?issues=AVsae-CQS-9G3txfbFN2&open=AVsae-CQS-9G3txfbFN2&id=myproject'
+ 'http://localhost/project/issues?issues=AVsae-CQS-9G3txfbFN2&open=AVsae-CQS-9G3txfbFN2&id=myproject',
);
// CCT attribute
const cctBadge = byText(
- `issue.clean_code_attribute_category.${issue.cleanCodeAttributeCategory}.title_short`
+ `issue.clean_code_attribute_category.${issue.cleanCodeAttributeCategory}.title_short`,
).get();
expect(cctBadge).toBeInTheDocument();
await expect(cctBadge).toHaveATooltipWithContent(
- `issue.clean_code_attribute.${issue.cleanCodeAttribute}`
+ `issue.clean_code_attribute.${issue.cleanCodeAttribute}`,
);
jest.runOnlyPendingTimers();
// SonarLint badge
expect(
- byText('issue.quick_fix_available_with_sonarlint_no_link').query()
+ byText('issue.quick_fix_available_with_sonarlint_no_link').query(),
).not.toBeInTheDocument();
// Rule external engine
function renderIssueHeader(
props: Partial<IssueHeader['props']> = {},
- externalRules: Dict<string> = {}
+ externalRules: Dict<string> = {},
) {
return renderComponent(
<WorkspaceContext.Provider
onIssueChange={jest.fn()}
{...props}
/>
- </WorkspaceContext.Provider>
+ </WorkspaceContext.Provider>,
);
}
expect(
within(ui.ruleFacetList.get()).getByRole('checkbox', {
name: /Advanced rule/,
- })
+ }),
).toBeInTheDocument();
expect(
within(ui.ruleFacetList.get()).getByRole('checkbox', {
name: /Simple rule/,
- })
+ }),
).toBeInTheDocument();
});
await user.click(await ui.languageFacet.find());
expect(await ui.languageFacetList.find()).toBeInTheDocument();
expect(
- within(ui.languageFacetList.get()).getByRole('checkbox', { name: 'java' })
+ within(ui.languageFacetList.get()).getByRole('checkbox', { name: 'java' }),
).toHaveTextContent('java25short_number_suffix.k');
expect(
- within(ui.languageFacetList.get()).getByRole('checkbox', { name: 'ts' })
+ within(ui.languageFacetList.get()).getByRole('checkbox', { name: 'ts' }),
).toHaveTextContent('ts3.4short_number_suffix.k');
await user.click(ui.languageFacet.get());
await user.click(ui.languageFacet.get());
expect(await ui.languageFacetList.find()).toBeInTheDocument();
expect(
- within(ui.languageFacetList.get()).getByRole('checkbox', { name: 'java' })
+ within(ui.languageFacetList.get()).getByRole('checkbox', { name: 'java' }),
).toHaveTextContent('java111');
expect(
- within(ui.languageFacetList.get()).getByRole('checkbox', { name: 'ts' })
+ within(ui.languageFacetList.get()).getByRole('checkbox', { name: 'ts' }),
).toHaveTextContent('ts674');
});
/* eslint-disable-next-line testing-library/render-result-naming-convention */
const linkName = renderOwaspTop102021Category(standard, val);
expect(screen.getByRole('checkbox', { name: linkName })).toBeInTheDocument();
- })
+ }),
);
});
});
await user.keyboard('{ArrowRight}');
});
expect(
- screen.getByRole('heading', { name: issuesHandler.list[1].issue.message })
+ screen.getByRole('heading', { name: issuesHandler.list[1].issue.message }),
).toBeInTheDocument();
// Go back
await user.keyboard('{ArrowLeft}');
});
expect(
- screen.queryByRole('heading', { name: issuesHandler.list[1].issue.message })
+ screen.queryByRole('heading', { name: issuesHandler.list[1].issue.message }),
).not.toBeInTheDocument();
// Navigate to 1st issue and select it
await user.keyboard('{ArrowRight}');
});
expect(
- screen.getByRole('heading', { name: issuesHandler.list[0].issue.message })
+ screen.getByRole('heading', { name: issuesHandler.list[0].issue.message }),
).toBeInTheDocument();
});
// Select the "why is this an issue" tab and check its content
await act(async () => {
await user.click(
- screen.getByRole('tab', { name: `coding_rules.description_section.title.root_cause` })
+ screen.getByRole('tab', { name: `coding_rules.description_section.title.root_cause` }),
);
});
expect(screen.getByRole('heading', { name: 'Because' })).toBeInTheDocument();
// Select the "how to fix it" tab
await act(async () => {
await user.click(
- screen.getByRole('tab', { name: `coding_rules.description_section.title.how_to_fix` })
+ screen.getByRole('tab', { name: `coding_rules.description_section.title.how_to_fix` }),
);
});
expect(screen.getByRole('radio', { name: 'Context 3' })).toBeInTheDocument();
expect(screen.getByRole('radio', { name: 'Spring' })).toBeInTheDocument();
expect(
- screen.getByRole('radio', { name: 'coding_rules.description_context.other' })
+ screen.getByRole('radio', { name: 'coding_rules.description_context.other' }),
).toBeInTheDocument();
expect(screen.getByRole('radio', { name: 'Spring', current: true })).toBeInTheDocument();
// Select the "other" context and check tab content
await act(async () => {
await user.click(
- screen.getByRole('radio', { name: 'coding_rules.description_context.other' })
+ screen.getByRole('radio', { name: 'coding_rules.description_context.other' }),
);
});
expect(screen.getByText('coding_rules.context.others.title')).toBeInTheDocument();
expect(screen.getByText('coding_rules.context.others.description.first')).toBeInTheDocument();
expect(
- screen.getByText('coding_rules.context.others.description.second')
+ screen.getByText('coding_rules.context.others.description.second'),
).toBeInTheDocument();
// Select the main info tab and check its content
await act(async () => {
await user.click(
- screen.getByRole('tab', { name: `coding_rules.description_section.title.more_info` })
+ screen.getByRole('tab', { name: `coding_rules.description_section.title.more_info` }),
);
});
expect(screen.getByRole('heading', { name: 'Link' })).toBeInTheDocument();
// Select the "why is this an issue tab" and check its content
await act(async () => {
await user.click(
- screen.getByRole('tab', { name: `coding_rules.description_section.title.root_cause` })
+ screen.getByRole('tab', { name: `coding_rules.description_section.title.root_cause` }),
);
});
expect(screen.getByRole('heading', { name: 'Default' })).toBeInTheDocument();
// The "Where is the issue" tab should be selected by default. Check its content
expect(screen.getAllByRole('button', { name: 'Issue on file', exact: false })).toHaveLength(
- 2
+ 2,
); // there will be 2 buttons one in concise issue and other in code viewer
expect(
screen.getByRole('row', {
name: '2 * SonarQube',
- })
+ }),
).toBeInTheDocument();
});
});
expect(
- screen.getByRole('button', { name: 'issues.bulk_change_X_issues.10' })
+ screen.getByRole('button', { name: 'issues.bulk_change_X_issues.10' }),
).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'issues.bulk_change_X_issues.10' }));
await user.click(screen.getByRole('button', { name: 'cancel' }));
const issueBoxFixThat = within(screen.getByRole('region', { name: 'Fix that' }));
await user.click(
- screen.getByRole('checkbox', { name: 'issues.action_select.label.Fix that' })
+ screen.getByRole('checkbox', { name: 'issues.action_select.label.Fix that' }),
);
await user.click(screen.getByRole('button', { name: 'issues.bulk_change_X_issues.1' }));
expect(
issueBoxFixThat.queryByLabelText(
- 'issue.transition.status_x_click_to_change.issue.status.falsepositive'
- )
+ 'issue.transition.status_x_click_to_change.issue.status.falsepositive',
+ ),
).not.toBeInTheDocument();
});
});
expect(
await screen.findByRole('tab', {
name: `coding_rules.description_section.title.root_cause`,
- })
+ }),
).toHaveAttribute('aria-current', 'true');
});
await user.keyboard('{Alt>}{ArrowRight}{/Alt}');
expect(screen.getByRole('link', { name: '1 Execution location 1' })).toHaveAttribute(
'aria-current',
- 'true'
+ 'true',
);
await user.keyboard('{Alt>}{ArrowLeft}{/Alt}');
expect(screen.getByRole('link', { name: '1 Data location 1' })).toHaveAttribute(
'aria-current',
- 'true'
+ 'true',
);
});
const user = userEvent.setup();
renderProjectIssuesApp('project/issues?issues=issue2&open=issue2&id=myproject');
await user.click(
- await screen.findByRole('tab', { name: `coding_rules.description_section.title.more_info` })
+ await screen.findByRole('tab', { name: `coding_rules.description_section.title.more_info` }),
);
expect(screen.getByRole('heading', { name: 'Defense-In-Depth', level: 3 })).toBeInTheDocument();
});
await user.click(listItem.getByText('issue.transition.confirm'));
});
expect(
- listItem.getByLabelText('issue.transition.status_x_click_to_change.issue.status.CONFIRMED')
+ listItem.getByLabelText('issue.transition.status_x_click_to_change.issue.status.CONFIRMED'),
).toBeInTheDocument();
// As won't fix
await user.click(listItem.getByRole('button', { name: 'issue.comment.formlink' }));
});
expect(
- listItem.queryByRole('button', { name: 'issue.comment.submit' })
+ listItem.queryByRole('button', { name: 'issue.comment.submit' }),
).not.toBeInTheDocument();
// Assign issue to a different user
await act(async () => {
await user.click(
- listItem.getByRole('combobox', { name: 'issue.assign.unassigned_click_to_assign' })
+ listItem.getByRole('combobox', { name: 'issue.assign.unassigned_click_to_assign' }),
);
await user.click(screen.getByLabelText('search.search_for_users'));
await user.keyboard('luke');
expect(
listItem.getByRole('combobox', {
name: 'issue.assign.assigned_to_x_click_to_change.luke',
- })
+ }),
).toBeInTheDocument();
// Change tags
await user.keyboard('{Escape}');
await expect(
- byRole('button', { name: 'accessibility android +' }).byText('accessibility').get()
+ byRole('button', { name: 'accessibility android +' }).byText('accessibility').get(),
).toHaveATooltipWithContent('accessibility, android');
await act(async () => {
await user.keyboard('{Escape}');
await expect(
- byRole('button', { name: 'android +' }).byText('android').get()
+ byRole('button', { name: 'android +' }).byText('android').get(),
).toHaveATooltipWithContent('android');
await act(async () => {
await user.keyboard('addNewTag');
});
expect(
- screen.getByRole('checkbox', { name: 'issue.create_tag: addnewtag' })
+ screen.getByRole('checkbox', { name: 'issue.create_tag: addnewtag' }),
).toBeInTheDocument();
});
expect(
screen.queryByRole('button', {
name: `issue.assign.unassigned_click_to_assign`,
- })
+ }),
).not.toBeInTheDocument();
expect(
screen.queryByRole('button', {
name: `issue.type.type_x_click_to_change.issue.type.CODE_SMELL`,
- })
+ }),
).not.toBeInTheDocument();
expect(
screen.queryByRole('button', {
name: `issue.transition.status_x_click_to_change.issue.status.OPEN`,
- })
+ }),
).not.toBeInTheDocument();
expect(
screen.queryByRole('button', {
name: `issue.severity.severity_x_click_to_change.severity.MAJOR`,
- })
+ }),
).not.toBeInTheDocument();
});
// Select the "why is this an issue" tab
await act(async () => {
await user.click(
- screen.getByRole('tab', { name: 'coding_rules.description_section.title.root_cause' })
+ screen.getByRole('tab', { name: 'coding_rules.description_section.title.root_cause' }),
);
});
expect(
screen.queryByRole('tab', {
name: `issue.tabs.${TabKeys.Code}`,
- })
+ }),
).toHaveAttribute('aria-current', 'false');
await act(async () => {
expect(
screen.queryByRole('tab', {
name: `issue.tabs.${TabKeys.Code}`,
- })
+ }),
).toHaveAttribute('aria-current', 'true');
// Select the same selected hotspot location should also navigate back to code page
await act(async () => {
await user.click(
- screen.getByRole('tab', { name: 'coding_rules.description_section.title.root_cause' })
+ screen.getByRole('tab', { name: 'coding_rules.description_section.title.root_cause' }),
);
});
expect(
screen.queryByRole('tab', {
name: `issue.tabs.${TabKeys.Code}`,
- })
+ }),
).toHaveAttribute('aria-current', 'false');
await act(async () => {
expect(
screen.queryByRole('tab', {
name: `issue.tabs.${TabKeys.Code}`,
- })
+ }),
).toHaveAttribute('aria-current', 'true');
});
});
await expect(
- screen.getByText('issue.quick_fix_available_with_sonarlint_no_link')
+ screen.getByText('issue.quick_fix_available_with_sonarlint_no_link'),
).toHaveATooltipWithContent('issue.quick_fix_available_with_sonarlint');
});
});
});
expect(
- screen.getByRole('tab', { name: `coding_rules.description_section.title.activity` })
+ screen.getByRole('tab', { name: `coding_rules.description_section.title.activity` }),
).toBeInTheDocument();
await act(async () => {
await user.click(
- screen.getByRole('tab', { name: `coding_rules.description_section.title.activity` })
+ screen.getByRole('tab', { name: `coding_rules.description_section.title.activity` }),
);
});
await user.click(
screen.getByRole('button', {
name: `issue.activity.add_comment`,
- })
+ }),
);
await user.click(screen.getByRole('textbox'));
await user.keyboard('activity comment');
await user.click(await screen.findByRole('link', { name: 'Fix that' }));
await user.click(
- screen.getByRole('tab', { name: `coding_rules.description_section.title.activity` })
+ screen.getByRole('tab', { name: `coding_rules.description_section.title.activity` }),
);
});
expect(screen.getByText('issue.activity.review_history.created')).toBeInTheDocument();
expect(
screen.getByText(
- 'issue.changelog.changed_to.issue.changelog.field.assign.darth.vader (issue.changelog.was.luke.skywalker)'
- )
+ 'issue.changelog.changed_to.issue.changelog.field.assign.darth.vader (issue.changelog.was.luke.skywalker)',
+ ),
).toBeInTheDocument();
expect(
screen.getByText(
- 'issue.changelog.changed_to.issue.changelog.field.status.REOPENED (issue.changelog.was.CONFIRMED)'
- )
+ 'issue.changelog.changed_to.issue.changelog.field.status.REOPENED (issue.changelog.was.CONFIRMED)',
+ ),
).toBeInTheDocument();
});
it('should not show guide for those who dismissed it', async () => {
renderIssueApp(
- mockCurrentUser({ isLoggedIn: true, dismissedNotices: { [NoticeType.ISSUE_GUIDE]: true } })
+ mockCurrentUser({ isLoggedIn: true, dismissedNotices: { [NoticeType.ISSUE_GUIDE]: true } }),
);
expect((await ui.issueItems.findAll()).length).toBeGreaterThan(0);
renderProjectIssuesApp(
'project/issues?issues=issue11&open=issue11&id=myproject',
undefined,
- mockCurrentUser({ isLoggedIn: true })
+ mockCurrentUser({ isLoggedIn: true }),
);
expect(await ui.guidePopup.find()).toBeInTheDocument();
describe('enableLocationsNavigator', () => {
it('should compute the correct flow index', () => {
expect(
- enableLocationsNavigator({ openIssue: mockIssue(true), selectedFlowIndex: 20 } as State)
+ enableLocationsNavigator({ openIssue: mockIssue(true), selectedFlowIndex: 20 } as State),
).toEqual(
expect.objectContaining({
locationsNavigator: true,
selectedFlowIndex: 20,
- })
+ }),
);
expect(enableLocationsNavigator({ openIssue: mockIssue(true) } as State)).toEqual(
expect.objectContaining({
locationsNavigator: true,
selectedFlowIndex: 0,
- })
+ }),
);
expect(
- enableLocationsNavigator({ openIssue: mockIssue(true, { flows: [] }) } as State)
+ enableLocationsNavigator({ openIssue: mockIssue(true, { flows: [] }) } as State),
).toEqual(
expect.objectContaining({
locationsNavigator: true,
selectedFlowIndex: undefined,
- })
+ }),
);
});
expect.objectContaining({
locationsNavigator: true,
selectedLocationIndex: undefined,
- })
+ }),
);
expect(
- enableLocationsNavigator({ openIssue: mockIssue(true), selectedLocationIndex: -1 } as State)
+ enableLocationsNavigator({ openIssue: mockIssue(true), selectedLocationIndex: -1 } as State),
).toEqual(
expect.objectContaining({
locationsNavigator: true,
selectedLocationIndex: 0,
- })
+ }),
);
expect(
- enableLocationsNavigator({ openIssue: mockIssue(true), selectedLocationIndex: 20 } as State)
+ enableLocationsNavigator({ openIssue: mockIssue(true), selectedLocationIndex: 20 } as State),
).toEqual(
expect.objectContaining({
locationsNavigator: true,
selectedLocationIndex: 20,
- })
+ }),
);
});
expect(
enableLocationsNavigator({
openIssue: mockIssue(true, { flows: [], secondaryLocations: [] }),
- } as State)
+ } as State),
).toBeNull();
});
statuses: ['a', 'b'],
tags: ['a', 'b'],
types: ['a', 'b'],
- })
+ }),
).toStrictEqual({
assignees: 'a,b',
author: ['a', 'b'],
impactSeverities: 'LOW',
severities: 'CRITICAL,MAJOR',
impactSoftwareQualities: 'MAINTAINABILITY',
- })
+ }),
).toStrictEqual({
assigned: true,
assignees: ['first', 'second'],
describe('shouldOpenStandardsChildFacet', () => {
it('should open standard child facet', () => {
expect(
- shouldOpenStandardsChildFacet({ owaspTop10: true }, {}, SecurityStandard.OWASP_TOP10)
+ shouldOpenStandardsChildFacet({ owaspTop10: true }, {}, SecurityStandard.OWASP_TOP10),
).toBe(true);
expect(
shouldOpenStandardsChildFacet(
{ cwe: true },
{ owaspTop10: ['A1'] },
- SecurityStandard.OWASP_TOP10
- )
+ SecurityStandard.OWASP_TOP10,
+ ),
).toBe(true);
expect(
shouldOpenStandardsChildFacet(
{ owaspTop10: false },
{ owaspTop10: ['A1'] },
- SecurityStandard.OWASP_TOP10
- )
+ SecurityStandard.OWASP_TOP10,
+ ),
).toBe(true);
expect(
- shouldOpenStandardsChildFacet({}, { owaspTop10: ['A1'] }, SecurityStandard.OWASP_TOP10)
+ shouldOpenStandardsChildFacet({}, { owaspTop10: ['A1'] }, SecurityStandard.OWASP_TOP10),
).toBe(true);
expect(
shouldOpenStandardsChildFacet(
{},
{ owaspTop10: ['A1'], sonarsourceSecurity: ['sql-injection'] },
- SecurityStandard.SONARSOURCE
- )
+ SecurityStandard.SONARSOURCE,
+ ),
).toBe(true);
});
it('should NOT open standard child facet', () => {
expect(
- shouldOpenStandardsChildFacet({ standards: true }, {}, SecurityStandard.OWASP_TOP10)
+ shouldOpenStandardsChildFacet({ standards: true }, {}, SecurityStandard.OWASP_TOP10),
).toBe(false);
expect(shouldOpenStandardsChildFacet({ cwe: true }, {}, SecurityStandard.OWASP_TOP10)).toBe(
- false
+ false,
);
expect(
- shouldOpenStandardsChildFacet({}, { types: ['VULNERABILITY'] }, SecurityStandard.OWASP_TOP10)
+ shouldOpenStandardsChildFacet({}, { types: ['VULNERABILITY'] }, SecurityStandard.OWASP_TOP10),
).toBe(false);
expect(
shouldOpenStandardsChildFacet(
{},
{ owaspTop10: ['A1'], sonarsourceSecurity: ['sql-injection'] },
- SecurityStandard.OWASP_TOP10_2021
- )
+ SecurityStandard.OWASP_TOP10_2021,
+ ),
).toBe(false);
});
});
expect(
shouldOpenSonarSourceSecurityFacet(
{ sonarsourceSecurity: false },
- { sonarsourceSecurity: ['xss'] }
- )
+ { sonarsourceSecurity: ['xss'] },
+ ),
).toBe(true);
});
}
export function selectNextLocation(
- state: Pick<State, 'selectedFlowIndex' | 'selectedLocationIndex' | 'openIssue'>
+ state: Pick<State, 'selectedFlowIndex' | 'selectedLocationIndex' | 'openIssue'>,
) {
const { selectedFlowIndex, selectedLocationIndex: index = -1, openIssue } = state;
if (openIssue) {
.then(resolve)
.catch(() => resolve([]));
},
- []
+ [],
);
return (
});
}
},
- () => {}
+ () => {},
);
}
set_severity: this.state.severity,
set_type: this.state.type,
},
- (x) => x !== undefined
+ (x) => x !== undefined,
);
const issueKeys = this.state.issues.map((issue) => issue.key);
(error) => {
this.setState({ submitting: false });
throwGlobalError(error);
- }
+ },
);
};
assignee ||
severity ||
transition ||
- type
+ type,
);
};
field: InputField,
label: string,
affected: number | undefined,
- input: React.ReactNode
+ input: React.ReactNode,
) => (
<FormField htmlFor={`issues-bulk-change-${field}`} label={translate(label)}>
<div className="sw-flex sw-items-center sw-justify-between">
renderTagsField = (
field: InputField.addTags | InputField.removeTags,
label: string,
- allowCreate: boolean
+ allowCreate: boolean,
) => {
const { initialTags } = this.state;
const tags = this.state[field] ?? [];
const displayProject =
!component ||
![ComponentQualifier.Project, ComponentQualifier.Directory].includes(
- component.qualifier as ComponentQualifier
+ component.qualifier as ComponentQualifier,
);
const displayBranchInformation = isView(component?.qualifier);
<DivStyled
aria-label={translateWithParameters(
'issues.on_file_x',
- `${displayProject ? issue.projectName + ', ' : ''}${componentName}`
+ `${displayProject ? issue.projectName + ', ' : ''}${componentName}`,
)}
className="sw-flex sw-box-border sw-body-sm sw-w-full sw-pb-2 sw-pt-4 sw-truncate"
>
const constructContent = (
first: string,
second: string,
- extraContent?: string | React.ReactNode
+ extraContent?: string | React.ReactNode,
) => (
<>
<span>{translate(first)}</span>
<li>{translate('guiding.issue_list.4.content.list.1')}</li>
<li>{translate('guiding.issue_list.4.content.list.2')}</li>
<li>{translate('guiding.issue_list.4.content.list.3')}</li>
- </ul>
+ </ul>,
),
title: translate('guiding.issue_list.4.title'),
},
if (issue.assignee !== login) {
updateIssue(
this.props.onIssueChange,
- setIssueAssignee({ issue: issue.key, assignee: login })
+ setIssueAssignee({ issue: issue.key, assignee: login }),
);
}
this.handleIssuePopupToggle('assign', false);
({ changelog }) => {
setChangeLog(changelog);
},
- () => {}
+ () => {},
);
}, [issue]);
handleSubmitComment = (comment: string) => {
return updateIssue(
this.props.onChange,
- addIssueComment({ issue: this.props.issue.key, text: comment })
+ addIssueComment({ issue: this.props.issue.key, text: comment }),
);
};
'owaspTop10-2021': shouldOpenStandardsChildFacet(
{},
query,
- SecurityStandard.OWASP_TOP10_2021
+ SecurityStandard.OWASP_TOP10_2021,
),
cleanCodeAttributeCategories: true,
impactSoftwareQualities: true,
const { components, issues, rules } = response;
const parsedIssues = issues.map((issue) =>
- parseIssueFromResponse(issue, components, undefined, rules)
+ parseIssueFromResponse(issue, components, undefined, rules),
);
return { ...response, issues: parsedIssues } as FetchIssuesPromise;
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
}).then((response) => {
const parsedIssues = response.issues.map((issue) =>
- parseIssueFromResponse(issue, response.components, response.users, response.rules)
+ parseIssueFromResponse(issue, response.components, response.users, response.rules),
);
return { ...response, issues: parsedIssues } as FetchIssuesPromise;
fetchIssues = (
additional: RawQuery,
requestFacets = false,
- firstRequest = false
+ firstRequest = false,
): Promise<FetchIssuesPromise> => {
const { component } = this.props;
const { myIssues, openFacets, query } = this.state;
fetchIssuesUntil = (
page: number,
- done: (pageIssues: Issue[], paging: Paging) => boolean
+ done: (pageIssues: Issue[], paging: Paging) => boolean,
): Promise<FetchIssuesPromise> => {
const recursiveFetch = (p: number, prevIssues: Issue[]): Promise<FetchIssuesPromise> => {
return this.fetchIssuesPage(p).then(({ issues: pageIssues, paging, ...other }) => {
if (this.mounted) {
this.setState({ loadingMore: false });
}
- }
+ },
);
};
},
() => {
/* Do nothing */
- }
+ },
);
};
if (willOpenProperty && property === STANDARDS) {
newState.openFacets.sonarsourceSecurity = shouldOpenSonarSourceSecurityFacet(
newState.openFacets,
- state.query
+ state.query,
);
// Force loading of sonarsource security facet data
<FlagMessage className="sw-mb-4" variant="warning">
{translateWithParameters(
'issues.cannot_open_issue_max_initial_X_fetched',
- MAX_INITAL_FETCH
+ MAX_INITAL_FETCH,
)}
</FlagMessage>
)}
title={openIssue.message}
titleTemplate={translateWithParameters(
'page_title.template.with_category',
- translate('issues.page')
+ translate('issues.page'),
)}
/>
) : (
(isCompleted === false || hasFailures === true || completedCount !== total)) ||
(component?.qualifier !== ComponentQualifier.Project &&
component?.needIssueSync === true),
- })
- )
- )
- )
- )
+ }),
+ ),
+ ),
+ ),
+ ),
);
const PageWrapperStyle = styled.div`
const selectedLocation = getSelectedLocation(
openIssue,
selectedFlowIndex,
- selectedLocationIndex
+ selectedLocationIndex,
);
const highlightedLocationMessage =
const results = await onSearch(query);
setSearchResults(results);
},
- [onSearch, setSearchResults]
+ [onSearch, setSearchResults],
);
const onSelect = React.useCallback(
(newTag: string) => {
onChange([...selectedTags, newTag]);
},
- [onChange, selectedTags]
+ [onChange, selectedTags],
);
const onUnselect = React.useCallback(
(toRemove: string) => {
onChange(selectedTags.filter((tag) => tag !== toRemove));
},
- [onChange, selectedTags]
+ [onChange, selectedTags],
);
return (
{
issues: [mockIssue(false, { assignee: 'someone' })],
},
- mockLoggedInUser({ name: 'Skywalker' })
+ mockLoggedInUser({ name: 'Skywalker' }),
);
await user.click(ui.combobox.get());
{
issues: [mockIssue(false, { assignee: 'luke' })],
},
- mockLoggedInUser({ login: 'luke', name: 'Skywalker' })
+ mockLoggedInUser({ login: 'luke', name: 'Skywalker' }),
);
await user.click(ui.combobox.get());
function renderAssigneeSelect(
overrides: Partial<AssigneeSelectProps> = {},
- currentUser: CurrentUser = mockCurrentUser()
+ currentUser: CurrentUser = mockCurrentUser(),
) {
return renderComponent(
<CurrentUserContextProvider currentUser={currentUser}>
<AssigneeSelect inputId="id" issues={[]} onAssigneeSelect={jest.fn()} {...overrides} />
- </CurrentUserContextProvider>
+ </CurrentUserContextProvider>,
);
}
renderBulkChangeModal(issues, { needIssueSync: true });
expect(
- await screen.findByText(`issue_bulk_change.form.title.${MAX_PAGE_SIZE}`)
+ await screen.findByText(`issue_bulk_change.form.title.${MAX_PAGE_SIZE}`),
).toBeInTheDocument();
expect(await screen.findByText('issue_bulk_change.max_issues_reached')).toBeInTheDocument();
mockLoggedInUser({
login: 'toto',
name: 'Toto',
- })
+ }),
);
expect(bulkChangeIssues).toHaveBeenCalledTimes(0);
// Assign
await user.click(
- await screen.findByRole('combobox', { name: 'issue_bulk_change.assignee.change' })
+ await screen.findByRole('combobox', { name: 'issue_bulk_change.assignee.change' }),
);
await user.click(await screen.findByText('Toto'));
function renderBulkChangeModal(
issues: Issue[],
props: Partial<ComponentPropsType<typeof BulkChangeModal>> = {},
- currentUser: CurrentUser = mockLoggedInUser()
+ currentUser: CurrentUser = mockLoggedInUser(),
) {
return renderComponent(
<CurrentUserContextProvider currentUser={currentUser}>
{...props}
/>
</CurrentUserContextProvider>,
- ''
+ '',
);
}
function renderComponentBreadcrumbs(component?: Component, issue: Partial<Issue> = {}) {
return renderComponent(
- <ComponentBreadcrumbs component={component} issue={{ ...baseIssue, ...issue }} />
+ <ComponentBreadcrumbs component={component} issue={{ ...baseIssue, ...issue }} />,
);
}
renderDuplicationPopup: (
component: SourceViewerFile,
index: number,
- line: number
+ line: number,
) => React.ReactNode;
snippetGroup: SnippetGroup;
}
line.coverageStatus = getCoverageStatus(line);
lineMap[line.line] = line;
return lineMap;
- }, {})
+ }, {}),
)
.then((newLinesMapped) => {
const newSnippets = expandSnippet({
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
};
handleSymbolClick = (clickedSymbols: string[]) => {
this.setState(({ highlightedSymbols }) => {
const newHighlightedSymbols = clickedSymbols.filter(
- (symb) => !highlightedSymbols.includes(symb)
+ (symb) => !highlightedSymbols.includes(symb),
);
return { highlightedSymbols: newHighlightedSymbols };
});
const issuesForLine = (issuesByLine[line.line] || []).filter(
(issueForline) =>
issue.key !== issueForline.key ||
- (issue.key === issueForline.key && issueLocations.length > 0)
+ (issue.key === issueForline.key && issueLocations.length > 0),
);
return (
locationsByLine={getLocationsByLine(
issue,
snippetGroup,
- isLastOccurenceOfPrimaryComponent
+ isLastOccurenceOfPrimaryComponent,
)}
onLocationSelect={this.props.onLocationSelect}
renderDuplicationPopup={this.renderDuplicationPopup}
function getLocationsByLine(
issue: TypeIssue,
snippetGroup: SnippetGroup,
- isLastOccurenceOfPrimaryComponent: boolean
+ isLastOccurenceOfPrimaryComponent: boolean,
) {
const isFlow = issue.secondaryLocations.length === 0;
const includeIssueLocation = isFlow ? isLastOccurenceOfPrimaryComponent : true;
},
() => {
/* No error hanlding here */
- }
+ },
);
};
const locationsByComponent = groupLocationsByComponent(issue, locations, components);
const lastOccurenceOfPrimaryComponent = findLastIndex(locationsByComponent, ({ component }) =>
- component ? component.key === issue.component : true
+ component ? component.key === issue.component : true,
);
if (components[issue.component] === undefined) {
<IssueSourceViewerStyle
className={classNames(
'sw-flex sw-justify-space-between sw-items-center sw-px-4 sw-py-3 sw-text-sm',
- className
+ className,
)}
role="separator"
aria-label={sourceViewerFile.path}
throttle(
(hoveredLine: number) =>
snippetSourcesMap ? setHoveredLine(snippetSourcesMap[hoveredLine]) : undefined,
- THROTTLE_SHORT_DELAY
+ THROTTLE_SHORT_DELAY,
),
- [snippetSourcesMap]
+ [snippetSourcesMap],
);
const onLineMouseLeave = React.useMemo(
debounce(
(line: number) =>
setHoveredLine((hoveredLine) => (hoveredLine?.line === line ? undefined : hoveredLine)),
- THROTTLE_SHORT_DELAY
+ THROTTLE_SHORT_DELAY,
),
- []
+ [],
);
return (
{snippet.map((line, index) => {
const secondaryIssueLocations = getSecondaryIssueLocationsForLine(
line,
- props.locations
+ props.locations,
);
const lineDuplications =
(duplicationsCount && duplicationsByLine && duplicationsByLine[line.line]) || [];
highlighted={false}
highlightedLocationMessage={optimizeLocationMessage(
props.highlightedLocationMessage,
- secondaryIssueLocations
+ secondaryIssueLocations,
)}
highlightedSymbols={optimizeHighlightedSymbols(
symbols[line.line],
- props.highlightedSymbols
+ props.highlightedSymbols,
)}
issueLocations={locationsByLine[line.line] || []}
issues={[]}
onExpand={jest.fn()}
sourceViewerFile={mockSourceViewerFile('foo/bar.ts', 'my-project')}
{...props}
- />
+ />,
);
}
renderDuplicationPopup={jest.fn()}
snippet={[]}
{...props}
- />
+ />,
);
}
'main.js': mockSnippetsByComponent(
'main.js',
'project',
- [14, 15, 16, 17, 18, 22, 23, 24, 25, 26]
+ [14, 15, 16, 17, 18, 22, 23, 24, 25, 26],
),
- }
+ },
);
expect(results).toHaveLength(1);
{
'A.js': mockSnippetsByComponent('A.js', 'project', [13, 14, 15, 16, 17, 18]),
'B.js': mockSnippetsByComponent('B.js', 'project', [14, 15, 16, 17, 18]),
- }
+ },
);
expect(results).toHaveLength(3);
return snippets;
},
- []
+ [],
);
// Sort snippets by line number
export function groupLocationsByComponent(
issue: Issue,
locations: FlowLocation[],
- components: { [key: string]: SnippetsByComponent }
+ components: { [key: string]: SnippetsByComponent },
) {
let currentComponent = '';
let currentGroup: SnippetGroup;
snippetToExpand.start = Math.max(
0,
- snippetToExpand.start - (direction === 'up' ? EXPAND_BY_LINES : 0)
+ snippetToExpand.start - (direction === 'up' ? EXPAND_BY_LINES : 0),
);
snippetToExpand.end += direction === 'down' ? EXPAND_BY_LINES : 0;
export function getIssueReviewHistory(
issue: Issue,
- changelog: IssueChangelog[]
+ changelog: IssueChangelog[],
): ReviewHistoryElement[] {
const history: ReviewHistoryElement[] = [];
name: log.userName || log.user,
},
diffs: log.diffs,
- }))
+ })),
);
}
html: comment.htmlText,
key: comment.key,
markdown: comment.markdown,
- }))
+ })),
);
}
event.preventDefault();
onClick(index);
},
- [index, onClick]
+ [index, onClick],
);
return (
const { concealed, issue, locations, onLocationSelect, selectedLocationIndex } = props;
const isCrossFile = useMemo(
() => locations.some((location) => location.component !== issue.component),
- [locations, issue.component]
+ [locations, issue.component],
);
return isCrossFile ? (
renderGroup = (
group: LocationGroup,
groupIndex: number,
- { onlyFirst = false, onlyLast = false } = {}
+ { onlyFirst = false, onlyLast = false } = {},
) => {
const { firstLocationIndex } = group;
const lastLocationIndex = group.locations.length - 1;
{onlyLast &&
this.renderLocation(
firstLocationIndex + lastLocationIndex,
- group.locations[lastLocationIndex].msg
+ group.locations[lastLocationIndex].msg,
)}
{!onlyFirst &&
!onlyLast &&
group.locations.map((location, index) =>
- this.renderLocation(firstLocationIndex + index, location.msg)
+ this.renderLocation(firstLocationIndex + index, location.msg),
)}
</GroupBody>
)}
>
{translateWithParameters(
'issues.show_x_more_locations',
- locations.length - VISIBLE_LOCATIONS_COLLAPSE
+ locations.length - VISIBLE_LOCATIONS_COLLAPSE,
)}
</ExpandLink>
</div>
}
}
},
- [selectedFlowIndex, onFlowSelect]
+ [selectedFlowIndex, onFlowSelect],
);
if (!hasSecondaryLocations && !hasFlows) {
],
{
selected: 'custom',
- }
+ },
);
expect(ui.expandBadgesButton.query()).not.toBeInTheDocument();
component: `component-${i}`,
index: i,
msg: `loc ${i}`,
- })
+ }),
);
renderConciseIssues(
{
selected: 'custom',
selectedFlowIndex: 0,
- }
+ },
);
expect(ui.expandBadgesButton.get()).toBeInTheDocument();
{
onFlowSelect,
selected: 'custom',
- }
+ },
);
expect(onFlowSelect).not.toHaveBeenCalled();
function renderConciseIssues(
issues: Issue[],
- listProps: Partial<ComponentPropsType<typeof SubnavigationIssuesList>> = {}
+ listProps: Partial<ComponentPropsType<typeof SubnavigationIssuesList>> = {},
) {
const wrapper = renderComponent(
<SubnavigationIssuesList
selectedFlowIndex={undefined}
selectedLocationIndex={undefined}
{...listProps}
- />
+ />,
);
function override(
issues: Issue[],
- listProps: Partial<ComponentPropsType<typeof SubnavigationIssuesList>> = {}
+ listProps: Partial<ComponentPropsType<typeof SubnavigationIssuesList>> = {},
) {
wrapper.rerender(
<SubnavigationIssuesList
selectedFlowIndex={undefined}
selectedLocationIndex={undefined}
{...listProps}
- />
+ />,
);
}
branch: searchParams.get('branch'),
pullRequest: searchParams.get('pullRequest'),
assignedToMe: 'false',
- })
+ }),
).toString(),
},
- { replace: true }
+ { replace: true },
);
} else {
const filteredTypes = types
this.props.onChange({ assigned: !this.props.assigned, assignees: [] });
} else if (multiple) {
const newValue = sortBy(
- assignees.includes(itemValue) ? without(assignees, itemValue) : [...assignees, itemValue]
+ assignees.includes(itemValue) ? without(assignees, itemValue) : [...assignees, itemValue],
);
this.props.onChange({ assigned: true, assignees: newValue });
// put "not assigned" first
(key) => (key === '' ? 0 : 1),
// the sort by number
- (key) => -stats[key]
+ (key) => -stats[key],
);
};
'issues.facet.createdAt.bar_description',
formatMeasure(stats[start], MetricType.ShortInteger),
formatDate(startDate, longFormatterOption),
- formatDate(tooltipEndDate, longFormatterOption)
+ formatDate(tooltipEndDate, longFormatterOption),
);
return {
const maxValue = max(data.map((d) => d.y));
const xValues = data.map((d) =>
- d.y === maxValue ? formatMeasure(maxValue, MetricType.ShortInteger) : ''
+ d.y === maxValue ? formatMeasure(maxValue, MetricType.ShortInteger) : '',
);
return (
return this.renderFile(
<>
{head}/{highlightTerm(tail, term)}
- </>
+ </>,
);
};
const options = this.getAllPossibleOptions();
const results = options.filter((language) =>
- language.name.toLowerCase().includes(query.toLowerCase())
+ language.name.toLowerCase().includes(query.toLowerCase()),
);
const paging = { pageIndex: 1, pageSize: results.length, total: results.length };
// and make sure we reference each language only once
return uniqBy(
[...Object.values(languages), ...Object.keys(stats).map((key) => ({ key, name: key }))],
- (language) => language.key
+ (language) => language.key,
);
};
if (multiple) {
const newValue = sortBy(
- values.includes(itemValue) ? without(values, itemValue) : [...values, itemValue]
+ values.includes(itemValue) ? without(values, itemValue) : [...values, itemValue],
);
this.props.onChange({ [this.props.property]: newValue });
: sortBy(
Object.keys(stats),
(key) => -stats[key],
- (key) => this.props.getFacetItemText(key)
+ (key) => this.props.getFacetItemText(key),
);
const limitedList = this.state.showFullList
export class ProjectFacet extends React.PureComponent<Props> {
handleSearch = (
query: string,
- page = 1
+ page = 1,
): Promise<{ results: SearchedProject[]; paging: Paging }> => {
const { component } = this.props;
const newValue = orderBy(
resolutions.includes(itemValue)
? without(resolutions, itemValue)
- : [...resolutions, itemValue]
+ : [...resolutions, itemValue],
);
this.props.onChange({ resolved: true, [this.property]: newValue });
});
}
},
- () => {}
+ () => {},
);
};
getValues = () => {
return [
...this.props.sonarsourceSecurity.map((item) =>
- renderSonarSourceSecurityCategory(this.state.standards, item, true)
+ renderSonarSourceSecurityCategory(this.state.standards, item, true),
),
...this.props.owaspTop10.map((item) =>
- renderOwaspTop10Category(this.state.standards, item, true)
+ renderOwaspTop10Category(this.state.standards, item, true),
),
...this.props['owaspTop10-2021'].map((item) =>
- renderOwaspTop102021Category(this.state.standards, item, true)
+ renderOwaspTop102021Category(this.state.standards, item, true),
),
...this.props.cwe.map((item) => renderCWECategory(this.state.standards, item)),
];
if (multiple) {
const newValue = sortBy(
- items.includes(itemValue) ? without(items, itemValue) : [...items, itemValue]
+ items.includes(itemValue) ? without(items, itemValue) : [...items, itemValue],
);
this.props.onChange({ [prop]: newValue });
handleCWESearch = (query: string) => {
return Promise.resolve({
results: Object.keys(this.state.standards.cwe).filter((cwe) =>
- renderCWECategory(this.state.standards, cwe).toLowerCase().includes(query.toLowerCase())
+ renderCWECategory(this.state.standards, cwe).toLowerCase().includes(query.toLowerCase()),
),
});
};
statsProp: StatsProp,
valuesProp: ValuesProp,
renderName: (standards: Standards, category: string) => string,
- onClick: (x: string, multiple?: boolean) => void
+ onClick: (x: string, multiple?: boolean) => void,
) => {
const stats = this.props[statsProp];
const values = this.props[valuesProp];
categories: string[],
renderName: (standards: Standards, category: string) => React.ReactNode,
renderTooltip: (standards: Standards, category: string) => string,
- onClick: (x: string, multiple?: boolean) => void
+ onClick: (x: string, multiple?: boolean) => void,
) => {
if (!categories.length) {
return <TextMuted className="sw-ml-2 sw-mt-1" text={translate('no_results')} />;
'owaspTop10Stats',
SecurityStandard.OWASP_TOP10,
renderOwaspTop10Category,
- this.handleOwaspTop10ItemClick
+ this.handleOwaspTop10ItemClick,
);
}
'owaspTop10-2021Stats',
SecurityStandard.OWASP_TOP10_2021,
renderOwaspTop102021Category,
- this.handleOwaspTop102021ItemClick
+ this.handleOwaspTop102021ItemClick,
);
}
const sortedItems = sortBy(
Object.keys(stats),
(key) => -stats[key],
- (key) => renderSonarSourceSecurityCategory(this.state.standards, key)
+ (key) => renderSonarSourceSecurityCategory(this.state.standards, key),
);
const limitedList = this.state.showFullSonarSourceList
if (multiple) {
const newValue = orderBy(
- statuses.includes(itemValue) ? without(statuses, itemValue) : [...statuses, itemValue]
+ statuses.includes(itemValue) ? without(statuses, itemValue) : [...statuses, itemValue],
);
this.props.onChange({ [this.property]: newValue });
const { types } = this.props;
if (multiple) {
const newValue = orderBy(
- types.includes(itemValue) ? without(types, itemValue) : [...types, itemValue]
+ types.includes(itemValue) ? without(types, itemValue) : [...types, itemValue],
);
this.props.onChange({ [this.property]: newValue });
} else {
onChange({ [FACET_NAME]: undefined });
} else if (multiple) {
const newValues = orderBy(
- values.includes(value) ? without(values, value) : [...values, value]
+ values.includes(value) ? without(values, value) : [...values, value],
);
onChange({ [FACET_NAME]: newValues });
}
},
- [values, onChange]
+ [values, onChange],
);
const id = `facet_${FACET_NAME}`;
{sortBy(
Object.keys(stats),
(key) => -stats[key],
- (key) => key
+ (key) => key,
).map((codeVariant) => (
<FacetItem
active={values.includes(codeVariant)}
stats={{ a: 10, b: 8, c: 1 }}
values={[]}
{...props}
- />
+ />,
);
}
function render(props: Partial<Props> = {}) {
return renderComponent(
- <ListStyleFacetFooter nbShown={1} showMore={jest.fn()} total={42} {...props} />
+ <ListStyleFacetFooter nbShown={1} showMore={jest.fn()} total={42} {...props} />,
);
}
referencedRules={{}}
referencedUsers={{}}
{...props}
- />
+ />,
);
}
}
export function renderIssueApp(
- currentUser = mockCurrentUser({ dismissedNotices: { [NoticeType.ISSUE_GUIDE]: true } })
+ currentUser = mockCurrentUser({ dismissedNotices: { [NoticeType.ISSUE_GUIDE]: true } }),
) {
renderApp('issues', <IssuesApp />, { currentUser });
}
export function renderProjectIssuesApp(
navigateTo?: string,
overrides?: Partial<Component>,
- currentUser = mockCurrentUser({ dismissedNotices: { [NoticeType.ISSUE_GUIDE]: true } })
+ currentUser = mockCurrentUser({ dismissedNotices: { [NoticeType.ISSUE_GUIDE]: true } }),
) {
renderAppWithComponentContext(
'project/issues',
</Route>
),
{ navigateTo, currentUser },
- { component: mockComponent(overrides) }
+ { component: mockComponent(overrides) },
);
}
author: isArray(query.author) ? query.author : [query.author].filter(isDefined),
cleanCodeAttributeCategories: parseAsArray<CleanCodeAttributeCategory>(
query.cleanCodeAttributeCategories,
- parseAsString
+ parseAsString,
),
createdAfter: parseAsDate(query.createdAfter),
createdAt: parseAsString(query.createdAt),
impactSeverities: parseAsArray<SoftwareImpactSeverity>(query.impactSeverities, parseAsString),
impactSoftwareQualities: parseAsArray<SoftwareQuality>(
query.impactSoftwareQualities,
- parseAsString
+ parseAsString,
),
inNewCodePeriod: parseAsBoolean(query.inNewCodePeriod, false),
issues: parseAsArray(query.issues, parseAsString),
export const searchAssignees = (
query: string,
- page = 1
+ page = 1,
): Promise<{ paging: Paging; results: RestUser[] }> => {
return getUsers<RestUser>({ pageIndex: page, q: query }).then(({ page, users }) => ({
paging: page,
secondaryLocations,
flowsWithType,
}: Pick<Issue, 'flows' | 'secondaryLocations' | 'flowsWithType'>,
- selectedFlowIndex: number | undefined
+ selectedFlowIndex: number | undefined,
) {
if (secondaryLocations.length > 0) {
return secondaryLocations;
export function getSelectedLocation(
issue: Pick<Issue, 'flows' | 'secondaryLocations' | 'flowsWithType'>,
selectedFlowIndex: number | undefined,
- selectedLocationIndex: number | undefined
+ selectedLocationIndex: number | undefined,
) {
const locations = getLocations(issue, selectedFlowIndex);
if (
export function allLocationsEmpty(
issue: Pick<Issue, 'flows' | 'secondaryLocations' | 'flowsWithType'>,
- selectedFlowIndex: number | undefined
+ selectedFlowIndex: number | undefined,
) {
return getLocations(issue, selectedFlowIndex).every((location) => !location.msg);
}
export function shouldOpenStandardsFacet(
openFacets: Dict<boolean>,
- query: Partial<Query>
+ query: Partial<Query>,
): boolean {
return (
openFacets[STANDARDS] ||
| SecurityStandard.CWE
| SecurityStandard.OWASP_TOP10
| SecurityStandard.OWASP_TOP10_2021
- | SecurityStandard.SONARSOURCE
+ | SecurityStandard.SONARSOURCE,
): boolean {
const filter = query[standardType];
return (
export function shouldOpenSonarSourceSecurityFacet(
openFacets: Dict<boolean>,
- query: Partial<Query>
+ query: Partial<Query>,
): boolean {
// Open it by default if the parent is open, and no other standard is open.
return (
| SecurityStandard.CWE
| SecurityStandard.OWASP_TOP10
| SecurityStandard.OWASP_TOP10_2021
- | SecurityStandard.SONARSOURCE
- ) => shouldOpenStandardsChildFacet(openFacets, query, standardType)
+ | SecurityStandard.SONARSOURCE,
+ ) => shouldOpenStandardsChildFacet(openFacets, query, standardType),
);
}
this.setState({ message, startedAt, state });
}
},
- () => {}
+ () => {},
);
};
// eslint-disable-next-line jest/no-conditional-expect
expect(link).toHaveAttribute('href', linkInfo.href);
}
- }
+ },
);
it('should poll status', async () => {
location={mockLocation({ query: { return_to: '/return/to' } })}
setup={false}
{...props}
- />
+ />,
);
}
});
// eslint-disable-next-line jest/no-conditional-expect
expect(link).toHaveAttribute('href', linkInfo.href);
}
- }
+ },
);
it('should handle DB migration', async () => {
function renderSetupApp(props: Partial<App['props']> = {}) {
return renderApp(
'/',
- <App location={mockLocation({ query: { return_to: '/return/to' } })} setup {...props} />
+ <App location={mockLocation({ query: { return_to: '/return/to' } })} setup {...props} />,
);
}
});
fetchAllPlugins = (): Promise<Plugin[] | void> => {
return Promise.all([getInstalledPluginsWithUpdates(), getAvailablePlugins()]).then(
([installed, available]) => uniqBy([...installed, ...available.plugins], 'key'),
- this.stopLoadingPlugins
+ this.stopLoadingPlugins,
);
};
this.setState({ ...formData });
}
},
- () => {}
+ () => {},
);
};
const rowWithMultipleUpdates = rows[1];
expect(rowWithMultipleUpdates).toHaveTextContent(
- '1.2.0marketplace._installedmarketplace.updates:1.3.0'
+ '1.2.0marketplace._installedmarketplace.updates:1.3.0',
);
await user.click(ui.releaseDetailsButton.get(rowWithMultipleUpdates));
expect(ui.releaseNotesLink.getAll(rowWithMultipleUpdates)).toHaveLength(2);
// eslint-disable-next-line jest/no-conditional-expect
expect(ui[`${key}Title`].query()).not.toBeInTheDocument();
}
- }
+ },
);
expect(ui.riskConsentMessage.query()).not.toBeInTheDocument();
- }
+ },
);
describe('accessibility', () => {
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
};
plugin.update.requires
.filter(({ key }) => !installedPluginKeys.includes(key))
.map((requiredPlugin) => requiredPlugin.name)
- .join(', ')
+ .join(', '),
)}
</strong>
</p>
release={previousUpdate.release}
update={previousUpdate}
/>
- ) : null
+ ) : null,
)}
<PluginChangeLogItem release={release} update={update} />
</ul>
aria-label={translateWithParameters(
'marketplace.show_plugin_changelog',
pluginName,
- release.version
+ release.version,
)}
>
<EllipsisIcon />
release={update.release}
update={update}
/>
- ) : null
+ ) : null,
)}
</ul>
</li>
(urlQuery: RawQuery): Query => ({
filter: parseAsString(urlQuery['filter']) || DEFAULT_FILTER,
search: parseAsString(urlQuery['search']),
- })
+ }),
);
export const serializeQuery = memoize(
cleanQuery({
filter: query.filter === DEFAULT_FILTER ? undefined : serializeString(query.filter),
search: query.search ? serializeString(query.search) : undefined,
- })
+ }),
);
function getLastUpdates(updates: undefined | Update[]): Update[] {
(status) => {
const index = findLastIndex(updates, (update) => update.status === status);
return index > -1 ? updates[index] : undefined;
- }
+ },
);
return lastUpdate.filter(isDefined);
}
.then(([installed, updates]) =>
installed.map((plugin: InstalledPlugin) => {
const updatePlugin: InstalledPlugin = updates.plugins.find(
- (p: InstalledPlugin) => p.key === plugin.key
+ (p: InstalledPlugin) => p.key === plugin.key,
);
if (updatePlugin) {
return {
...updatePlugin,
...plugin,
updates: getLastUpdates(updatePlugin.updates).map((update) =>
- addChangelog(update, updatePlugin.updates)
+ addChangelog(update, updatePlugin.updates),
),
};
}
return plugin;
- })
+ }),
)
.catch(throwGlobalError);
}
.then(([updates, installed]) =>
updates.plugins.map((updatePlugin: InstalledPlugin) => {
const updates = getLastUpdates(updatePlugin.updates).map((update) =>
- addChangelog(update, updatePlugin.updates)
+ addChangelog(update, updatePlugin.updates),
);
const plugin = installed.find((p: InstalledPlugin) => p.key === updatePlugin.key);
if (plugin) {
};
}
return { ...updatePlugin, updates };
- })
+ }),
)
.catch(throwGlobalError);
}
analyses={[]}
ariaLabel={translateWithParameters(
'overview.activity.graph_shows_data_for_x',
- displayedMetrics.map((metricKey) => localizeMetric(metricKey)).join(', ')
+ displayedMetrics.map((metricKey) => localizeMetric(metricKey)).join(', '),
)}
canShowDataAsTable={false}
graph={graph}
// versions first
(event) => (event.category === 'VERSION' ? 0 : 1),
// then the rest sorted by category
- 'category'
+ 'category',
);
// use `TRK` for all components but applications
className="sw-ml-1"
overlay={translateWithParameters(
'overview.max_new_code_period_from_x',
- leakPeriod.projectName
+ leakPeriod.projectName,
)}
>
<HelperHintIcon />
<FlagMessage variant="warning">
{translateWithParameters(
'overview.quality_gate.application.non_cayc.projects_x',
- projects.length
+ projects.length,
)}
</FlagMessage>
if (this.mounted) {
this.setState({ appLeak: undefined });
}
- }
+ },
);
// We need to load the measures for each project in an application
projectBranchLike,
// Only load metrics that apply to failing QG conditions; we don't
// need the others anyway.
- project.conditions.filter((c) => c.status !== 'OK').map((c) => c.metric)
+ project.conditions.filter((c) => c.status !== 'OK').map((c) => c.metric),
).then(({ measures }) => ({
measures,
project,
projectBranchLike,
}));
- })
+ }),
).then(
(results) => {
if (this.mounted) {
if (this.mounted) {
this.setState({ loadingStatus: false, qgStatuses: undefined });
}
- }
+ },
);
};
if (this.mounted) {
this.setState({ loadingStatus: false, qgStatuses: undefined });
}
- }
+ },
);
};
loadMeasuresAndMeta = (
componentKey: string,
branchLike?: BranchLike,
- metricKeys: string[] = []
+ metricKeys: string[] = [],
) => {
return getMeasuresWithPeriodAndMetrics(
componentKey,
metricKeys.length > 0 ? metricKeys : METRICS,
- getBranchLikeQuery(branchLike)
+ getBranchLikeQuery(branchLike),
).then(({ component: { measures }, metrics, period }) => {
return {
measures: enhanceMeasuresWithMetrics(measures || [], metrics || []),
return Promise.all([this.loadHistoryMeasures(), this.loadAnalyses()]).then(
this.doneLoadingHistory,
- this.doneLoadingHistory
+ this.doneLoadingHistory,
);
};
});
}
},
- () => {}
+ () => {},
);
};
});
}
},
- () => {}
+ () => {},
);
};
loadingStatus === false &&
(measures === undefined ||
measures.find((measure) =>
- ([MetricKey.lines, MetricKey.new_lines] as string[]).includes(measure.metric.key)
+ ([MetricKey.lines, MetricKey.new_lines] as string[]).includes(measure.metric.key),
) === undefined);
return (
ariaLabel={translateWithParameters(
'overview.see_more_details_on_x_of_y',
formattedValue,
- metricName
+ metricName,
)}
branchLike={branchLike}
className="overview-measures-value text-light"
aria-label={translateWithParameters(
'overview.see_more_details_on_x_y',
measure.value,
- localizeMetric(metric)
+ localizeMetric(metric),
)}
to={url}
>
<FlagMessage className="sw-mt-4" variant="info">
<span>
{`${translate('indexation.in_progress')} ${translate(
- 'indexation.details_unavailable'
+ 'indexation.details_unavailable',
)}`}
<DocLink
className="sw-ml-1 sw-whitespace-nowrap"
}
export default function MeasuresPanelCard(
- props: React.PropsWithChildren<Props & React.HTMLAttributes<HTMLDivElement>>
+ props: React.PropsWithChildren<Props & React.HTMLAttributes<HTMLDivElement>>,
) {
const { category, children, rating, ...attributes } = props;
aria-label={translateWithParameters(
'overview.see_more_details_on_x_of_y',
value,
- localizeMetric(metricKey)
+ localizeMetric(metricKey),
)}
to={url}
>
} else if (branchLike !== undefined) {
title = translateWithParameters(
'overview.project.branch_X_empty',
- getBranchLikeDisplayName(branchLike)
+ getBranchLikeDisplayName(branchLike),
);
} else {
title = translate('overview.project.empty');
} else if (branchLike !== undefined) {
title = translateWithParameters(
'overview.project.branch_X_no_lines_of_code',
- getBranchLikeDisplayName(branchLike)
+ getBranchLikeDisplayName(branchLike),
);
}
}
leakPeriod,
['manual_baseline', NewCodeDefinitionType.SpecificAnalysis].includes(leakPeriod.mode)
? (date: string) => formatTime(date, formatterOption)
- : (date: string) => formatDate(date, longFormatterOption)
+ : (date: string) => formatDate(date, longFormatterOption),
);
if (!leakPeriodLabel) {
leakPeriod.mode === 'previous_analysis'
? 'overview.previous_analysis_x'
: 'overview.started_x',
- fromNow
+ fromNow,
)
}
</DateFromNow>
const overallFailedConditionsCount = qgStatuses.reduce(
(acc, qgStatus) => acc + qgStatus.failedConditions.length,
- 0
+ 0,
);
const isApp = isApplication(component.qualifier);
}
function splitConditions(
- conditions: QualityGateStatusConditionEnhanced[]
+ conditions: QualityGateStatusConditionEnhanced[],
): [QualityGateStatusConditionEnhanced[], QualityGateStatusConditionEnhanced[]] {
const newCodeFailedConditions = [];
const overallFailedConditions = [];
}, [collapsed]);
const [newCodeFailedConditions, overallFailedConditions] = splitConditions(
- qgStatus.failedConditions
+ qgStatus.failedConditions,
);
const showSectionTitles =
? translate('quality_gates.conditions.new_code_1')
: translateWithParameters(
'quality_gates.conditions.new_code_x',
- newCodeFailedConditions.length.toString()
+ newCodeFailedConditions.length.toString(),
);
const overallText =
? translate('quality_gates.conditions.overall_code_1')
: translateWithParameters(
'quality_gates.conditions.overall_code_x',
- overallFailedConditions.length.toString()
+ overallFailedConditions.length.toString(),
);
const renderFailedConditions = () => {
mockMeasure({
metric: key,
...(isDiffMetric(key) ? { leak: '1' } : { period: undefined }),
- })
+ }),
);
});
return Promise.resolve({
status: 'ERROR',
},
],
- })
+ }),
);
qualityGatesMock.setApplicationQualityGateStatus(mockQualityGateApplicationStatus());
});
qualityGatesMock.setQualityGateProjectStatus(
mockQualityGateProjectStatus({
status: 'OK',
- })
+ }),
);
renderBranchOverview();
expect(await screen.findByText('metric.level.OK')).toBeInTheDocument();
expect(screen.getByText('overview.passed.clean_code')).toBeInTheDocument();
expect(
- screen.queryByText('overview.quality_gate.conditions.cayc.warning')
+ screen.queryByText('overview.quality_gate.conditions.cayc.warning'),
).not.toBeInTheDocument();
//Measures panel
jest
.mocked(getQualityGateProjectStatus)
.mockResolvedValueOnce(
- mockQualityGateProjectStatus({ status: 'OK', caycStatus: CaycStatus.NonCompliant })
+ mockQualityGateProjectStatus({ status: 'OK', caycStatus: CaycStatus.NonCompliant }),
);
renderBranchOverview();
expect(await screen.findByText('metric.level.OK')).toBeInTheDocument();
expect(
- screen.queryByText('overview.quality_gate.conditions.cayc.warning')
+ screen.queryByText('overview.quality_gate.conditions.cayc.warning'),
).not.toBeInTheDocument();
});
jest
.mocked(getQualityGateProjectStatus)
.mockResolvedValueOnce(
- mockQualityGateProjectStatus({ status: 'OK', caycStatus: CaycStatus.NonCompliant })
+ mockQualityGateProjectStatus({ status: 'OK', caycStatus: CaycStatus.NonCompliant }),
);
qualityGatesMock.setIsAdmin(true);
qualityGatesMock.setGetGateForProjectName('Non Cayc QG');
await screen.findByText('metric.level.OK');
expect(
- await screen.findByText('overview.quality_gate.conditions.cayc.warning')
+ await screen.findByText('overview.quality_gate.conditions.cayc.warning'),
).toBeInTheDocument();
});
status: 'ERROR',
},
],
- })
+ }),
);
renderBranchOverview();
renderBranchOverview({ component });
expect(
- await screen.findByText('overview.quality_gate.application.non_cayc.projects_x.3')
+ await screen.findByText('overview.quality_gate.application.non_cayc.projects_x.3'),
).toBeInTheDocument();
expect(screen.getByText('first project')).toBeInTheDocument();
expect(screen.queryByText('second')).not.toBeInTheDocument();
await screen.findByText('overview.quality_gate.status');
expect(screen.queryByText('overview.project.next_steps.set_up_ci') === null).toBe(expected);
- }
+ },
);
it('should correctly handle graph type storage', async () => {
expect(saveActivityGraph).toHaveBeenCalledWith(
BRANCH_OVERVIEW_ACTIVITY_GRAPH,
'foo',
- GraphType.issues
+ GraphType.issues,
);
});
})}
{...props}
/>
- </CurrentUserContextProvider>
+ </CurrentUserContextProvider>,
);
}
expect(
screen.getByLabelText(
- 'overview.see_more_details_on_x_of_y.work_duration.x_minutes.1.sqale_index'
- )
+ 'overview.see_more_details_on_x_of_y.work_duration.x_minutes.1.sqale_index',
+ ),
).toBeInTheDocument();
expect(screen.getByText('sqale_index')).toBeInTheDocument();
expect(
screen.getByLabelText(
- 'overview.see_more_details_on_x_of_y.work_duration.x_minutes.1.new_technical_debt'
- )
+ 'overview.see_more_details_on_x_of_y.work_duration.x_minutes.1.new_technical_debt',
+ ),
).toBeInTheDocument();
expect(screen.getByText('new_technical_debt')).toBeInTheDocument();
mockMeasureEnhanced({ metric: mockMetric({ key: MetricKey.new_technical_debt }) }),
]}
{...props}
- />
+ />,
);
}
const rtl = renderProjectLeakPeriodInfo({ mode: 'manual_baseline' });
expect(
- await screen.findByText(/overview\.period\.manual_baseline\.formattedTime\..*/)
+ await screen.findByText(/overview\.period\.manual_baseline\.formattedTime\..*/),
).toBeInTheDocument();
rtl.unmount();
renderProjectLeakPeriodInfo({ mode: 'manual_baseline', parameter: '1.1.2' });
} as IntlShape
}
leakPeriod={mockPeriod({ ...period })}
- />
+ />,
);
}
warning = translateWithParameters(
'provisioning.no_analysis_on_main_branch.bad_configuration',
getBranchLikeDisplayName(branchLike),
- translate('branches.main_branch')
+ translate('branches.main_branch'),
);
} else {
warning = translateWithParameters(
'provisioning.no_analysis_on_main_branch',
- getBranchLikeDisplayName(branchLike)
+ getBranchLikeDisplayName(branchLike),
);
}
'aria-label': translateWithParameters(
'overview.see_list_of_x_y_issues',
value as string,
- localizeMetric(metricKey)
+ localizeMetric(metricKey),
),
to: url,
};
const { period } = this.props;
const leakPeriodLabel = getNewCodePeriodLabel(
period,
- MODE_INCLUDES_TIME[period.mode] ? this.formatDateTime : this.formatDate
+ MODE_INCLUDES_TIME[period.mode] ? this.formatDateTime : this.formatDate,
);
if (!leakPeriodLabel) {
return null;
period.mode === 'previous_analysis'
? 'overview.previous_analysis_on_x'
: 'overview.started_on_x',
- formattedLeakPeriodDate
+ formattedLeakPeriodDate,
)}
</span>
);
period.mode === 'previous_analysis'
? 'overview.previous_analysis_x'
: 'overview.started_x',
- fromNow
+ fromNow,
)}
</span>
)}
ariaLabel={translateWithParameters(
'overview.see_more_details_on_x_of_y',
formattedValue,
- localizeMetric(metricKey)
+ localizeMetric(metricKey),
)}
branchLike={branchLike}
className="overview-measures-value text-light"
</div>
<TextMuted text={`${operator} ${formatMeasure(threshold, metric.type)}`} />
</div>
- </div>
+ </div>,
);
}
}
const handleToggleCollapsed = React.useCallback(() => toggleCollapsed(!collapsed), [collapsed]);
const sortedConditions = sortBy(failedConditions, (condition) =>
- LEVEL_ORDER.indexOf(condition.level)
+ LEVEL_ORDER.indexOf(condition.level),
);
let renderConditions;
export function SonarLintPromotion({ currentUser, qgConditions }: SonarLintPromotionProps) {
const showMessage = qgConditions?.some(
(qgCondition) =>
- CONDITIONS_TO_SHOW.includes(qgCondition.metric as MetricKey) && qgCondition.level === 'ERROR'
+ CONDITIONS_TO_SHOW.includes(qgCondition.metric as MetricKey) && qgCondition.level === 'ERROR',
);
if (!showMessage || currentUser.usingSonarLintConnectedMode) {
return null;
renderApp({}, mockCurrentUser());
expect(
- await screen.findByText('provisioning.no_analysis_on_main_branch.main')
+ await screen.findByText('provisioning.no_analysis_on_main_branch.main'),
).toBeInTheDocument();
});
expect(
await screen.findByText(
- 'provisioning.no_analysis_on_main_branch.bad_configuration.main.branches.main_branch'
- )
+ 'provisioning.no_analysis_on_main_branch.bad_configuration.main.branches.main_branch',
+ ),
).toBeInTheDocument();
});
componentKey: 'my-project',
type: TaskTypes.GithubProjectPermissionsProvisioning,
status: TaskStatuses.InProgress,
- })
+ }),
);
renderApp();
await jest.runOnlyPendingTimersAsync();
expect(
- await screen.findByText('provisioning.permission_synch_in_progress')
+ await screen.findByText('provisioning.permission_synch_in_progress'),
).toBeInTheDocument();
handlerCe.clearTasks();
componentKey: 'my-project',
type: TaskTypes.GithubProjectPermissionsProvisioning,
status: TaskStatuses.Success,
- })
+ }),
);
await jest.runOnlyPendingTimersAsync();
<CurrentUserContextProvider currentUser={mockCurrentUser({ isLoggedIn: true, ...userProps })}>
<App hasFeature={jest.fn().mockReturnValue(false)} component={mockComponent()} {...props} />
</CurrentUserContextProvider>,
- '/?id=my-project'
+ '/?id=my-project',
);
}
expect(
await screen.findByRole('link', {
name: 'overview.see_list_of_x_y_issues.1.0.metric.bugs.name',
- })
+ }),
).toBeInTheDocument();
rtl.unmount();
expect(
await screen.findByRole('link', {
name: 'overview.see_list_of_x_y_issues.1.0.metric.new_bugs.name',
- })
+ }),
).toBeInTheDocument();
});
expect(
await screen.findByRole('link', {
name: 'overview.see_list_of_x_y_issues.1.0.metric.security_hotspots.name',
- })
+ }),
).toBeInTheDocument();
expect(screen.getByText('tooltip text')).toBeInTheDocument();
expect(
screen.queryByRole('link', {
name: 'overview.see_list_of_x_y_issues.1.0.metric.security_hotspots.name',
- })
+ }),
).not.toBeInTheDocument();
});
measures={[]}
type={IssueType.Bug}
{...props}
- />
+ />,
);
}
]}
type={IssueType.Bug}
{...props}
- />
+ />,
);
}
renderLeakPeriodLegend({ mode: 'days', parameter: '10' });
expect(
- await screen.findByText('overview.new_code_period_x.overview.period.days.10')
+ await screen.findByText('overview.new_code_period_x.overview.period.days.10'),
).toBeInTheDocument();
});
renderLeakPeriodLegend({ mode: 'date', parameter: '2013-01-01' });
expect(
- await screen.findByText('overview.new_code_period_x.overview.period.date.formatted.2013-01-01')
+ await screen.findByText('overview.new_code_period_x.overview.period.date.formatted.2013-01-01'),
).toBeInTheDocument();
expect(await screen.findByText('overview.started_x.9 years ago')).toBeInTheDocument();
expect(await screen.findByText(/overview\.started_on_x\..*/)).toBeInTheDocument();
renderLeakPeriodLegend({ mode: 'version', parameter: '0.1' });
expect(
- await screen.findByText('overview.new_code_period_x.overview.period.version.0.1')
+ await screen.findByText('overview.new_code_period_x.overview.period.version.0.1'),
).toBeInTheDocument();
expect(await screen.findByText(/overview\.started_x\..*/)).toBeInTheDocument();
expect(await screen.findByText(/overview\.started_on_x\..*/)).toBeInTheDocument();
renderLeakPeriodLegend({ mode: 'previous_version' });
expect(
- await screen.findByText('overview.new_code_period_x.overview.period.previous_version_only_date')
+ await screen.findByText(
+ 'overview.new_code_period_x.overview.period.previous_version_only_date',
+ ),
).toBeInTheDocument();
expect(await screen.findByText(/overview\.started_x\..*/)).toBeInTheDocument();
expect(await screen.findByText(/overview\.started_on_x\..*/)).toBeInTheDocument();
renderLeakPeriodLegend({ mode: 'previous_analysis' });
expect(
- await screen.findByText('overview.new_code_period_x.overview.period.previous_analysis.')
+ await screen.findByText('overview.new_code_period_x.overview.period.previous_analysis.'),
).toBeInTheDocument();
expect(await screen.findByText(/overview\.previous_analysis_x\..*/)).toBeInTheDocument();
expect(await screen.findByText(/overview\.previous_analysis_x\..*/)).toBeInTheDocument();
expect(
await screen.findByText(
- /overview\.new_code_period_x\.overview\.period\.manual_baseline\.formattedTime\..*/
- )
+ /overview\.new_code_period_x\.overview\.period\.manual_baseline\.formattedTime\..*/,
+ ),
).toBeInTheDocument();
expect(await screen.findByText(/overview\.started_x\..*/)).toBeInTheDocument();
expect(await screen.findByText(/overview\.started_on_x\..*/)).toBeInTheDocument();
renderLeakPeriodLegend({ mode: 'manual_baseline', parameter: '1.1.2' });
expect(
- await screen.findByText('overview.new_code_period_x.overview.period.manual_baseline.1.1.2')
+ await screen.findByText('overview.new_code_period_x.overview.period.manual_baseline.1.1.2'),
).toBeInTheDocument();
expect(
- await screen.findByText('overview.new_code_period_x.overview.period.manual_baseline.1.1.2')
+ await screen.findByText('overview.new_code_period_x.overview.period.manual_baseline.1.1.2'),
).toBeInTheDocument();
});
renderLeakPeriodLegend({ date: '2018-08-17T00:00:00+0200', mode: 'previous_version' });
expect(
- await screen.findByText('overview.new_code_period_x.overview.period.previous_version_only_date')
+ await screen.findByText(
+ 'overview.new_code_period_x.overview.period.previous_version_only_date',
+ ),
).toBeInTheDocument();
expect(await screen.findByText(/overview\.started_x\..*/)).toBeInTheDocument();
expect(await screen.findByText(/overview\.started_on_x\..*/)).toBeInTheDocument();
mode: 'version',
...period,
}}
- />
+ />,
);
}
expect(
screen.getByRole('link', {
name: 'overview.see_more_details_on_x_of_y.1.0%.metric.duplicated_lines_density.name',
- })
+ }),
).toBeInTheDocument();
expect(await screen.findByText('metric.duplicated_lines_density.short_name')).toBeInTheDocument();
expect(
screen.getByRole('link', {
name: 'overview.see_more_details_on_x_of_y.1.0%.metric.new_duplicated_lines_density.name',
- })
+ }),
).toBeInTheDocument();
expect(await screen.findByText('overview.duplications_on_X_new_lines')).toBeInTheDocument();
});
measures={[mockMeasureEnhanced({ metric: mockMetric({ key: MetricKey.coverage }) })]}
type={MeasurementType.Coverage}
{...props}
- />
+ />,
);
}
])('should render correclty', async (condition) => {
renderQualityGateCondition({ condition });
expect(
- await screen.findByText(`metric.${condition.measure.metric.name}.name`)
+ await screen.findByText(`metric.${condition.measure.metric.name}.name`),
).toBeInTheDocument();
expect(
- await screen.findByText(`quality_gates.operator.${condition.op}`, { exact: false })
+ await screen.findByText(`quality_gates.operator.${condition.op}`, { exact: false }),
).toBeInTheDocument();
// if (condition.measure.metric.type === 'RATING') {
// expect(await screen.findByText('.rating', { exact: false })).toBeInTheDocument();
expect(await screen.findByText('metric.new_maintainability_rating.name')).toBeInTheDocument();
expect(
- await screen.findByText('quality_gates.operator.GT.rating', { exact: false })
+ await screen.findByText('quality_gates.operator.GT.rating', { exact: false }),
).toBeInTheDocument();
});
component={{ key: 'abcd-key' }}
condition={mockQualityGateStatusConditionEnhanced()}
{...props}
- />
+ />,
);
}
function quickMock(
metric: MetricKey,
type = 'RATING',
- addPeriod = false
+ addPeriod = false,
): QualityGateStatusConditionEnhanced {
return mockQualityGateStatusConditionEnhanced({
error: '1',
expect(await screen.findAllByText(/.*metric..+.name.*/)).toHaveLength(ALL_CONDITIONS);
expect(await screen.findAllByText('quality_gates.operator', { exact: false })).toHaveLength(
- ALL_CONDITIONS
+ ALL_CONDITIONS,
);
});
expect(await screen.findAllByText(/.*metric..+.name.*/)).toHaveLength(HALF_CONDITIONS);
expect(await screen.findAllByText('quality_gates.operator', { exact: false })).toHaveLength(
- HALF_CONDITIONS
+ HALF_CONDITIONS,
);
await user.click(screen.getByRole('link', { name: 'show_more' }));
expect(await screen.findAllByText(/.*metric..+.name.*/)).toHaveLength(ALL_CONDITIONS);
expect(await screen.findAllByText('quality_gates.operator', { exact: false })).toHaveLength(
- ALL_CONDITIONS
+ ALL_CONDITIONS,
);
});
conditions.push(
mockQualityGateStatusConditionEnhanced({
measure: mockMeasureEnhanced({ metric: mockMetric({ key: i.toString() }) }),
- })
+ }),
);
}
return renderComponent(
- <QualityGateConditions component={mockComponent()} failedConditions={conditions} {...props} />
+ <QualityGateConditions component={mockComponent()} failedConditions={conditions} {...props} />,
);
}
it('should render correctly', () => {
renderSonarLintPromotion();
expect(
- screen.queryByText('overview.fix_failed_conditions_with_sonarlint')
+ screen.queryByText('overview.fix_failed_conditions_with_sonarlint'),
).not.toBeInTheDocument();
renderSonarLintPromotion({ currentUser: mockCurrentUser({ usingSonarLintConnectedMode: true }) });
expect(
- screen.queryByText('overview.fix_failed_conditions_with_sonarlint')
+ screen.queryByText('overview.fix_failed_conditions_with_sonarlint'),
).not.toBeInTheDocument();
});
MetricKey.new_security_rating,
MetricKey.new_maintainability_rating,
MetricKey.new_reliability_rating,
- ].map(Array.of)
+ ].map(Array.of),
)('should show message for %s', async (metric) => {
renderSonarLintPromotion({
qgConditions: [mockQualityGateStatusCondition({ metric: metric as string })],
});
expect(
- await screen.findByText('overview.fix_failed_conditions_with_sonarlint')
+ await screen.findByText('overview.fix_failed_conditions_with_sonarlint'),
).toBeInTheDocument();
});
},
() => {
setLoadingMeasure(false);
- }
+ },
);
}, [branchLike, component.key, conditions]);
useDiffMetric
/>
</Card>
- )
+ ),
)}
</div>
</div>
jest.mock('../../../../api/quality-gates', () => {
const { mockQualityGateProjectStatus, mockQualityGateApplicationStatus } = jest.requireActual(
- '../../../../helpers/mocks/quality-gates'
+ '../../../../helpers/mocks/quality-gates',
);
const { MetricKey } = jest.requireActual('../../../../types/metrics');
return {
status: 'ERROR',
},
],
- })
+ }),
),
getApplicationQualityGate: jest.fn().mockResolvedValue(mockQualityGateApplicationStatus()),
};
renderPullRequestOverview();
await waitFor(async () =>
- expect(await screen.findByText('overview.quality_gate.ignored_conditions')).toBeInTheDocument()
+ expect(await screen.findByText('overview.quality_gate.ignored_conditions')).toBeInTheDocument(),
);
});
renderPullRequestOverview();
await waitFor(async () =>
- expect(await screen.findByText('metric.level.ERROR')).toBeInTheDocument()
+ expect(await screen.findByText('metric.level.ERROR')).toBeInTheDocument(),
);
expect(await screen.findByText('metric.new_coverage.name')).toBeInTheDocument();
expect(await screen.findByText('quality_gates.operator.GT 2.0%')).toBeInTheDocument();
expect(
- await screen.findByText('metric.duplicated_lines.name quality_gates.conditions.new_code')
+ await screen.findByText('metric.duplicated_lines.name quality_gates.conditions.new_code'),
).toBeInTheDocument();
expect(await screen.findByText('quality_gates.operator.GT 1.0%')).toBeInTheDocument();
});
function renderPullRequestOverview(
- props: Partial<ComponentPropsType<typeof PullRequestOverview>> = {}
+ props: Partial<ComponentPropsType<typeof PullRequestOverview>> = {},
) {
renderComponent(
<CurrentUserContextProvider currentUser={mockLoggedInUser()}>
})}
{...props}
/>
- </CurrentUserContextProvider>
+ </CurrentUserContextProvider>,
);
}
projectKeyPattern: string;
}) => {
return updatePermissionTemplate({ id: this.props.permissionTemplate.id, ...data }).then(
- this.props.refresh
+ this.props.refresh,
);
};
setDefault = (qualifier: string) => () => {
setDefaultPermissionTemplate(this.props.permissionTemplate.id, qualifier).then(
this.props.refresh,
- () => {}
+ () => {},
);
};
return availableQualifiers.map((qualifier) =>
this.renderSetDefaultLink(
qualifier,
- <span>{translate('permission_templates.set_default')}</span>
- )
+ <span>{translate('permission_templates.set_default')}</span>,
+ ),
);
}
<span>
{translate('permission_templates.set_default_for')}{' '}
<QualifierIcon qualifier={qualifier} /> {translate('qualifiers', qualifier)}
- </span>
- )
+ </span>,
+ ),
);
}
<div className="modal-body">
{translateWithParameters(
'permission_template.do_you_want_to_delete_template_xxx',
- t.name
+ t.name,
)}
</div>
const sortedPerm = sortPermissions(permissions);
const permissionTemplatesMerged = mergeDefaultsToTemplates(
mergePermissionsToTemplates(permissionTemplates, sortedPerm),
- defaultTemplates
+ defaultTemplates,
);
this.setState({
ready: true,
});
const [usersResponse, groupsResponse] = await this.loadUsersAndGroups(
usersPaging ? usersPaging.pageIndex + 1 : 1,
- groupsPaging ? groupsPaging.pageIndex + 1 : 1
+ groupsPaging ? groupsPaging.pageIndex + 1 : 1,
);
if (this.mounted) {
this.setState(({ groups, users }) => ({
removePermissionFromEntity = <T extends { login?: string; name: string; permissions: string[] }>(
entities: T[],
entity: string,
- permission: string
+ permission: string,
): T[] =>
entities.map((candidate) =>
candidate.name === entity || candidate.login === entity
? { ...candidate, permissions: without(candidate.permissions, permission) }
- : candidate
+ : candidate,
);
addPermissionToEntity = <T extends { login?: string; name: string; permissions: string[] }>(
entities: T[],
entity: string,
- permission: string
+ permission: string,
): T[] =>
entities.map((candidate) =>
candidate.name === entity || candidate.login === entity
? { ...candidate, permissions: [...candidate.permissions, permission] }
- : candidate
+ : candidate,
);
grantPermissionToUser = (login: string, permission: string) => {
this.state;
const permissions = convertToPermissionDefinitions(
PERMISSIONS_ORDER_FOR_PROJECT_TEMPLATE,
- 'projects_role'
+ 'projects_role',
);
const allUsers = [...users];
// Shows warning for browse and code viewer permissions.
await expect(ui.getHeaderTooltipIconByIndex(1)).toHaveATooltipWithContent(
- 'projects_role.public_projects_warning'
+ 'projects_role.public_projects_warning',
);
await expect(ui.getHeaderTooltipIconByIndex(2)).toHaveATooltipWithContent(
- 'projects_role.public_projects_warning'
+ 'projects_role.public_projects_warning',
);
// Check summaries.
const row1 = within(screen.getByRole('row', { name: /Permission Template 1/ }));
PERMISSIONS_ORDER_FOR_PROJECT_TEMPLATE.forEach((permission, i) => {
expect(row1.getAllByRole('cell').at(i + 1)?.textContent).toMatchSnapshot(
- `Permission Template 1: ${permission}`
+ `Permission Template 1: ${permission}`,
);
});
const row2 = within(screen.getByRole('row', { name: /Permission Template 2/ }));
PERMISSIONS_ORDER_FOR_PROJECT_TEMPLATE.forEach((permission, i) => {
expect(row2.getAllByRole('cell').at(i + 1)?.textContent).toMatchSnapshot(
- `Permission Template 2: ${permission}`
+ `Permission Template 2: ${permission}`,
);
});
});
await ui.appLoaded();
await expect(ui.getHeaderTooltipIconByIndex(i)).toHaveATooltipWithContent(
- `projects_role.${permission}.desc`
+ `projects_role.${permission}.desc`,
);
- }
+ },
);
});
'Permission Template 2',
'Updated name',
'Updated description',
- '/new pattern/'
+ '/new pattern/',
);
expect(ui.templateLink('Updated name').get()).toBeInTheDocument();
'Permission Template 2',
'Updated name',
'Updated description',
- '/new pattern/'
+ '/new pattern/',
);
expect(screen.getByText('Updated name')).toBeInTheDocument();
const regex = new RegExp(`permission_template\\.default_for\\.(.*)qualifiers.${qualifier}`);
expect(row2.getByText(regex)).toBeInTheDocument();
expect(row1.queryByText(regex)).not.toBeInTheDocument();
- }
+ },
);
it('should show github warning', async () => {
if (pattern) {
await user.type(
modal.getByRole('textbox', { name: 'permission_template.key_pattern' }),
- pattern
+ pattern,
);
}
await user.click(modal.getByRole('button', { name: 'create' }));
name: string,
newName: string,
newDescription: string,
- newPattern: string
+ newPattern: string,
) {
await user.click(ui.cogMenuBtn(name).get());
await user.click(ui.updateDetailsBtn.get());
function renderPermissionTemplatesApp(
qualifiers = [ComponentQualifier.Project],
- featureList: Feature[] = []
+ featureList: Feature[] = [],
) {
renderAppWithAdminContext('admin/permission_templates', routes, {
appState: mockAppState({ qualifiers }),
export function mergePermissionsToTemplates(
permissionTemplates: PermissionTemplate[],
- basePermissions: Permission[]
+ basePermissions: Permission[],
): PermissionTemplate[] {
return permissionTemplates.map((permissionTemplate) => {
// it's important to keep the order of the permission template's permissions
// the same as the order of base permissions
const permissions = basePermissions.map((basePermission) => {
const projectPermission = permissionTemplate.permissions.find(
- (p) => p.key === basePermission.key
+ (p) => p.key === basePermission.key,
);
return { usersCount: 0, groupsCount: 0, ...basePermission, ...projectPermission };
});
export function mergeDefaultsToTemplates(
permissionTemplates: PermissionTemplate[],
- defaultTemplates: Array<{ templateId: string; qualifier: string }> = []
+ defaultTemplates: Array<{ templateId: string; qualifier: string }> = [],
): PermissionTemplate[] {
return permissionTemplates.map((permissionTemplate) => {
const defaultFor: string[] = [];
this.loadUsersAndGroups(
usersPaging ? usersPaging.pageIndex + 1 : 1,
- groupsPaging ? groupsPaging.pageIndex + 1 : 1
+ groupsPaging ? groupsPaging.pageIndex + 1 : 1,
).then(([usersResponse, groupsResponse]) => {
if (this.mounted) {
this.setState(({ groups, users }) => ({
return groups.map((candidate) =>
candidate.name === group
? { ...candidate, permissions: [...candidate.permissions, permission] }
- : candidate
+ : candidate,
);
};
return users.map((candidate) =>
candidate.login === user
? { ...candidate, permissions: [...candidate.permissions, permission] }
- : candidate
+ : candidate,
);
};
return groups.map((candidate) =>
candidate.name === group
? { ...candidate, permissions: without(candidate.permissions, permission) }
- : candidate
+ : candidate,
);
};
return users.map((candidate) =>
candidate.login === user
? { ...candidate, permissions: without(candidate.permissions, permission) }
- : candidate
+ : candidate,
);
};
const hasApplicationsEnabled = appState.qualifiers.includes(ComponentQualifier.Application);
const permissions = convertToPermissionDefinitions(
filterPermissions(PERMISSIONS_ORDER_GLOBAL, hasApplicationsEnabled, hasPortfoliosEnabled),
- 'global_permissions'
+ 'global_permissions',
);
return (
<main className="page page-limited">
without(
flattenPermissionsList(PERMISSIONS_ORDER_GLOBAL),
Permissions.ApplicationCreation,
- Permissions.PortfolioCreation
+ Permissions.PortfolioCreation,
).forEach((permission) => {
expect(ui.globalPermissionCheckbox('johndoe', permission).get()).toBeInTheDocument();
});
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
};
render() {
const header = translateWithParameters(
'projects_role.apply_template_to_x',
- this.props.project.name
+ this.props.project.name,
);
const options = this.state.permissionTemplates
this.loadUsersAndGroups(
usersPaging ? usersPaging.pageIndex + 1 : 1,
- groupsPaging ? groupsPaging.pageIndex + 1 : 1
+ groupsPaging ? groupsPaging.pageIndex + 1 : 1,
).then(([usersResponse, groupsResponse]) => {
if (this.mounted) {
this.setState(({ groups, users }) => ({
selectedPermission:
state.selectedPermission === selectedPermission ? undefined : selectedPermission,
}),
- this.loadHolders
+ this.loadHolders,
);
}
};
return this.state.groups.map((candidate) =>
candidate.name === group
? { ...candidate, permissions: [...candidate.permissions, permission] }
- : candidate
+ : candidate,
);
};
return this.state.users.map((candidate) =>
candidate.login === user
? { ...candidate, permissions: [...candidate.permissions, permission] }
- : candidate
+ : candidate,
);
};
return this.state.groups.map((candidate) =>
candidate.name === group
? { ...candidate, permissions: without(candidate.permissions, permission) }
- : candidate
+ : candidate,
);
};
return this.state.users.map((candidate) =>
candidate.login === user
? { ...candidate, permissions: without(candidate.permissions, permission) }
- : candidate
+ : candidate,
);
};
expect(ui.visibilityRadio(Visibility.Public).get()).toBeChecked();
expect(
- ui.projectPermissionCheckbox('sonar-users', Permissions.Browse).query()
+ ui.projectPermissionCheckbox('sonar-users', Permissions.Browse).query(),
).not.toBeInTheDocument();
await act(async () => {
await ui.turnProjectPrivate();
});
expect(ui.visibilityRadio(Visibility.Private).get()).toBeChecked();
expect(
- ui.projectPermissionCheckbox('sonar-users', Permissions.Browse).get()
+ ui.projectPermissionCheckbox('sonar-users', Permissions.Browse).get(),
).toBeInTheDocument();
await ui.turnProjectPublic();
{ featureList: [Feature.GithubProvisioning] },
{
component: mockComponent({ visibility: Visibility.Private }),
- }
+ },
);
await ui.appLoaded();
expect(ui.pageTitle.get()).toBeInTheDocument();
await waitFor(() =>
- expect(ui.pageTitle.get()).toHaveAccessibleName(/project_permission.github_managed/)
+ expect(ui.pageTitle.get()).toHaveAccessibleName(/project_permission.github_managed/),
);
expect(ui.pageTitle.byRole('img').get()).toBeInTheDocument();
expect(ui.githubExplanations.get()).toBeInTheDocument();
expect(ui.projectPermissionCheckbox('John', Permissions.Admin).get()).toBeChecked();
expect(ui.projectPermissionCheckbox('John', Permissions.Admin).get()).toHaveAttribute(
'aria-disabled',
- 'true'
+ 'true',
);
expect(ui.projectPermissionCheckbox('Alexa', Permissions.IssueAdmin).get()).toBeChecked();
expect(ui.projectPermissionCheckbox('Alexa', Permissions.IssueAdmin).get()).toHaveAttribute(
'aria-disabled',
- 'false'
+ 'false',
);
await ui.toggleProjectPermission('Alexa', Permissions.IssueAdmin);
expect(ui.confirmRemovePermissionDialog.get()).toBeInTheDocument();
expect(ui.confirmRemovePermissionDialog.get()).toHaveTextContent(
- `${Permissions.IssueAdmin}Alexa`
+ `${Permissions.IssueAdmin}Alexa`,
);
await act(() =>
- user.click(ui.confirmRemovePermissionDialog.byRole('button', { name: 'confirm' }).get())
+ user.click(ui.confirmRemovePermissionDialog.byRole('button', { name: 'confirm' }).get()),
);
expect(ui.projectPermissionCheckbox('Alexa', Permissions.IssueAdmin).get()).not.toBeChecked();
expect(ui.projectPermissionCheckbox('sonar-users', Permissions.Browse).get()).toBeChecked();
expect(ui.projectPermissionCheckbox('sonar-users', Permissions.Browse).get()).toHaveAttribute(
'aria-disabled',
- 'false'
+ 'false',
);
await ui.toggleProjectPermission('sonar-users', Permissions.Browse);
expect(ui.confirmRemovePermissionDialog.get()).toBeInTheDocument();
expect(ui.confirmRemovePermissionDialog.get()).toHaveTextContent(
- `${Permissions.Browse}sonar-users`
+ `${Permissions.Browse}sonar-users`,
);
await act(() =>
- user.click(ui.confirmRemovePermissionDialog.byRole('button', { name: 'confirm' }).get())
+ user.click(ui.confirmRemovePermissionDialog.byRole('button', { name: 'confirm' }).get()),
);
expect(ui.projectPermissionCheckbox('sonar-users', Permissions.Browse).get()).not.toBeChecked();
expect(ui.projectPermissionCheckbox('sonar-admins', Permissions.Admin).get()).toBeChecked();
expect(ui.projectPermissionCheckbox('sonar-admins', Permissions.Admin).get()).toHaveAttribute(
'aria-disabled',
- 'true'
+ 'true',
);
const johnRow = screen.getAllByRole('row')[4];
expect(
screen
.getAllByRole('checkbox', { checked: false })
- .every((item) => item.getAttribute('aria-disabled') === 'true')
+ .every((item) => item.getAttribute('aria-disabled') === 'true'),
).toBe(true);
});
});
renderPermissionsProjectApp(
{ visibility: Visibility.Private },
- { featureList: [Feature.GithubProvisioning] }
+ { featureList: [Feature.GithubProvisioning] },
);
await ui.appLoaded();
// no restrictions
expect(
- screen.getAllByRole('checkbox').every((item) => item.getAttribute('aria-disabled') !== 'true')
+ screen.getAllByRole('checkbox').every((item) => item.getAttribute('aria-disabled') !== 'true'),
).toBe(true);
});
// no restrictions
expect(
- screen.getAllByRole('checkbox').every((item) => item.getAttribute('aria-disabled') !== 'true')
+ screen.getAllByRole('checkbox').every((item) => item.getAttribute('aria-disabled') !== 'true'),
).toBe(true);
});
function renderPermissionsProjectApp(
override: Partial<Component> = {},
contextOverride: Partial<RenderContext> = {},
- componentContextOverride: Partial<ComponentContextShape> = {}
+ componentContextOverride: Partial<ComponentContextShape> = {},
) {
return renderAppWithComponentContext(
'project_roles?id=my-project',
...override,
}),
...componentContextOverride,
- }
+ },
);
}
}),
nonGHProjectWarning: byText('project_permission.local_project_with_github_provisioning'),
makePublicDisclaimer: byText(
- 'projects_role.are_you_sure_to_turn_project_to_public.warning.TRK'
+ 'projects_role.are_you_sure_to_turn_project_to_public.warning.TRK',
),
confirmPublicBtn: byRole('button', { name: 'projects_role.turn_project_to_public.TRK' }),
applyTemplateBtn: byRole('button', { name: 'projects_role.apply_template' }),
category: string;
permissions: Permissions[];
}
- >
+ >,
) {
function isPermissions(
p:
| {
category: string;
permissions: Permissions[];
- }
+ },
): p is Permissions {
return typeof p === 'string';
}
key: 'E1',
name: 'changed',
category: ProjectAnalysisEventCategory.Version,
- })(state).analyses[0]
+ })(state).analyses[0],
).toMatchSnapshot();
expect(
actions.changeEvent('A2', {
key: 'E2',
name: 'foo',
category: ProjectAnalysisEventCategory.Version,
- })(state).analyses[1].events
+ })(state).analyses[1].events,
).toHaveLength(0);
});
});
expect(
utils.getAnalysesByVersionByDay(ANALYSES, {
category: '',
- })
+ }),
).toMatchSnapshot();
});
it('should also filter analysis based on the query', () => {
expect(
utils.getAnalysesByVersionByDay(ANALYSES, {
category: 'QUALITY_PROFILE',
- })
+ }),
).toMatchSnapshot();
expect(
utils.getAnalysesByVersionByDay(ANALYSES, {
to: dates.parseDate('2017-06-09T11:12:27.000Z'),
from: dates.parseDate('2017-05-18T14:13:07.000Z'),
- })
+ }),
).toMatchSnapshot();
});
it('should create fake version', () => {
],
{
category: '',
- }
- )
+ },
+ ),
).toMatchSnapshot();
});
});
from: '2017-04-27T08:21:32.000Z',
custom_metrics: 'foo,bar,baz',
id: 'foo',
- })
+ }),
).toEqual(QUERY);
});
});
from: '2017-04-27T08:21:32+0000',
project: 'foo',
category: 'test',
- }
+ },
);
});
});
graph: GraphType.coverage,
category: 'test',
customMetrics: [],
- })
+ }),
).toEqual({
from: '2017-04-27T08:21:32+0000',
id: 'foo',
return {
...item,
events: item.events.map((eventItem) =>
- eventItem.key === event.key ? { ...eventItem, ...event } : eventItem
+ eventItem.key === event.key ? { ...eventItem, ...event } : eventItem,
),
};
}),
onClose={() => setDeleting(false)}
onConfirm={props.onDelete}
removeEventQuestion={translate(
- `project_activity.${isVersion ? 'remove_version' : 'remove_custom_event'}.question`
+ `project_activity.${isVersion ? 'remove_version' : 'remove_custom_event'}.question`,
)}
/>
)}
// versions last
(event) => (event.category === ProjectAnalysisEventCategory.Version ? 1 : 0),
// then the rest sorted by category
- 'category'
+ 'category',
);
return (
'sw-sticky sw-top-0 sw-left-0 sw-pb-1 -sw-ml-4 sw-z-normal',
{
'sw-top-0 sw-pt-0': idx === 0,
- }
+ },
)}
>
<Tooltip
'it__project-activity-analysis sw-flex sw-cursor-pointer sw-p-1 sw-relative',
{
active: selected,
- }
+ },
)}
aria-label={translateWithParameters(
'project_activity.show_analysis_X_on_graph',
- analysis.buildString || formatDate(parsedDate, formatterOption)
+ analysis.buildString || formatDate(parsedDate, formatterOption),
)}
onClick={() => props.onUpdateSelectedDate(analysis.date)}
ref={(ref) => (node = ref)}
<ActionsDropdown
ariaLabel={translateWithParameters(
'project_activity.analysis_X_actions',
- analysis.buildString || formatDate(parsedDate, formatterOption)
+ analysis.buildString || formatDate(parsedDate, formatterOption),
)}
buttonSize="small"
id="it__analysis-actions"
if (this.mounted) {
this.updateGraphData(
this.state.query.graph || DEFAULT_GRAPH,
- this.state.query.customMetrics
+ this.state.query.customMetrics,
);
this.setState(actions.deleteAnalysis(analysis));
}
statuses: ProjectActivityStatuses[],
p: number,
ps: number,
- additional?: RawQuery
+ additional?: RawQuery,
) => {
const parameters = {
project,
date: parseDate(analysis.date),
value: analysis.value,
})),
- }))
+ })),
);
};
if (this.mounted) {
this.setState({ analysesLoading: false });
}
- }
+ },
);
};
loadAllActivities = (
project: string,
- prevResult?: { analyses: ParsedAnalysis[]; paging: Paging }
+ prevResult?: { analyses: ParsedAnalysis[]; paging: Paging },
): Promise<{ analyses: ParsedAnalysis[]; paging: Paging }> => {
if (
prevResult &&
ProjectActivityStatuses.STATUS_LIVE_MEASURE_COMPUTE,
],
nextPage,
- ACTIVITY_PAGE_SIZE
+ ACTIVITY_PAGE_SIZE,
).then((result) => {
if (!prevResult) {
return this.loadAllActivities(project, result);
if (isPortfolioLike(qualifier)) {
return Object.values(metrics).filter(
- (metric) => metric.key !== MetricKey.security_hotspots_reviewed
+ (metric) => metric.key !== MetricKey.security_hotspots_reviewed,
);
}
return Object.values(metrics).filter(
- (metric) => metric.key !== MetricKey.security_review_rating
+ (metric) => metric.key !== MetricKey.security_review_rating,
);
};
],
1,
ACTIVITY_PAGE_SIZE_FIRST_BATCH,
- serializeQuery(query)
+ serializeQuery(query),
),
this.fetchMeasuresHistory(graphMetrics),
]).then(
if (this.mounted) {
this.setState({ initialized: true, graphLoading: false });
}
- }
+ },
);
}
if (this.mounted) {
this.setState({ graphLoading: false, measuresHistory: [] });
}
- }
+ },
);
};
}
export default withComponentContext(
- withRouter(withMetricsContext(withBranchLikes(RedirectWrapper)))
+ withRouter(withMetricsContext(withBranchLikes(RedirectWrapper))),
);
props.measuresHistory,
props.query.graph,
props.metrics,
- getDisplayedHistoryMetrics(props.query.graph, props.query.customMetrics)
+ getDisplayedHistoryMetrics(props.query.graph, props.query.customMetrics),
);
this.state = {
series,
this.props.measuresHistory,
this.props.query.graph,
this.props.metrics,
- getDisplayedHistoryMetrics(this.props.query.graph, this.props.query.customMetrics)
+ getDisplayedHistoryMetrics(this.props.query.graph, this.props.query.customMetrics),
);
newGraphs = splitSeriesInGraphs(newSeries, MAX_GRAPH_NB, MAX_SERIES_PER_GRAPH);
}
if (newDates.to === undefined && newDates.from === undefined && newSeries !== undefined) {
const firstValid = minBy(
newSeries.map((serie) => serie.data.find((p) => Boolean(p.y || p.y === 0))),
- 'x'
+ 'x',
);
const lastValid = maxBy<Point>(
newSeries.map((serie) => findLast(serie.data, (p) => Boolean(p.y || p.y === 0))!),
- 'x'
+ 'x',
);
return {
graphEndDate: lastValid?.x,
handleRemoveCustomMetric = (removedMetric: string) => {
const customMetrics = this.props.query.customMetrics.filter(
- (metric) => metric !== removedMetric
+ (metric) => metric !== removedMetric,
);
saveActivityGraph(PROJECT_ACTIVITY_GRAPH, this.props.project, GraphType.custom, customMetrics);
this.props.updateQuery({ customMetrics });
(option: { value: string } | null) => {
updateQuery({ category: option ? option.value : '' });
},
- [updateQuery]
+ [updateQuery],
);
return (
history: projectActivityHandler
.getAnalysesList()
.map(({ date }) => mockHistoryItem({ value: '3', date: parseDate(date) })),
- })
- )
+ }),
+ ),
);
});
breadcrumbs: [
{ key: 'breadcrumb', name: 'breadcrumb', qualifier: ComponentQualifier.Project },
],
- })
+ }),
);
await ui.appLoaded();
breadcrumbs: [
{ key: 'breadcrumb', name: 'breadcrumb', qualifier: ComponentQualifier.Project },
],
- })
+ }),
);
await ui.changeGraphType(GraphType.custom);
mockComponent({
qualifier,
breadcrumbs: [{ key: 'breadcrumb', name: 'breadcrumb', qualifier }],
- })
+ }),
);
await ui.changeGraphType(GraphType.custom);
expect(ui.metricCheckbox(MetricKey.security_review_rating).get()).toBeInTheDocument();
expect(
- ui.metricCheckbox(MetricKey.security_hotspots_reviewed).query()
+ ui.metricCheckbox(MetricKey.security_hotspots_reviewed).query(),
).not.toBeInTheDocument();
- }
+ },
);
});
{ key: 'breadcrumb', name: 'breadcrumb', qualifier: ComponentQualifier.Project },
],
configuration: { showHistory: true },
- })
+ }),
);
await ui.appLoaded();
{ key: 'breadcrumb', name: 'breadcrumb', qualifier: ComponentQualifier.Project },
],
configuration: { showHistory: true },
- })
+ }),
);
await ui.appLoaded();
{ key: 'breadcrumb', name: 'breadcrumb', qualifier: ComponentQualifier.Project },
],
configuration: { showHistory: true },
- })
+ }),
);
await ui.appLoaded();
key: `analysis-${i}`,
date: '2016-01-01T00:00:00+0200',
});
- })
+ }),
);
const { ui } = getPageObject();
{ key: 'foo', name: 'foo', qualifier: ComponentQualifier.Portfolio },
{ key: 'unknown', name: 'unknown', qualifier: ComponentQualifier.SubPortfolio },
],
- })
+ }),
);
await ui.appLoaded();
key: `analysis-${i}`,
date: date.toDateString(),
});
- })
+ }),
);
const { ui } = getPageObject();
},
async filterByCategory(
- category: ProjectAnalysisEventCategory | ApplicationAnalysisEventCategory
+ category: ProjectAnalysisEventCategory | ApplicationAnalysisEventCategory,
) {
await user.click(ui.categorySelect.get());
const optionForType = await screen.findByText(`event.category.${category}`);
await user.click(monthSelector);
const selectedMonthElements = within(ui.monthSelector.get()).getAllByText(
- monthMap[parseDate(parsedDate).getMonth()]
+ monthMap[parseDate(parsedDate).getMonth()],
);
await user.click(selectedMonthElements[selectedMonthElements.length - 1]);
await user.click(yearSelector);
const selectedYearElements = within(ui.yearSelector.get()).getAllByText(
- parseDate(parsedDate).getFullYear()
+ parseDate(parsedDate).getFullYear(),
);
await user.click(selectedYearElements[selectedYearElements.length - 1]);
await user.click(
- screen.getByText(parseDate(parsedDate).getDate().toString(), { selector: 'button' })
+ screen.getByText(parseDate(parsedDate).getDate().toString(), { selector: 'button' }),
);
},
function renderProjectActivityAppContainer(
component = mockComponent({
breadcrumbs: [{ key: 'breadcrumb', name: 'breadcrumb', qualifier: ComponentQualifier.Project }],
- })
+ }),
) {
return renderAppWithComponentContext(
'project/activity',
mockMetric({ key: MetricKey.security_hotspots_reviewed }),
mockMetric({ key: MetricKey.security_review_rating, type: MetricType.Rating }),
],
- 'key'
+ 'key',
),
},
- { component }
+ { component },
);
}
export function getAnalysesByVersionByDay(
analyses: ParsedAnalysis[],
- query: Pick<Query, 'category' | 'from' | 'to'>
+ query: Pick<Query, 'category' | 'from' | 'to'>,
) {
return analyses.reduce<AnalysesByDay[]>((acc, analysis) => {
let currentVersion = acc[acc.length - 1];
expect(ui.linkForAdmin.query()).not.toBeInTheDocument();
expect(await ui.branchRow.findAll()).toHaveLength(4);
expect(ui.branchRow.getAt(1)).toHaveTextContent(
- 'mainbranches.main_branchOK1 month agoproject_branch_pull_request.branch.auto_deletion.main_branch_tooltip'
+ 'mainbranches.main_branchOK1 month agoproject_branch_pull_request.branch.auto_deletion.main_branch_tooltip',
);
expect(within(ui.branchRow.getAt(1)).getByRole('switch')).toBeDisabled();
expect(within(ui.branchRow.getAt(1)).getByRole('switch')).toBeChecked();
expect(ui.renameBranchDialog.get()).toBeInTheDocument();
expect(within(ui.renameBranchDialog.get()).getByRole('textbox')).toHaveValue('main');
expect(
- within(ui.renameBranchDialog.get()).getByRole('button', { name: 'rename' })
+ within(ui.renameBranchDialog.get()).getByRole('button', { name: 'rename' }),
).toBeDisabled();
await user.clear(within(ui.renameBranchDialog.get()).getByRole('textbox'));
expect(
- within(ui.renameBranchDialog.get()).getByRole('button', { name: 'rename' })
+ within(ui.renameBranchDialog.get()).getByRole('button', { name: 'rename' }),
).toBeDisabled();
await user.type(within(ui.renameBranchDialog.get()).getByRole('textbox'), 'develop');
expect(within(ui.renameBranchDialog.get()).getByRole('button', { name: 'rename' })).toBeEnabled();
await act(() =>
- user.click(within(ui.renameBranchDialog.get()).getByRole('button', { name: 'rename' }))
+ user.click(within(ui.renameBranchDialog.get()).getByRole('button', { name: 'rename' })),
);
expect(ui.branchRow.getAt(1)).toHaveTextContent(
- 'developbranches.main_branchOK1 month agoproject_branch_pull_request.branch.auto_deletion.main_branch_tooltip'
+ 'developbranches.main_branchOK1 month agoproject_branch_pull_request.branch.auto_deletion.main_branch_tooltip',
);
await user.click(await ui.updateSecondBranchBtn.find());
await user.click(
within(ui.dialog.get()).getByRole('button', {
name: 'project_branch_pull_request.branch.set_x_as_main.delete-branch',
- })
+ }),
);
});
// "delete-branch" is now the main branch.
expect(ui.getBranchRow(/delete-branch/)).toBeInTheDocument();
expect(
- within(ui.getBranchRow(/delete-branch/)).getByText('branches.main_branch')
+ within(ui.getBranchRow(/delete-branch/)).getByText('branches.main_branch'),
).toBeInTheDocument();
expect(within(ui.getBranchRow(/delete-branch/)).getByRole('switch')).toBeChecked();
expect(within(ui.getBranchRow(/delete-branch/)).getByRole('switch')).toBeDisabled();
expect(ui.deleteBranchDialog.get()).toBeInTheDocument();
expect(ui.deleteBranchDialog.get()).toHaveTextContent('delete-branch');
await act(() =>
- user.click(within(ui.deleteBranchDialog.get()).getByRole('button', { name: 'delete' }))
+ user.click(within(ui.deleteBranchDialog.get()).getByRole('button', { name: 'delete' })),
);
expect(ui.branchRow.getAll()).toHaveLength(3);
expect(await ui.pullRequestRow.findAll()).toHaveLength(4);
expect(ui.pullRequestRow.getAt(1)).toHaveTextContent('01 – TEST-191 update masterOK1 month ago');
expect(ui.pullRequestRow.getAt(2)).toHaveTextContent(
- '02 – TEST-192 update normal-branchERROR2 days ago'
+ '02 – TEST-192 update normal-branchERROR2 days ago',
);
});
expect(await ui.deletePullRequestDialog.find()).toBeInTheDocument();
expect(ui.deletePullRequestDialog.get()).toHaveTextContent('01 – TEST-191 update master');
await act(() =>
- user.click(within(ui.deletePullRequestDialog.get()).getByRole('button', { name: 'delete' }))
+ user.click(within(ui.deletePullRequestDialog.get()).getByRole('button', { name: 'delete' })),
);
expect(ui.pullRequestRow.getAll()).toHaveLength(3);
});
<ProjectBranchesApp />
</ComponentContext.Provider>,
'/?id=my-project',
- { appState: mockAppState(overrides), featureList: [Feature.BranchSupport] }
+ { appState: mockAppState(overrides), featureList: [Feature.BranchSupport] },
);
}
<ActionsDropdown
label={translateWithParameters(
'project_branch_pull_request.branch.actions_label',
- getBranchLikeDisplayName(branchLike)
+ getBranchLikeDisplayName(branchLike),
)}
>
{isBranch(branchLike) && !isMainBranch(branchLike) && (
{translate(
isPullRequest(branchLike)
? 'project_branch_pull_request.pull_request.delete'
- : 'project_branch_pull_request.branch.delete'
+ : 'project_branch_pull_request.branch.delete',
)}
</ActionsDropdownItem>
)}
<div className="display-flex-center">
<span>
{translate(
- 'project_branch_pull_request.branch.auto_deletion.keep_when_inactive'
+ 'project_branch_pull_request.branch.auto_deletion.keep_when_inactive',
)}
</span>
<HelpTooltip
className="little-spacer-left"
overlay={translate(
- 'project_branch_pull_request.branch.auto_deletion.keep_when_inactive.tooltip'
+ 'project_branch_pull_request.branch.auto_deletion.keep_when_inactive.tooltip',
)}
/>
</div>
const title = translate(
isBranchMode
? 'project_branch_pull_request.table.branch'
- : 'project_branch_pull_request.table.pull_request'
+ : 'project_branch_pull_request.table.pull_request',
);
return (
{isTheMainBranch && (
<HelpTooltip
overlay={translate(
- 'project_branch_pull_request.branch.auto_deletion.main_branch_tooltip'
+ 'project_branch_pull_request.branch.auto_deletion.main_branch_tooltip',
)}
/>
)}
{ component, branchLike },
{
onSuccess: props.onClose,
- }
+ },
);
};
const header = translate(
isPullRequest(branchLike)
? 'project_branch_pull_request.pull_request.delete'
- : 'project_branch_pull_request.branch.delete'
+ : 'project_branch_pull_request.branch.delete',
);
return (
isPullRequest(branchLike)
? 'project_branch_pull_request.pull_request.delete.are_you_sure'
: 'project_branch_pull_request.branch.delete.are_you_sure',
- getBranchLikeDisplayName(branchLike)
+ getBranchLikeDisplayName(branchLike),
)}
</div>
<footer className="modal-foot">
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
}
<p className="sw-mb-4">
{translateWithParameters(
'project_branch_pull_request.branch.main_branch.are_you_sure',
- branch.name
+ branch.name,
)}
</p>
<p className="sw-mb-4">
<FormattedMessage
id="project_branch_pull_request.branch.main_branch.learn_more"
defaultMessage={translate(
- 'project_branch_pull_request.branch.main_branch.learn_more'
+ 'project_branch_pull_request.branch.main_branch.learn_more',
)}
values={{
documentation: (
await deleteMethod(component.key);
addGlobalSuccessMessage(
- translateWithParameters('project_deletion.resource_deleted', component.name)
+ translateWithParameters('project_deletion.resource_deleted', component.name),
);
this.props.router.replace(redirectTo);
};
isDestructive
modalBody={translateWithParameters(
'project_deletion.delete_resource_confirmation',
- component.name
+ component.name,
)}
modalHeader={translate('qualifier.delete', component.qualifier)}
onConfirm={this.handleDelete}
});
renderProjectDeletionApp(
- mockComponent({ key: 'foo', name: 'Foo', qualifier: ComponentQualifier.Project })
+ mockComponent({ key: 'foo', name: 'Foo', qualifier: ComponentQualifier.Project }),
);
expect(byText('deletion.page').get()).toBeInTheDocument();
user.click(byRole('button', { name: 'delete' }).get());
expect(await byRole('dialog', { name: 'qualifier.delete.TRK' }).find()).toBeInTheDocument();
user.click(
- byRole('dialog', { name: 'qualifier.delete.TRK' }).byRole('button', { name: 'delete' }).get()
+ byRole('dialog', { name: 'qualifier.delete.TRK' }).byRole('button', { name: 'delete' }).get(),
);
expect(await byText(/project_deletion.resource_dele/).find()).toBeInTheDocument();
});
renderProjectDeletionApp(
- mockComponent({ key: 'foo', name: 'Foo', qualifier: ComponentQualifier.Portfolio })
+ mockComponent({ key: 'foo', name: 'Foo', qualifier: ComponentQualifier.Portfolio }),
);
expect(byText('deletion.page').get()).toBeInTheDocument();
expect(await byRole('dialog', { name: 'qualifier.delete.VW' }).find()).toBeInTheDocument();
user.click(
- byRole('dialog', { name: 'qualifier.delete.VW' }).byRole('button', { name: 'delete' }).get()
+ byRole('dialog', { name: 'qualifier.delete.VW' }).byRole('button', { name: 'delete' }).get(),
);
expect(await byText(/project_deletion.resource_dele/).find()).toBeInTheDocument();
});
renderProjectDeletionApp(
- mockComponent({ key: 'foo', name: 'Foo', qualifier: ComponentQualifier.Application })
+ mockComponent({ key: 'foo', name: 'Foo', qualifier: ComponentQualifier.Application }),
);
expect(byText('deletion.page').get()).toBeInTheDocument();
user.click(byRole('button', { name: 'delete' }).get());
expect(await byRole('dialog', { name: 'qualifier.delete.APP' }).find()).toBeInTheDocument();
user.click(
- byRole('dialog', { name: 'qualifier.delete.APP' }).byRole('button', { name: 'delete' }).get()
+ byRole('dialog', { name: 'qualifier.delete.APP' }).byRole('button', { name: 'delete' }).get(),
);
expect(await byText(/project_deletion.resource_dele/).find()).toBeInTheDocument();
'project-delete',
<ComponentContext.Provider value={{ component } as ComponentContextShape}>
<App />
- </ComponentContext.Provider>
+ </ComponentContext.Provider>,
);
}
lastImportTask,
lastAnalysisTask,
};
- }
+ },
);
};
},
() => {
/* no catch needed */
- }
+ },
);
};
'import_export',
routes,
{ featureList },
- { component: mockComponent({ key: COMPONENT_KEY }) }
+ { component: mockComponent({ key: COMPONENT_KEY }) },
);
}
renderWhenExportFailed() {
const { componentKey } = this.props;
const detailsUrl = `/project/background_tasks?id=${encodeURIComponent(
- componentKey
+ componentKey,
)}&status=FAILED&taskType=PROJECT_EXPORT`;
return (
const detailsUrl = getComponentBackgroundTaskUrl(
componentKey,
TaskStatuses.Failed,
- TaskTypes.ProjectImport
+ TaskTypes.ProjectImport,
);
return (
}
export default withComponentContext(
- withCurrentUserContext(withMetricsContext(withAvailableFeatures(ProjectInformationApp)))
+ withCurrentUserContext(withMetricsContext(withAvailableFeatures(ProjectInformationApp))),
);
description: 'Test description',
tags: ['bar'],
},
- mockLoggedInUser()
+ mockLoggedInUser(),
);
expect(await ui.projectPageTitle.find()).toBeInTheDocument();
expect(ui.qualityGateList.get()).toBeInTheDocument();
description: 'Test description',
tags: ['bar'],
},
- mockLoggedInUser()
+ mockLoggedInUser(),
);
expect(await ui.applicationPageTitle.find()).toBeInTheDocument();
expect(ui.qualityGateList.query()).not.toBeInTheDocument();
function renderProjectInformationApp(
overrides: Partial<Component> = {},
- currentUser: CurrentUser = mockCurrentUser()
+ currentUser: CurrentUser = mockCurrentUser(),
) {
const component = mockComponent(overrides);
componentsMock.registerComponent(component, [componentsMock.components[0].component]);
'project/information',
routes,
{ currentUser },
- { component }
+ { component },
);
}
if (!isApp) {
getProjectLinks(component.key).then(
(links) => setLinks(links),
- () => {}
+ () => {},
);
}
}, [component.key, isApp]);
});
setDeprecatedByKey(deprecatedByKey);
},
- () => {}
+ () => {},
);
}, [profiles]);
aria-label={translateWithParameters(
'overview.link_to_x_profile_y',
languageName,
- profile.name
+ profile.name,
)}
>
{profile.name}
<span
aria-label={translateWithParameters(
'project.info.see_more_info_on_x_locs',
- ncloc.value
+ ncloc.value,
)}
>
{formatMeasure(ncloc.value, 'SHORT_INT')}
const handleSetProjectTags = (values: string[]) => {
setTags(values).then(
() => props.onComponentChange({ tags: values }),
- () => {}
+ () => {},
);
};
ps: Math.min(selectedTags.length - 1 + LIST_SIZE, MAX_LIST_SIZE),
}).then(
({ tags }) => setSearchResult(tags),
- () => {}
+ () => {},
);
};
it('should render correctly', () => {
renderMetaKey();
expect(
- screen.getByText(`overview.project_key.${ComponentQualifier.Project}`)
+ screen.getByText(`overview.project_key.${ComponentQualifier.Project}`),
).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Copy to clipboard' })).toBeInTheDocument();
});
function renderMetaKey(props: Partial<Parameters<typeof MetaKey>[0]> = {}) {
return renderComponent(
- <MetaKey componentKey="foo" qualifier={ComponentQualifier.Project} {...props} />
+ <MetaKey componentKey="foo" qualifier={ComponentQualifier.Project} {...props} />,
);
}
});
function renderMetaQualityprofiles(
- overrides: Partial<Parameters<typeof MetaQualityProfiles>[0]> = {}
+ overrides: Partial<Parameters<typeof MetaQualityProfiles>[0]> = {},
) {
return renderComponent(
<LanguagesContext.Provider value={{ css: mockLanguage() }}>
]}
{...overrides}
/>
- </LanguagesContext.Provider>
+ </LanguagesContext.Provider>,
);
}
});
return renderComponent(
- <MetaTags component={component} onComponentChange={jest.fn()} {...overrides} />
+ <MetaTags component={component} onComponentChange={jest.fn()} {...overrides} />,
);
}
'overview.badges',
BadgeType.qualityGate,
'description',
- qualifier
+ qualifier,
)}
/>
</div>
jest.mock('../../../../helpers/urls', () => ({
getHostUrl: () => 'host',
getPathUrlAsString: (l: Location) => l.pathname,
- getProjectUrl: () => ({ pathname: '/dashboard' } as Location),
+ getProjectUrl: () => ({ pathname: '/dashboard' }) as Location,
}));
jest.mock('../../../../api/project-badges', () => ({
await waitFor(() =>
expect(screen.getByAltText(`overview.badges.${BadgeType.qualityGate}.alt`)).toHaveAttribute(
'src',
- 'host/api/project_badges/quality_gate?branch=branch-6.7&project=my-project&token=foo'
- )
+ 'host/api/project_badges/quality_gate?branch=branch-6.7&project=my-project&token=foo',
+ ),
);
expect(screen.getByAltText(`overview.badges.${BadgeType.measure}.alt`)).toHaveAttribute(
'src',
- 'host/api/project_badges/measure?branch=branch-6.7&project=my-project&metric=alert_status&token=foo'
+ 'host/api/project_badges/measure?branch=branch-6.7&project=my-project&metric=alert_status&token=foo',
);
await user.click(screen.getByText('overview.badges.renew'));
expect(
- await screen.findByAltText(`overview.badges.${BadgeType.qualityGate}.alt`)
+ await screen.findByAltText(`overview.badges.${BadgeType.qualityGate}.alt`),
).toHaveAttribute(
'src',
- 'host/api/project_badges/quality_gate?branch=branch-6.7&project=my-project&token=bar'
+ 'host/api/project_badges/quality_gate?branch=branch-6.7&project=my-project&token=bar',
);
expect(screen.getByAltText(`overview.badges.${BadgeType.measure}.alt`)).toHaveAttribute(
'src',
- 'host/api/project_badges/measure?branch=branch-6.7&project=my-project&metric=alert_status&token=bar'
+ 'host/api/project_badges/measure?branch=branch-6.7&project=my-project&metric=alert_status&token=bar',
);
});
expect(
await screen.findByText(
- '[![alert_status](host/api/project_badges/measure?branch=branch-6.7&project=my-project&metric=alert_status&token=foo)](/dashboard)'
- )
+ '[![alert_status](host/api/project_badges/measure?branch=branch-6.7&project=my-project&metric=alert_status&token=foo)](/dashboard)',
+ ),
).toBeInTheDocument();
await selectEvent.select(screen.getByLabelText('overview.badges.format'), [
expect(
screen.getByText(
- 'host/api/project_badges/measure?branch=branch-6.7&project=my-project&metric=alert_status&token=foo'
- )
+ 'host/api/project_badges/measure?branch=branch-6.7&project=my-project&metric=alert_status&token=foo',
+ ),
).toBeInTheDocument();
await selectEvent.select(screen.getByLabelText('overview.badges.metric'), MetricKey.coverage);
expect(
screen.getByText(
- `host/api/project_badges/measure?branch=branch-6.7&project=my-project&metric=${MetricKey.coverage}&token=foo`
- )
+ `host/api/project_badges/measure?branch=branch-6.7&project=my-project&metric=${MetricKey.coverage}&token=foo`,
+ ),
).toBeInTheDocument();
});
branchLike={mockBranch()}
component={mockComponent({ key: 'foo', qualifier: ComponentQualifier.Project })}
{...props}
- />
+ />,
);
}
describe('#getBadgeUrl', () => {
it('should generate correct quality gate badge links', () => {
expect(getBadgeUrl(BadgeType.qualityGate, options, 'foo')).toBe(
- 'host/api/project_badges/quality_gate?branch=master&project=foo&token=foo'
+ 'host/api/project_badges/quality_gate?branch=master&project=foo&token=foo',
);
});
it('should generate correct measures badge links', () => {
expect(getBadgeUrl(BadgeType.measure, options, 'foo')).toBe(
- 'host/api/project_badges/measure?branch=master&project=foo&metric=alert_status&token=foo'
+ 'host/api/project_badges/measure?branch=master&project=foo&metric=alert_status&token=foo',
);
});
it('should ignore undefined parameters', () => {
expect(getBadgeUrl(BadgeType.measure, { metric: 'alert_status' }, 'foo')).toBe(
- 'host/api/project_badges/measure?metric=alert_status&token=foo'
+ 'host/api/project_badges/measure?metric=alert_status&token=foo',
);
});
it('should force metric parameters', () => {
expect(getBadgeUrl(BadgeType.measure, {}, 'foo')).toBe(
- 'host/api/project_badges/measure?metric=alert_status&token=foo'
+ 'host/api/project_badges/measure?metric=alert_status&token=foo',
);
});
});
describe('#getBadgeSnippet', () => {
it('should generate a correct markdown image', () => {
expect(getBadgeSnippet(BadgeType.measure, { ...options, format: 'md' }, 'foo')).toBe(
- '[![alert_status](host/api/project_badges/measure?branch=master&project=foo&metric=alert_status&token=foo)](host/dashboard?id=foo&branch=master)'
+ '[![alert_status](host/api/project_badges/measure?branch=master&project=foo&metric=alert_status&token=foo)](host/dashboard?id=foo&branch=master)',
);
});
});
export function getBadgeUrl(
type: BadgeType,
{ branch, project, metric = 'alert_status', pullRequest }: BadgeOptions,
- token: string
+ token: string,
) {
switch (type) {
case BadgeType.qualityGate:
return `${getHostUrl()}/api/project_badges/quality_gate?${new URLSearchParams(
- omitNil({ branch, project, pullRequest, token })
+ omitNil({ branch, project, pullRequest, token }),
).toString()}`;
case BadgeType.measure:
default:
return `${getHostUrl()}/api/project_badges/measure?${new URLSearchParams(
- omitNil({ branch, project, metric, pullRequest, token })
+ omitNil({ branch, project, metric, pullRequest, token }),
).toString()}`;
}
}
(notification) =>
notification.type === type &&
notification.channel === channel &&
- notification.project === component.key
+ notification.project === component.key,
);
};
className="sw-flex sw-justify-between"
label={translateWithParameters(
'notification.dispatcher.descrption_x',
- getDispatcherLabel(type)
+ getDispatcherLabel(type),
)}
checked={isEnabled(type, emailChannel)}
id={getCheckboxId(type, emailChannel)}
renderProjectNotifications();
expect(
- await screen.findByText('project_information.project_notifications.title')
+ await screen.findByText('project_information.project_notifications.title'),
).toBeInTheDocument();
expect(
screen.getByLabelText(
- 'notification.dispatcher.descrption_x.notification.dispatcher.NewAlerts.project'
- )
+ 'notification.dispatcher.descrption_x.notification.dispatcher.NewAlerts.project',
+ ),
).toBeChecked();
expect(
screen.getByLabelText(
- 'notification.dispatcher.descrption_x.notification.dispatcher.NewIssues.project'
- )
+ 'notification.dispatcher.descrption_x.notification.dispatcher.NewIssues.project',
+ ),
).not.toBeChecked();
// Toggle New Alerts
await user.click(
screen.getByLabelText(
- 'notification.dispatcher.descrption_x.notification.dispatcher.NewAlerts.project'
- )
+ 'notification.dispatcher.descrption_x.notification.dispatcher.NewAlerts.project',
+ ),
);
expect(
screen.getByLabelText(
- 'notification.dispatcher.descrption_x.notification.dispatcher.NewAlerts.project'
- )
+ 'notification.dispatcher.descrption_x.notification.dispatcher.NewAlerts.project',
+ ),
).not.toBeChecked();
// Toggle New Issues
await user.click(
screen.getByLabelText(
- 'notification.dispatcher.descrption_x.notification.dispatcher.NewIssues.project'
- )
+ 'notification.dispatcher.descrption_x.notification.dispatcher.NewIssues.project',
+ ),
);
expect(
screen.getByLabelText(
- 'notification.dispatcher.descrption_x.notification.dispatcher.NewIssues.project'
- )
+ 'notification.dispatcher.descrption_x.notification.dispatcher.NewIssues.project',
+ ),
).toBeChecked();
});
function renderProjectNotifications() {
return renderComponent(
- <ProjectNotifications component={mockComponent({ key: 'foo', name: 'Foo' })} />
+ <ProjectNotifications component={mockComponent({ key: 'foo', name: 'Foo' })} />,
);
}
const branches = await getBranches(component.key);
const availableBranches = branches.filter(
- (br) => br.analysisDate && (isMainBranch(br) || br.excludedFromPurge)
+ (br) => br.analysisDate && (isMainBranch(br) || br.excludedFromPurge),
);
const mainBranch = availableBranches.find(isMainBranch);
const otherBranchSorted = orderBy(
availableBranches.filter((b) => !isMainBranch(b)),
- (b) => b.name
+ (b) => b.name,
);
const sortedBranch = mainBranch ? [mainBranch, ...otherBranchSorted] : otherBranchSorted;
const options = sortedBranch.map((br) => {
expect(ui.downloadButton.get()).toBeInTheDocument();
expect(ui.downloadButton.get()).toHaveAttribute(
'href',
- `/api/regulatory_reports/download?project=&branch=${compatibleBranch.name}`
+ `/api/regulatory_reports/download?project=&branch=${compatibleBranch.name}`,
);
});
expect(ui.downloadButton.get()).toBeInTheDocument();
expect(ui.downloadButton.get()).toHaveAttribute(
'href',
- `/api/regulatory_reports/download?project=&branch=${mainBranch.name}`
+ `/api/regulatory_reports/download?project=&branch=${mainBranch.name}`,
);
});
});
'project/key',
() => <Route path="project/key" element={<ProjectKeyApp />} />,
{},
- { component: componentsMock.components[0].component }
+ { component: componentsMock.components[0].component },
);
}
isDestructive
modalBody={translateWithParameters(
'project_links.are_you_sure_to_delete_x_link',
- link.name!
+ link.name!,
)}
modalHeader={translate('project_links.delete_project_link')}
onConfirm={this.props.onDelete}
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
};
'project/links',
() => <Route path="project/links" element={<ProjectLinksApp />} />,
{},
- { component: mockComponent() }
+ { component: mockComponent() },
);
}
},
() => {
this.scrollToSelected();
- }
+ },
);
});
}
ariaLabel={translateWithParameters(
'baseline.branch_analyses.analysis_for_x',
`${intl.formatDate(analysis.date, longFormatterOption)}, ${intl.formatTime(
- analysis.date
- )}`
+ analysis.date,
+ )}`,
)}
onCheck={() => {}}
value=""
}
function BranchAnalysisListRenderer(
- props: BranchAnalysisListRendererProps & WrappedComponentProps
+ props: BranchAnalysisListRendererProps & WrappedComponentProps,
) {
const { analyses, loading, range, selectedAnalysisKey, intl } = props;
getAnalysesByVersionByDay(analyses, {
category: '',
}),
- [analyses]
+ [analyses],
);
const hasFilteredData =
isFirst: analyses[0].key === analysis.key,
onSelectAnalysis: props.onSelectAnalysis,
intl,
- })
+ }),
)}
</ul>
</li>
});
const previouslyNonCompliantBranchNCDs = newCodePeriods.filter(
- isPreviouslyNonCompliantDaysNCD
+ isPreviouslyNonCompliantDaysNCD,
);
this.setState({
},
() => {
this.setState({ loading: false });
- }
+ },
);
}
this.setState(({ previouslyNonCompliantBranchNCDs }) => ({
branches: this.updateBranchNewCodePeriod(branch, newSetting),
previouslyNonCompliantBranchNCDs: previouslyNonCompliantBranchNCDs?.filter(
- ({ branchKey }) => branchKey !== branch
+ ({ branchKey }) => branchKey !== branch,
),
editedBranch: undefined,
}));
function branchInheritsItselfAsReference(
branch: BranchWithNewCodePeriod,
- inheritedSetting: NewCodeDefinition
+ inheritedSetting: NewCodeDefinition,
) {
return (
!branch.newCodePeriod &&
function referenceBranchDoesNotExist(
branch: BranchWithNewCodePeriod,
- existingBranches: Array<string>
+ existingBranches: Array<string>,
) {
return (
branch.newCodePeriod &&
if (branchInheritsItselfAsReference(branch, inheritedSetting)) {
settingWarning = translateWithParameters(
'baseline.reference_branch.invalid_branch_setting',
- branch.name
+ branch.name,
);
} else if (referenceBranchDoesNotExist(branch, existingBranches)) {
settingWarning = translateWithParameters(
'baseline.reference_branch.does_not_exist',
- branch.newCodePeriod?.value || ''
+ branch.newCodePeriod?.value || '',
);
}
saving: false,
});
}
- }
+ },
);
}
};
<Tooltip
overlay={translateWithParameters(
'baseline.reference_branch.does_not_exist',
- option.value
+ option.value,
)}
>
<span>
}
export default function NewCodeDefinitionSettingReferenceBranch(
- props: BaselineSettingReferenceBranchProps
+ props: BaselineSettingReferenceBranchProps,
) {
const { branchList, className, disabled, referenceBranch, selected, settingLevel } = props;
const resetStatesFromProjectNewCodeDefinition = useCallback(() => {
setIsSpecificNewCodeDefinition(
- projectNewCodeDefinition === undefined ? undefined : !projectNewCodeDefinition.inherited
+ projectNewCodeDefinition === undefined ? undefined : !projectNewCodeDefinition.inherited,
);
setSelectedNewCodeDefinitionType(
- projectNewCodeDefinition?.type ?? DEFAULT_NEW_CODE_DEFINITION_TYPE
+ projectNewCodeDefinition?.type ?? DEFAULT_NEW_CODE_DEFINITION_TYPE,
);
setNumberOfDays(getNumberOfDaysDefaultValue(globalNewCodeDefinition, projectNewCodeDefinition));
setReferenceBranch(
projectNewCodeDefinition?.type === NewCodeDefinitionType.ReferenceBranch
? projectNewCodeDefinition.value
- : defaultReferenceBranch
+ : defaultReferenceBranch,
);
setSpecificAnalysis(
projectNewCodeDefinition?.type === NewCodeDefinitionType.SpecificAnalysis
? projectNewCodeDefinition.value
- : undefined
+ : undefined,
);
}, [defaultReferenceBranch, globalNewCodeDefinition, projectNewCodeDefinition]);
}
export default withComponentContext(
- withAvailableFeatures(withAppStateContext(withBranchLikes(ProjectNewCodeDefinitionApp)))
+ withAvailableFeatures(withAppStateContext(withBranchLikes(ProjectNewCodeDefinitionApp))),
);
await ui.setBranchPreviousVersionSetting('main');
expect(
- within(byRole('table').get()).getByText('new_code_definition.previous_version')
+ within(byRole('table').get()).getByText('new_code_definition.previous_version'),
).toBeInTheDocument();
await user.click(await ui.branchActionsButton('main').find());
await user.click(ui.resetToDefaultButton.get());
expect(
- first(within(byRole('table').get()).getAllByText('branch_list.default_setting'))
+ first(within(byRole('table').get()).getAllByText('branch_list.default_setting')),
).toBeInTheDocument();
});
await ui.setBranchNumberOfDaysSetting('main', '15');
expect(
- within(byRole('table').get()).getByText('new_code_definition.number_days: 15')
+ within(byRole('table').get()).getByText('new_code_definition.number_days: 15'),
).toBeInTheDocument();
});
await ui.setBranchReferenceToBranchSetting('main', 'normal-branch');
expect(
- byRole('table').byText('baseline.reference_branch: normal-branch').get()
+ byRole('table').byText('baseline.reference_branch: normal-branch').get(),
).toBeInTheDocument();
});
expect(await ui.branchNCDsBanner.find()).toBeInTheDocument();
expect(
- ui.branchNCDsBanner.byText('new_code_definition.auto_update.branch.list_itemmaster32150').get()
+ ui.branchNCDsBanner.byText('new_code_definition.auto_update.branch.list_itemmaster32150').get(),
).toBeInTheDocument();
});
},
{
component: mockComponent(),
- }
+ },
);
}
it('should work for Days', () => {
expect(getSettingValue({ ...state, type: NewCodeDefinitionType.NumberOfDays })).toBe(
- state.numberOfDays
+ state.numberOfDays,
);
});
it('should work for Analysis', () => {
expect(getSettingValue({ ...state, type: NewCodeDefinitionType.SpecificAnalysis })).toBe(
- state.analysis
+ state.analysis,
);
});
it('should work for Previous version', () => {
expect(
- getSettingValue({ ...state, type: NewCodeDefinitionType.PreviousVersion })
+ getSettingValue({ ...state, type: NewCodeDefinitionType.PreviousVersion }),
).toBeUndefined();
});
it('should work for Reference branch', () => {
expect(getSettingValue({ ...state, type: NewCodeDefinitionType.ReferenceBranch })).toBe(
- state.referenceBranch
+ state.referenceBranch,
);
});
});
validateSetting({
numberOfDays: '12',
selectedNewCodeDefinitionType: NewCodeDefinitionType.NumberOfDays,
- })
+ }),
).toEqual(true);
expect(
validateSetting({
numberOfDays: 'nope',
selectedNewCodeDefinitionType: NewCodeDefinitionType.NumberOfDays,
- })
+ }),
).toEqual(false);
expect(
validateSetting({
numberOfDays: '',
selectedNewCodeDefinitionType: NewCodeDefinitionType.SpecificAnalysis,
- })
+ }),
).toEqual(false);
expect(
validateSetting({
numberOfDays: '',
referenceBranch: 'master',
selectedNewCodeDefinitionType: NewCodeDefinitionType.ReferenceBranch,
- })
+ }),
).toEqual(true);
expect(
validateSetting({
numberOfDays: '',
referenceBranch: '',
selectedNewCodeDefinitionType: NewCodeDefinitionType.ReferenceBranch,
- })
+ }),
).toEqual(false);
});
it('should validate at project level', () => {
expect(validateSetting({ numberOfDays: '', overrideGlobalNewCodeDefinition: false })).toEqual(
- true
+ true,
);
expect(
validateSetting({
selectedNewCodeDefinitionType: NewCodeDefinitionType.PreviousVersion,
numberOfDays: '',
overrideGlobalNewCodeDefinition: true,
- })
+ }),
).toEqual(true);
expect(
validateSetting({
selectedNewCodeDefinitionType: NewCodeDefinitionType.NumberOfDays,
numberOfDays: '',
overrideGlobalNewCodeDefinition: true,
- })
+ }),
).toEqual(false);
expect(
validateSetting({
selectedNewCodeDefinitionType: NewCodeDefinitionType.NumberOfDays,
numberOfDays: '12',
overrideGlobalNewCodeDefinition: true,
- })
+ }),
).toEqual(true);
});
});
qualitygates.map(async (qg) => {
const detailedQp = await fetchQualityGate({ name: qg.name }).catch(() => qg);
return { ...detailedQp, ...qg };
- })
+ }),
);
};
function renderProjectQualityGateApp(
context?: RenderContext,
- componentOverrides: Partial<Component> = { configuration: { showQualityGates: true } }
+ componentOverrides: Partial<Component> = { configuration: { showQualityGates: true } },
) {
renderAppWithComponentContext('project/quality_gate', routes, context, {
component: mockComponent(componentOverrides),
selected: Boolean(results.find((p) => p.key === component.key)?.selected),
profile,
}))
- .catch(() => ({ selected: false, profile }))
- )
+ .catch(() => ({ selected: false, profile })),
+ ),
);
const selectedProjectProfiles = projectProfiles
const componentProfiles = differenceBy(
component.qualityProfiles,
selectedProjectProfiles.map((p) => p.profile),
- 'key'
+ 'key',
)
// Discard languages we already have up-to-date info for.
.filter(
- ({ language }) => !selectedProjectProfiles.some((p) => p.profile.language === language)
+ ({ language }) => !selectedProjectProfiles.some((p) => p.profile.language === language),
)
.map(({ key }) => {
const profile = allProfiles.find((p) => p.key === key);
// be taken into account after a new analysis. Fetch the
// default profile.
const defaultProfile = allProfiles.find(
- (p) => p.isDefault && p.language === profile.language
+ (p) => p.isDefault && p.language === profile.language,
);
return (
defaultProfile && {
addGlobalSuccessMessage(
translateWithParameters(
'project_quality_profile.successfully_updated',
- newProfile.languageName
- )
+ newProfile.languageName,
+ ),
);
}
} catch (e) {
const newProfile = newKey && allProfiles.find((p) => p.key === newKey);
const oldProjectProfile = projectProfiles.find((p) => p.profile.key === oldKey);
const defaultProfile = allProfiles.find(
- (p) => p.isDefault && p.language === oldProjectProfile?.profile.language
+ (p) => p.isDefault && p.language === oldProjectProfile?.profile.language,
);
if (defaultProfile === undefined || oldProjectProfile === undefined) {
addGlobalSuccessMessage(
translateWithParameters(
'project_quality_profile.successfully_updated',
- defaultProfile.languageName
- )
+ defaultProfile.languageName,
+ ),
);
}
};
}
export default function ProjectQualityProfilesAppRenderer(
- props: ProjectQualityProfilesAppRendererProps
+ props: ProjectQualityProfilesAppRendererProps,
) {
const {
allProfiles,
expect(ui.pageDescription.get()).toBeInTheDocument();
expect(ui.addLanguageButton.get()).toBeInTheDocument();
await expect(ui.helpTooltip.get()).toHaveATooltipWithContent(
- 'quality_profiles.list.projects.help'
+ 'quality_profiles.list.projects.help',
);
expect(ui.profileRows.getAll()).toHaveLength(5);
expect(ui.cssLanguage.get()).toBeInTheDocument();
await user.click(ui.buttonSave.get());
expect(associateProject).toHaveBeenLastCalledWith(
expect.objectContaining({ key: 'html', name: 'html profile' }),
- 'my-project'
+ 'my-project',
);
expect(addGlobalSuccessMessage).toHaveBeenCalledWith(
- 'project_quality_profile.successfully_updated.HTML'
+ 'project_quality_profile.successfully_updated.HTML',
);
// Updates the page after API call
expect(htmlRow.get()).toBeInTheDocument();
expect(htmlRow.byRole('link', { name: '10' }).get()).toHaveAttribute(
'href',
- '/coding_rules?activation=true&qprofile=html'
+ '/coding_rules?activation=true&qprofile=html',
);
expect(ui.builtInTag.query()).not.toBeInTheDocument();
await user.click(
- htmlRow.byRole('button', { name: 'project_quality_profile.change_profile' }).get()
+ htmlRow.byRole('button', { name: 'project_quality_profile.change_profile' }).get(),
);
//Opens modal to change profile
await user.click(ui.buttonSave.get());
expect(addGlobalSuccessMessage).toHaveBeenCalledWith(
- 'project_quality_profile.successfully_updated.HTML'
+ 'project_quality_profile.successfully_updated.HTML',
);
// Updates the page after API call
function renderProjectQualityProfilesApp(
context?: RenderContext,
- componentOverrides: Partial<Component> = { configuration: { showQualityProfiles: true } }
+ componentOverrides: Partial<Component> = { configuration: { showQualityProfiles: true } },
) {
return renderAppWithComponentContext('project/quality_profiles', routes, context, {
component: mockComponent(componentOverrides),
const languageOptions: LabelValueSelectOption[] = difference(
Object.keys(profilesByLanguage),
- unavailableLanguages
+ unavailableLanguages,
).map((l) => ({ value: l, label: languages[l].name }));
const profileOptions: ProfileOption[] =
isDisabled={submitting}
id="language"
aria-label={translate(
- 'project_quality_profile.add_language_modal.choose_language'
+ 'project_quality_profile.add_language_modal.choose_language',
)}
onChange={({ value }: LabelValueSelectOption) => {
setSelected({ language: value, key: undefined });
isDisabled={submitting || !language}
id="profiles"
aria-label={translate(
- 'project_quality_profile.add_language_modal.choose_profile'
+ 'project_quality_profile.add_language_modal.choose_profile',
)}
onChange={({ value }: ProfileOption) => setSelected({ language, key: value })}
options={profileOptions}
<>
<p>
{translate(
- 'project_quality_profile.add_language_modal.profile_unavailable_no_active_rules'
+ 'project_quality_profile.add_language_modal.profile_unavailable_no_active_rules',
)}
</p>
{option.label && option.language && (
export default function SetQualityProfileModal(props: SetQualityProfileModalProps) {
const { availableProfiles, component, currentProfile, usesDefault } = props;
const [selected, setSelected] = React.useState(
- usesDefault ? USE_SYSTEM_DEFAULT : currentProfile.key
+ usesDefault ? USE_SYSTEM_DEFAULT : currentProfile.key,
);
const defaultProfile = availableProfiles.find((p) => p.isDefault);
const header = translateWithParameters(
'project_quality_profile.change_lang_X_profile',
- currentProfile.languageName
+ currentProfile.languageName,
);
const profileOptions: ProfileOption[] = availableProfiles.map((p) => ({
value: p.key,
const hasSelectedSysDefault = selected === USE_SYSTEM_DEFAULT;
const hasChanged = usesDefault ? !hasSelectedSysDefault : selected !== currentProfile.key;
const needsReanalysis = !component.qualityProfiles?.some((p) =>
- hasSelectedSysDefault ? p.key === defaultProfile.key : p.key === selected
+ hasSelectedSysDefault ? p.key === defaultProfile.key : p.key === selected,
);
return (
value={profileOptions.find(
(option) =>
option.value ===
- (!hasSelectedSysDefault ? selected : currentProfile.key)
+ (!hasSelectedSysDefault ? selected : currentProfile.key),
)}
/>
</div>
it('render years and months only', () => {
expect(utils.formatDuration(ONE_YEAR * 4 + ONE_MONTH * 2 + ONE_DAY * 10)).toEqual(
- 'duration.years.4 duration.months.2 '
+ 'duration.years.4 duration.months.2 ',
);
});
it('render hours and minutes', () => {
expect(utils.formatDuration(ONE_HOUR * 4 + ONE_MINUTE * 10)).toEqual(
- 'duration.hours.4 duration.minutes.10 '
+ 'duration.hours.4 duration.minutes.10 ',
);
});
component: Component & {
measures: { languages?: string; new_coverage?: string };
isScannable: boolean;
- }
+ },
) => {
// eslint-disable-next-line jest/no-conditional-in-test
if (component.key === 'foo') {
}
component.isScannable = false;
return component;
- }
+ },
),
total: 2,
<PageSidebar
applicationsEnabled={this.props.appState.qualifiers.includes(
- ComponentQualifier.Application
+ ComponentQualifier.Application,
)}
facets={this.state.facets}
loadSearchResultCount={this.loadSearchResultCount}
// eslint-disable-next-line react-hooks/exhaustive-deps
[
/* Run once on mount only */
- ]
+ ],
);
return <AllProjects {...props} />;
// eslint-disable-next-line react-hooks/exhaustive-deps
[
/* run only once on mount*/
- ]
+ ],
);
if (checking) {
value: option.value,
label: translate('projects.sorting', option.value),
className: option.class,
- })
+ }),
);
};
const projects = ui.projects.getAll();
expect(await within(projects[0]).findByRole('link')).toHaveTextContent(
- 'sonarlint-omnisharp-dotnet'
+ 'sonarlint-omnisharp-dotnet',
);
// Change perspective
renderApplicationCreation(
{ router },
- mockLoggedInUser({ permissions: { global: ['admin', 'applicationcreator'] } })
+ mockLoggedInUser({ permissions: { global: ['admin', 'applicationcreator'] } }),
);
await user.click(ui.buttonAddApplication.get());
'app',
'app description',
'app-key',
- Visibility.Private
+ Visibility.Private,
);
expect(routerPush).toHaveBeenCalledWith({
pathname: '/project/admin/extension/developer-server/application-console',
function renderApplicationCreation(
props: Partial<FCProps<typeof ApplicationCreation>> = {},
- currentUser: LoggedInUser = mockLoggedInUser()
+ currentUser: LoggedInUser = mockLoggedInUser(),
) {
return renderComponent(
<ApplicationCreation
router={mockRouter()}
appState={mockAppState({ qualifiers: [ComponentQualifier.Application] })}
{...props}
- />
+ />,
);
}
// eslint-disable-next-line
function AllProjects() {
return <div>All Projects</div>;
- }
+ },
);
jest.mock('../../../../helpers/storage', () => ({
<Route path="*" element={<RouteDisplayer />} />
</Route>
</Routes>
- </MemoryRouter>
+ </MemoryRouter>,
);
}
await user.click(screen.getByText(optionTranslationId));
expect(save).toHaveBeenLastCalledWith('sonarqube.projects.default', localStorageValue);
- }
+ },
);
it('does not render for anonymous', () => {
location={location}
router={mockRouter()}
params={{}}
- />
+ />,
);
}
onPerspectiveChange: onPerspectiveChangeMock,
onSortChange: onSortChangeMock,
},
- mockLoggedInUser({ permissions: { global: ['admin', 'provisioning', 'applicationcreator'] } })
+ mockLoggedInUser({ permissions: { global: ['admin', 'provisioning', 'applicationcreator'] } }),
);
expect(getAlmSettings).toHaveBeenCalled();
expect(ui.buttonAddProject.get()).toBeInTheDocument();
renderPageHeader(
{},
- mockLoggedInUser({ permissions: { global: ['admin', 'provisioning', 'applicationcreator'] } })
+ mockLoggedInUser({ permissions: { global: ['admin', 'provisioning', 'applicationcreator'] } }),
);
await user.click(ui.buttonAddProject.get());
expect(ui.selectOptionBitbucket.get()).toHaveAttribute('href', '/projects/create?mode=bitbucket');
expect(ui.selectOptionBitbucketCloud.get()).toHaveAttribute(
'href',
- '/projects/create?mode=bitbucketcloud'
+ '/projects/create?mode=bitbucketcloud',
);
});
function renderPageHeader(
props: Partial<FCProps<typeof PageHeader>> = {},
- currentUser: CurrentUser = mockLoggedInUser()
+ currentUser: CurrentUser = mockLoggedInUser(),
) {
return renderComponent(
<CurrentUserContextProvider currentUser={currentUser}>
/>
</CurrentUserContextProvider>,
'/',
- { appState: mockAppState({ qualifiers: [ComponentQualifier.Application] }) }
+ { appState: mockAppState({ qualifiers: [ComponentQualifier.Application] }) },
);
}
view="overall"
{...overrides}
/>
- </CurrentUserContext.Provider>
+ </CurrentUserContext.Provider>,
).container;
}
function renderFirstLine(
project: Props['project'],
handleFavorite: Props['handleFavorite'],
- isNewCode: boolean
+ isNewCode: boolean,
) {
const { analysisDate, isFavorite, key, measures, name, qualifier, tags, visibility } = project;
const formatted = formatMeasure(measures[MetricKey.alert_status], MetricType.Level);
function renderSecondLine(
currentUser: Props['currentUser'],
project: Props['project'],
- isNewCode: boolean
+ isNewCode: boolean,
) {
const { analysisDate, key, leakPeriodDate, measures, qualifier, isScannable } = project;
return (
<ProjectCardWrapper
className={classNames(
- 'it_project_card sw-relative sw-box-border sw-rounded-1 sw-mb-page sw-h-full'
+ 'it_project_card sw-relative sw-box-border sw-rounded-1 sw-mb-page sw-h-full',
)}
data-key={project.key}
>
const parsedLanguages = distribution.split(';').map((item) => item.split('='));
const finalLanguages = sortBy(parsedLanguages, (l) => -1 * Number(l[1])).map((l) =>
- getLanguageName(languages, l[0])
+ getLanguageName(languages, l[0]),
);
const languagesText =
}
export default function ProjectCardMeasure(
- props: React.PropsWithChildren<ProjectCardMeasureProps>
+ props: React.PropsWithChildren<ProjectCardMeasureProps>,
) {
const { label, metricKey, children, className } = props;
function renderProjectCard(project: Project, user: CurrentUser = USER_LOGGED_OUT, type?: string) {
renderComponent(
- <ProjectCard currentUser={user} handleFavorite={jest.fn()} project={project} type={type} />
+ <ProjectCard currentUser={user} handleFavorite={jest.fn()} project={project} type={type} />,
);
}
it('should handle more then 3 languages', async () => {
renderProjectCardLanguages('java=137;js=18;cpp=10;c=8;php=4');
await expect(screen.getByText('Java, JavaScript, ...')).toHaveATooltipWithContent(
- 'JavaJavaScriptcppcphp'
+ 'JavaJavaScriptcppcphp',
);
});
function renderProjectCardLanguages(distribution?: string) {
return renderComponent(
- <ProjectCardLanguages languages={languages} distribution={distribution} />
+ <ProjectCardLanguages languages={languages} distribution={distribution} />,
);
}
it("should be not be rendered if there's no line of code and application", () => {
renderProjectCardMeasures(
{ [MetricKey.ncloc]: undefined },
- { componentQualifier: ComponentQualifier.Application }
+ { componentQualifier: ComponentQualifier.Application },
);
expect(screen.getByText('portfolio.app.empty')).toBeInTheDocument();
});
function renderProjectCardMeasures(
measuresOverride: Dict<string | undefined> = {},
- props: Partial<ProjectCardMeasuresProps> = {}
+ props: Partial<ProjectCardMeasuresProps> = {},
) {
const measures = {
[MetricKey.alert_status]: 'ERROR',
isNewCode={false}
measures={measures}
{...props}
- />
+ />,
);
}
? translate('projects.facets.coverage.label', option.toString())
: translateWithParameters(
'projects.facets.label_no_data_x',
- translate('metric_domain.Coverage')
+ translate('metric_domain.Coverage'),
);
}
? translate('projects.facets.duplication.label', option.toString())
: translateWithParameters(
'projects.facets.label_no_data_x',
- translate('metric_domain.Duplications')
+ translate('metric_domain.Duplications'),
);
}
// and make sure we reference each language only once
return uniqBy(
[...Object.values(languages), ...Object.keys(facet ?? {}).map((key) => ({ key, name: key }))],
- (language) => language.key
+ (language) => language.key,
);
}, [languages, facet]);
const { languages } = newValue;
onQueryChange({ languages: languages.join(',') });
},
- [onQueryChange]
+ [onQueryChange],
);
const handleSearch = React.useCallback(
(query: string) => {
const results = searchOptions.filter((lang) =>
- lang.name.toLowerCase().includes(query.toLowerCase())
+ lang.name.toLowerCase().includes(query.toLowerCase()),
);
const paging = { pageIndex: 1, pageSize: results.length, total: results.length };
results,
});
},
- [searchOptions]
+ [searchOptions],
);
const handleSearchResultCount = React.useCallback(
(languages: Language[]) => {
return loadSearchResultCount(
'languages',
- languages.map((l) => l.key)
+ languages.map((l) => l.key),
);
},
- [loadSearchResultCount]
+ [loadSearchResultCount],
);
const renderSearchResults = React.useCallback(
(lang: Language, term: string) => highlightTerm(lang.name, term),
- []
+ [],
);
const renderLanguageName = React.useCallback(
return languages[key]?.name || key;
},
- [languages]
+ [languages],
);
return (
qualifier: active ? '' : itemValue,
});
},
- [onQueryChange, value]
+ [onQueryChange, value],
);
return (
});
}
},
- [onQueryChange, value]
+ [onQueryChange, value],
);
return (
return translateWithParameters(
'projects.facets.rating_label_single_x',
translate('metric_domain', name),
- formatMeasure(option, MetricType.Rating)
+ formatMeasure(option, MetricType.Rating),
);
}
return translateWithParameters(
'projects.facets.rating_label_multi_x',
translate('metric_domain', name),
- formatMeasure(option, MetricType.Rating)
+ formatMeasure(option, MetricType.Rating),
);
},
- [name]
+ [name],
);
return (
return translateWithParameters(
'projects.facets.rating_label_single_x',
translate('metric_domain.SecurityReview'),
- formatMeasure(option, MetricType.Rating)
+ formatMeasure(option, MetricType.Rating),
);
}
return translateWithParameters(
'projects.facets.rating_label_multi_x',
translate('metric_domain.SecurityReview'),
- formatMeasure(option, MetricType.Rating)
+ formatMeasure(option, MetricType.Rating),
);
}
NO_DATA: 4,
}}
{...props}
- />
+ />,
);
}
facet={{ js: 12, ts: 7, java: 4, xml: 1, '<null>': 1 }}
value={['js', 'ts']}
{...props}
- />
+ />,
);
}
onQueryChange={jest.fn()}
facet={{ OK: 6, ERROR: 3 }}
{...props}
- />
+ />,
);
}
facet={{ cheese: 5, style: 3, custom1: 1 }}
value={['custom1']}
{...props}
- />
+ />,
);
}
}
['coverage', 'new_coverage'].forEach((property) =>
- pushMetricToArray(query, property, conditions, convertCoverage)
+ pushMetricToArray(query, property, conditions, convertCoverage),
);
['duplications', 'new_duplications'].forEach((property) =>
- pushMetricToArray(query, property, conditions, convertDuplications)
+ pushMetricToArray(query, property, conditions, convertDuplications),
);
['size', 'new_lines'].forEach((property) =>
- pushMetricToArray(query, property, conditions, convertSize)
+ pushMetricToArray(query, property, conditions, convertSize),
);
[
].forEach((property) => pushMetricToArray(query, property, conditions, convertIssuesRating));
['languages', 'tags', 'qualifier'].forEach((property) =>
- pushMetricToArray(query, property, conditions, convertArrayMetric)
+ pushMetricToArray(query, property, conditions, convertArrayMetric),
);
if (query['search'] != null) {
query: Query,
property: string,
conditionsArray: string[],
- convertFunction: (metric: string, value: any) => string
+ convertFunction: (metric: string, value: any) => string,
): void {
const metric = mapPropertyToMetric(property);
if (query[property] != null && metric) {
fetchProjectMeasures(response.components, query),
Promise.resolve(response),
fetchScannableProjects(),
- ])
+ ]),
)
.then(([measures, { components, facets, paging }, { scannableProjects }]) => {
return {
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
}
if (this.mounted) {
this.setState({ submitting: false });
}
- }
+ },
);
}
};
{this.props.selection.length
? translateWithParameters(
'permission_templates.bulk_apply_permission_template.apply_to_selected',
- this.props.selection.length
+ this.props.selection.length,
)
: translateWithParameters(
'permission_templates.bulk_apply_permission_template.apply_to_all',
- this.props.total
+ this.props.total,
)}
</Alert>
);
{translate(
`settings.projects.change_visibility_form.warning${
githubProbivisioningEnabled ? '.github' : ''
- }`
+ }`,
)}
</Alert>
</div>
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
};
<Alert variant="success">
<FormattedMessage
defaultMessage={translate(
- 'projects_management.project_has_been_successfully_created'
+ 'projects_management.project_has_been_successfully_created',
)}
id="projects_management.project_has_been_successfully_created"
values={{
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
};
{this.props.selection.length
? translateWithParameters(
'projects_management.delete_selected_warning',
- this.props.selection.length
+ this.props.selection.length,
)
: translateWithParameters('projects_management.delete_all_warning', this.props.total)}
</Alert>
onProvisionedChanged = (provisioned: boolean) => {
this.setState(
{ ready: false, page: 1, query: '', provisioned, qualifiers: 'TRK', selection: [] },
- this.requestProjects
+ this.requestProjects,
);
};
qualifiers: newQualifier,
selection: [],
},
- this.requestProjects
+ this.requestProjects,
);
};
visibility: newVisibility === 'all' ? undefined : newVisibility,
selection: [],
},
- this.requestProjects
+ this.requestProjects,
);
};
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
};
canBrowseProject: canBrowseProjectResponse.users.length > 0,
showPermissions: showPermissionsResponse.users.length > 0,
},
- })
+ }),
);
}),
}));
await user.click(ui.deleteProjects.get());
expect(ui.deleteDialog.get()).toBeInTheDocument();
expect(
- within(ui.deleteDialog.get()).getByText('projects_management.delete_selected_warning.2')
+ within(ui.deleteDialog.get()).getByText('projects_management.delete_selected_warning.2'),
).toBeInTheDocument();
await user.click(ui.delete.get(ui.deleteDialog.get()));
expect(ui.row.getAll()).toHaveLength(3);
it('should bulk apply permission templates to projects', async () => {
const user = userEvent.setup();
handler.setProjects(
- Array.from({ length: 11 }, (_, i) => mockProject({ key: i.toString(), name: `Test ${i}` }))
+ Array.from({ length: 11 }, (_, i) => mockProject({ key: i.toString(), name: `Test ${i}` })),
);
renderProjectManagementApp();
expect(await ui.bulkApplyDialog.find()).toBeInTheDocument();
expect(
within(ui.bulkApplyDialog.get()).getByText(
- 'permission_templates.bulk_apply_permission_template.apply_to_selected.11'
- )
+ 'permission_templates.bulk_apply_permission_template.apply_to_selected.11',
+ ),
).toBeInTheDocument();
await user.click(ui.apply.get(ui.bulkApplyDialog.get()));
expect(
- await screen.findByText('bulk apply permission template error message')
+ await screen.findByText('bulk apply permission template error message'),
).toBeInTheDocument();
expect(ui.bulkApplyDialog.get()).toBeInTheDocument();
expect(await ui.bulkApplyDialog.find()).toBeInTheDocument();
expect(
within(ui.bulkApplyDialog.get()).getByText(
- 'permission_templates.bulk_apply_permission_template.apply_to_selected.2'
- )
+ 'permission_templates.bulk_apply_permission_template.apply_to_selected.2',
+ ),
).toBeInTheDocument();
await selectEvent.select(
ui.selectTemplate.get(ui.bulkApplyDialog.get()),
- 'Permission Template 2'
+ 'Permission Template 2',
);
await user.click(ui.apply.get(ui.bulkApplyDialog.get()));
expect(
- await within(ui.bulkApplyDialog.get()).findByText('projects_role.apply_template.success')
+ await within(ui.bulkApplyDialog.get()).findByText('projects_role.apply_template.success'),
).toBeInTheDocument();
});
key: ComponentQualifier.Project + i.toString(),
name: `Project ${i}`,
qualifier: ComponentQualifier.Project,
- })
+ }),
),
...Array.from({ length: 60 }, (_, i) =>
mockProject({
key: ComponentQualifier.Portfolio + i.toString(),
name: `Portfolio ${i}`,
qualifier: ComponentQualifier.Portfolio,
- })
+ }),
),
...Array.from({ length: 60 }, (_, i) =>
mockProject({
key: ComponentQualifier.Application + i.toString(),
name: `Application ${i}`,
qualifier: ComponentQualifier.Application,
- })
+ }),
),
]);
renderProjectManagementApp();
expect(ui.applyTemplateDialog.get()).toBeInTheDocument();
await selectEvent.select(
ui.selectTemplate.get(ui.applyTemplateDialog.get()),
- 'Permission Template 2'
+ 'Permission Template 2',
);
await user.click(ui.apply.get(ui.applyTemplateDialog.get()));
expect(
- await within(ui.applyTemplateDialog.get()).findByText('projects_role.apply_template.success')
+ await within(ui.applyTemplateDialog.get()).findByText('projects_role.apply_template.success'),
).toBeInTheDocument();
});
renderProjectManagementApp(
{},
{ login: 'gooduser2', local: true },
- { featureList: [Feature.GithubProvisioning] }
+ { featureList: [Feature.GithubProvisioning] },
);
await waitFor(() => expect(ui.row.getAll()).toHaveLength(5));
const rows = ui.row.getAll();
renderProjectManagementApp(
{},
{ login: 'gooduser2', local: false },
- { featureList: [Feature.GithubProvisioning] }
+ { featureList: [Feature.GithubProvisioning] },
);
await waitFor(() => expect(ui.row.getAll()).toHaveLength(5));
const rows = ui.row.getAll();
function renderProjectManagementApp(
overrides: Partial<AppState> = {},
user: Partial<LoggedInUser> = {},
- context: Partial<RenderContext> = {}
+ context: Partial<RenderContext> = {},
) {
login = user?.login ?? 'gooduser1';
renderAppWithAdminContext('admin/projects_management', routes, {
it('should return the correct corresponding metric', () => {
expect(getLocalizedMetricNameNoDiffMetric(mockMetric(), {})).toBe('coverage');
expect(getLocalizedMetricNameNoDiffMetric(mockMetric({ key: 'new_bugs' }), METRICS)).toBe(
- 'Bugs'
+ 'Bugs',
);
expect(
getLocalizedMetricNameNoDiffMetric(
mockMetric({ key: 'new_custom_metric', name: 'Custom Metric on New Code' }),
- METRICS
- )
+ METRICS,
+ ),
).toBe('Custom Metric on New Code');
expect(
- getLocalizedMetricNameNoDiffMetric(mockMetric({ key: 'new_maintainability_rating' }), METRICS)
+ getLocalizedMetricNameNoDiffMetric(
+ mockMetric({ key: 'new_maintainability_rating' }),
+ METRICS,
+ ),
).toBe('Maintainability Rating');
});
});
expect(result.newCodeConditions.map(conditionsMap)).toEqual(expectedConditionsOrderNewCode);
expect(result.overallCodeConditions.map(conditionsMap)).toEqual(
- expectConditionsOrderOverallCode
+ expectConditionsOrderOverallCode,
);
});
});
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
};
defer={false}
titleTemplate={translateWithParameters(
'page_title.template.with_category',
- translate('quality_gates.page')
+ translate('quality_gates.page'),
)}
/>
<div className="layout-page" id="quality-gates-page">
removeCondition = (condition: ConditionType) => {
deleteCondition({ id: condition.id }).then(
() => this.props.onRemoveCondition(condition),
- () => {}
+ () => {},
);
};
<EditButton
aria-label={translateWithParameters(
'quality_gates.condition.edit',
- metric.name
+ metric.name,
)}
data-test="quality-gates__condition-update"
onClick={this.handleOpenUpdate}
<DeleteButton
aria-label={translateWithParameters(
'quality_gates.condition.delete',
- metric.name
+ metric.name,
)}
data-test="quality-gates__condition-delete"
onClick={this.handleDeleteClick}
>
{translateWithParameters(
'quality_gates.delete_condition.confirm.message',
- getLocalizedMetricName(this.props.metric)
+ getLocalizedMetricName(this.props.metric),
)}
</ConfirmModal>
)}
<MetricSelect
metric={metric}
metricsArray={metrics.filter((m) =>
- scope === 'new' ? isDiffMetric(m.key) : !isDiffMetric(m.key)
+ scope === 'new' ? isDiffMetric(m.key) : !isDiffMetric(m.key),
)}
onMetricChange={this.handleMetricChange}
/>
this.props.onSaveCondition(resultCondition, currentCondition);
}
})
- .catch(() => undefined)
+ .catch(() => undefined),
);
});
gateName: qualityGate.name,
})
.then((resultCondition) => this.props.onAddCondition(resultCondition))
- .catch(() => undefined)
+ .catch(() => undefined),
);
});
const { weakConditions, missingConditions } = getWeakMissingAndNonCaycConditions(conditions);
const sortedWeakConditions = sortBy(
weakConditions,
- (condition) => metrics[condition.metric] && metrics[condition.metric].name
+ (condition) => metrics[condition.metric] && metrics[condition.metric].name,
);
const sortedMissingConditions = sortBy(
missingConditions,
- (condition) => metrics[condition.metric] && metrics[condition.metric].name
+ (condition) => metrics[condition.metric] && metrics[condition.metric].name,
);
return (
<ConfirmModal
header={translateWithParameters(
'quality_gates.cayc.review_update_modal.header',
- qualityGate.name
+ qualityGate.name,
)}
confirmButtonText={translate('quality_gates.cayc.review_update_modal.confirm_text')}
onClose={this.props.onClose}
<h4 className="big-spacer-top spacer-bottom">
{translateWithParameters(
'quality_gates.cayc.review_update_modal.add_condition.header',
- sortedMissingConditions.length
+ sortedMissingConditions.length,
)}
</h4>
<ConditionsTable
<h4 className="big-spacer-top spacer-bottom">
{translateWithParameters(
'quality_gates.cayc.review_update_modal.modify_condition.header',
- sortedWeakConditions.length
+ sortedWeakConditions.length,
)}
</h4>
<ConditionsTable
}: Props) {
if (condition.metric === 'new_maintainability_rating') {
const maintainabilityGrid = getMaintainabilityGrid(
- settings[GlobalSettingKeys.RatingGrid] ?? ''
+ settings[GlobalSettingKeys.RatingGrid] ?? '',
);
const maintainabilityRatingThreshold =
maintainabilityGrid[Math.floor(Number(condition.error)) - GRID_INDEX_OFFSET];
{condition.error === '1'
? translateWithParameters(
'quality_gates.cayc.new_maintainability_rating.A',
- formatMeasure(maintainabilityGrid[0] * PERCENT_MULTIPLIER, 'PERCENT')
+ formatMeasure(maintainabilityGrid[0] * PERCENT_MULTIPLIER, 'PERCENT'),
)
: translateWithParameters(
'quality_gates.cayc.new_maintainability_rating',
ratingLetter,
- formatMeasure(maintainabilityRatingThreshold * PERCENT_MULTIPLIER, 'PERCENT')
+ formatMeasure(maintainabilityRatingThreshold * PERCENT_MULTIPLIER, 'PERCENT'),
)}
)
</span>
<>
(
{translate(
- `quality_gates.cayc.${condition.metric}.${formatMeasure(condition.error, metric.type)}`
+ `quality_gates.cayc.${condition.metric}.${formatMeasure(condition.error, metric.type)}`,
)}
)
</>
(metric) =>
!metric.hidden &&
!FORBIDDEN_METRIC_TYPES.includes(metric.type) &&
- !FORBIDDEN_METRICS.includes(metric.key)
+ !FORBIDDEN_METRICS.includes(metric.key),
),
conditions,
- (metric, condition) => metric.key === condition.metric
+ (metric, condition) => metric.key === condition.metric,
);
return (
<ConditionModal
const existingConditions = conditions.filter((condition) => metrics[condition.metric]);
const { overallCodeConditions, newCodeConditions } = groupAndSortByPriorityConditions(
existingConditions,
- metrics
+ metrics,
);
const duplicates: ConditionType[] = [];
const savedConditions = existingConditions.filter((condition) => condition.id != null);
savedConditions.forEach((condition) => {
const sameCount = savedConditions.filter(
- (sample) => sample.metric === condition.metric
+ (sample) => sample.metric === condition.metric,
).length;
if (sameCount > 1) {
duplicates.push(condition);
isDestructive
modalBody={translateWithParameters(
'quality_gates.delete.confirm.message',
- qualityGate.name
+ qualityGate.name,
)}
modalHeader={translate('quality_gates.delete')}
onConfirm={this.onDelete}
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
};
const { refreshItem, refreshList } = this.props;
return Promise.all([refreshItem(), refreshList()]).then(
() => {},
- () => {}
+ () => {},
);
};
this.props.onSetDefault();
setQualityGateAsDefault({ name: qualityGate.name }).then(
this.handleActionRefresh,
- this.handleActionRefresh
+ this.handleActionRefresh,
);
}
};
label: getLocalizedMetricNameNoDiffMetric(m, metrics),
domain: m.domain,
})),
- 'domain'
+ 'domain',
);
// Use "disabled" property to emulate optgroups.
}
export default function QualityGatePermissionsAddModalRenderer(
- props: QualityGatePermissionsAddModalRendererProps
+ props: QualityGatePermissionsAddModalRendererProps,
) {
const { selection, submitting } = props;
const defaultQualityGate = handler.getDefaultQualityGate();
expect(
- await screen.findByRole('link', { current: 'page', name: `${defaultQualityGate.name} default` })
+ await screen.findByRole('link', {
+ current: 'page',
+ name: `${defaultQualityGate.name} default`,
+ }),
).toBeInTheDocument();
});
expect(
await screen.findByRole('link', {
name: `${handler.getDefaultQualityGate().name} default`,
- })
+ }),
).toBeInTheDocument();
expect(
screen.getByRole('link', {
name: `${handler.getBuiltInQualityGate().name} quality_gates.built_in`,
- })
+ }),
).toBeInTheDocument();
});
await user.click(dialog.getByRole('button', { name: 'quality_gates.add_condition' }));
expect(
- await overallConditions.findByRole('cell', { name: 'Maintainability Rating' })
+ await overallConditions.findByRole('cell', { name: 'Maintainability Rating' }),
).toBeInTheDocument();
expect(await overallConditions.findByRole('cell', { name: 'B' })).toBeInTheDocument();
});
const newConditions = within(await screen.findByTestId('quality-gates__conditions-new'));
await user.click(
- newConditions.getByLabelText('quality_gates.condition.edit.Coverage on New Code')
+ newConditions.getByLabelText('quality_gates.condition.edit.Coverage on New Code'),
);
const dialog = within(screen.getByRole('dialog'));
await user.click(dialog.getByRole('textbox', { name: 'quality_gates.conditions.value' }));
await user.click(
// make it a regexp to ignore badges:
- await screen.findByRole('link', { name: new RegExp(handler.getCorruptedQualityGateName()) })
+ await screen.findByRole('link', { name: new RegExp(handler.getCorruptedQualityGateName()) }),
);
expect(await screen.findByText('quality_gates.duplicated_conditions')).toBeInTheDocument();
expect(
- await screen.findByRole('cell', { name: 'Complexity / Function deprecated' })
+ await screen.findByRole('cell', { name: 'Complexity / Function deprecated' }),
).toBeInTheDocument();
});
const newConditions = within(await screen.findByTestId('quality-gates__conditions-new'));
await user.click(
- newConditions.getByLabelText('quality_gates.condition.delete.Coverage on New Code')
+ newConditions.getByLabelText('quality_gates.condition.delete.Coverage on New Code'),
);
const dialog = within(screen.getByRole('dialog'));
renderQualityGateApp({ featureList: [Feature.BranchSupport] });
expect(
- await screen.findByText('quality_gates.conditions.new_code.description')
+ await screen.findByText('quality_gates.conditions.new_code.description'),
).toBeInTheDocument();
expect(
- await screen.findByText('quality_gates.conditions.overall_code.description')
+ await screen.findByText('quality_gates.conditions.overall_code.description'),
).toBeInTheDocument();
});
expect(screen.getByText('quality_gates.cayc_missing.banner.title')).toBeInTheDocument();
expect(screen.getByText('quality_gates.cayc_missing.banner.description')).toBeInTheDocument();
expect(
- screen.getByRole('button', { name: 'quality_gates.cayc_condition.review_update' })
+ screen.getByRole('button', { name: 'quality_gates.cayc_condition.review_update' }),
).toBeInTheDocument();
await user.click(
- screen.getByRole('button', { name: 'quality_gates.cayc_condition.review_update' })
+ screen.getByRole('button', { name: 'quality_gates.cayc_condition.review_update' }),
);
expect(
screen.getByRole('dialog', {
name: 'quality_gates.cayc.review_update_modal.header.SonarSource way - CFamily',
- })
+ }),
).toBeInTheDocument();
expect(
- screen.getByText('quality_gates.cayc.review_update_modal.description1')
+ screen.getByText('quality_gates.cayc.review_update_modal.description1'),
).toBeInTheDocument();
expect(
- screen.getByText('quality_gates.cayc.review_update_modal.description2')
+ screen.getByText('quality_gates.cayc.review_update_modal.description2'),
).toBeInTheDocument();
expect(
- screen.getByRole('button', { name: 'quality_gates.cayc.review_update_modal.confirm_text' })
+ screen.getByRole('button', { name: 'quality_gates.cayc.review_update_modal.confirm_text' }),
).toBeInTheDocument();
await user.click(
- screen.getByRole('button', { name: 'quality_gates.cayc.review_update_modal.confirm_text' })
+ screen.getByRole('button', { name: 'quality_gates.cayc.review_update_modal.confirm_text' }),
);
const conditionsWrapper = within(await screen.findByTestId('quality-gates__conditions-new'));
expect(conditionsWrapper.getByText('Duplicated Lines (%)')).toBeInTheDocument();
const overallConditionsWrapper = within(
- await screen.findByTestId('quality-gates__conditions-overall')
+ await screen.findByTestId('quality-gates__conditions-overall'),
);
expect(overallConditionsWrapper.getByText('Complexity / Function')).toBeInTheDocument();
});
await user.click(nonCompliantQualityGate);
expect(await screen.findByRole('alert')).toHaveTextContent(
- /quality_gates.cayc_missing.banner.title/
+ /quality_gates.cayc_missing.banner.title/,
);
expect(screen.getAllByText('quality_gates.cayc.tooltip.message').length).toBeGreaterThan(0);
});
expect(screen.getByText('quality_gates.cayc.banner.title')).toBeInTheDocument();
expect(
- screen.getByText('quality_gates.cayc.banner.description1', { exact: false })
+ screen.getByText('quality_gates.cayc.banner.description1', { exact: false }),
).toBeInTheDocument();
expect(
- screen.queryByText('quality_gates.cayc_condition.missing_warning.title')
+ screen.queryByText('quality_gates.cayc_condition.missing_warning.title'),
).not.toBeInTheDocument();
expect(
- screen.queryByRole('button', { name: 'quality_gates.cayc_condition.review_update' })
+ screen.queryByRole('button', { name: 'quality_gates.cayc_condition.review_update' }),
).not.toBeInTheDocument();
const conditionsWrapper = within(await screen.findByTestId('quality-gates__conditions-new'));
expect(
screen.queryByRole('button', {
name: 'quality_gates.condition.edit.Security Rating on New Code',
- })
+ }),
).not.toBeInTheDocument();
expect(
screen.queryByRole('button', {
name: 'quality_gates.condition.delete.Security Rating on New Code',
- })
+ }),
).not.toBeInTheDocument();
await user.click(screen.getByText('quality_gates.cayc.unlock_edit'));
expect(
- screen.getByRole('button', { name: 'quality_gates.condition.edit.Security Rating on New Code' })
+ screen.getByRole('button', {
+ name: 'quality_gates.condition.edit.Security Rating on New Code',
+ }),
).toBeInTheDocument();
expect(
screen.getByRole('button', {
name: 'quality_gates.condition.delete.Security Rating on New Code',
- })
+ }),
).toBeInTheDocument();
});
expect(
await screen.findByRole('link', {
name: `${handler.getDefaultQualityGate().name} default`,
- })
+ }),
).toBeInTheDocument();
expect(screen.queryByText('quality_gates.permissions')).not.toBeInTheDocument();
{
overallCodeConditions: [] as Condition[],
newCodeConditions: [] as Condition[],
- }
+ },
);
}
export function groupAndSortByPriorityConditions(
conditions: Condition[],
- metrics: Dict<Metric>
+ metrics: Dict<Metric>,
): GroupedByMetricConditions {
const groupedConditions = groupConditionsByMetric(conditions);
export function replaceCondition(
qualityGate: QualityGate,
newCondition: Condition,
- oldCondition: Condition
+ oldCondition: Condition,
): QualityGate {
const conditions =
qualityGate.conditions &&
await user.click(
ui.permissionSection
.byRole('button', { name: 'quality_profiles.permissions.remove.user_x.Buzz' })
- .get()
+ .get(),
);
expect(ui.dialog.get()).toBeInTheDocument();
await user.click(ui.removeButton.get());
await user.click(
ui.permissionSection
.byRole('button', { name: 'quality_profiles.permissions.remove.group_x.ACDC' })
- .get()
+ .get(),
);
expect(ui.dialog.get()).toBeInTheDocument();
await user.click(ui.removeButton.get());
renderQualityProfile('sonar');
expect(await ui.projectSection.find()).toBeInTheDocument();
expect(
- await ui.projectSection.byText('quality_profiles.projects_for_default').get()
+ await ui.projectSection.byText('quality_profiles.projects_for_default').get(),
).toBeInTheDocument();
});
});
expect(ui.activateMoreLink.get()).toBeInTheDocument();
expect(ui.activateMoreLink.get()).toHaveAttribute(
'href',
- '/coding_rules?qprofile=old-php-qp&activation=false'
+ '/coding_rules?qprofile=old-php-qp&activation=false',
);
});
expect(ui.activateMoreRulesLink.get()).toBeInTheDocument();
expect(ui.activateMoreRulesLink.get()).toHaveAttribute(
'href',
- '/coding_rules?qprofile=old-php-qp&activation=false'
+ '/coding_rules?qprofile=old-php-qp&activation=false',
);
});
expect(
ui.dialog
.byText(/quality_profiles.are_you_sure_want_delete_profile_x_and_descendants/)
- .get()
+ .get(),
).toBeInTheDocument();
await act(async () => {
await user.click(ui.dialog.byRole('button', { name: 'delete' }).get());
expect(ui.rulesMissingSonarWayLink.get()).toBeInTheDocument();
expect(ui.rulesMissingSonarWayLink.get()).toHaveAttribute(
'href',
- '/coding_rules?qprofile=old-php-qp&activation=false&languages=php'
+ '/coding_rules?qprofile=old-php-qp&activation=false&languages=php',
);
});
expect(ui.rulesDeprecatedLink.get()).toBeInTheDocument();
expect(ui.rulesDeprecatedLink.get()).toHaveAttribute(
'href',
- '/coding_rules?qprofile=old-php-qp&activation=true&statuses=DEPRECATED'
+ '/coding_rules?qprofile=old-php-qp&activation=true&statuses=DEPRECATED',
);
});
await user.click(await ui.qualityProfileActions.find());
expect(ui.backUpLink.get()).toHaveAttribute(
'href',
- '/api/qualityprofiles/backup?language=php&qualityProfile=Good%20old%20PHP%20quality%20profile'
+ '/api/qualityprofiles/backup?language=php&qualityProfile=Good%20old%20PHP%20quality%20profile',
);
expect(ui.backUpLink.get()).toHaveAttribute('download', 'old-php-qp.xml');
});
expect(ui.compareLink.get()).toBeInTheDocument();
expect(ui.compareLink.get()).toHaveAttribute(
'href',
- '/profiles/compare?language=php&name=Good+old+PHP+quality+profile'
+ '/profiles/compare?language=php&name=Good+old+PHP+quality+profile',
);
});
});
expect(await ui.deprecatedRulesRegion.find()).toBeInTheDocument();
expect(
- ui.deprecatedRulesRegion.byRole('link', { name: 'Good old PHP quality profile' }).get()
+ ui.deprecatedRulesRegion.byRole('link', { name: 'Good old PHP quality profile' }).get(),
).toBeInTheDocument();
expect(
- ui.deprecatedRulesRegion.byRole('link', { name: 'java quality profile #2' }).get()
+ ui.deprecatedRulesRegion.byRole('link', { name: 'java quality profile #2' }).get(),
).toBeInTheDocument();
});
expect(await ui.stagnantProfilesRegion.find()).toBeInTheDocument();
expect(
- ui.stagnantProfilesRegion.byRole('link', { name: 'Good old PHP quality profile' }).get()
+ ui.stagnantProfilesRegion.byRole('link', { name: 'Good old PHP quality profile' }).get(),
).toBeInTheDocument();
});
props.events,
// sort events by date, rounded to a minute, recent events first
(e) => -Number(parseDate(e.date)),
- (e) => e.action
+ (e) => e.action,
);
const rows = sortedRows.map((event, index) => {
{value == null
? translateWithParameters(
'quality_profiles.changelog.parameter_reset_to_default_value',
- name
+ name,
)
: translateWithParameters('quality_profiles.parameter_set_to', name, value)}
</div>
expect(rows[1]).not.toHaveTextContent('quality_profiles.severity');
expect(rows[2]).toHaveTextContent('April 23, 2019');
expect(rows[2]).toHaveTextContent(
- 'Systemquality_profiles.changelog.DEACTIVATEDRule 0quality_profiles.severity_set_to severity.MAJOR'
+ 'Systemquality_profiles.changelog.DEACTIVATEDRule 0quality_profiles.severity_set_to severity.MAJOR',
);
expect(rows[3]).not.toHaveTextContent('April 23, 2019');
expect(rows[3]).not.toHaveTextContent('Systemquality_profiles.changelog.DEACTIVATED');
expect(rows[5]).toHaveTextContent('March 23, 2019');
expect(rows[5]).toHaveTextContent('John Doequality_profiles.changelog.ACTIVATEDRule 2');
expect(rows[5]).toHaveTextContent(
- 'quality_profiles.severity_set_to severity.CRITICALquality_profiles.parameter_set_to.credentialWords.foo,bar'
+ 'quality_profiles.severity_set_to severity.CRITICALquality_profiles.parameter_set_to.credentialWords.foo,bar',
);
await user.click(ui.link.get(rows[1]));
expect(screen.getByText('/coding_rules?rule_key=c%3Arule0')).toBeInTheDocument();
mockQualityProfileChangelogEvent({
ruleKey: `c:rule${i}`,
ruleName: `Rule ${i}`,
- })
+ }),
);
renderChangeLog();
expect(rows).toHaveLength(2);
expect(rows[1]).toHaveTextContent('May 23, 2019');
expect(rows[1]).toHaveTextContent(
- 'Systemquality_profiles.changelog.DEACTIVATEDPHP Rulequality_profiles.severity_set_to severity.MAJOR'
+ 'Systemquality_profiles.changelog.DEACTIVATEDPHP Rulequality_profiles.severity_set_to severity.MAJOR',
);
expect(ui.showMore.query()).not.toBeInTheDocument();
});
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
};
const path = getProfileComparePath(
this.props.profile.name,
this.props.profile.language,
- withKey
+ withKey,
);
this.props.router.push(path);
};
optionRenderer(
options: Option[],
- props: OptionProps<Omit<Option, 'label' | 'isDefault'>, false>
+ props: OptionProps<Omit<Option, 'label' | 'isDefault'>, false>,
) {
const { data } = props;
return <components.Option {...props}>{renderValue(data, options)}</components.Option>;
singleValueRenderer = (
options: Option[],
- props: SingleValueProps<Omit<Option, 'label' | 'isDefault'>, false>
+ props: SingleValueProps<Omit<Option, 'label' | 'isDefault'>, false>,
) => (
<components.SingleValue {...props}>{renderValue(props.data, options)}</components.SingleValue>
);
if (this.mounted) {
this.setState({ state: 'closed' });
}
- }
+ },
);
};
placement="bottom"
overlay={translateWithParameters(
'quality_profiles.comparison.activate_rule',
- profile.name
+ profile.name,
)}
>
<Button
disabled={this.state.state !== 'closed'}
aria-label={translateWithParameters(
'quality_profiles.comparison.activate_rule',
- profile.name
+ profile.name,
)}
onClick={this.handleButtonClick}
>
<th>
{translateWithParameters(
'quality_profiles.x_rules_only_in',
- this.props.inLeft.length
+ this.props.inLeft.length,
)}{' '}
{this.props.left.name}
</th>
<th>
{translateWithParameters(
'quality_profiles.x_rules_only_in',
- this.props.inRight.length
+ this.props.inRight.length,
)}{' '}
{this.props.right.name}
</th>
<caption>
{translateWithParameters(
'quality_profiles.x_rules_have_different_configuration',
- this.props.modified.length
+ this.props.modified.length,
)}
</caption>
<thead>
{translateWithParameters(
'quality_profiles.are_you_sure_want_delete_profile_x_and_descendants',
profile.name,
- profile.languageName
+ profile.languageName,
)}
</p>
</div>
{translateWithParameters(
'quality_profiles.are_you_sure_want_delete_profile_x',
profile.name,
- profile.languageName
+ profile.languageName,
)}
</p>
)}
},
() => {
/* noop */
- }
+ },
);
}
};
label={translateWithParameters(
'quality_profiles.actions',
profile.name,
- profile.languageName
+ profile.languageName,
)}
disabled={!hasAnyAction}
>
tooltipPlacement="left"
tooltipOverlay={translateWithParameters(
'quality_profiles.extend_help',
- profile.name
+ profile.name,
)}
className="it__quality-profiles__extend"
onClick={this.handleExtendClick}
title={profile.name}
titleTemplate={translateWithParameters(
'page_title.template.with_category',
- translate('quality_profiles.page')
+ translate('quality_profiles.page'),
)}
/>
<ProfileHeader
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
}
</Route>
</Routes>
</MemoryRouter>
- </HelmetProvider>
+ </HelmetProvider>,
);
}
isChangeLogPage
? 'quality_profiles.page_title_changelog_x'
: 'quality_profiles.page_title_compare_x',
- profile.name
+ profile.name,
)}
/>
)}
className="little-spacer-left"
overlay={translateWithParameters(
'quality_profiles.extend_description_help',
- profile.parentName
+ profile.parentName,
)}
/>
</>
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
}
() => {
this.loadData();
},
- () => {}
+ () => {},
);
this.closeForm();
};
<p>
{translateWithParameters(
'quality_profiles.x_overridden_rules',
- profile.overridingRuleCount
+ profile.overridingRuleCount,
)}
</p>
)}
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
}
<DeleteButton
aria-label={translateWithParameters(
'quality_profiles.permissions.remove.group_x',
- group.name
+ group.name,
)}
className="pull-right spacer-top spacer-left spacer-right button-small"
onClick={this.handleDeleteClick}
<DeleteButton
aria-label={translateWithParameters(
'quality_profiles.permissions.remove.user_x',
- user.name
+ user.name,
)}
className="pull-right spacer-top spacer-left spacer-right button-small"
onClick={this.handleDeleteClick}
activatedTotal: null,
activatedByType: keyBy(
TYPES.map((t) => ({ val: t, count: null })),
- 'val'
+ 'val',
),
allByType: keyBy(
TYPES.map((t) => ({ val: t, count: null })),
- 'val'
+ 'val',
),
compareToSonarWay: null,
total: null,
total: allRules.paging.total,
});
}
- }
+ },
);
}
if (this.mounted) {
this.setState({ preloading: false });
}
- }
+ },
);
}
label={translate(
action === ProfileActionModals.Copy
? 'quality_profiles.creation.choose_copy_quality_profile'
- : 'quality_profiles.creation.choose_parent_quality_profile'
+ : 'quality_profiles.creation.choose_parent_quality_profile',
)}
required
isInvalid={isValidProflie !== undefined && !isValidProflie}
if (parentProfile) {
const parentRules = this.getDeprecatedRulesInheritanceChain(
parentProfile,
- profilesWithDeprecations
+ profilesWithDeprecations,
);
if (parentRules.length) {
count -= parentRules.reduce((n, rule) => n + rule.count, 0);
{translateWithParameters(
'coding_rules.filters.inheritance.x_inherited_from_y',
rule.count,
- rule.from.name
+ rule.from.name,
)}
</div>
);
render() {
const profilesWithDeprecations = this.props.profiles.filter(
- (profile) => profile.activeDeprecatedRuleCount > 0
+ (profile) => profile.activeDeprecatedRuleCount > 0,
);
if (profilesWithDeprecations.length === 0) {
<div className="spacer-bottom">
{translateWithParameters(
'quality_profiles.deprecated_rules_are_still_activated',
- profilesWithDeprecations.length
+ profilesWithDeprecations.length,
)}
</div>
<ul>
aria-label={translateWithParameters(
'quality_profile.lang_deprecated_x_rules',
profile.languageName,
- profile.activeDeprecatedRuleCount
+ profile.activeDeprecatedRuleCount,
)}
>
{translateWithParameters(
'quality_profile.x_rules',
- profile.activeDeprecatedRuleCount
+ profile.activeDeprecatedRuleCount,
)}
</Link>
{this.renderInheritedInfo(profile, profilesWithDeprecations)}
},
() => {
/*noop*/
- }
+ },
);
}
const seeAllRulesText = `${translate('see_all')} ${formatMeasure(
latestRulesTotal,
'SHORT_INT',
- null
+ null,
)}`;
return (
? translateWithParameters(
'quality_profiles.latest_new_rules.activated',
rule.langName!,
- rule.activations
+ rule.activations,
)
: translateWithParameters(
'quality_profiles.latest_new_rules.not_activated',
- rule.langName!
+ rule.langName!,
)}
</div>
</div>
{translateWithParameters(
'quality_profiles.x_updated_on_y',
profile.languageName,
- formattedDate
+ formattedDate,
)}
</div>
)}
() => {
this.props.router.push(getProfilePath(profile.name, profile.language));
},
- () => {}
+ () => {},
);
};
const profilesIndex: Dict<Profile[]> = groupBy<Profile>(
profiles,
- (profile) => profile.language
+ (profile) => profile.language,
);
const profilesToShow = language ? pick(profilesIndex, language) : profilesIndex;
)}
{languagesToShow.map((languageKey) =>
- this.renderLanguage(languageKey, profilesToShow[languageKey])
+ this.renderLanguage(languageKey, profilesToShow[languageKey]),
)}
</div>
);
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
};
'quality_profiles.restore_profile.warning',
profile.name,
ruleSuccesses,
- ruleFailures
+ ruleFailures,
)}
</Alert>
) : (
{translateWithParameters(
'quality_profiles.restore_profile.success',
profile.name,
- ruleSuccesses
+ ruleSuccesses,
)}
</Alert>
);
}
export function withQualityProfilesContext<P extends Partial<QualityProfilesContextProps>>(
- WrappedComponent: React.ComponentType<P>
+ WrappedComponent: React.ComponentType<P>,
): React.ComponentType<Omit<P, keyof QualityProfilesContextProps>> {
function ComponentWithQualityProfilesProps(props: P) {
const context = useOutletContext<QualityProfilesContextProps>();
(ComponentWithQualityProfilesProps as React.FC<P>).displayName = getWrappedDisplayName(
WrappedComponent,
- 'withQualityProfilesContext'
+ 'withQualityProfilesContext',
);
return ComponentWithQualityProfilesProps;
function retrieveChildren(parent: BaseProfile | null) {
return sorted.filter(
(p) =>
- (parent == null && p.parentKey == null) || (parent != null && p.parentKey === parent.key)
+ (parent == null && p.parentKey == null) || (parent != null && p.parentKey === parent.key),
);
}
sorted
.filter(
(profile) =>
- profile.parentKey == null || sorted.find((p) => p.key === profile.parentKey) == null
+ profile.parentKey == null || sorted.find((p) => p.key === profile.parentKey) == null,
)
.forEach((profile) => putProfile(profile));
export const getProfileChangelogPath = (
name: string,
language: string,
- filter?: { since?: string; to?: string }
+ filter?: { since?: string; to?: string },
) => {
const query = { language, name };
if (filter) {
}
constructFiltersFromProps(
- props: Props
+ props: Props,
): Pick<HotspotFilters, 'assignedToMe' | 'inNewCodePeriod'> {
return {
assignedToMe: props.location.query.assignedToMe === 'true' && isLoggedIn(props.currentUser),
status: HotspotStatus.TO_REVIEW, // we're only interested in unresolved hotspots
...getBranchLikeQuery(branchLike),
},
- component.needIssueSync
+ component.needIssueSync,
);
}
: undefined;
const standard = SECURITY_STANDARDS.find(
- (stnd) => stnd !== SecurityStandard.CWE && location.query[stnd] !== undefined
+ (stnd) => stnd !== SecurityStandard.CWE && location.query[stnd] !== undefined,
);
const filterByCategory = standard
projectKey: component.key,
...getBranchLikeQuery(branchLike),
},
- component.needIssueSync
+ component.needIssueSync,
);
}
status,
...getBranchLikeQuery(branchLike),
},
- component.needIssueSync
+ component.needIssueSync,
);
}
if (changes.inNewCodePeriod !== undefined) {
this.fetchSecurityHotspotsReviewed();
}
- }
+ },
);
};
return Promise.all(
range(hotspotsPageIndex).map((p) =>
- this.fetchSecurityHotspots(p + 1 /* pages are 1-indexed */)
- )
+ this.fetchSecurityHotspots(p + 1 /* pages are 1-indexed */),
+ ),
)
.then((hotspotPages) => {
const allHotspots = flatMap(hotspotPages, 'hotspots');
hotspotsReviewedMeasure={hotspotsReviewedMeasure}
hotspotsTotal={hotspotsTotal}
isStaticListOfHotspots={Boolean(
- (hotspotKeys && hotspotKeys.length > 0) || filterByCategory || filterByCWE || filterByFile
+ (hotspotKeys && hotspotKeys.length > 0) ||
+ filterByCategory ||
+ filterByCWE ||
+ filterByFile,
)}
loading={loading}
loadingMeasure={loadingMeasure}
Component: SecurityHotspotsApp,
showIndexationMessage: ({ component }) =>
!!(component.qualifier === ComponentQualifier.Application && component.needIssueSync),
- })
- )
- )
- )
+ }),
+ ),
+ ),
+ ),
);
describe('rendering', () => {
it('should render code variants correctly', async () => {
renderSecurityHotspotsApp(
- 'security_hotspots?id=guillaume-peoch-sonarsource_benflix_AYGpXq2bd8qy4i0eO9ed&hotspots=test-2'
+ 'security_hotspots?id=guillaume-peoch-sonarsource_benflix_AYGpXq2bd8qy4i0eO9ed&hotspots=test-2',
);
expect(await screen.findAllByText('variant 1, variant 2')).toHaveLength(2);
const user = userEvent.setup();
renderSecurityHotspotsApp(
- `security_hotspots?id=guillaume-peoch-sonarsource_benflix_AYGpXq2bd8qy4i0eO9ed&files=src%2Findex.js&cwe=foo&inNewCodePeriod=true`
+ `security_hotspots?id=guillaume-peoch-sonarsource_benflix_AYGpXq2bd8qy4i0eO9ed&files=src%2Findex.js&cwe=foo&inNewCodePeriod=true`,
);
await waitFor(() => {
it('should navigate when coming from SonarLint', async () => {
// On main branch
const rtl = renderSecurityHotspotsApp(
- 'security_hotspots?id=guillaume-peoch-sonarsource_benflix_AYGpXq2bd8qy4i0eO9ed&hotspots=test-1'
+ 'security_hotspots?id=guillaume-peoch-sonarsource_benflix_AYGpXq2bd8qy4i0eO9ed&hotspots=test-1',
);
expect(await ui.hotspotTitle(/'3' is a magic number./).find()).toBeInTheDocument();
// On specific branch
rtl.unmount();
renderSecurityHotspotsApp(
- 'security_hotspots?id=guillaume-peoch-sonarsource_benflix_AYGpXq2bd8qy4i0eO9ed&hotspots=b1-test-1&branch=normal-branch'
+ 'security_hotspots?id=guillaume-peoch-sonarsource_benflix_AYGpXq2bd8qy4i0eO9ed&hotspots=b1-test-1&branch=normal-branch',
);
expect(await ui.hotspotTitle(/'F' is a magic number./).find()).toBeInTheDocument();
});
resolution: undefined,
status: 'TO_REVIEW',
},
- undefined
+ undefined,
);
await user.click(ui.filterDropdown.get());
resolution: undefined,
status: 'TO_REVIEW',
},
- undefined
+ undefined,
);
await user.click(ui.filterDropdown.get());
renderSecurityHotspotsApp(
'security_hotspots?id=guillaume-peoch-sonarsource_benflix_AYGpXq2bd8qy4i0eO9ed',
- { component: { ...mockComponentInstance, needIssueSync: true } }
+ { component: { ...mockComponentInstance, needIssueSync: true } },
);
await user.click(ui.filterDropdown.get());
function renderSecurityHotspotsApp(
navigateTo?: string,
- component?: Partial<ComponentContextShape>
+ component?: Partial<ComponentContextShape>,
) {
return renderAppWithComponentContext(
MetricKey.security_hotspots,
onComponentChange: jest.fn(),
component: mockComponentInstance,
...component,
- }
+ },
);
}
type: ReviewHistoryType.Creation,
date: hotspot.creationDate,
user: hotspot.authorUser,
- })
+ }),
);
expect(reviewHistory[2]).toEqual(
expect.objectContaining({
date: commentElement.createdAt,
user: commentElement.user,
html: commentElement.htmlText,
- })
+ }),
);
expect(reviewHistory[1]).toEqual(
expect.objectContaining({
date: commentElement1.createdAt,
user: commentElement1.user,
html: commentElement1.htmlText,
- })
+ }),
);
expect(reviewHistory[0]).toEqual(
expect.objectContaining({
active: changelogElement.isUserActive,
},
diffs: changelogElement.diffs,
- })
+ }),
);
});
});
describe('getStatusOptionFromStatusAndResolution', () => {
it('should return the correct values', () => {
expect(
- getStatusOptionFromStatusAndResolution(HotspotStatus.REVIEWED, HotspotResolution.FIXED)
+ getStatusOptionFromStatusAndResolution(HotspotStatus.REVIEWED, HotspotResolution.FIXED),
).toBe(HotspotStatusOption.FIXED);
expect(
- getStatusOptionFromStatusAndResolution(HotspotStatus.REVIEWED, HotspotResolution.SAFE)
+ getStatusOptionFromStatusAndResolution(HotspotStatus.REVIEWED, HotspotResolution.SAFE),
).toBe(HotspotStatusOption.SAFE);
expect(getStatusOptionFromStatusAndResolution(HotspotStatus.REVIEWED)).toBe(
- HotspotStatusOption.FIXED
+ HotspotStatusOption.FIXED,
);
expect(getStatusOptionFromStatusAndResolution(HotspotStatus.TO_REVIEW)).toBe(
- HotspotStatusOption.TO_REVIEW
+ HotspotStatusOption.TO_REVIEW,
);
});
});
describe('getStatusFilterFromStatusOption', () => {
it('should return the correct values', () => {
expect(getStatusFilterFromStatusOption(HotspotStatusOption.TO_REVIEW)).toEqual(
- HotspotStatusFilter.TO_REVIEW
+ HotspotStatusFilter.TO_REVIEW,
);
expect(getStatusFilterFromStatusOption(HotspotStatusOption.SAFE)).toEqual(
- HotspotStatusFilter.SAFE
+ HotspotStatusFilter.SAFE,
);
expect(getStatusFilterFromStatusOption(HotspotStatusOption.FIXED)).toEqual(
- HotspotStatusFilter.FIXED
+ HotspotStatusFilter.FIXED,
);
});
});
const handleSearchAssignees = (
query: string,
- cb: (options: Options<LabelValueSelectOption<string>>) => void
+ cb: (options: Options<LabelValueSelectOption<string>>) => void,
) => {
getUsers<RestUser>({ q: query })
.then((result) => {
addGlobalSuccessMessage(
userOption.value
? translateWithParameters('hotspots.assign.success', userOption.label)
- : translate('hotspots.assign.unassign.success')
+ : translate('hotspots.assign.unassign.success'),
);
})
.catch(noop);
return (
<Modal
headerTitle={translate(
- props.value !== undefined ? 'issue.comment.edit' : 'hotspots.status.add_comment'
+ props.value !== undefined ? 'issue.comment.edit' : 'hotspots.status.add_comment',
)}
onClose={props.onCancel}
body={
...getBranchLikeQuery(branchLike),
hotspots: key,
}),
- false
+ false,
);
const categoryStandard = standards?.[SecurityStandard.SONARSOURCE][rule.securityCategory]?.title;
) {
const groupedHotspots = this.groupHotspots(
this.props.hotspots,
- this.props.securityCategories
+ this.props.securityCategories,
);
this.setState({ groupedHotspots });
}
});
}
},
- [selected]
+ [selected],
);
const handleClick = () => {
1,
Math.min(
...[textRange, ...secondaryLocations.map((l) => l.textRange)].map(
- (t) => t.startLine - BUFFER_LINES
- )
- )
+ (t) => t.startLine - BUFFER_LINES,
+ ),
+ ),
);
// Search for the max endLine within primary and secondary locations
const to = Math.max(
...[textRange, ...secondaryLocations.map((l) => l.textRange)].map(
// Add 1 to check for end-of-file
- (t) => t.endLine + BUFFER_LINES + 1
- )
+ (t) => t.endLine + BUFFER_LINES + 1,
+ ),
);
this.setState({ loading: true });
text: location.msg,
})),
},
- () => resolve(undefined)
+ () => resolve(undefined),
);
});
}
} else {
// remove extra sourceline if we didn't reach the end:
concatSourceLines = sourceLines.concat(
- lastLine ? additionalLines : additionalLines.slice(0, -1)
+ lastLine ? additionalLines : additionalLines.slice(0, -1),
);
}
export async function animateExpansion(
scrollableRef: React.RefObject<HTMLDivElement>,
expandBlock: (direction: ExpandDirection) => Promise<void>,
- direction: ExpandDirection
+ direction: ExpandDirection,
) {
const wrapper = scrollableRef.current?.querySelector<HTMLElement>('.it__source-viewer-code');
const table = wrapper?.firstChild as HTMLElement;
}
export default function HotspotSnippetContainerRenderer(
- props: HotspotSnippetContainerRendererProps
+ props: HotspotSnippetContainerRendererProps,
) {
const {
highlightedSymbols,
secondaryLocationSelected={secondaryLocationSelected}
/>
),
- [hotspot, secondaryLocationSelected]
+ [hotspot, secondaryLocationSelected],
);
const renderHotspotBoxInLine = (line: SourceLine) =>
const { isScrolled, isCompressed, resetScrollDownCompress } = useScrollDownCompress(
STICKY_HEADER_COMPRESS_THRESHOLD,
- STICKY_HEADER_SHADOW_OFFSET
+ STICKY_HEADER_SHADOW_OFFSET,
);
const tabs = React.useMemo(() => {
const { hotspot } = props;
const initialStatus = React.useMemo(
() => getStatusOptionFromStatusAndResolution(hotspot.status, hotspot.resolution),
- [hotspot]
+ [hotspot],
);
const [loading, setLoading] = React.useState(false);
export default function useScrollDownCompress(compressThreshold: number, scrollThreshold: number) {
const [isCompressed, setIsCompressed] = useState(false);
const [isScrolled, setIsScrolled] = useState(
- () => document?.documentElement?.scrollTop > scrollThreshold
+ () => document?.documentElement?.scrollTop > scrollThreshold,
);
const initialScrollHeightRef = useRef<number | undefined>(undefined);
} else if (relativeScrollTop !== scrollTopRef.current) {
// Compress when scrolling in down direction and we are scrolled more than a threshold
setIsCompressed(
- relativeScrollTop > scrollTopRef.current && relativeScrollTop > scrollThreshold
+ relativeScrollTop > scrollTopRef.current && relativeScrollTop > scrollThreshold,
);
}
export function groupByCategory(
hotspots: RawHotspot[] = [],
- securityCategories: StandardSecurityCategories
+ securityCategories: StandardSecurityCategories,
) {
const groups = groupBy(hotspots, (h) => h.securityCategory);
return [
...sortBy(
groupList.filter((group) => group.key !== OTHERS_SECURITY_CATEGORY),
- (group) => group.title
+ (group) => group.title,
),
...groupList.filter(({ key }) => key === OTHERS_SECURITY_CATEGORY),
];
export function constructSourceViewerFile(
{ component, project }: Hotspot,
- lines?: number
+ lines?: number,
): SourceViewerFile {
return {
key: component.key,
name: log.userName || log.user,
},
diffs: log.diffs,
- }))
+ })),
);
}
html: comment.htmlText,
key: comment.key,
markdown: comment.markdown,
- }))
+ })),
);
}
export function getStatusOptionFromStatusAndResolution(
status: HotspotStatus,
- resolution?: HotspotResolution
+ resolution?: HotspotResolution,
) {
// Resolution is the most determinist info here, so we use it first to get the matching status option
// If not provided, we use the status (which will be TO_REVIEW)
.map((flow) =>
flow.map((location) => {
return { ...location };
- })
+ }),
);
const onlySecondaryLocations = parsedFlows.every((flow) => flow.length === 1);
return sortBy(
locations,
(location) => location.textRange && location.textRange.startLine,
- (location) => location.textRange && location.textRange.startOffset
+ (location) => location.textRange && location.textRange.startOffset,
);
}
},
() => {
/* already handled */
- }
+ },
);
}
// No OAuth providers, login form display by default.
expect(
- screen.queryByRole('link', { name: 'login.login_with_x', exact: false })
+ screen.queryByRole('link', { name: 'login.login_with_x', exact: false }),
).not.toBeInTheDocument();
expect(screen.getByLabelText('login')).toBeInTheDocument();
});
function renderLoginContainer(props: Partial<LoginContainer['props']> = {}) {
return renderComponent(
- <LoginContainer location={mockLocation({ query: { return_to: '/some/path' } })} {...props} />
+ <LoginContainer location={mockLocation({ query: { return_to: '/some/path' } })} {...props} />,
);
}
key: 'test',
};
expect(getDefaultValue(setting)).toEqual(expected);
- }
+ },
);
});
? // Project settings
c.availableForProject
: // Global settings
- c.availableGlobally
+ c.availableGlobally,
)
- .filter((c) => props.hasFeature(Feature.BranchSupport) || !c.requiresBranchSupport)
+ .filter((c) => props.hasFeature(Feature.BranchSupport) || !c.requiresBranchSupport),
);
const sortedCategories = sortBy(categoriesWithName, (category) => category.name.toLowerCase());
const { category, component, definitions } = this.props;
const categoryDefinitions = definitions.filter(
- (definition) => definition.category.toLowerCase() === category.toLowerCase()
+ (definition) => definition.category.toLowerCase() === category.toLowerCase(),
);
const keys = categoryDefinitions.map((definition) => definition.key);
this.setState({
validationMessage: translateWithParameters(
'settings.state.url_not_valid',
- changedValue ?? ''
+ changedValue ?? '',
),
});
return false;
className="spacer-right"
aria-label={translateWithParameters(
'settings.definition.reset',
- getPropertyName(setting.definition)
+ getPropertyName(setting.definition),
)}
onClick={this.handleReset}
>
const { component } = this.props;
const definitions: ExtendedSettingDefinition[] = await getDefinitions(component?.key).catch(
- () => []
+ () => [],
);
if (this.mounted) {
const categories = React.useMemo(() => {
return uniqBy(
definitions.map((definition) => definition.category),
- (category) => category.toLowerCase()
+ (category) => category.toLowerCase(),
);
}, [definitions]);
this.handleFocus = debounce(this.handleFocus, DEBOUNCE_DELAY);
const definitions = props.definitions.concat(
- props.component ? ADDITIONAL_PROJECT_SETTING_DEFINITIONS : ADDITIONAL_SETTING_DEFINITIONS
+ props.component ? ADDITIONAL_PROJECT_SETTING_DEFINITIONS : ADDITIONAL_SETTING_DEFINITIONS,
);
this.index = this.buildSearchIndex(definitions);
this.definitionsByKey = keyBy(definitions, 'key');
cleanQuery
.split(/\s+/)
.map((s) => `${s} *${s}*`)
- .join(' ')
+ .join(' '),
)
.map((match) => this.definitionsByKey[match.ref]);
description: getSubCategoryDescription(bySubCategory[key][0].definition.category, key),
}));
const sortedSubCategories = sortBy(subCategories, (subCategory) =>
- subCategory.name.toLowerCase()
+ subCategory.name.toLowerCase(),
);
const filteredSubCategories = subCategory
? sortedSubCategories.filter((c) => c.key === subCategory)
defaultCategory="general"
selectedCategory=""
{...props}
- />
+ />,
);
}
renderDefinition({ type: settingType });
expect(
- await ui.nameHeading('property.sonar.announcement.message.name').find()
+ await ui.nameHeading('property.sonar.announcement.message.name').find(),
).toBeInTheDocument();
// Should see no empty validation message
// Clicking reset opens dialog and reset to default on confirm
await user.click(
- ui.resetButton('settings.definition.reset.property.sonar.announcement.message.name').get()
+ ui.resetButton('settings.definition.reset.property.sonar.announcement.message.name').get(),
);
await user.click(ui.resetButton().get());
expect(ui.announcementInput.get()).toHaveValue('');
- }
+ },
);
it('renders definition for SettingType = JSON and can do operations', async () => {
renderDefinition({ type: SettingType.JSON });
expect(
- await ui.nameHeading('property.sonar.announcement.message.name').find()
+ await ui.nameHeading('property.sonar.announcement.message.name').find(),
).toBeInTheDocument();
// Should show error message if JSON format is not valid
});
expect(
- await ui.nameHeading('property.sonar.announcement.message.name').find()
+ await ui.nameHeading('property.sonar.announcement.message.name').find(),
).toBeInTheDocument();
// Can toggle
// Can reset toggle
await user.click(
- ui.resetButton('settings.definition.reset.property.sonar.announcement.message.name').get()
+ ui.resetButton('settings.definition.reset.property.sonar.announcement.message.name').get(),
);
await user.click(ui.resetButton().get());
expect(ui.toggleButton.get()).not.toBeChecked();
});
expect(
- await ui.nameHeading('property.sonar.announcement.message.name').find()
+ await ui.nameHeading('property.sonar.announcement.message.name').find(),
).toBeInTheDocument();
// Can select option
// Can reset
await user.click(
- ui.resetButton('settings.definition.reset.property.sonar.announcement.message.name').get()
+ ui.resetButton('settings.definition.reset.property.sonar.announcement.message.name').get(),
);
await user.click(ui.resetButton().get());
expect(ui.selectOption('Select...').get()).toBeInTheDocument();
});
expect(
- await ui.nameHeading('property.sonar.announcement.message.name').find()
+ await ui.nameHeading('property.sonar.announcement.message.name').find(),
).toBeInTheDocument();
// Should see no empty validation message
key: DEFAULT_DEFINITIONS_MOCK[2].key,
values: DEFAULT_DEFINITIONS_MOCK[2].defaultValue?.split(','),
},
- mockComponent()
+ mockComponent(),
);
expect(await ui.nameHeading('property.sonar.javascript.globals.name').find()).toBeInTheDocument();
// Can reset to default
await user.click(
- ui.resetButton('settings.definition.reset.property.sonar.javascript.globals.name').get()
+ ui.resetButton('settings.definition.reset.property.sonar.javascript.globals.name').get(),
);
await user.click(ui.resetButton().get());
expect(ui.multiValuesInput.getAll()).toHaveLength(4);
renderDefinition(DEFAULT_DEFINITIONS_MOCK[5]);
expect(
- await ui.nameHeading('property.sonar.cobol.compilationConstants.name').find()
+ await ui.nameHeading('property.sonar.cobol.compilationConstants.name').find(),
).toBeInTheDocument();
expect(screen.getByRole('columnheader', { name: 'Name' })).toBeInTheDocument();
expect(screen.getByRole('columnheader', { name: 'Value' })).toBeInTheDocument();
mockDefinition({
...DEFAULT_DEFINITIONS_MOCK[0],
key,
- })
+ }),
);
renderDefinition({
key,
});
expect(
- await ui.nameHeading('property.sonar.announcement.message.secured.name').find()
+ await ui.nameHeading('property.sonar.announcement.message.secured.name').find(),
).toBeInTheDocument();
// Can type new value and cancel change
function renderDefinition(
definition: Partial<ExtendedSettingDefinition> = {},
initialSetting?: SettingValue,
- component?: Component
+ component?: Component,
) {
return renderComponent(
<Definition
definition={{ ...DEFAULT_DEFINITIONS_MOCK[0], ...definition }}
initialSettingValue={initialSetting}
component={component}
- />
+ />,
);
}
function renderLanguages(
overrides: Partial<AdditionalCategoryComponentProps> = {},
- component = mockComponent()
+ component = mockComponent(),
) {
return renderApp(
'/',
categories={['javascript', 'sjava']}
selectedCategory=""
{...overrides}
- />
+ />,
);
}
// Visible only for project
expect(
- ui.categoryLink('settings.pr_decoration.binding.category').query()
+ ui.categoryLink('settings.pr_decoration.binding.category').query(),
).not.toBeInTheDocument();
expect(await ui.announcementHeading.find()).toBeInTheDocument();
function getPRDecorationFeatureStatus(
branchesEnabled: boolean,
- type: AlmSettingsBindingStatusType.Success | AlmSettingsBindingStatusType.Failure
+ type: AlmSettingsBindingStatusType.Success | AlmSettingsBindingStatusType.Failure,
) {
if (branchesEnabled) {
return STATUS_ICON[type];
<FormattedMessage
id="settings.almintegration.feature.pr_decoration.disabled.no_branches"
defaultMessage={translate(
- 'settings.almintegration.feature.pr_decoration.disabled.no_branches'
+ 'settings.almintegration.feature.pr_decoration.disabled.no_branches',
)}
values={{
link: (
target="_blank"
>
{translate(
- 'settings.almintegration.feature.pr_decoration.disabled.no_branches.link'
+ 'settings.almintegration.feature.pr_decoration.disabled.no_branches.link',
)}
</a>
),
function getImportFeatureStatus(
alm: AlmKeys,
definition: AlmBindingDefinitionBase,
- type: AlmSettingsBindingStatusType.Success | AlmSettingsBindingStatusType.Failure
+ type: AlmSettingsBindingStatusType.Success | AlmSettingsBindingStatusType.Failure,
) {
if (!definition.url && alm !== AlmKeys.BitbucketCloud) {
return (
return translate('settings.almintegration.feature.status_reporting.description_mr');
case AlmKeys.GitHub:
return translate(
- 'settings.almintegration.feature.status_reporting.description_pr_and_commits'
+ 'settings.almintegration.feature.status_reporting.description_pr_and_commits',
);
default:
return translate('settings.almintegration.feature.status_reporting.description_pr');
<Button
aria-label={translateWithParameters(
'settings.almintegration.edit_configuration',
- definition.key
+ definition.key,
)}
onClick={() => {
props.onEdit(definition.key);
<Button
aria-label={translateWithParameters(
'settings.almintegration.delete_configuration',
- definition.key
+ definition.key,
)}
className="button-red spacer-left"
onClick={() => {
<div>
<Tooltip
overlay={translate(
- 'settings.almintegration.feature.alm_repo_import.description'
+ 'settings.almintegration.feature.alm_repo_import.description',
)}
>
<span>
<FormattedMessage
id="settings.almintegration.github.additional_permission"
defaultMessage={translate(
- 'settings.almintegration.github.additional_permission'
+ 'settings.almintegration.github.additional_permission',
)}
values={{
link: (
<Button
aria-label={translateWithParameters(
'settings.almintegration.check_configuration_x',
- definition.key
+ definition.key,
)}
className="big-spacer-top"
onClick={() => props.onCheck(definition.key)}
};
handleBitbucketVariantChange = (
- bitbucketVariant: AlmKeys.BitbucketServer | AlmKeys.BitbucketCloud
+ bitbucketVariant: AlmKeys.BitbucketServer | AlmKeys.BitbucketCloud,
) => {
this.setState({
bitbucketVariant,
}
export function AlmBindingDefinitionFormField<B extends AlmBindingDefinitionBase>(
- props: AlmBindingDefinitionFormFieldProps<B>
+ props: AlmBindingDefinitionFormFieldProps<B>,
) {
const {
autoFocus,
<ButtonLink
aria-label={translateWithParameters(
'settings.almintegration.form.secret.update_field_x',
- translate('settings.almintegration.form', id)
+ translate('settings.almintegration.form', id),
)}
onClick={() => {
props.onFieldChange(propKey, '');
submitting: boolean;
bitbucketVariant?: AlmKeys.BitbucketServer | AlmKeys.BitbucketCloud;
onBitbucketVariantChange: (
- bitbucketVariant: AlmKeys.BitbucketServer | AlmKeys.BitbucketCloud
+ bitbucketVariant: AlmKeys.BitbucketServer | AlmKeys.BitbucketCloud,
) => void;
validationError?: string;
}
AlmKeys.GitLab,
].forEach((alm) => {
definitions[alm].forEach((def: AlmBindingDefinitionBase) =>
- this.handleCheck(def.key, false)
+ this.handleCheck(def.key, false),
);
});
}
return { type, failureMessage };
},
- () => ({ type: AlmSettingsBindingStatusType.Warning, failureMessage: '' })
+ () => ({ type: AlmSettingsBindingStatusType.Warning, failureMessage: '' }),
)
.then(({ type, failureMessage }) => {
if (this.mounted) {
help={
<FormattedMessage
defaultMessage={translate(
- 'settings.almintegration.form.personal_access_token.azure.help'
+ 'settings.almintegration.form.personal_access_token.azure.help',
)}
id="settings.almintegration.form.personal_access_token.azure.help"
values={{
export default function BitbucketCloudForm(props: BitbucketCloudFormProps) {
const { formData } = props;
const workspaceIDIsInvalid = Boolean(
- formData.workspace && !BITBUCKET_CLOUD_WORKSPACE_ID_FORMAT.test(formData.workspace)
+ formData.workspace && !BITBUCKET_CLOUD_WORKSPACE_ID_FORMAT.test(formData.workspace),
);
return (
isUpdate: boolean;
onFieldChange: (
fieldId: keyof (BitbucketServerBindingDefinition & BitbucketCloudBindingDefinition),
- value: string
+ value: string,
) => void;
variant?: AlmKeys.BitbucketServer | AlmKeys.BitbucketCloud;
onVariantChange: (variant: AlmKeys.BitbucketServer | AlmKeys.BitbucketCloud) => void;
help={
<FormattedMessage
defaultMessage={translate(
- 'settings.almintegration.form.personal_access_token.bitbucket.help'
+ 'settings.almintegration.form.personal_access_token.bitbucket.help',
)}
id="settings.almintegration.form.personal_access_token.bitbucket.help"
values={{
target="_blank"
>
{translate(
- 'settings.almintegration.form.personal_access_token.bitbucket.help.url'
+ 'settings.almintegration.form.personal_access_token.bitbucket.help.url',
)}
</Link>
),
help={
<FormattedMessage
defaultMessage={translate(
- `settings.almintegration.form.personal_access_token.gitlab.help`
+ `settings.almintegration.form.personal_access_token.gitlab.help`,
)}
id="settings.almintegration.form.personal_access_token.gitlab.help"
values={{
enforceValidation
alm={AlmKeys.GitLab}
{...props}
- />
+ />,
);
}
await ui.deleteConfiguration('New Name');
expect(ui.emptyIntro(almKey).get()).toBeInTheDocument();
});
- }
+ },
);
describe('bitbucket tab', () => {
'url.bitbucket': 'https://api.bitbucket.com',
personal_access_token: 'Access Token',
},
- AlmKeys.BitbucketServer
+ AlmKeys.BitbucketServer,
);
// Create new Bitbucket Cloud configuration
'client_id.bitbucketcloud': 'Client ID',
'client_secret.bitbucketcloud': 'Client Secret',
},
- AlmKeys.BitbucketCloud
+ AlmKeys.BitbucketCloud,
);
// Edit, check delete Bitbucket Server configuration
'New Name',
'Name',
'personal_access_token',
- AlmKeys.BitbucketServer
+ AlmKeys.BitbucketServer,
);
await ui.checkConfiguration('New Name');
async function createConfiguration(
name: string,
params: { [key: string]: string },
- almKey?: AlmKeys.BitbucketCloud | AlmKeys.BitbucketServer
+ almKey?: AlmKeys.BitbucketCloud | AlmKeys.BitbucketServer,
) {
await userEvent.click(ui.createConfigurationButton.get());
expect(ui.saveConfigurationButton.get()).toBeDisabled();
newName: string,
currentName: string,
secretId: string,
- almKey: AlmKeys
+ almKey: AlmKeys,
) {
almSettings.setDefinitionErrorMessage('Something is wrong');
await userEvent.click(ui.editConfigurationButton(currentName).get());
almSettings.setDefinitionErrorMessage('');
await userEvent.click(ui.checkConfigurationButton(name).get());
expect(
- ui.validationMessage('settings.almintegration.configuration_valid').getAll()[0]
+ ui.validationMessage('settings.almintegration.configuration_valid').getAll()[0],
).toBeInTheDocument();
}
return renderComponent(
<AvailableFeaturesContext.Provider value={features}>
<AlmIntegration />
- </AvailableFeaturesContext.Provider>
+ </AvailableFeaturesContext.Provider>,
);
}
aria-label={translateWithParameters(
'settings.definition.delete_value',
getPropertyName(definition),
- value
+ value,
)}
onClick={() => handleDeleteValue(index)}
/>
export default function AuthenticationSecuredField(props: SamlToggleFieldProps) {
const { settingValue, definition, optional = true, isNotSet } = props;
const [showSecretField, setShowSecretField] = React.useState(
- !isNotSet && isSecuredDefinition(definition)
+ !isNotSet && isSecuredDefinition(definition),
);
useEffect(() => {
defaultMessage={translate(
`settings.authentication.${
hasLegacyConfiguration ? `legacy_help.${tab}` : 'help'
- }`
+ }`,
)}
values={{
link: (
const invalidOrgs =
isValidApp && data
? data.installations.filter(
- (org) => org[applicationField].status === GitHubProvisioningStatus.Failed
+ (org) => org[applicationField].status === GitHubProvisioningStatus.Failed,
)
: [];
translateWithParameters(
`${intlPrefix}.invalid_org`,
org.organization,
- org[applicationField].errorMessage ?? ''
- )
+ org[applicationField].errorMessage ?? '',
+ ),
);
if (isValidApp && invalidOrgs.length === 0) {
translateWithParameters(
`${intlPrefix}.valid${data.installations.length === 1 ? '_one' : ''}`,
translate(
- `settings.authentication.github.form.provisioning_with_github_short.${applicationField}`
+ `settings.authentication.github.form.provisioning_with_github_short.${applicationField}`,
),
data.installations.length === 1
? data.installations[0].organization
- : data.installations.length
+ : data.installations.length,
),
]);
setAlertVariant('success');
setMessages([
translateWithParameters(
`${intlPrefix}.invalid`,
- data?.application[applicationField].errorMessage ?? ''
+ data?.application[applicationField].errorMessage ?? '',
),
...invalidOrgsMessages,
]);
<RadioCard
className="spacer-top"
label={translate(
- 'settings.authentication.github.form.provisioning_with_github'
+ 'settings.authentication.github.form.provisioning_with_github',
)}
title={translate(
- 'settings.authentication.github.form.provisioning_with_github'
+ 'settings.authentication.github.form.provisioning_with_github',
)}
selected={newGithubProvisioningStatus ?? githubProvisioningStatus}
onClick={() => setNewGithubProvisioningStatus(true)}
)}
<p className="spacer-bottom">
{translate(
- 'settings.authentication.github.form.provisioning_with_github.description'
+ 'settings.authentication.github.form.provisioning_with_github.description',
)}
</p>
<p className="spacer-bottom">
<FormattedMessage
id="settings.authentication.github.form.provisioning.disabled"
defaultMessage={translate(
- 'settings.authentication.github.form.provisioning.disabled'
+ 'settings.authentication.github.form.provisioning.disabled',
)}
values={{
documentation: (
onConfirm={() => changeProvisioning()}
header={translate(
'settings.authentication.github.confirm',
- newGithubProvisioningStatus ? 'auto' : 'jit'
+ newGithubProvisioningStatus ? 'auto' : 'jit',
)}
onClose={() => setShowConfirmProvisioningModal(false)}
isDestructive={!newGithubProvisioningStatus}
{translate(
'settings.authentication.github.confirm',
newGithubProvisioningStatus ? 'auto' : 'jit',
- 'description'
+ 'description',
)}
</ConfirmModal>
)}
)}
<p className="spacer-bottom ">
{translate(
- 'settings.authentication.saml.form.provisioning_with_scim.sub'
+ 'settings.authentication.saml.form.provisioning_with_scim.sub',
)}
</p>
<p className="spacer-bottom ">
{translate(
- 'settings.authentication.saml.form.provisioning_with_scim.description'
+ 'settings.authentication.saml.form.provisioning_with_scim.description',
)}
</p>
<p>
<FormattedMessage
id="settings.authentication.saml.form.provisioning_with_scim.description.doc"
defaultMessage={translate(
- 'settings.authentication.saml.form.provisioning_with_scim.description.doc'
+ 'settings.authentication.saml.form.provisioning_with_scim.description.doc',
)}
values={{
documentation: (
onConfirm={() => handleConfirmChangeProvisioning()}
header={translate(
'settings.authentication.saml.confirm',
- newScimStatus ? 'scim' : 'jit'
+ newScimStatus ? 'scim' : 'jit',
)}
onClose={() => setShowConfirmProvisioningModal(false)}
isDestructive={!newScimStatus}
{translate(
'settings.authentication.saml.confirm',
newScimStatus ? 'scim' : 'jit',
- 'description'
+ 'description',
)}
</ConfirmModal>
)}
expect(screen.getByRole('tab', { name: 'SAML' })).toHaveAttribute('aria-selected', 'false');
expect(screen.getByRole('tab', { name: 'github GitHub' })).toHaveAttribute(
'aria-selected',
- 'true'
+ 'true',
);
});
await act(() => user.click(github.viewConfigValidityDetailsButton.get()));
expect(github.getConfigDetailsTitle()).toHaveTextContent(
- 'settings.authentication.github.configuration.validation.details.valid_label'
+ 'settings.authentication.github.configuration.validation.details.valid_label',
);
expect(github.getOrgs()[0]).toHaveTextContent(
- 'settings.authentication.github.configuration.validation.details.valid_labelorg1'
+ 'settings.authentication.github.configuration.validation.details.valid_labelorg1',
);
expect(github.getOrgs()[1]).toHaveTextContent(
- 'settings.authentication.github.configuration.validation.details.valid_labelorg2'
+ 'settings.authentication.github.configuration.validation.details.valid_labelorg2',
);
});
await act(() => user.click(github.viewConfigValidityDetailsButton.get()));
expect(github.getConfigDetailsTitle()).toHaveTextContent(
- 'settings.authentication.github.configuration.validation.details.valid_label'
+ 'settings.authentication.github.configuration.validation.details.valid_label',
);
expect(github.getOrgs()[0]).toHaveTextContent(
- 'settings.authentication.github.configuration.validation.details.invalid_labelorg1 - Installation suspended'
+ 'settings.authentication.github.configuration.validation.details.invalid_labelorg1 - Installation suspended',
);
await act(() =>
- user.click(within(github.configDetailsDialog.get()).getByRole('button', { name: 'close' }))
+ user.click(within(github.configDetailsDialog.get()).getByRole('button', { name: 'close' })),
);
await user.click(github.githubProvisioningButton.get());
await act(() => user.click(github.viewConfigValidityDetailsButton.get()));
expect(github.getConfigDetailsTitle()).toHaveTextContent(
- 'settings.authentication.github.configuration.validation.details.valid_label'
+ 'settings.authentication.github.configuration.validation.details.valid_label',
);
expect(github.getOrgs()[0]).toHaveTextContent(
- 'settings.authentication.github.configuration.validation.details.valid_labelorg1'
+ 'settings.authentication.github.configuration.validation.details.valid_labelorg1',
);
expect(github.getOrgs()[1]).toHaveTextContent(
- 'settings.authentication.github.configuration.validation.details.org_not_found.organization1'
+ 'settings.authentication.github.configuration.validation.details.org_not_found.organization1',
);
});
await act(() => user.click(github.viewConfigValidityDetailsButton.get()));
expect(github.getConfigDetailsTitle()).toHaveTextContent(
- 'settings.authentication.github.configuration.validation.details.invalid_label'
+ 'settings.authentication.github.configuration.validation.details.invalid_label',
);
expect(github.configDetailsDialog.get()).toHaveTextContent(errorMessage);
});
await act(() => user.click(github.viewConfigValidityDetailsButton.get()));
expect(github.getConfigDetailsTitle()).toHaveTextContent(
- 'settings.authentication.github.configuration.validation.details.valid_label'
+ 'settings.authentication.github.configuration.validation.details.valid_label',
);
await act(() =>
- user.click(within(github.configDetailsDialog.get()).getByRole('button', { name: 'close' }))
+ user.click(within(github.configDetailsDialog.get()).getByRole('button', { name: 'close' })),
);
await act(() => user.click(github.githubProvisioningButton.get()));
await act(() => user.click(github.viewConfigValidityDetailsButton.get()));
expect(github.getConfigDetailsTitle()).toHaveTextContent(
- 'settings.authentication.github.configuration.validation.details.invalid_label'
+ 'settings.authentication.github.configuration.validation.details.invalid_label',
);
});
await act(() => user.click(github.viewConfigValidityDetailsButton.get()));
expect(github.getOrgs()[0]).toHaveTextContent(
- 'settings.authentication.github.configuration.validation.details.valid_labelorg1'
+ 'settings.authentication.github.configuration.validation.details.valid_labelorg1',
);
expect(github.getOrgs()[1]).toHaveTextContent(
- 'settings.authentication.github.configuration.validation.details.invalid_labelorg2 - Test error'
+ 'settings.authentication.github.configuration.validation.details.invalid_labelorg2 - Test error',
);
await act(() =>
- user.click(within(github.configDetailsDialog.get()).getByRole('button', { name: 'close' }))
+ user.click(within(github.configDetailsDialog.get()).getByRole('button', { name: 'close' })),
);
await act(() => user.click(github.githubProvisioningButton.get()));
expect(github.configurationValidityError.get()).toBeInTheDocument();
expect(github.configurationValidityError.get()).toHaveTextContent(
- `settings.authentication.github.configuration.validation.invalid_org.org2.${errorMessage}`
+ `settings.authentication.github.configuration.validation.invalid_org.org2.${errorMessage}`,
);
await act(() => user.click(github.viewConfigValidityDetailsButton.get()));
expect(github.getOrgs()[1]).toHaveTextContent(
- `settings.authentication.github.configuration.validation.details.invalid_labelorg2 - ${errorMessage}`
+ `settings.authentication.github.configuration.validation.details.invalid_labelorg2 - ${errorMessage}`,
);
});
renderComponent(
<AvailableFeaturesContext.Provider value={features}>
<Authentication definitions={definitions} />
- </AvailableFeaturesContext.Provider>
+ </AvailableFeaturesContext.Provider>,
);
}
export default function useConfiguration(
definitions: ExtendedSettingDefinition[],
- optionalFields: string[]
+ optionalFields: string[],
) {
const keys = definitions.map((definition) => definition.key);
const [values, setValues] = useState<Dict<SettingValue>>({});
definition,
};
}),
- 'key'
- )
+ 'key',
+ ),
);
}
}, [data, definitions]);
Object.values(values).filter((v) => v.mandatory),
(v) =>
(v.newValue !== undefined && !isEmpty(v.newValue)) ||
- (!v.isNotSet && v.newValue === undefined)
+ (!v.isNotSet && v.newValue === undefined),
);
const hasConfiguration = every(
Object.values(values).filter((v) => v.mandatory),
- (v) => !v.isNotSet
+ (v) => !v.isNotSet,
);
const deleteMutation = update(
useResetSettingsMutation(),
'mutate',
- (mutate) => () => mutate(Object.keys(values))
+ (mutate) => () => mutate(Object.keys(values)),
) as Omit<UseMutationResult<void, unknown, void, unknown>, 'mutateAsync'>;
const isValueChange = useCallback(
const value = values[setting];
return value && value.newValue !== undefined && (value.value ?? '') !== value.newValue;
},
- [values]
+ [values],
);
return {
const { values, isValueChange, setNewValue } = config;
const hasGithubProvisioning = useContext(AvailableFeaturesContext).includes(
- Feature.GithubProvisioning
+ Feature.GithubProvisioning,
);
const { data: githubProvisioningStatus } = useGithubProvisioningEnabledQuery();
const toggleGithubProvisioning = useToggleGithubProvisioningMutation();
aria-label={translateWithParameters(
'settings.definition.delete_value',
getPropertyName(setting.definition),
- value
+ value,
)}
onClick={() => this.handleDeleteValue(index)}
/>
<div>
<ul>
{displayedValue.map((value, index) =>
- this.renderInput(value, index, index === displayedValue.length - 1)
+ this.renderInput(value, index, index === displayedValue.length - 1),
)}
</ul>
</div>
aria-label={translateWithParameters(
'settings.definitions.delete_fields',
getPropertyName(setting.definition),
- index
+ index,
)}
className="js-remove-value"
onClick={() => this.handleDeleteValue(index)}
</thead>
<tbody>
{displayedValue.map((fieldValues, index) =>
- this.renderFields(fieldValues, index, index === displayedValue.length - 1)
+ this.renderFields(fieldValues, index, index === displayedValue.length - 1),
)}
</tbody>
</table>
function renderFieldWrapper(
label: React.ReactNode,
input: React.ReactNode,
- help?: React.ReactNode
+ help?: React.ReactNode,
) {
return (
<div className="settings-definition">
props: Omit<CommonFieldProps, 'optional'> & {
value: boolean;
inputExtra?: React.ReactNode;
- }
+ },
) {
const { id, value, onFieldChange, propKey, inputExtra } = props;
return renderFieldWrapper(
</div>
{inputExtra}
</div>,
- renderHelp(props)
+ renderHelp(props),
);
}
function renderField(
props: CommonFieldProps & {
value: string;
- }
+ },
) {
const { id, propKey, value, onFieldChange } = props;
return renderFieldWrapper(
type="text"
value={value}
/>,
- renderHelp(props)
+ renderHelp(props),
);
}
const [checkingConfiguration, setCheckingConfiguration] = React.useState(false);
const { data: originalData } = useProjectBindingQuery(component.key);
const { mutateAsync: deleteMutation, isLoading: isDeleting } = useDeleteProjectAlmBindingMutation(
- component.key
+ component.key,
);
const { mutateAsync: updateMutation, isLoading: isUpdating } = useSetProjectBindingMutation();
}
return REQUIRED_FIELDS_BY_ALM[selected.alm].reduce(
(result: boolean, field) => result && Boolean(additionalFields[field]),
- true
+ true,
);
};
slug: oSlug = '',
summaryCommentEnabled: osummaryCommentEnabled = false,
monorepo: omonorepo = false,
- }: FormData
+ }: FormData,
) => {
return (
key === oKey &&
const submitProjectAlmBinding = (
alm: AlmKeys,
key: string,
- almSpecificFields: Omit<FormData, 'key'>
+ almSpecificFields: Omit<FormData, 'key'>,
): Promise<void> => {
const almSetting = key;
const { repository, slug = '', monorepo = false } = almSpecificFields;
<FormattedMessage
id="settings.pr_decoration.binding.check_configuration.failure.check_global_settings"
defaultMessage={translate(
- 'settings.pr_decoration.binding.check_configuration.failure.check_global_settings'
+ 'settings.pr_decoration.binding.check_configuration.failure.check_global_settings',
)}
values={{
link: (
<Link to={getGlobalSettingsUrl(ALM_INTEGRATION_CATEGORY, { alm })}>
{translate(
- 'settings.pr_decoration.binding.check_configuration.failure.check_global_settings.link'
+ 'settings.pr_decoration.binding.check_configuration.failure.check_global_settings.link',
)}
</Link>
),
// Set form data
await selectEvent.select(ui.input('name', 'combobox').get(), (content) =>
- content.includes(key)
+ content.includes(key),
);
const list = inputsList[alm];
almSettings.setProjectBindingConfigurationErrors(undefined);
await ui.setInput(
Object.keys(list).find((key) => key.endsWith('.repository')) as string,
- 'Anything'
+ 'Anything',
);
await act(() => user.click(ui.saveButton.get()));
expect(
- await ui.validationMsg('settings.pr_decoration.binding.check_configuration.success').find()
+ await ui.validationMsg('settings.pr_decoration.binding.check_configuration.success').find(),
).toBeInTheDocument();
await act(() => user.click(ui.validateButton.get()));
expect(
- ui.validationMsg('settings.pr_decoration.binding.check_configuration.success').get()
+ ui.validationMsg('settings.pr_decoration.binding.check_configuration.success').get(),
).toBeInTheDocument();
// Rerender and verify that validation is done for binding
rerender(
- <MockedPRDecorationBinding component={mockComponent()} currentUser={mockCurrentUser()} />
+ <MockedPRDecorationBinding component={mockComponent()} currentUser={mockCurrentUser()} />,
);
expect(
- await ui.validationMsg('settings.pr_decoration.binding.check_configuration.success').find()
+ await ui.validationMsg('settings.pr_decoration.binding.check_configuration.success').find(),
).toBeInTheDocument();
expect(ui.saveButton.query()).not.toBeInTheDocument();
await act(() => user.click(ui.resetButton.get()));
expect(ui.input('', 'textbox').query()).not.toBeInTheDocument();
expect(ui.input('', 'switch').query()).not.toBeInTheDocument();
- }
+ },
);
function getPageObjects() {
function renderPRDecorationBinding(
component: Component = mockComponent(),
- currentUser: CurrentUser = mockCurrentUser()
+ currentUser: CurrentUser = mockCurrentUser(),
) {
return renderComponent(
- <MockedPRDecorationBinding component={component} currentUser={currentUser} />
+ <MockedPRDecorationBinding component={component} currentUser={currentUser} />,
);
}
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
};
if (this.mounted) {
this.setState({ encrypting: false });
}
- }
+ },
);
};
border-right: none;
overflow: hidden;
text-overflow: ellipsis;
- transition: color 0.3s ease, background-color 0.3s ease;
+ transition:
+ color 0.3s ease,
+ background-color 0.3s ease;
}
.side-tabs-menu > li > a:hover,
export function combineDefinitionAndSettingValue(
definition: ExtendedSettingDefinition,
- value?: SettingValue
+ value?: SettingValue,
): SettingWithCategory {
const hasValue = value !== undefined && value.inherited !== true;
return {
return DEFAULT_CATEGORY;
}
const sortedCategories = sortBy(categories, (category) =>
- getCategoryName(category).toLowerCase()
+ getCategoryName(category).toLowerCase(),
);
return sortedCategories[0];
}
export function buildSettingLink(
definition: ExtendedSettingDefinition,
- component?: Component
+ component?: Component,
): Partial<Path> {
const { category, key } = definition;
u.getSystemLogsLevel(
mockClusterSysInfo({
'Application Nodes': [{ Name: 'App 1' }, { Name: 'App 2' }],
- })
- )
+ }),
+ ),
).toBe(u.LogsLevels.INFO);
expect(
u.getSystemLogsLevel(
mockClusterSysInfo({
'Application Nodes': [{ 'Compute Engine Logging': {} }, { Name: 'App 2' }],
- })
- )
+ }),
+ ),
).toBe(u.LogsLevels.INFO);
expect(u.getSystemLogsLevel({} as SysInfoStandalone)).toBe(u.LogsLevels.INFO);
});
describe('getStandaloneSecondarySections', () => {
it('should return the correct information', () => {
expect(Object.keys(u.getStandaloneSecondarySections(mockStandaloneSysInfo()))).toEqual(
- expect.arrayContaining(['Compute Engine', 'Search Engine', 'Web'])
+ expect.arrayContaining(['Compute Engine', 'Search Engine', 'Web']),
);
expect(Object.keys(u.getStandaloneSecondarySections(mockClusterSysInfo()))).toEqual(
- expect.arrayContaining(['Compute Engine', 'Search Engine', 'Web'])
+ expect.arrayContaining(['Compute Engine', 'Search Engine', 'Web']),
);
});
});
'Health',
'Health Causes',
'Database',
- ])
+ ]),
);
});
});
'Compute Engine Tasks',
'Search State',
'Search Indexes',
- ])
+ ]),
);
});
});
u.getSearchNodes(
mockClusterSysInfo({
'Search Nodes': [{ Name: 'searchnode1' }],
- })
- )
+ }),
+ ),
).toEqual([{ Name: 'searchnode1' }]);
});
});
u.getAppNodes(
mockClusterSysInfo({
'Application Nodes': [{ Name: 'appnode1' }],
- })
- )
+ }),
+ ),
).toEqual([{ Name: 'appnode1' }]);
});
});
describe('getLogsLevel', () => {
it('should return the correct information, if available', () => {
expect(u.getLogsLevel({ 'Compute Engine Logging': { 'Logs Level': 'TRACE' } })).toEqual(
- 'TRACE'
+ 'TRACE',
);
});
u.getLogsLevel({
'Web Logging': mockLogs(u.LogsLevels.DEBUG),
'Compute Engine Logging': mockLogs(u.LogsLevels.TRACE),
- })
+ }),
).toEqual(u.LogsLevels.TRACE);
});
describe('getServerId', () => {
it('should return the correct information, if available', () => {
expect(u.getServerId(mockStandaloneSysInfo({ System: { 'Server ID': 'foo-bar' } }))).toEqual(
- 'foo-bar'
+ 'foo-bar',
);
});
u.getClusterVersion(
mockClusterSysInfo({
'Application Nodes': [{ System: { Version: '1.0' } }],
- })
- )
+ }),
+ ),
).toEqual('1.0');
});
it('should return undefined if no information is available', () => {
expect(
- u.getClusterVersion(mockClusterSysInfo({ 'Application Nodes': [{ System: {} }] }))
+ u.getClusterVersion(mockClusterSysInfo({ 'Application Nodes': [{ System: {} }] })),
).toBeUndefined();
expect(
u.getClusterVersion(
mockClusterSysInfo({
'Application Nodes': [],
System: { Version: '1.0' },
- })
- )
+ }),
+ ),
).toBeUndefined();
});
});
this.setState({ updating: true });
setLogLevel(newLevel).then(
() => this.props.onChange(),
- () => this.setState({ updating: false })
+ () => this.setState({ updating: false }),
);
}
};
{this.state.openLogsLevelForm && (
<ChangeLogLevelForm
infoMsg={translate(
- this.props.cluster ? 'system.cluster_log_level.info' : 'system.log_level.info'
+ this.props.cluster ? 'system.cluster_log_level.info' : 'system.log_level.info',
)}
logLevel={this.props.logLevel}
onChange={this.handleLogsLevelChange}
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
};
expect(ui.copyIdInformation.get()).toHaveAttribute(
'data-clipboard-text',
- expect.stringContaining(`Server ID: asd564-asd54a-5dsfg45`)
+ expect.stringContaining(`Server ID: asd564-asd54a-5dsfg45`),
);
expect(ui.sectionButton('System').get()).toBeInTheDocument();
['Main Process', 'Compute Engine', 'Search Engine', 'Web Server', 'Access Logs'].forEach(
(link) => {
expect(screen.getByRole('link', { name: link })).toBeInTheDocument();
- }
+ },
);
expect(ui.downloadSystemInfoButton.get()).toBeInTheDocument();
});
expect(ui.copyIdInformation.get()).toHaveAttribute(
'data-clipboard-text',
- expect.stringContaining(`Server ID: asd564-asd54a-5dsfg45`)
+ expect.stringContaining(`Server ID: asd564-asd54a-5dsfg45`),
);
// Renders health checks
getLogsLevel(sysInfoObject[WEB_LOGGING_FIELD]),
getLogsLevel(sysInfoObject[CE_LOGGING_FIELD]),
],
- (logLevel: LogsLevels) => LOGS_LEVELS.indexOf(logLevel)
+ (logLevel: LogsLevels) => LOGS_LEVELS.indexOf(logLevel),
)[1];
}
}
}
export function isCluster(
- sysInfoData: SysInfoCluster | SysInfoStandalone
+ sysInfoData: SysInfoCluster | SysInfoStandalone,
): sysInfoData is SysInfoCluster {
return sysInfoData[SYSTEM_FIELD] && sysInfoData[SYSTEM_FIELD][HA_FIELD] === true;
}
}
export function hasLoggingInfo(
- sysInfoObject: SysInfoValueObject
+ sysInfoObject: SysInfoValueObject,
): sysInfoObject is SysInfoStandalone | SysInfoAppNode {
return Boolean(sysInfoObject[WEB_LOGGING_FIELD] || sysInfoObject[CE_LOGGING_FIELD]);
}
export function getSystemLogsLevel(sysInfoData: SysInfoCluster | SysInfoStandalone): string {
if (isCluster(sysInfoData)) {
const logLevels = sortBy(getAppNodes(sysInfoData).map(getLogsLevel), (logLevel: LogsLevels) =>
- LOGS_LEVELS.indexOf(logLevel)
+ LOGS_LEVELS.indexOf(logLevel),
);
return logLevels.length > 0 ? logLevels[logLevels.length - 1] : DEFAULT_LOG_LEVEL;
}
[PLUGINS_FIELD, SETTINGS_FIELD, STATS_FIELD, SYSTEM_FIELD].includes(key) ||
key.startsWith(CE_FIELD_PREFIX) ||
key.startsWith(SEARCH_PREFIX) ||
- key.startsWith(WEB_PREFIX)
+ key.startsWith(WEB_PREFIX),
) as SysInfoValueObject),
};
}
return {
Web: pickBy(sysInfoData, (_, key) => key.startsWith(WEB_PREFIX)) as SysInfoValueObject,
'Compute Engine': pickBy(sysInfoData, (_, key) =>
- key.startsWith(CE_FIELD_PREFIX)
+ key.startsWith(CE_FIELD_PREFIX),
) as SysInfoValueObject,
'Search Engine': pickBy(sysInfoData, (_, key) =>
- key.startsWith(SEARCH_PREFIX)
+ key.startsWith(SEARCH_PREFIX),
) as SysInfoValueObject,
};
}
export const parseQuery = memoize(
(urlQuery: RawQuery): Query => ({
expandedCards: parseAsArray(urlQuery.expand, parseAsString),
- })
+ }),
);
export const serializeQuery = memoize(
(query: Query): RawQuery =>
cleanQuery({
expand: serializeStringArray(query.expandedCards),
- })
+ }),
);
managed,
...usersActivityParams,
},
- numberOfPages
+ numberOfPages,
);
const manageProvider = useManageProvider();
{users.map((user) => (
<UserListItem
identityProvider={identityProviders.find(
- (provider) => user.externalProvider === provider.key
+ (provider) => user.externalProvider === provider.key,
)}
key={user.login}
user={user}
aliceRowWithLocalBadge: byRole('row', {
name: (accessibleName) =>
accessibleName.startsWith(
- 'AM Alice Merveille alice.merveille alice.merveille@wonderland.com local '
+ 'AM Alice Merveille alice.merveille alice.merveille@wonderland.com local ',
),
}),
bobRow: byRole('row', {
await act(async () => {
await selectEvent.select(
ui.activityFilter.get(),
- 'users.activity_filter.active_sonarlint_users'
+ 'users.activity_filter.active_sonarlint_users',
);
});
await act(async () => {
await selectEvent.select(
ui.activityFilter.get(),
- 'users.activity_filter.active_sonarqube_users'
+ 'users.activity_filter.active_sonarqube_users',
);
});
await act(() => user.click(ui.createUserDialogButton.get()));
expect(ui.dialogCreateUser.get()).toBeInTheDocument();
expect(
- await within(ui.dialogCreateUser.get()).findByText('Error: Empty SCM')
+ await within(ui.dialogCreateUser.get()).findByText('Error: Empty SCM'),
).toBeInTheDocument();
// Remove SCM account
await user.click(ui.deleteSCMButton().get());
await act(async () => user.click(await ui.aliceUpdateButton.find()));
await user.click(
- await within(ui.aliceRow.get()).findByRole('button', { name: 'update_details' })
+ await within(ui.aliceRow.get()).findByRole('button', { name: 'update_details' }),
);
expect(await ui.dialogUpdateUser.find()).toBeInTheDocument();
await act(async () => user.click(await ui.aliceUpdateButton.find()));
await user.click(
- await within(ui.aliceRow.get()).findByRole('button', { name: 'users.deactivate' })
+ await within(ui.aliceRow.get()).findByRole('button', { name: 'users.deactivate' }),
);
expect(await ui.dialogDeactivateUser.find()).toBeInTheDocument();
expect(ui.deleteUserAlert.query()).not.toBeInTheDocument();
await act(() =>
user.click(
- within(ui.dialogDeactivateUser.get()).getByRole('button', { name: 'users.deactivate' })
- )
+ within(ui.dialogDeactivateUser.get()).getByRole('button', { name: 'users.deactivate' }),
+ ),
);
expect(ui.aliceRow.query()).not.toBeInTheDocument();
});
await act(async () => user.click(await ui.aliceUpdateButton.find()));
await user.click(
- await within(ui.aliceRow.get()).findByRole('button', { name: 'my_profile.password.title' })
+ await within(ui.aliceRow.get()).findByRole('button', { name: 'my_profile.password.title' }),
);
expect(await ui.dialogPasswords.find()).toBeInTheDocument();
expect(ui.changeButton.get()).toBeEnabled();
expect(
- screen.queryByText(`user.${ChangePasswordResults.OldPasswordIncorrect}`)
+ screen.queryByText(`user.${ChangePasswordResults.OldPasswordIncorrect}`),
).not.toBeInTheDocument();
await act(() => user.click(ui.changeButton.get()));
expect(
await within(ui.dialogPasswords.get()).findByText(
- `user.${ChangePasswordResults.OldPasswordIncorrect}`
- )
+ `user.${ChangePasswordResults.OldPasswordIncorrect}`,
+ ),
).toBeInTheDocument();
await user.clear(ui.oldPassword.get());
await user.type(ui.confirmPassword.get(), 'test');
expect(
- screen.queryByText(`user.${ChangePasswordResults.NewPasswordSameAsOld}`)
+ screen.queryByText(`user.${ChangePasswordResults.NewPasswordSameAsOld}`),
).not.toBeInTheDocument();
await act(() => user.click(ui.changeButton.get()));
expect(
- await screen.findByText(`user.${ChangePasswordResults.NewPasswordSameAsOld}`)
+ await screen.findByText(`user.${ChangePasswordResults.NewPasswordSameAsOld}`),
).toBeInTheDocument();
await user.clear(ui.newPassword.get());
await user.click(ui.bobUpdateButton.get());
expect(
- ui.bobRow.byRole('button', { name: 'users.deactivate' }).query()
+ ui.bobRow.byRole('button', { name: 'users.deactivate' }).query(),
).not.toBeInTheDocument();
expect(
- ui.bobRow.byRole('button', { name: 'my_profile.password.title' }).query()
+ ui.bobRow.byRole('button', { name: 'my_profile.password.title' }).query(),
).not.toBeInTheDocument();
await user.click(await ui.bobRow.byRole('button', { name: 'update_scm' }).get());
user.click(
await within(await ui.aliceRow.find()).findByRole('button', {
name: 'users.update_tokens_for_x.Alice Merveille',
- })
- )
+ }),
+ ),
);
expect(await ui.dialogTokens.find()).toBeInTheDocument();
.byRole('button', {
name: 'users.update_tokens_for_x.Alice Merveille',
})
- .find()
+ .find(),
);
expect(await ui.dialogTokens.find()).toBeInTheDocument();
await expect(await ui.dialogTokens.find()).toHaveNoA11yViolations();
// user password dialog should be accessible
await user.click(await ui.aliceUpdateButton.find());
await user.click(
- await ui.aliceRow.byRole('button', { name: 'my_profile.password.title' }).find()
+ await ui.aliceRow.byRole('button', { name: 'my_profile.password.title' }).find(),
);
expect(await ui.dialogPasswords.find()).toBeInTheDocument();
await expect(await ui.dialogPasswords.find()).toHaveNoA11yViolations();
{ login: user.login, anonymize },
{
onSuccess: props.onClose,
- }
+ },
);
};
const { user } = props;
const [confirmPassword, setConfirmPassword] = React.useState('');
const [errorTranslationKey, setErrorTranslationKey] = React.useState<string | undefined>(
- undefined
+ undefined,
);
const [newPassword, setNewPassword] = React.useState('');
const [oldPassword, setOldPassword] = React.useState('');
const [projects, setProjects] = React.useState<LabelValueSelectOption[]>([]);
const [selectedProject, setSelectedProject] = React.useState<LabelValueSelectOption>();
const [newTokenExpiration, setNewTokenExpiration] = React.useState<TokenExpiration>(
- TokenExpiration.OneMonth
+ TokenExpiration.OneMonth,
);
const [tokenExpirationOptions, setTokenExpirationOptions] =
React.useState<{ value: TokenExpiration; label: string }[]>(EXPIRATION_OPTIONS);
password,
scmAccounts,
},
- { onSuccess: props.onClose, onError: handleError }
+ { onSuccess: props.onClose, onError: handleError },
);
};
name: user?.local ? name : undefined,
scmAccount: scmAccounts,
},
- { onSuccess: props.onClose, onError: handleError }
+ { onSuccess: props.onClose, onError: handleError },
);
};
(urlQuery: RawQuery): Query => ({
search: parseAsString(urlQuery['search']),
managed: urlQuery['managed'] !== undefined ? urlQuery['managed'] === 'true' : undefined,
- })
+ }),
);
export const serializeQuery = memoize(
cleanQuery({
search: query.search ? serializeString(query.search) : undefined,
managed: query.managed,
- })
+ }),
);
(acc, [name, methods]) => [
...acc,
...Object.entries(
- omit(methods, 'summary', '$ref', 'description', 'servers', 'parameters') ?? {}
+ omit(methods, 'summary', '$ref', 'description', 'servers', 'parameters') ?? {},
).map(([method, info]) => ({ name, method, info })),
],
- []
+ [],
);
}, [data]);
apiSidebarItem: byTestId('js-subnavigation-item'),
requestBody: byText('api_documentation.v2.request_subheader.request_body'),
queryParameter: byRole('list', { name: 'api_documentation.v2.request_subheader.query' }).byRole(
- 'listitem'
+ 'listitem',
),
pathParameter: byRole('list', { name: 'api_documentation.v2.request_subheader.path' }).byRole(
- 'listitem'
+ 'listitem',
),
requestHeader: byRole('list', { name: 'api_documentation.v2.request_subheader.header' }).byRole(
- 'listitem'
+ 'listitem',
),
response: byRole('list', { name: 'api_documentation.v2.response_header' }).byRole('listitem'),
};
expect(
screen.getByText('This is a sample Pet Store Server based on the OpenAPI 3.0 specification.', {
exact: false,
- })
+ }),
).toBeInTheDocument();
await user.click(ui.apiScopePet.get());
await user.click(ui.apiSidebarItem.getAt(0));
},
},
},
- })
+ }),
).toStrictEqual({
openapi: '3.0.1',
info: {
type: 'boolean',
},
},
- })
+ }),
).toStrictEqual({
str: 'string',
int: 'integer (int32)',
items: {
type: 'string',
},
- })
+ }),
).toStrictEqual(['string']);
expect(
mapOpenAPISchema({
type: 'string',
enum: ['GREEN', 'YELLOW', 'RED'],
- })
+ }),
).toStrictEqual(['GREEN', 'YELLOW', 'RED']);
});
(api) =>
api.name.toLowerCase().includes(lowerCaseSearch) ||
api.method.toLowerCase().includes(lowerCaseSearch) ||
- api.info.summary?.toLowerCase().includes(lowerCaseSearch)
+ api.info.summary?.toLowerCase().includes(lowerCaseSearch),
)
.reduce<Record<string, Api[]>>((acc, api) => {
const subgroup = api.name.split('/')[1];
[subgroup]: [...(acc[subgroup] ?? []), api],
};
}, {}),
- [lowerCaseSearch, apisList]
+ [lowerCaseSearch, apisList],
);
return (
{Object.entries(groupedList).map(([group, apis]) => (
<SubnavigationAccordion
initExpanded={apis.some(
- ({ name, method }) => name === activeApi[0] && method === activeApi[1]
+ ({ name, method }) => name === activeApi[0] && method === activeApi[1],
)}
className="sw-mt-2"
header={group}
type ConvertedSchema = string | { [Key: string]: ConvertedSchema } | ConvertedSchema[];
export const mapOpenAPISchema = (
- schema: ExcludeReferences<OpenAPIV3.SchemaObject>
+ schema: ExcludeReferences<OpenAPIV3.SchemaObject>,
): ConvertedSchema => {
if (schema.type === 'object') {
const result = { ...schema.properties };
};
export const dereferenceSchema = (
- document: OpenAPIV3.Document
+ document: OpenAPIV3.Document,
): ExcludeReferences<OpenAPIV3.Document> => {
const dereference = (ref: string) => {
const path = ref.replace('#/', '').split('/');
serializeQuery({
deprecated: Boolean(action.deprecatedSince),
internal: Boolean(action.internal),
- })
+ }),
),
}}
>
const filteredDomains = (domains || [])
.map((domain) => {
const filteredActions = domain.actions.filter((action) =>
- actionsFilter(query, domain, action)
+ actionsFilter(query, domain, action),
);
return { ...domain, filteredActions };
})
const { domain, action } = this.props;
fetchResponseExampleApi(domain.path, action.key).then(
(responseExample) => this.setState({ responseExample }),
- () => {}
+ () => {},
);
}
this.setState({ domains: this.parseDomains(domains) });
}
},
- () => {}
+ () => {},
);
}
const domain = domains.find((domain) => splat.startsWith(domain.path));
if (domain) {
const action = domain.actions.find(
- (action) => getActionKey(domain.path, action.key) === splat
+ (action) => getActionKey(domain.path, action.key) === splat,
);
const internal = Boolean(!query.internal && (domain.internal || (action && action.internal)));
const deprecated = Boolean(
- !query.deprecated && (domain.deprecatedSince || (action && action.deprecatedSince))
+ !query.deprecated && (domain.deprecatedSince || (action && action.deprecatedSince)),
);
if (internal || deprecated) {
this.updateQuery({ internal, deprecated });
function getLatestDeprecatedAction(domain: Pick<WebApi.Domain, 'actions'>) {
const noVersion = { major: 0, minor: 0 };
const allActionsDeprecated = domain.actions.every(
- ({ deprecatedSince }) => deprecatedSince !== undefined
+ ({ deprecatedSince }) => deprecatedSince !== undefined,
);
const latestDeprecation =
allActionsDeprecated &&
showDeprecated={false}
showInternal={false}
{...props}
- />
+ />,
);
}
search: parseAsString(urlQuery['query']),
deprecated: parseAsOptionalBoolean(urlQuery['deprecated']) || false,
internal: parseAsOptionalBoolean(urlQuery['internal']) || false,
- })
+ }),
);
export const serializeQuery = memoize(
query: query.search ? serializeString(query.search) : undefined,
deprecated: query.deprecated || undefined,
internal: query.internal || undefined,
- })
+ }),
);
export function parseVersion(version: string) {
() => ({
project: component?.key,
}),
- [component?.key]
+ [component?.key],
);
const fetchWebhooks = useCallback(async () => {
hasSecret: data.secret === undefined ? webhook.hasSecret : Boolean(data.secret),
url: data.url,
}
- : webhook
- )
+ : webhook,
+ ),
);
}
<p className="spacer-bottom">
{translateWithParameters(
'webhooks.delivery.response_x',
- delivery.httpStatus || translate('webhooks.delivery.server_unreachable')
+ delivery.httpStatus || translate('webhooks.delivery.server_unreachable'),
)}
</p>
<p className="spacer-bottom">
{translateWithParameters(
'webhooks.delivery.duration_x',
- formatMeasure(delivery.durationMs, 'MILLISEC')
+ formatMeasure(delivery.durationMs, 'MILLISEC'),
)}
</p>
<p className="spacer-bottom">{translate('webhooks.delivery.payload')}</p>
it('should not allow webhook creation when too many', async () => {
const { ui } = getPageObject();
webhookService.addWebhook(
- ...Array.from({ length: 8 }).map((_, i) => mockWebhook({ key: `newwebhook${i}` }))
+ ...Array.from({ length: 8 }).map((_, i) => mockWebhook({ key: `newwebhook${i}` })),
);
renderWebhooksApp();
await ui.waitForWebhooksLoaded();
expect(ui.webhookCreateButton.get()).toBeDisabled();
await expect(ui.webhookCreateButton.get()).toHaveATooltipWithContent(
- `webhooks.maximum_reached.${WEBHOOKS_LIMIT}`
+ `webhooks.maximum_reached.${WEBHOOKS_LIMIT}`,
);
});
await ui.toggleDeliveryRow(2);
});
expect(
- screen.getByText('webhooks.delivery.response_x.webhooks.delivery.server_unreachable')
+ screen.getByText('webhooks.delivery.response_x.webhooks.delivery.server_unreachable'),
).toBeInTheDocument();
expect(screen.getByText('webhooks.delivery.duration_x.1s')).toBeInTheDocument();
expect(screen.getByText('{ "id": "global-webhook-1-delivery-1" }')).toBeInTheDocument();
const row = ui.getWebhookRow(rowIndex);
await act(async () => {
await user.click(
- within(row).getByRole('button', { name: `webhooks.show_actions.${webhookName}` })
+ within(row).getByRole('button', { name: `webhooks.show_actions.${webhookName}` }),
);
await user.click(within(row).getByRole('button', { name: actionName }));
});
await user.click(
within(row).getByRole('button', {
name: `webhooks.last_execution.open_for_x.${webhookName}`,
- })
+ }),
);
});
},
checkWebhookRow: (
index: number,
- expected: { name: string; url: string; secret: boolean; lastDeliveryDate?: string }
+ expected: { name: string; url: string; secret: boolean; lastDeliveryDate?: string },
) => {
const row = ui.getWebhookRow(index);
const [name, url, secret, lastDelivery] = within(row).getAllByRole('cell');
expect(lastDelivery).toHaveTextContent(
expected.lastDeliveryDate
? new RegExp(expected.lastDeliveryDate)
- : 'webhooks.last_execution.none'
+ : 'webhooks.last_execution.none',
);
},
if (this.props.onLoaded && this.state.component && this.state.issues) {
this.props.onLoaded(this.state.component, finalSources, this.state.issues);
}
- }
+ },
);
}
}
key: string,
from: number | undefined,
to: number | undefined,
- branchLike: BranchLike | undefined
+ branchLike: BranchLike | undefined,
) {
return getSources({ key, from, to, ...getBranchLikeQuery(branchLike) });
}
if (this.props.onLoaded) {
this.props.onLoaded(component, finalSources, issues);
}
- }
+ },
);
}
},
() => {
/* no op */
- }
+ },
);
};
sourcesRequest.then(
(sources) => loadIssuesCallback(component, sources),
- (response) => onFailLoadSources(response, component)
+ (response) => onFailLoadSources(response, component),
);
};
this.loadComponent(this.props.component, this.props.branchLike).then(
onResolve,
- onFailLoadComponent
+ onFailLoadComponent,
);
}
this.props.component,
from,
firstSourceLine.line - 1,
- this.props.branchLike
+ this.props.branchLike,
).then(
(sources) => {
if (this.mounted) {
},
() => {
/* no op */
- }
+ },
);
};
},
() => {
/* no op */
- }
+ },
);
};
},
() => {
/* no op */
- }
+ },
);
};
handleIssueChange = (issue: Issue) => {
this.setState(({ issues = [] }) => {
const newIssues = issues.map((candidate) =>
- candidate.key === issue.key ? issue : candidate
+ candidate.key === issue.key ? issue : candidate,
);
return { issues: newIssues, issuesByLine: issuesByLine(newIssues) };
highlighted={line.line === highlightedLine}
highlightedLocationMessage={optimizeLocationMessage(
highlightedLocationMessage,
- secondaryIssueLocations
+ secondaryIssueLocations,
)}
highlightedSymbols={optimizeHighlightedSymbols(
symbolsByLine[line.line],
- highlightedSymbols
+ highlightedSymbols,
)}
issueLocations={this.getIssueLocationsForLine(line)}
issues={issuesForLine}
displayIssues,
index,
line: decoratedLinesMap[line.line] || line,
- })
+ }),
)}
</tbody>
</table>
};
const measure = componentMeasures.find(
- (m) => m.metric === ISSUETYPE_METRIC_KEYS_MAP[type].metric
+ (m) => m.metric === ISSUETYPE_METRIC_KEYS_MAP[type].metric,
);
const linkUrl =
const unitTestsOrLines = q === ComponentQualifier.TestFile ? MetricKey.tests : MetricKey.lines;
const query = new URLSearchParams(
- omitNil({ key, ...getBranchLikeQuery(this.props.branchLike) })
+ omitNil({ key, ...getBranchLikeQuery(this.props.branchLike) }),
).toString();
const rawSourcesLink = `${getBaseUrl()}/api/sources/raw?${query}`;
await user.click(
rowScreen.getByRole('button', {
name: 'source_viewer.line_X.1',
- })
+ }),
);
expect(
queryHelpers.queryByAttribute(
'data-clipboard-text',
row,
- 'http://localhost/code?id=foo&selected=foo%3Atest1.js&line=1'
- )
+ 'http://localhost/code?id=foo&selected=foo%3Atest1.js&line=1',
+ ),
).toBeInTheDocument();
await act(async () => {
queryHelpers.queryByAttribute(
'data-clipboard-text',
row,
- 'http://localhost/code?id=foo&selected=foo%3Atest1.js&line=1'
- )
+ 'http://localhost/code?id=foo&selected=foo%3Atest1.js&line=1',
+ ),
).not.toBeInTheDocument();
row = await screen.findByRole('row', { name: / \* 6$/ });
await user.click(
lowerRowScreen.getByRole('button', {
name: 'source_viewer.line_X.6',
- })
+ }),
);
});
expect(
lowerRowScreen.getByRole('menuitem', {
name: 'source_viewer.copy_permalink',
- })
+ }),
).toBeInTheDocument();
});
// Assign issue to a different user
await act(async () => {
await user.click(
- await screen.findByRole('combobox', { name: 'issue.assign.unassigned_click_to_assign' })
+ await screen.findByRole('combobox', { name: 'issue.assign.unassigned_click_to_assign' }),
);
await user.click(screen.getByLabelText('search.search_for_users'));
await user.keyboard('luke');
const firstRowScreen = within(row);
expect(
- firstRowScreen.getByRole('cell', { name: 'stas.vilchik@sonarsource.com' })
+ firstRowScreen.getByRole('cell', { name: 'stas.vilchik@sonarsource.com' }),
).toBeInTheDocument();
await user.click(
firstRowScreen.getByRole('button', {
name: 'source_viewer.author_X.stas.vilchik@sonarsource.com, source_viewer.click_for_scm_info.1',
- })
+ }),
);
// After using miui component the tooltip is appearing outside of the row
const secondRowScreen = within(row);
expect(
- secondRowScreen.queryByRole('cell', { name: 'stas.vilchik@sonarsource.com' })
+ secondRowScreen.queryByRole('cell', { name: 'stas.vilchik@sonarsource.com' }),
).not.toBeInTheDocument();
// SCM with no date
await user.click(
fourthRowScreen.getByRole('button', {
name: 'source_viewer.author_X.stas.vilchik@sonarsource.com, source_viewer.click_for_scm_info.4',
- })
+ }),
);
});
await user.click(
fithRowScreen.getByRole('button', {
name: 'source_viewer.click_for_scm_info.5',
- })
+ }),
);
});
await user.click(
issueRow.getByRole('button', {
name: 'source_viewer.issues_on_line.X_issues_of_type_Y.source_viewer.issues_on_line.show.2.issue.type.BUG.plural',
- })
+ }),
);
});
renderSourceViewer();
const coverdLine = within(
- await screen.findByRole('row', { name: /\* mailto:info AT sonarsource DOT com$/ })
+ await screen.findByRole('row', { name: /\* mailto:info AT sonarsource DOT com$/ }),
);
expect(
- coverdLine.getByLabelText('source_viewer.tooltip.covered.conditions.1')
+ coverdLine.getByLabelText('source_viewer.tooltip.covered.conditions.1'),
).toBeInTheDocument();
const partialyCoveredWithConditionLine = within(
- await screen.findByRole('row', { name: / \* 5$/ })
+ await screen.findByRole('row', { name: / \* 5$/ }),
);
expect(
partialyCoveredWithConditionLine.getByLabelText(
- 'source_viewer.tooltip.partially-covered.conditions.1.2'
- )
+ 'source_viewer.tooltip.partially-covered.conditions.1.2',
+ ),
).toBeInTheDocument();
const partialyCoveredLine = within(await screen.findByRole('row', { name: /\/\*$/ }));
expect(
- partialyCoveredLine.getByLabelText('source_viewer.tooltip.partially-covered')
+ partialyCoveredLine.getByLabelText('source_viewer.tooltip.partially-covered'),
).toBeInTheDocument();
const uncoveredLine = within(await screen.findByRole('row', { name: / \* 6$/ }));
expect(uncoveredLine.getByLabelText('source_viewer.tooltip.uncovered')).toBeInTheDocument();
const uncoveredWithConditionLine = within(
- await screen.findByRole('row', { name: / \* SonarQube$/ })
+ await screen.findByRole('row', { name: / \* SonarQube$/ }),
);
expect(
- uncoveredWithConditionLine.getByLabelText('source_viewer.tooltip.uncovered.conditions.1')
+ uncoveredWithConditionLine.getByLabelText('source_viewer.tooltip.uncovered.conditions.1'),
).toBeInTheDocument();
const coveredWithNoCondition = within(await screen.findByRole('row', { name: /\* Copyright$/ }));
expect(
- coveredWithNoCondition.getByLabelText('source_viewer.tooltip.covered')
+ coveredWithNoCondition.getByLabelText('source_viewer.tooltip.covered'),
).toBeInTheDocument();
});
const duplicateLine = within(await screen.findByRole('row', { name: /\* 7$/ }));
expect(
- duplicateLine.getByLabelText('source_viewer.tooltip.duplicated_block')
+ duplicateLine.getByLabelText('source_viewer.tooltip.duplicated_block'),
).toBeInTheDocument();
await act(async () => {
await user.click(
- duplicateLine.getByRole('button', { name: 'source_viewer.tooltip.duplicated_block' })
+ duplicateLine.getByRole('button', { name: 'source_viewer.tooltip.duplicated_block' }),
);
});
renderSourceViewer();
expect(
- await screen.findByText('code_viewer.no_source_code_displayed_due_to_security')
+ await screen.findByText('code_viewer.no_source_code_displayed_due_to_security'),
).toBeInTheDocument();
});
onLoaded={jest.fn()}
onLocationSelect={jest.fn()}
{...override}
- />
+ />,
);
return function (reoverride?: Partial<Props>) {
onLocationSelect={jest.fn()}
{...override}
{...reoverride}
- />
+ />,
);
};
}
sources={[mockSourceLine(), mockSourceLine(), mockSourceLine()]}
symbolsByLine={{}}
{...props}
- />
+ />,
);
}
duplications = sortBy(
duplications,
(d) => d.file.projectName !== sourceViewerFile.projectName,
- (d) => d.file.key !== sourceViewerFile.key
+ (d) => d.file.key !== sourceViewerFile.key,
);
return (
>
<span>{collapsedDirFromPath(duplication.file.name)}</span>
<span>{fileFromPath(duplication.file.name)}</span>
- </span>
+ </span>,
)}
</div>
)}
{' – '}
{block.from + block.size - 1}
</>,
- block.from
+ block.from,
)}
{index < duplication.blocks.length - 1 && ', '}
</Fragment>
const handleLineMouseEnter = React.useCallback(
() => onLineMouseEnter(line.line),
- [line.line, onLineMouseEnter]
+ [line.line, onLineMouseEnter],
);
const handleLineMouseLeave = React.useCallback(
() => onLineMouseLeave(line.line),
- [line.line, onLineMouseLeave]
+ [line.line, onLineMouseLeave],
);
const { branchLike, file } = useSourceViewerContext();
const permalink = getPathUrlAsString(
getCodeUrl(file.project, branchLike, file.key, line.line),
- false
+ false,
);
const getStatusTooltip = (line: SourceLine) => {
? translateWithParameters(
'source_viewer.tooltip.partially-covered.conditions',
line.coveredConditions ?? 0,
- line.conditions
+ line.conditions,
)
: translate('source_viewer.tooltip.partially-covered');
default:
highlightedSymbols,
issueLocations,
secondaryIssueLocations,
- })
+ }),
)}
</LineCodePreFormatted>
<div ref={this.findingNode}>{children}</div>
if (issueTypes.length > 1) {
tooltipContent = translateWithParameters(
'source_viewer.issues_on_line.multiple_issues',
- tooltipShowHide
+ tooltipShowHide,
);
} else if (issues.length === 1) {
tooltipContent = translateWithParameters(
'source_viewer.issues_on_line.issue_of_type_X',
tooltipShowHide,
- translate('issue.type', mostImportantIssue.type)
+ translate('issue.type', mostImportantIssue.type),
);
} else {
tooltipContent = translateWithParameters(
'source_viewer.issues_on_line.X_issues_of_type_Y',
tooltipShowHide,
issues.length,
- translate('issue.type', mostImportantIssue.type, 'plural')
+ translate('issue.type', mostImportantIssue.type, 'plural'),
);
}
if (line.scmAuthor) {
ariaLabel = `${translateWithParameters(
'source_viewer.author_X',
- line.scmAuthor
+ line.scmAuthor,
)}, ${ariaLabel}`;
}
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
};
...getBranchLikeQuery(this.props.branchLike),
}).then((measures) => {
const withMetrics = enhanceMeasuresWithMetrics(measures, metrics).filter(
- (measure) => measure.metric
+ (measure) => measure.metric,
);
return keyBy(withMetrics, (measure) => measure.metric.key);
});
resolved: 'false',
...getBranchLikeQuery(this.props.branchLike),
},
- ['types', 'severities', 'tags']
+ ['types', 'severities', 'tags'],
).then(({ facets }) => {
const severitiesFacet = facets.find((f) => f.property === 'severities');
const tagsFacet = facets.find((f) => f.property === 'tags');
{formatMeasure(f.count, MetricType.ShortInteger)}
</span>
</div>
- )
+ ),
)}
</div>
)}
{formatMeasure(f.count, MetricType.ShortInteger)}
</span>
</div>
- )
+ ),
)}
</div>
)}
</div>
{sortBy(
measures.filter((measure) => measure.value !== undefined),
- (measure) => getLocalizedMetricName(measure.metric)
+ (measure) => getLocalizedMetricName(measure.metric),
).map((measure) => this.renderMeasure(measure))}
</div>
</div>
<span className="measure-name">
{isMetricKey(measure.metric.key) &&
[MetricKey.bugs, MetricKey.vulnerabilities, MetricKey.code_smells].includes(
- measure.metric.key
+ measure.metric.key,
) && <IssueTypeIcon className="little-spacer-right" query={measure.metric.key} />}
{getLocalizedMetricName(measure.metric)}
</span>
issuePopup={undefined}
issuesForLine={[]}
{...props}
- />
+ />,
);
}
onClose={jest.fn()}
sourceViewerFile={sourceViewerFile}
{...props}
- />
+ />,
);
}
metric: { id: '1', key: 'coverage', name: 'Coverage', type: 'PERCENT' },
value: '72',
}}
- />
- )
+ />,
+ ),
).toMatchSnapshot();
});
metric: { id: '1', key: 'bugs', name: 'Bugs', type: 'INT' },
value: '2',
}}
- />
- )
+ />,
+ ),
).toMatchSnapshot();
});
isDuplicationBlockInRemovedComponent([
{ _ref: '0', from: 2, size: 2 },
{ _ref: '0', from: 3, size: 1 },
- ])
+ ]),
).toBe(false);
expect(
isDuplicationBlockInRemovedComponent([
{ _ref: undefined, from: 2, size: 2 },
{ _ref: '0', from: 3, size: 1 },
- ])
+ ]),
).toBe(true);
});
});
{ from: 3, line: 6, to: 999999 },
{ from: 0, line: 7, to: 999999 },
{ from: 0, line: 8, to: 56 },
- ]
+ ],
);
expect(getLinearLocations({ startLine: 6, startOffset: 0, endLine: 6, endOffset: 42 })).toEqual(
- [{ from: 0, line: 6, to: 42 }]
+ [{ from: 0, line: 6, to: 42 }],
);
});
});
export function getDuplicationBlocksForIndex(
duplications: Duplication[] | undefined,
- index: number
+ index: number,
) {
return (duplications && duplications[index] && duplications[index].blocks) || [];
}
return tokens.map((token) =>
symbolRegExp.test(token.className)
? { ...token, className: `${token.className} highlighted` }
- : token
+ : token,
);
}
tokens: Token[],
issueLocations: LinearIssueLocation[],
modifier: keyof TokenModifiers,
- rootClassName: string = ISSUE_LOCATION_CLASS
+ rootClassName: string = ISSUE_LOCATION_CLASS,
): Token[] {
issueLocations.forEach((location) => {
const nextTokens: Token[] = [];
tokens,
secondaryIssueLocations,
'isLocation',
- 'issue-location'
+ 'issue-location',
);
if (highlightedLocationMessage) {
const location = secondaryIssueLocations.find(
- (location) => location.index === highlightedLocationMessage.index
+ (location) => location.index === highlightedLocationMessage.index,
);
if (location) {
tokens = highlightIssueLocations(tokens, [location], 'isSelected', 'selected');
tokens.map((token) => {
const keys = token.className.match(/sym-\d+/g);
return keys != null ? keys : [];
- })
+ }),
);
index[line.line] = symbols.filter((key) => key);
});
export function getSecondaryIssueLocationsForLine(
line: SourceLine,
- highlightedLocations: (FlowLocation | undefined)[] | undefined
+ highlightedLocations: (FlowLocation | undefined)[] | undefined,
): LinearIssueLocation[] {
if (!highlightedLocations) {
return [];
export function optimizeHighlightedSymbols(
symbolsForLine: string[] = [],
- highlightedSymbols: string[] = []
+ highlightedSymbols: string[] = [],
): string[] | undefined {
const symbols = intersection(symbolsForLine, highlightedSymbols);
export function optimizeLocationMessage(
highlightedLocationMessage: { index: number; text: string | undefined } | undefined,
- optimizedSecondaryIssueLocations: LinearIssueLocation[]
+ optimizedSecondaryIssueLocations: LinearIssueLocation[],
) {
return highlightedLocationMessage != null &&
optimizedSecondaryIssueLocations.some(
- (location) => location.index === highlightedLocationMessage.index
+ (location) => location.index === highlightedLocationMessage.index,
)
? highlightedLocationMessage
: undefined;
p: page,
ps: pageSize,
}).then((r) =>
- r.issues.map((issue) => parseIssueFromResponse(issue, r.components, r.users, r.rules))
+ r.issues.map((issue) => parseIssueFromResponse(issue, r.components, r.users, r.rules)),
);
}
query: RawQuery,
needIssueSync = false,
page = 1,
- pageSize = PAGE_SIZE
+ pageSize = PAGE_SIZE,
): Promise<Issue[]> {
const issues = needIssueSync
? await loadListPage(query, page)
export default function loadIssues(
component: string,
branchLike: BranchLike | undefined,
- needIssueSync = false
+ needIssueSync = false,
): Promise<Issue[]> {
const query = needIssueSync
? buildListQuery(component, branchLike)
return shallow<A11yProvider>(
<A11yProvider>
<div />
- </A11yProvider>
+ </A11yProvider>,
);
}
anchor={link.key}
label={link.label}
removeA11ySkipLink={removeA11ySkipLink}
- />
+ />,
);
expect(wrapper).toMatchSnapshot();
filterSelected = (query: string, selectedElements: string[]) => {
return selectedElements.filter((element) =>
- this.getLocalizedMetricNameFromKey(element).toLowerCase().includes(query.toLowerCase())
+ this.getLocalizedMetricNameFromKey(element).toLowerCase().includes(query.toLowerCase()),
);
};
filterMetricsElements = (
{ metricsTypeFilter, metrics, selectedMetrics }: Props,
- query: string
+ query: string,
) => {
return metrics
.filter((metric) => {
const filteredMetrics = this.filterMetricsElements(this.props, query);
const selectedMetrics = this.getSelectedMetricsElements(
this.props.metrics,
- this.props.selectedMetrics
+ this.props.selectedMetrics,
);
return (
metricsTypeFilter
.map((type: string) => translate('metric.type', type))
.sort((a, b) => a.localeCompare(b))
- .join(', ')
+ .join(', '),
)}
</FlagMessage>
);
props,
<FlagMessage variant="warning">
{translate('project_activity.graphs.data_table.no_data_warning')}
- </FlagMessage>
+ </FlagMessage>,
);
}
- const tableData = series.reduce((acc, serie) => {
- const data = filter(
- serie.data,
- // Make sure we respect the date filtering. On the graph, this is done by dynamically
- // "zooming" on the series. Here, we actually have to "cut off" part of the serie's
- // data points.
- ({ x }) => {
- if (graphEndDate && x > graphEndDate) {
- return false;
+ const tableData = series.reduce(
+ (acc, serie) => {
+ const data = filter(
+ serie.data,
+ // Make sure we respect the date filtering. On the graph, this is done by dynamically
+ // "zooming" on the series. Here, we actually have to "cut off" part of the serie's
+ // data points.
+ ({ x }) => {
+ if (graphEndDate && x > graphEndDate) {
+ return false;
+ }
+ if (graphStartDate && x < graphStartDate) {
+ return false;
+ }
+ return true;
+ },
+ );
+
+ data.forEach(({ x, y }) => {
+ const key = x.getTime();
+ if (acc[key] === undefined) {
+ acc[key] = { date: x } as DataTableEntry;
}
- if (graphStartDate && x < graphStartDate) {
- return false;
- }
- return true;
- }
- );
-
- data.forEach(({ x, y }) => {
- const key = x.getTime();
- if (acc[key] === undefined) {
- acc[key] = { date: x } as DataTableEntry;
- }
- if (y !== undefined && !(typeof y === 'number' && isNaN(y))) {
- acc[key][serie.name] = formatMeasure(y, serie.type);
- }
- });
+ if (y !== undefined && !(typeof y === 'number' && isNaN(y))) {
+ acc[key][serie.name] = formatMeasure(y, serie.type);
+ }
+ });
- return acc;
- }, {} as { [x: number]: DataTableEntry });
+ return acc;
+ },
+ {} as { [x: number]: DataTableEntry },
+ );
const metrics = series.map(({ name }) => name);
const rows = slice(
sortBy(Object.values(tableData), ({ date }) => -date),
0,
- MAX_DATA_TABLE_ROWS
+ MAX_DATA_TABLE_ROWS,
).map(({ date, ...values }) => (
<tr key={date.getTime()}>
<td className="sw-whitespace-nowrap">
<FlagMessage variant="warning">
<FormattedMessage
defaultMessage={translate(
- `project_activity.graphs.data_table.no_data_warning_check_dates${suffix}`
+ `project_activity.graphs.data_table.no_data_warning_check_dates${suffix}`,
)}
id={`project_activity.graphs.data_table.no_data_warning_check_dates${suffix}`}
values={{ start, end }}
/>
- </FlagMessage>
+ </FlagMessage>,
);
}
<FlagMessage variant="warning">
{translateWithParameters(
'project_activity.graphs.data_table.max_lines_warning',
- MAX_DATA_TABLE_ROWS
+ MAX_DATA_TABLE_ROWS,
)}
</FlagMessage>
)}
</thead>
<tbody>{rows}</tbody>
</StyledTable>
- </>
+ </>,
);
}
onUpdateGraph(value);
}
},
- [graph, onUpdateGraph]
+ [graph, onUpdateGraph],
);
const noCustomGraph =
{translate(
isCustom
? 'project_activity.graphs.custom.no_history'
- : 'component_measures.no_history'
+ : 'component_measures.no_history',
)}
</LightLabel>
</div>
'project_activity.graphs.explanation_x',
uniqBy(graphSeries, 'name')
.map(({ translatedName }) => translatedName)
- .join(', ')
+ .join(', '),
)
}
showAreas={showAreas}
}
export default function GraphsTooltipsContentDuplication(
- props: GraphsTooltipsContentDuplicationProps
+ props: GraphsTooltipsContentDuplicationProps,
) {
const { addSeparator, measuresHistory, tooltipIdx } = props;
const duplicationDensity = measuresHistory.find(
- (measure) => measure.metric === MetricKey.duplicated_lines_density
+ (measure) => measure.metric === MetricKey.duplicated_lines_density,
);
if (!duplicationDensity?.history[tooltipIdx]) {
return null;
function renderActivityGraph(
graphsHistoryProps: Partial<GraphsHistory['props']> = {},
- graphsHeaderProps: Partial<ComponentPropsType<typeof GraphsHeader>> = {}
+ graphsHeaderProps: Partial<ComponentPropsType<typeof GraphsHeader>> = {},
) {
function ActivityGraph() {
const [selectedMetrics, setSelectedMetrics] = React.useState<string[]>([]);
});
history.push(
mockHistoryItem({ date: parseDate('2018-10-27T12:21:15+0200') }),
- mockHistoryItem({ date: parseDate('2020-10-27T16:33:50+0200') })
+ mockHistoryItem({ date: parseDate('2020-10-27T16:33:50+0200') }),
);
measuresHistory.push(mockMeasureHistory({ metric, history }));
metrics.push(
mockMetric({
key: metric,
type: metric.includes('_density') || metric === MetricKey.coverage ? 'PERCENT' : 'INT',
- })
+ }),
);
});
// The following should be filtered out, and not be suggested as options.
metrics.push(
mockMetric({ key: MetricKey.new_bugs, type: 'INT' }),
- mockMetric({ key: MetricKey.burned_budget, type: 'DATA' })
+ mockMetric({ key: MetricKey.burned_budget, type: 'DATA' }),
);
// The following will not be filtered out, but has no values.
date.setDate(date.getDate() + i);
return mockHistoryItem({ date, value: undefined });
}),
- })
+ }),
);
const series = generateSeries(
measuresHistory,
graph,
metrics,
- getDisplayedHistoryMetrics(graph, selectedMetrics)
+ getDisplayedHistoryMetrics(graph, selectedMetrics),
);
const graphs = splitSeriesInGraphs(series, MAX_GRAPHS, MAX_SERIES_PER_GRAPH);
const metricsTypeFilter =
it('should render correctly if there are no series', () => {
renderDataTableModal({ series: [] });
expect(
- screen.getByText('project_activity.graphs.data_table.no_data_warning')
+ screen.getByText('project_activity.graphs.data_table.no_data_warning'),
).toBeInTheDocument();
});
it('should render correctly if there is too much data', () => {
renderDataTableModal({ series: mockSeries(MAX_DATA_TABLE_ROWS + 1) });
expect(
- screen.getByText(`project_activity.graphs.data_table.max_lines_warning.${MAX_DATA_TABLE_ROWS}`)
+ screen.getByText(`project_activity.graphs.data_table.max_lines_warning.${MAX_DATA_TABLE_ROWS}`),
).toBeInTheDocument();
});
expect(
screen.getByText('project_activity.graphs.data_table.no_data_warning_check_dates_x', {
exact: false,
- })
+ }),
).toBeInTheDocument();
});
expect(
screen.getByText('project_activity.graphs.data_table.no_data_warning_check_dates_y', {
exact: false,
- })
+ }),
).toBeInTheDocument();
});
expect(
screen.getByText('project_activity.graphs.data_table.no_data_warning_check_dates_x_y', {
exact: false,
- })
+ }),
).toBeInTheDocument();
});
function renderDataTableModal(props: Partial<DataTableModalProps> = {}) {
return renderComponent(
- <DataTableModal analyses={[]} series={mockSeries()} onClose={jest.fn()} {...props} />
+ <DataTableModal analyses={[]} series={mockSeries()} onClose={jest.fn()} {...props} />,
);
}
key: metric,
name: metric,
type: 'INT',
- })
+ }),
);
});
MetricKey.bugs,
MetricKey.code_smells,
MetricKey.vulnerabilities,
- ])
+ ]),
);
}
},
}),
},
- `branch=${branchLike.name}&id=my-project`
+ `branch=${branchLike.name}&id=my-project`,
);
expect(await ui.definitionChangeLabel.find()).toBeInTheDocument();
expect(await ui.projectAddedTxt(branchLike).find()).toBeInTheDocument();
expect(ui.projectLink('Foo').get()).toBeInTheDocument();
expect(screen.getByText('master-foo')).toBeInTheDocument();
- }
+ },
);
it.each([mockMainBranch(), mockBranch()])(
},
}),
},
- `branch=${branchLike.name}&id=my-project`
+ `branch=${branchLike.name}&id=my-project`,
);
expect(ui.definitionChangeLabel.get()).toBeInTheDocument();
expect(await ui.projectRemovedTxt(branchLike).find()).toBeInTheDocument();
expect(ui.projectLink('Bar').get()).toBeInTheDocument();
expect(screen.getByText('master-bar')).toBeInTheDocument();
- }
+ },
);
it('should render correctly for "BRANCH_CHANGED" events', async () => {
return renderAppWithComponentContext(
'/',
() => <Route path="*" element={<EventInner event={mockAnalysisEvent()} {...props} />} />,
- { navigateTo: params ? `/?id=my-project&${params}` : '/?id=my-project' }
+ { navigateTo: params ? `/?id=my-project&${params}` : '/?id=my-project' },
);
}
screen.getByRole('row', {
// eslint-disable-next-line jest/no-conditional-in-test
name: rating ? `${n} ${key} ${rating}` : `${n} ${key}`,
- })
+ }),
).toBeInTheDocument();
});
- }
+ },
);
function renderGraphsTooltips(props: Partial<Props> = {}) {
mockMeasureHistory({
metric,
history: [mockHistoryItem({ date, value })],
- })
+ }),
);
metrics.push(
mockMetric({
key: metric,
type: metric.includes('_density') || metric === MetricKey.coverage ? 'PERCENT' : 'INT',
- })
+ }),
);
});
measuresHistory,
graph,
metrics,
- getDisplayedHistoryMetrics(graph, graph === GraphType.custom ? [MetricKey.bugs] : [])
+ getDisplayedHistoryMetrics(graph, graph === GraphType.custom ? [MetricKey.bugs] : []),
);
return renderComponent(
tooltipPos={0}
formatValue={(n: number | string) => String(n)}
{...props}
- />
+ />,
);
}
utils.generateSeries(HISTORY, GraphType.coverage, METRICS, [
MetricKey.uncovered_lines,
MetricKey.lines_to_cover,
- ])
+ ]),
).toMatchSnapshot();
});
it('should correctly handle non-existent data', () => {
});
it('should return all custom metrics for the custom graph', () => {
expect(utils.getDisplayedHistoryMetrics(GraphType.custom, customMetrics)).toEqual(
- customMetrics
+ customMetrics,
);
});
});
name: 'bar',
translatedName: 'bar',
}),
- ])
+ ]),
).toBe(true);
expect(
utils.hasHistoryData([
translatedName: 'bar',
data: [{ x: dates.parseDate('2017-04-27T08:21:32.000Z'), y: 2 }],
}),
- ])
+ ]),
).toBe(false);
});
});
expect(save).toHaveBeenCalledWith('foo', GraphType.custom, 'bar');
// eslint-disable-next-line jest/no-conditional-in-test
expect(save).toHaveBeenCalledWith('foo.custom', metrics.join(','), 'bar');
- }
+ },
);
});
// eslint-disable-next-line jest/no-conditional-in-test
customGraphs: data ? [MetricKey.bugs, MetricKey.code_smells] : [],
});
- }
+ },
);
it('should correctly retrieve data for unknown graphs', () => {
export function splitSeriesInGraphs(series: Serie[], maxGraph: number, maxSeries: number) {
return flatMap(
groupBy(series, (serie) => serie.type),
- (type) => chunk(type, maxSeries)
+ (type) => chunk(type, maxSeries),
).slice(0, maxGraph);
}
export function generateCoveredLinesMetric(
uncoveredLines: MeasureHistory,
- measuresHistory: MeasureHistory[]
+ measuresHistory: MeasureHistory[],
): Serie {
const linesToCover = measuresHistory.find(
- (measure) => measure.metric === MetricKey.lines_to_cover
+ (measure) => measure.metric === MetricKey.lines_to_cover,
);
return {
measuresHistory: MeasureHistory[],
graph: GraphType,
metrics: Metric[],
- displayedMetrics: string[]
+ displayedMetrics: string[],
): Serie[] {
if (displayedMetrics.length <= 0 || measuresHistory === undefined) {
return [];
}),
(serie) =>
displayedMetrics.indexOf(
- serie.name === 'covered_lines' ? MetricKey.uncovered_lines : serie.name
- )
+ serie.name === 'covered_lines' ? MetricKey.uncovered_lines : serie.name,
+ ),
);
}
namespace: string,
project: string,
graph: GraphType,
- metrics?: string[]
+ metrics?: string[],
) {
save(namespace, graph, project);
export function getActivityGraph(
namespace: string,
- project: string
+ project: string,
): { graph: GraphType; customGraphs: string[] } {
const customGraphs = get(`${namespace}.custom`, project);
this.props.updateTooltip(
selectedDatePos.selectedDate,
selectedDatePos.selectedDateXPos,
- selectedDatePos.selectedDateIdx
+ selectedDatePos.selectedDateIdx,
);
}
}
getYScale = (
props: PropsWithDefaults,
availableHeight: number,
- flatData: Chart.Point[]
+ flatData: Chart.Point[],
): YScale => {
if (props.metricType === MetricType.Rating) {
return this.getRatingScale(availableHeight);
getXScale = (
{ startDate, endDate }: PropsWithDefaults,
availableWidth: number,
- flatData: Chart.Point[]
+ flatData: Chart.Point[],
) => {
const dateRange = extent(flatData, (d) => d.x) as [Date, Date];
const start = startDate && startDate > dateRange[0] ? startDate : dateRange[0];
cx={xScale(point.x)}
cy={yScale(point.y as YPoint)}
fill={themeColor(
- `graphLineColor.${serieIdx}` as Parameters<typeof themeColor>[0]
+ `graphLineColor.${serieIdx}` as Parameters<typeof themeColor>[0],
)({
theme,
})}
/>
);
})
- .filter(isDefined)
+ .filter(isDefined),
)
.filter((dots) => dots.length > 0)}
</g>
.map((d) => getLanguageName(languages, d.language))
.map(cutLanguageName);
const yTooltips = parsedDistribution.map((d) =>
- d.lines > NUMBER_FORMAT_THRESHOLD ? formatMeasure(d.lines, MetricType.Integer) : ''
+ d.lines > NUMBER_FORMAT_THRESHOLD ? formatMeasure(d.lines, MetricType.Integer) : '',
);
const yValues = parsedDistribution.map((d) => formatMeasure(d.lines, MetricType.ShortInteger));
if (newZoomStart != null && overlayLeftPos != null && data.deltaX) {
this.handleZoomUpdate(
xScale,
- sortBy([newZoomStart, Math.max(xDim[0], Math.min(data.x - overlayLeftPos, xDim[1]))])
+ sortBy([newZoomStart, Math.max(xDim[0], Math.min(data.x - overlayLeftPos, xDim[1]))]),
);
}
};
options.fixedPos,
options.xDim,
options.direction,
- true
+ true,
)}
onStop={this.handleSelectionHandleDrag(
options.xScale,
options.fixedPos,
options.xDim,
- options.direction
+ options.direction,
)}
position={{ x: options.xPos, y: 0 }}
>
width={100}
zoomSpeed={1}
{...props}
- />
+ />,
);
}
];
const ticks = ['A', 'B', 'C'];
const chart = shallow(
- <BarChart barsWidth={20} data={data} height={100} width={100} xTicks={ticks} />
+ <BarChart barsWidth={20} data={data} height={100} width={100} xTicks={ticks} />,
);
expect(chart.find('.bar-chart-tick').length).toBe(3);
});
];
const values = ['A', 'B', 'C'];
const chart = shallow(
- <BarChart barsWidth={20} data={data} height={100} width={100} xValues={values} />
+ <BarChart barsWidth={20} data={data} height={100} width={100} xValues={values} />,
);
expect(chart.find('.bar-chart-tick').length).toBe(3);
});
const ticks = ['A', 'B', 'C'];
const values = ['A', 'B', 'C'];
const chart = shallow(
- <BarChart barsWidth={20} data={data} height={100} width={100} xTicks={ticks} xValues={values} />
+ <BarChart
+ barsWidth={20}
+ data={data}
+ height={100}
+ width={100}
+ xTicks={ticks}
+ xValues={values}
+ />,
);
expect(chart.find('.bar-chart-bar').length).toBe(3);
expect(chart.find('.bar-chart-tick').length).toBe(6);
showColorNA
height={20}
width={200}
- />
+ />,
);
expect(wrapper).toMatchSnapshot();
});
thickness={2}
width={20}
{...props}
- />
+ />,
);
}
distribution="java=1734;js=845;cpp=73;<null>=15"
languages={{ java: { key: 'java', name: 'Java' }, js: { key: 'js', name: 'JavaScript' } }}
{...props}
- />
+ />,
);
}
window.open(
`${getBaseUrl()}${getFormattingHelpUrl()}`,
'Formatting',
- 'height=300,width=600,scrollbars=1,resizable=1'
+ 'height=300,width=600,scrollbars=1,resizable=1',
);
}, []);
window.open(
getFormattingHelpUrl(),
'Formatting',
- 'height=300,width=600,scrollbars=1,resizable=1'
+ 'height=300,width=600,scrollbars=1,resizable=1',
);
}
!isEmpty(
xor(
[...prevProps.selectedElements, ...prevProps.elements],
- [...this.props.selectedElements, ...this.props.elements]
- )
+ [...this.props.selectedElements, ...this.props.elements],
+ ),
)
) {
this.computeElements();
handleSelectChange = (selected: boolean, item: string) => {
this.setState(({ elements }) => {
const newElements = elements.map((e) =>
- e.value === item ? { value: e.value, selected } : e
+ e.value === item ? { value: e.value, selected } : e,
);
return { elements: newElements };
});
active: this.props.active === this.props.item,
hover: selected,
},
- this.props.className
+ this.props.className,
)}
onClick={this.handleSelect}
onFocus={this.handleHover}
'small-status-indicator': size === 'small',
'big-status-indicator': size === 'big',
},
- className
+ className,
)}
/>
</>
expect(anchorElement).toBeInTheDocument();
expect(anchorElement).toHaveAttribute(
'href',
- '/project/activity?id=foo&graph=custom&custom_metrics=new_bugs%2Cbugs'
+ '/project/activity?id=foo&graph=custom&custom_metrics=new_bugs%2Cbugs',
);
});
});
function renderAnalysisWarningsModal(
- props: Partial<ComponentPropsType<typeof AnalysisWarningsModal>> = {}
+ props: Partial<ComponentPropsType<typeof AnalysisWarningsModal>> = {},
) {
return renderComponent(
<AnalysisWarningsModal
mockTaskWarning({ message: 'warning 2' }),
]}
{...props}
- />
+ />,
);
}
expect(shallowRender({ noCopy: true })).toMatchSnapshot('no copy');
expect(shallowRender({ snippet: ['foo', 'bar'] })).toMatchSnapshot('array snippet');
expect(shallowRender({ isOneLine: true, snippet: ['foo', 'bar'] })).toMatchSnapshot(
- 'single line with array snippet'
+ 'single line with array snippet',
);
});
expect(shallowRender()).toMatchSnapshot('default');
expect(shallowRender({ option: { value: 'baz' } })).toMatchSnapshot('no label');
expect(
- shallowRender({ option: { label: 'Bar', value: 'bar', isDisabled: true } })
+ shallowRender({ option: { label: 'Bar', value: 'bar', isDisabled: true } }),
).toMatchSnapshot('disabled');
expect(
shallowRender({
option: { label: 'Bar', value: 'bar', isDisabled: true },
disabledReason: 'bar baz',
- })
+ }),
).toMatchSnapshot('disabled, with explanation');
});
option={{ label: 'Foo', value: 'foo' }}
disableTooltipOverlay={() => 'foo bar'}
{...props}
- />
+ />,
);
}
<Link to="/" target="_blank">
Interactive element after
</Link>
- </>
+ </>,
);
}
function shallowRender(
children: (msg: string) => React.ReactChild,
message: string,
- onSonarCloud = false
+ onSonarCloud = false,
) {
(getInstance as jest.Mock).mockImplementation(() => (onSonarCloud ? 'SonarCloud' : 'SonarQube'));
return shallow(<InstanceMessage message={message}>{children}</InstanceMessage>);
renderLink({ target: '_blank', to: 'http://example.com' });
expect(screen.getByRole('link', { name: 'opens_in_new_window click me' })).toHaveAttribute(
'rel',
- 'noopener noreferrer'
+ 'noopener noreferrer',
);
});
return renderComponent(
<Link to={{ pathname: 'to' }} {...props}>
click me
- </Link>
+ </Link>,
);
}
function shallowRender(props: Partial<PageCounterProps> = {}) {
return shallow<PageCounterProps>(
- <PageCounter label="label" current={123} total={1234} {...props} />
+ <PageCounter label="label" current={123} total={1234} {...props} />,
);
}
qualifier={ComponentQualifier.Project}
visibility={Visibility.Private}
{...props}
- />
+ />,
);
}
expect(shallowRender()).toMatchSnapshot('default');
expect(shallowRender({ projectKey: 'foo' })).toMatchSnapshot('with value');
expect(
- shallowRender({ help: 'foo.help', label: 'foo.label', placeholder: 'foo.placeholder' })
+ shallowRender({ help: 'foo.help', label: 'foo.label', placeholder: 'foo.placeholder' }),
).toMatchSnapshot('with label, help, and placeholder');
expect(shallowRender({ touched: true })).toMatchSnapshot('valid');
expect(shallowRender({ touched: true, error: 'bar.baz' })).toMatchSnapshot('invalid');
function shallowRender(props: Partial<ProjectKeyInputProps> = {}) {
return shallow<ProjectKeyInputProps>(
- <ProjectKeyInput onProjectKeyChange={jest.fn()} touched={false} {...props} />
+ <ProjectKeyInput onProjectKeyChange={jest.fn()} touched={false} {...props} />,
);
}
{...props}
>
{children}
- </SelectList>
+ </SelectList>,
);
}
<SelectListItem active="myitem" item="seconditem">
<i className="custom-icon" />
<p>seconditem</p>
- </SelectListItem>
- )
+ </SelectListItem>,
+ ),
).toMatchSnapshot();
});
className={classNames(
'link-no-underline',
{ 'cursor-not-allowed': this.props.disabled },
- this.props.className
+ this.props.className,
)}
href="#"
onClick={this.handleClick}
height: 10px;
border: 1px solid var(--darkBlue);
border-radius: 2px;
- transition: border-color 0.2s ease, background-color 0.2s ease, background-image 0.2s ease,
+ transition:
+ border-color 0.2s ease,
+ background-color 0.2s ease,
+ background-image 0.2s ease,
box-shadow 0.4s ease;
}
: 'component_report.unsubscribe_x_success';
const frequencyTranslation = translate(
'report.frequency',
- status?.componentFrequency || status?.globalFrequency || ''
+ status?.componentFrequency || status?.globalFrequency || '',
).toLowerCase();
const qualifierTranslation = translate('qualifier', component.qualifier).toLowerCase();
addGlobalSuccessMessage(
- translateWithParameters(translationKey, frequencyTranslation, qualifierTranslation)
+ translateWithParameters(translationKey, frequencyTranslation, qualifierTranslation),
);
this.loadReportStatus();
<ButtonSecondary>
{translateWithParameters(
'component_report.report',
- translate('qualifier', component.qualifier)
+ translate('qualifier', component.qualifier),
)}
<ChevronDownIcon className="sw-ml-1" />
</ButtonSecondary>
<a download={downloadName} href={reportUrl} target="_blank" rel="noopener noreferrer">
{translateWithParameters(
'component_report.download',
- translate('qualifier', component.qualifier).toLowerCase()
+ translate('qualifier', component.qualifier).toLowerCase(),
)}
</a>
);
},
() => {
/* noop */
- }
+ },
);
}
this.props.onClose();
return React.createElement(
this.props.tagName || 'div',
{ className: classNames('dropdown', this.props.className) },
- toggler
+ toggler,
);
}
}
className={classNames(
'identity-provider-link',
{ 'dark-text': !isDarkColor(backgroundColor), small },
- className
+ className,
)}
href={url}
onClick={onClick}
disabled: loading,
onClick: props.reload,
} as Button['props'],
- translate('reload')
+ translate('reload'),
);
} else if (hasMore && props.loadMore) {
button = React.createElement(
disabled: loading,
onClick: onLoadMore,
} as Button['props'],
- translate('show_more')
+ translate('show_more'),
);
}
'list-footer', // .list-footer is only used by Selenium tests; we should find a way to remove it.
'sw-body-sm sw-mt-4 sw-flex sw-items-center sw-justify-center',
{ 'sw-opacity-50 sw-duration-500 sw-ease-in-out': !ready },
- className
+ className,
)}
>
<span aria-live="polite" aria-busy={loading}>
? translateWithParameters(
'x_of_y_shown',
formatMeasure(count, MetricType.Integer, null),
- formatMeasure(total, MetricType.Integer, null)
+ formatMeasure(total, MetricType.Integer, null),
)
: translateWithParameters('x_show', formatMeasure(count, MetricType.Integer, null))}
</span>
alignLabel ? 'display-inline-flex-start' : 'display-inline-flex-center',
'link-radio',
className,
- { disabled }
+ { disabled },
)}
href="#"
onClick={this.handleClick}
disabled,
selected,
},
- className
+ className,
)}
onClick={isActionable && !disabled && !selected ? onClick : undefined}
role="radio"
}
.search-box-clear.button:focus {
- box-shadow: 0 0 0 1px white, 0 0 0 4px rgba(35, 106, 151, 0.5);
+ box-shadow:
+ 0 0 0 1px white,
+ 0 0 0 4px rgba(35, 106, 151, 0.5);
}
.search-box-input-note {
export function dropdownIndicator<
Option = LabelValueSelectOption,
IsMulti extends boolean = boolean,
- Group extends GroupBase<Option> = GroupBase<Option>
+ Group extends GroupBase<Option> = GroupBase<Option>,
>({ innerProps }: DropdownIndicatorProps<Option, IsMulti, Group>) {
return <ArrowSpan {...innerProps} />;
}
export function clearIndicator<
Option = LabelValueSelectOption,
IsMulti extends boolean = boolean,
- Group extends GroupBase<Option> = GroupBase<Option>
+ Group extends GroupBase<Option> = GroupBase<Option>,
>(props: ClearIndicatorProps<Option, IsMulti, Group>) {
const { innerProps } = props;
return (
export function loadingIndicator<
Option = LabelValueSelectOption,
IsMulti extends boolean = boolean,
- Group extends GroupBase<Option> = GroupBase<Option>
+ Group extends GroupBase<Option> = GroupBase<Option>,
>({ innerProps }: LoadingIndicatorProps<Option, IsMulti, Group>) {
return <i className={classNames('spinner spacer-left spacer-right', innerProps.className)} />;
}
export function multiValueRemove<
Option = LabelValueSelectOption,
IsMulti extends boolean = boolean,
- Group extends GroupBase<Option> = GroupBase<Option>
+ Group extends GroupBase<Option> = GroupBase<Option>,
>(props: MultiValueRemoveProps<Option, IsMulti, Group>) {
return <components.MultiValueRemove {...props}>×</components.MultiValueRemove>;
}
export default class Select<
Option = LabelValueSelectOption,
IsMulti extends boolean = boolean,
- Group extends GroupBase<Option> = GroupBase<Option>
+ Group extends GroupBase<Option> = GroupBase<Option>,
> extends React.Component<NamedProps<Option, IsMulti, Group> & StyleExtensionProps> {
render() {
return (
export function CreatableSelect<
Option = LabelValueSelectOption,
IsMulti extends boolean = boolean,
- Group extends GroupBase<Option> = GroupBase<Option>
+ Group extends GroupBase<Option> = GroupBase<Option>,
>(props: AsyncCreatableProps<Option, IsMulti, Group>) {
return (
<AsyncCreatableReactSelect<Option, IsMulti, Group>
export function SearchSelect<
Option = LabelValueSelectOption,
IsMulti extends boolean = boolean,
- Group extends GroupBase<Option> = GroupBase<Option>
+ Group extends GroupBase<Option> = GroupBase<Option>,
>(
props: NamedProps<Option, IsMulti, Group> &
AsyncProps<Option, IsMulti, Group> &
- StyleExtensionProps
+ StyleExtensionProps,
) {
return (
<AsyncReactSelect<Option, IsMulti, Group>
export function selectStyle<
Option = LabelValueSelectOption,
IsMulti extends boolean = boolean,
- Group extends GroupBase<Option> = GroupBase<Option>
+ Group extends GroupBase<Option> = GroupBase<Option>,
>(
props?: NamedProps<Option, IsMulti, Group> &
AsyncProps<Option, IsMulti, Group> &
- StyleExtensionProps
+ StyleExtensionProps,
): StylesConfig<Option, IsMulti, Group> {
return {
container: () => ({
})
.then(this.stopLoading)
.catch(this.stopLoading);
- }
+ },
);
changeFilter = (filter: SelectListFilter) => this.search({ filter, page: 1 });
border-radius: 22px;
box-sizing: border-box;
background-color: #f6f6f6;
- transition: transform 0.3s cubic-bezier(0.87, -0.41, 0.19, 1.44), border 0.3s ease;
+ transition:
+ transform 0.3s cubic-bezier(0.87, -0.41, 0.19, 1.44),
+ border 0.3s ease;
}
.boolean-toggle-handle > * {
adjustArrowPosition = (
placement: Placement,
- { leftFix, topFix }: { leftFix: number; topFix: number }
+ { leftFix, topFix }: { leftFix: number; topFix: number },
) => {
switch (placement) {
case 'left':
};
handleMouseEnter = () => {
- this.mouseEnterTimeout = window.setTimeout(() => {
- // For some reason, even after the `this.mouseEnterTimeout` is cleared, it still
- // triggers. To workaround this issue, check that its value is not `undefined`
- // (if it's `undefined`, it means the timer has been reset).
- if (
- this.mounted &&
- this.props.visible === undefined &&
- this.mouseEnterTimeout !== undefined
- ) {
- this.setState({ visible: true });
- }
- }, (this.props.mouseEnterDelay || 0) * 1000);
+ this.mouseEnterTimeout = window.setTimeout(
+ () => {
+ // For some reason, even after the `this.mouseEnterTimeout` is cleared, it still
+ // triggers. To workaround this issue, check that its value is not `undefined`
+ // (if it's `undefined`, it means the timer has been reset).
+ if (
+ this.mounted &&
+ this.props.visible === undefined &&
+ this.mouseEnterTimeout !== undefined
+ ) {
+ this.setState({ visible: true });
+ }
+ },
+ (this.props.mouseEnterDelay || 0) * 1000,
+ );
if (this.props.onShow) {
this.props.onShow();
}
if (!this.mouseIn) {
- this.mouseLeaveTimeout = window.setTimeout(() => {
- if (this.mounted && this.props.visible === undefined && !this.mouseIn) {
- this.setState({ visible: false });
- }
- if (this.props.onHide && !this.mouseIn) {
- this.props.onHide();
- }
- }, (this.props.mouseLeaveDelay || 0) * 1000);
+ this.mouseLeaveTimeout = window.setTimeout(
+ () => {
+ if (this.mounted && this.props.visible === undefined && !this.mouseIn) {
+ this.setState({ visible: false });
+ }
+ if (this.props.onHide && !this.mouseIn) {
+ this.props.onHide();
+ }
+ },
+ (this.props.mouseLeaveDelay || 0) * 1000,
+ );
}
};
// position (which is no longer correct).
this.positionTooltip();
}
- }
+ },
);
}, 1);
return null;
{...props}
>
<span>Hello world</span>
- </ActionsDropdown>
+ </ActionsDropdown>,
);
}
});
]}
value="two"
{...props}
- />
+ />,
);
}
Click me
</button>
</ClickEventBoundary>
- </div>
+ </div>,
);
}
getReportStatus: jest
.fn()
.mockResolvedValue(
- jest.requireActual('../../../helpers/mocks/component-report').mockComponentReportStatus()
+ jest.requireActual('../../../helpers/mocks/component-report').mockComponentReportStatus(),
),
subscribeToEmailReport: jest.fn().mockResolvedValue(undefined),
unsubscribeFromEmailReport: jest.fn().mockResolvedValue(undefined),
.mocked(getReportStatus)
.mockResolvedValueOnce(mockComponentReportStatus({ globalFrequency: 'monthly' }))
.mockResolvedValueOnce(
- mockComponentReportStatus({ subscribed: true, globalFrequency: 'monthly' })
+ mockComponentReportStatus({ subscribed: true, globalFrequency: 'monthly' }),
);
const user = userEvent.setup();
await user.click(button);
const unsubscribeButton = screen.getByText(
- 'component_report.unsubscribe_x.report.frequency.monthly'
+ 'component_report.unsubscribe_x.report.frequency.monthly',
);
expect(unsubscribeButton).toBeInTheDocument();
expect(unsubscribeFromEmailReport).toHaveBeenCalledWith(component.key, branch.name);
expect(screen.getByRole('status')).toHaveTextContent(
- 'component_report.subscribe_x_s...component_report.unsubscribe_x...'
+ 'component_report.subscribe_x_s...component_report.unsubscribe_x...',
);
});
await user.click(
await screen.findByRole('button', {
name: 'component_report.report.qualifier.TRK',
- })
+ }),
);
const subscribeButton = screen.getByText('component_report.no_email_to_subscribe');
component={mockComponent()}
currentUser={mockCurrentUser()}
{...props}
- />
+ />,
);
}
it('should display a confirm modal', () => {
expect(
- shallowRender().find('ModalButton').prop<Function>('modal')({ onClose: jest.fn() })
+ shallowRender().find('ModalButton').prop<Function>('modal')({ onClose: jest.fn() }),
).toMatchSnapshot();
});
onConfirm={jest.fn()}
>
{() => 'Confirm button'}
- </ConfirmButton>
+ </ConfirmButton>,
);
}
onConfirm={jest.fn()}
>
<p>My confirm message</p>
- </ConfirmModal>
+ </ConfirmModal>,
);
expect(wrapper).toMatchSnapshot();
expect(wrapper.find('SimpleModal').dive()).toMatchSnapshot();
onConfirm={onConfirm}
>
<p>My confirm message</p>
- </ConfirmModal>
+ </ConfirmModal>,
);
const modalContent = wrapper.find('SimpleModal').dive();
submit(modalContent.find('form'));
onChange={jest.fn()}
placeholder="placeholder"
{...props}
- />
+ />,
);
const instance = wrapper.instance();
return { wrapper, instance };
it('should render', () => {
expect(
- shallow(<DateRangeInput onChange={jest.fn()} value={{ from: dateA, to: dateB }} />)
+ shallow(<DateRangeInput onChange={jest.fn()} value={{ from: dateA, to: dateB }} />),
).toMatchSnapshot();
expect(
- shallow(<DateRangeInput onChange={jest.fn()} minDate={dateA} maxDate={dateB} />)
+ shallow(<DateRangeInput onChange={jest.fn()} minDate={dateA} maxDate={dateB} />),
).toMatchSnapshot('with min/max');
expect(
minDate={dateA}
maxDate={dateB}
value={{ from: dateA, to: dateB }}
- />
- )
+ />,
+ ),
).toMatchSnapshot('with min/max and value');
});
expect(
shallow(<Dropdown overlay={<div id="overlay" />}>{() => <div />}</Dropdown>)
.find('div')
- .exists()
+ .exists(),
).toBe(true);
});
shallow(
<Dropdown overlay={<div id="overlay" />}>
<Button />
- </Dropdown>
- )
+ </Dropdown>,
+ ),
);
checkToggle(
shallow(
<Dropdown overlay={<div id="overlay" />}>
<a href="#">click me!</a>
- </Dropdown>
+ </Dropdown>,
),
- 'a'
+ 'a',
);
});
shallow(
<Dropdown overlay={<div id="overlay" />}>
{({ onToggleClick }) => <Button onClick={onToggleClick} />}
- </Dropdown>
- )
+ </Dropdown>,
+ ),
);
});
const wrapper = mount(
<Dropdown onOpen={onOpen} overlay={<div id="overlay" />}>
<Button />
- </Dropdown>
+ </Dropdown>,
);
expect(onOpen).not.toHaveBeenCalled();
click(wrapper.find('Button'));
<div />
</DropdownOverlay>,
// disable ScreenPositionFixer positioning
- { disableLifecycleMethods: true }
+ { disableLifecycleMethods: true },
);
expect(wrapper.is(ScreenPositionFixer)).toBe(true);
const wrapper = shallow(
<DropdownOverlay placement={PopupPlacement.BottomRight}>
<div />
- </DropdownOverlay>
+ </DropdownOverlay>,
);
expect(wrapper.is('Popup')).toBe(true);
});
function renderFavorite(props: Partial<Favorite['props']> = {}) {
return renderComponent(
- <Favorite component="foo" favorite qualifier={ComponentQualifier.Project} {...props} />
+ <Favorite component="foo" favorite qualifier={ComponentQualifier.Project} {...props} />,
);
}
currentUser={mockLoggedInUser()}
updateCurrentUserHomepage={jest.fn()}
{...props}
- />
+ />,
);
}
url="/url/foo/bar"
>
Link text
- </IdentityProviderLink>
- )
+ </IdentityProviderLink>,
+ ),
).toMatchSnapshot();
});
touched
value="foo"
{...props}
- />
+ />,
);
}
}
/* eslint-enable jest/no-conditional-in-test */
/* eslint-enable jest/no-conditional-expect */
- }
+ },
);
});
}
/* eslint-enable jest/no-conditional-in-test */
/* eslint-enable jest/no-conditional-expect */
- }
+ },
);
});
function renderListFooter(props: Partial<ListFooterProps> = {}) {
return renderComponent(
- <ListFooter count={3} loadMore={jest.fn()} total={5} useMIUIButtons {...props} />
+ <ListFooter count={3} loadMore={jest.fn()} total={5} useMIUIButtons {...props} />,
);
}
});
const wrapper = shallow(
<ModalButton modal={({ onClose }) => <button id="js-close" onClick={onClose} type="button" />}>
{({ onClick }) => <button id="js-open" onClick={onClick} type="button" />}
- </ModalButton>
+ </ModalButton>,
);
expect(wrapper.find('#js-open').exists()).toBe(true);
{...props}
>
{({ className }) => <input className={className} type="text" />}
- </ModalValidationField>
+ </ModalValidationField>,
);
}
shallow(
<RadioCard recommended="Recommended for you" title="Radio Card" titleInfo="info">
<div>content</div>
- </RadioCard>
- )
+ </RadioCard>,
+ ),
).toMatchSnapshot();
expect(
vertical
>
<div>content</div>
- </RadioCard>
- )
+ </RadioCard>,
+ ),
).toMatchSnapshot();
});
const wrapper = shallow(
<RadioCard onClick={onClick} title="Radio Card">
<div>content</div>
- </RadioCard>
+ </RadioCard>,
);
expect(wrapper).toMatchSnapshot();
onChange={jest.fn()}
placeholder="placeholder"
value="foo"
- />
+ />,
);
expect(wrapper).toMatchSnapshot();
});
it('warns when input is too short', () => {
const wrapper = shallow(
- <SearchBox minLength={2} onChange={jest.fn()} placeholder="placeholder" value="f" />
+ <SearchBox minLength={2} onChange={jest.fn()} placeholder="placeholder" value="f" />,
);
expect(wrapper.find('.search-box-note').exists()).toBe(true);
});
it('does not change when value is too short', () => {
const onChange = jest.fn();
const wrapper = shallow(
- <SearchBox minLength={3} onChange={onChange} placeholder="placeholder" value="" />
+ <SearchBox minLength={3} onChange={onChange} placeholder="placeholder" value="" />,
);
change(wrapper.find('.search-box-input'), 'fo');
expect(onChange).not.toHaveBeenCalled();
components: {
Input: inputRenderer,
},
- })
+ }),
).toMatchSnapshot('other props');
});
it('should render dropdownIndicator correctly', () => {
expect(
- dropdownIndicator(mockReactSelectDropdownIndicatorProps({ value: '' }))
+ dropdownIndicator(mockReactSelectDropdownIndicatorProps({ value: '' })),
).toMatchSnapshot();
});
loadingIndicator({ innerProps: { className: 'additional-class' } } as LoadingIndicatorProps<
{},
false
- >)
+ >),
).toMatchSnapshot();
});
function shallowRender<
Option = unknown,
IsMulti extends boolean = boolean,
- Group extends GroupBase<Option> = GroupBase<Option>
+ Group extends GroupBase<Option> = GroupBase<Option>,
>(props: Partial<ReactSelectProps<Option, IsMulti, Group>> = {}) {
return shallow<ReactSelectProps<Option, IsMulti, Group>>(<Select {...props} />);
}
expect(
shallow(<Component />)
.dive()
- .dive()
+ .dive(),
).toMatchSnapshot();
});
renderElement={(foo: string) => foo}
selectedElements={selectedElements}
{...props}
- />
+ />,
);
}
renderElement={(foo: string) => foo}
selectedElements={['foo']}
{...props}
- />
+ />,
);
}
renderElement={(foo: string) => foo}
selected={false}
{...props}
- />
+ />,
);
}
return shallow<SimpleModal>(
<SimpleModal header="" onClose={jest.fn()} onSubmit={jest.fn()} {...props}>
{children}
- </SimpleModal>
+ </SimpleModal>,
);
}
<>
<textarea name="test-area" />
<button type="button">last</button>
- </>
+ </>,
);
await openToggler(user);
<TooltipInner overlay={<span id="overlay" />} visible>
<div id="tooltip" />
</TooltipInner>,
- { disableLifecycleMethods: true }
- )
+ { disableLifecycleMethods: true },
+ ),
).toMatchSnapshot();
});
return shallow<TooltipProps>(
<Tooltip overlay={undefined}>
<div id="tooltip" />
- </Tooltip>
+ </Tooltip>,
);
}
return shallow<TooltipInner>(
<TooltipInner overlay={<span id="overlay" />} {...props}>
<div id="tooltip" />
- </TooltipInner>
+ </TooltipInner>,
);
}
const wrapper = shallow(
<ValidationForm initialValues={{ foo: 'bar' }} onSubmit={onSubmit} validate={jest.fn()}>
{render}
- </ValidationForm>
+ </ValidationForm>,
);
expect(wrapper).toMatchSnapshot();
wrapper.dive();
expect(render).toHaveBeenCalledWith(
- expect.objectContaining({ dirty: false, errors: {}, values: { foo: 'bar' } })
+ expect.objectContaining({ dirty: false, errors: {}, values: { foo: 'bar' } }),
);
onSubmit.mockResolvedValue(undefined).mockClear();
isInvalid: true,
isValid: false,
required: false,
- })
+ }),
).toMatchSnapshot('with error');
expect(
shallowRender({
errorPlacement: ValidationInputErrorPlacement.Bottom,
isInvalid: true,
isValid: false,
- })
+ }),
).toMatchSnapshot('error under the input');
expect(shallowRender({ labelHtmlFor: undefined, label: undefined })).toMatchSnapshot('no label');
});
{...props}
>
<div />
- </ValidationInput>
+ </ValidationInput>,
);
}
value={props.values.field}
/>
)}
- </ValidationModal>
+ </ValidationModal>,
);
}
return shallow(
<ButtonIcon tooltip="my tooltip" tooltipProps={{ visible: true }} {...props}>
<i />
- </ButtonIcon>
+ </ButtonIcon>,
);
}
});
{copySuccess ? 'copied' : 'click to copy'}
</span>
)}
- </ClipboardBase>
+ </ClipboardBase>,
);
}
});
font-size: var(--smallFontSize);
text-decoration: none;
cursor: pointer;
- transition: border-color 0.2s ease, box-shadow 0.2s ease, background-color 0.2s ease;
+ transition:
+ border-color 0.2s ease,
+ box-shadow 0.2s ease,
+ background-color 0.2s ease;
}
.button:hover,
border-bottom: 1px solid var(--primarya40);
font-weight: 400;
font-size: inherit;
- transition: border-color 0.2s ease, box-shadow 0.2s ease, color 0.2s ease, border-bottom 0.2s ease;
+ transition:
+ border-color 0.2s ease,
+ box-shadow 0.2s ease,
+ color 0.2s ease,
+ border-bottom 0.2s ease;
}
.dropdown .button-link {
}
function singleValueRenderer(
- props: SingleValueProps<LabelValueSelectOption<AlmSettingsInstance>, false>
+ props: SingleValueProps<LabelValueSelectOption<AlmSettingsInstance>, false>,
) {
return (
<components.SingleValue {...props}>{customOptions(props.data.value)}</components.SingleValue>
const { values } = this.props;
if (multiple) {
const newValue = sortBy(
- values.includes(itemValue) ? without(values, itemValue) : [...values, itemValue]
+ values.includes(itemValue) ? without(values, itemValue) : [...values, itemValue],
);
this.props.onChange({ [this.props.property]: newValue });
} else {
: sortBy(
Object.keys(stats),
(key) => -stats[key],
- (key) => this.props.getFacetItemText(key)
+ (key) => this.props.getFacetItemText(key),
);
const limitedList = this.state.showFullList
{translate(
isOnMac()
? 'shortcuts.section.global.facets.multiselection.mac'
- : 'shortcuts.section.global.facets.multiselection'
+ : 'shortcuts.section.global.facets.multiselection',
)}
</div>
</div>
it('should correctly render a header with helper text', async () => {
renderFacet(undefined, { helper: 'Help text' });
await expect(screen.getByRole('img', { description: 'Help text' })).toHaveATooltipWithContent(
- 'Help text'
+ 'Help text',
);
});
function renderFacet(
facetBoxProps: Partial<FacetBoxProps> = {},
facetHeaderProps: Partial<FacetHeader['props']> = {},
- facetItemProps: Partial<FacetItem['props']> = {}
+ facetItemProps: Partial<FacetItem['props']> = {},
) {
function Facet() {
const [open, setOpen] = React.useState(facetHeaderProps.open ?? false);
stats={{ a: 10, b: 8, c: 1 }}
values={[]}
{...props}
- />
+ />,
);
}
it('should not render "show more"', () => {
expect(
- shallow(<ListStyleFacetFooter count={3} showLess={undefined} showMore={jest.fn()} total={3} />)
+ shallow(<ListStyleFacetFooter count={3} showLess={undefined} showMore={jest.fn()} total={3} />),
).toMatchSnapshot();
});
it('should show more', () => {
const showMore = jest.fn();
const wrapper = shallow(
- <ListStyleFacetFooter count={3} showLess={undefined} showMore={showMore} total={15} />
+ <ListStyleFacetFooter count={3} showLess={undefined} showMore={showMore} total={15} />,
);
expect(wrapper).toMatchSnapshot();
click(wrapper.find(ButtonLink));
it('should show less', () => {
const showLess = jest.fn();
const wrapper = shallow(
- <ListStyleFacetFooter count={15} showLess={showLess} showMore={jest.fn()} total={15} />
+ <ListStyleFacetFooter count={15} showLess={showLess} showMore={jest.fn()} total={15} />,
);
expect(wrapper).toMatchSnapshot();
click(wrapper.find(ButtonLink));
it('should not render "show less"', () => {
const wrapper = shallow(
- <ListStyleFacetFooter count={15} showLess={undefined} showMore={jest.fn()} total={15} />
+ <ListStyleFacetFooter count={15} showLess={undefined} showMore={jest.fn()} total={15} />,
);
expect(wrapper).toMatchSnapshot();
});
}}
>
<UnderTest />
- </CurrentUserContext.Provider>
+ </CurrentUserContext.Provider>,
);
}
}}
>
<TestComponentWithIndexationContext />
- </IndexationContext.Provider>
+ </IndexationContext.Provider>,
);
}
it('should render indexation message when showIndexationMessage returns true', () => {
renderComponentWithIndexationGuard(() => true);
expect(
- screen.getByText(/indexation\.page_unavailable\.description\.additional_information/)
+ screen.getByText(/indexation\.page_unavailable\.description\.additional_information/),
).toBeInTheDocument();
});
}}
>
<TestComponentWithGuard />
- </IndexationContext.Provider>
+ </IndexationContext.Provider>,
);
}
onHighlight,
onSelect,
selected: COMPONENTS[1],
- })
+ }),
);
keydown({ key: KeyboardKeys.DownArrow });
applyProps({
onEndOfList,
onHighlight,
- })
+ }),
);
keydown({ key: KeyboardKeys.DownArrow });
onHighlight,
onSelect,
selected: COMPONENTS[1],
- })
+ }),
);
expect(onHighlight).not.toHaveBeenCalled();
},
],
perProjectTypes: ['type-common'],
- })
+ }),
),
removeNotification: jest.fn().mockResolvedValue({}),
}));
*/
export function getWrappedDisplayName<P>(
WrappedComponent: React.ComponentType<P>,
- hocName: string
+ hocName: string,
) {
const wrappedDisplayName = WrappedComponent.displayName ?? WrappedComponent.name ?? 'Component';
return `${hocName}(${wrappedDisplayName})`;
import { getWrappedDisplayName } from './utils';
export function withCLanguageFeature<P>(
- WrappedComponent: React.ComponentType<P & { hasCLanguageFeature: boolean }>
+ WrappedComponent: React.ComponentType<P & { hasCLanguageFeature: boolean }>,
) {
class Wrapper extends React.Component<Omit<P, 'hasCLanguageFeature'>> {
static displayName = getWrappedDisplayName(WrappedComponent, 'withCLanguageFeature');
}
export default function withIndexationContext<P>(
- WrappedComponent: React.ComponentType<P & WithIndexationContextProps>
+ WrappedComponent: React.ComponentType<P & WithIndexationContextProps>,
) {
return class WithIndexationContext extends React.PureComponent<
Omit<P, keyof WithIndexationContextProps>
}
export default function withKeyboardNavigation<P>(
- WrappedComponent: React.ComponentType<P & Partial<WithKeyboardNavigationProps>>
+ WrappedComponent: React.ComponentType<P & Partial<WithKeyboardNavigationProps>>,
) {
return class Wrapper extends React.Component<P & WithKeyboardNavigationProps> {
static displayName = getWrappedDisplayName(WrappedComponent, 'withKeyboardNavigation');
return selected
? components.findIndex(
(component) =>
- getComponentMeasureUniqueKey(component) === getComponentMeasureUniqueKey(selected)
+ getComponentMeasureUniqueKey(component) === getComponentMeasureUniqueKey(selected),
)
: -1;
};
const first = cycle ? 0 : index;
this.props.onHighlight(
- index < components.length - 1 ? components[index + 1] : components[first]
+ index < components.length - 1 ? components[index + 1] : components[first],
);
if (index + 1 === components.length - 1 && this.props.onEndOfList) {
import { Location, useLocation } from 'react-router-dom';
export default function withLocation<P>(
- WrappedComponent: React.ComponentType<P & { location: Location }>
+ WrappedComponent: React.ComponentType<P & { location: Location }>,
) {
return function WithLocation(props: Omit<P, 'location'>) {
const location = useLocation();
}
export function withNotifications<P>(
- WrappedComponent: React.ComponentType<P & WithNotificationsProps>
+ WrappedComponent: React.ComponentType<P & WithNotificationsProps>,
) {
class Wrapper extends React.Component<P, State> {
mounted = false;
if (this.mounted) {
this.setState({ loading: false });
}
- }
+ },
);
};
removeNotificationFromState = (removed: Notification) => {
this.setState((state) => {
const notifications = state.notifications.filter(
- (notification) => !this.areNotificationsEqual(notification, removed)
+ (notification) => !this.areNotificationsEqual(notification, removed),
);
return { notifications };
});
}
export function withRouter<P extends Partial<WithRouterProps>>(
- WrappedComponent: React.ComponentType<P>
+ WrappedComponent: React.ComponentType<P>,
): React.ComponentType<Omit<P, keyof WithRouterProps>> {
function ComponentWithRouterProp(props: P) {
const locationRouter = useLocationRouter();
navigate(path);
},
}),
- [navigate]
+ [navigate],
);
const location = {
(ComponentWithRouterProp as React.FC<P>).displayName = getWrappedDisplayName(
WrappedComponent,
- 'withRouter'
+ 'withRouter',
);
return ComponentWithRouterProp;
<CircleIconContainer
className={classNames(
'sw-inline-flex sw-items-center sw-justify-center sw-shrink-0 sw-w-6 sw-h-6',
- className
+ className,
)}
>
<IssueTypeIcon fill={themeContrast('issueTypeIcon')({ theme })} type={type} {...iconProps} />
return render(
<Icon {...props}>
<path d="test-path" />
- </Icon>
+ </Icon>,
);
}
function renderDateFormatter(
overrides: Partial<DateFormatterProps> = {},
- children?: (d: string) => React.ReactNode
+ children?: (d: string) => React.ReactNode,
) {
return renderComponent(
<DateFormatter date={new Date('2020-02-20T20:20:20Z')} {...overrides}>
{children}
- </DateFormatter>
+ </DateFormatter>,
);
}
function renderDateFromNow(
overrides: Partial<DateFromNowProps> = {},
- children: jest.Mock = jest.fn((d) => <>{d}</>)
+ children: jest.Mock = jest.fn((d) => <>{d}</>),
) {
return renderComponent(
<DateFromNow date={date} {...overrides}>
{children}
- </DateFromNow>
+ </DateFromNow>,
);
}
return renderComponent(
<DateTimeFormatter date={new Date('2020-02-20T20:20:20Z')} timeZone="UTC">
{children}
- </DateTimeFormatter>
+ </DateTimeFormatter>,
);
}
function renderTimeFormatter(
overrides: Partial<TimeFormatterProps> = {},
- children?: (d: string) => React.ReactNode
+ children?: (d: string) => React.ReactNode,
) {
return renderComponent(
<TimeFormatter date={new Date('2020-02-20T20:20:20Z')} timeZone="UTC" {...overrides}>
{children}
- </TimeFormatter>
+ </TimeFormatter>,
);
}
const UPDATE_INTERVAL_IN_SECONDS = 10;
export function getRelativeTimeProps(
- parsableDate: ParsableDate
+ parsableDate: ParsableDate,
): Pick<FormattedRelativeTimeProps, 'unit' | 'value' | 'updateIntervalInSeconds'> {
const date = parseDate(parsableDate);
const y = differenceInYears(date, Date.now());
(popupName: string, open?: boolean) => {
onPopupToggle(issue.key, popupName, open);
},
- [issue.key, onPopupToggle]
+ [issue.key, onPopupToggle],
);
const handleAssignement = useCallback(
}
togglePopup('assign', false);
},
- [issue.assignee, issue.key, onChange, togglePopup]
+ [issue.assignee, issue.key, onChange, togglePopup],
);
const handleKeyDown = useCallback(
}
return true;
},
- [issue.actions, issue.key, togglePopup, handleAssignement, onCheck]
+ [issue.actions, issue.key, togglePopup, handleAssignement, onCheck],
);
React.useEffect(() => {
expect(ui.effort('2 days').get()).toBeInTheDocument();
expect(ui.issueMessageLink.get()).toHaveAttribute(
'href',
- '/issues?scopes=MAIN&impactSeverities=LOW&types=VULNERABILITY&open=AVsae-CQS-9G3txfbFN2'
+ '/issues?scopes=MAIN&impactSeverities=LOW&types=VULNERABILITY&open=AVsae-CQS-9G3txfbFN2',
);
await ui.clickIssueMessage();
it('should render the SonarLint icon correctly', async () => {
renderIssue({ issue: mockIssue(false, { quickFixAvailable: true }) });
await expect(
- screen.getByText('issue.quick_fix_available_with_sonarlint_no_link')
+ screen.getByText('issue.quick_fix_available_with_sonarlint_no_link'),
).toHaveATooltipWithContent('issue.quick_fix_available_with_sonarlint');
});
changelogRow: (key: string, oldValue: string, newValue: string) =>
byRole('row', {
name: new RegExp(
- `issue\\.changelog\\.changed_to\\.issue\\.changelog\\.field\\.${key}\\.${newValue} \\(issue\\.changelog\\.was\\.${oldValue}\\)`
+ `issue\\.changelog\\.changed_to\\.issue\\.changelog\\.field\\.${key}\\.${newValue} \\(issue\\.changelog\\.was\\.${oldValue}\\)`,
),
}),
}
function renderIssue(
- props: Partial<Omit<ComponentPropsType<typeof Issue>, 'onChange' | 'onPopupToggle'>> = {}
+ props: Partial<Omit<ComponentPropsType<typeof Issue>, 'onChange' | 'onPopupToggle'>> = {},
) {
function Wrapper(
- wrapperProps: Omit<ComponentPropsType<typeof Issue>, 'onChange' | 'onPopupToggle'>
+ wrapperProps: Omit<ComponentPropsType<typeof Issue>, 'onChange' | 'onPopupToggle'>,
) {
const [issue, setIssue] = React.useState(wrapperProps.issue);
const [openPopup, setOpenPopup] = React.useState<string | undefined>();
),
{
currentUser: mockLoggedInUser({ login: 'leia', name: 'Organa' }),
- }
+ },
);
}
onChange: (issue: Issue) => void,
resultPromise: Promise<IssueResponse>,
oldIssue?: Issue,
- newIssue?: Issue
+ newIssue?: Issue,
) => {
const optimisticUpdate = oldIssue !== undefined && newIssue !== undefined;
if (optimisticUpdate) {
response.issue,
response.components,
response.users,
- response.rules
+ response.rules,
);
onChange(issue);
}
onChange(oldIssue!);
}
throwGlobalError(param);
- }
+ },
);
};
const handleSearchAssignees = (
query: string,
- cb: (options: Options<LabelValueSelectOption<string>>) => void
+ cb: (options: Options<LabelValueSelectOption<string>>) => void,
) => {
getUsers<RestUser>({ q: query })
.then((result) => {
aria-expanded={isOpen}
aria-label={translateWithParameters(
'issue.changelog.found_on_x_show_more',
- formatDate(creationDate, formatterOption)
+ formatDate(creationDate, formatterOption),
)}
className="issue-action issue-action-with-options js-issue-show-changelog"
onClick={() => {
{translateWithParameters(
'issue.change.file_move',
diff.oldValue ?? '',
- diff.newValue ?? ''
+ diff.newValue ?? '',
)}
</p>
);
{translateWithParameters(
'issue.change.from_branch',
diff.oldValue ?? '',
- diff.newValue ?? ''
+ diff.newValue ?? '',
)}
</p>
);
{translateWithParameters(
'issue.change.from_non_branch',
diff.oldValue ?? '',
- diff.newValue ?? ''
+ diff.newValue ?? '',
)}
</p>
);
message = translateWithParameters(
'issue.changelog.changed_to',
translate('issue.changelog.field', diff.key),
- newValue
+ newValue,
);
} else {
message = translateWithParameters(
'issue.changelog.removed',
- translate('issue.changelog.field', diff.key)
+ translate('issue.changelog.field', diff.key),
);
}
this.props.onChange,
setIssueTags({ issue: issue.key, tags: tags.join(',') }),
issue as Issue,
- newIssue as Issue
+ newIssue as Issue,
);
};
V,
Option extends LabelValueSelectOption<V>,
IsMulti extends boolean = false,
- Group extends GroupBase<Option> = GroupBase<Option>
+ Group extends GroupBase<Option> = GroupBase<Option>,
>(props: OptionProps<Option, IsMulti, Group>) {
return (
<components.SingleValue {...props}>
setTransition = ({ value }: { value: string }) => {
updateIssue(
this.props.onChange,
- setIssueTransition({ issue: this.props.issue.key, transition: value })
+ setIssueTransition({ issue: this.props.issue.key, transition: value }),
);
this.toggleSetTransition(false);
<DiscreetSelect
aria-label={translateWithParameters(
'issue.transition.status_x_click_to_change',
- translate('issue.status', issue.status)
+ translate('issue.status', issue.status),
)}
size="medium"
className="it__issue-transition"
{
'no-click': this.props.onClick === undefined,
selected: this.props.selected,
- }
+ },
);
return (
diff: mockIssueChangelogDiff({ key, newValue: 'newValue', oldValue: 'oldValue', ...diff }),
});
expect(screen.getByText(expected)).toBeInTheDocument();
- }
+ },
);
function renderIssueChangelogDiff(props: Partial<IssueChangelogDiffProps> = {}) {
this.setState({ changelog });
}
},
- () => {}
+ () => {},
);
}
{item.webhookSource &&
translateWithParameters(
'issue.changelog.webhook_source',
- item.webhookSource
+ item.webhookSource,
)}
</div>
{item.diffs.map((diff) => (
// sorting comment i.e showing newest on top
const sortedComments = [...comments]?.sort(
(com1, com2) =>
- new Date(com2.createdAt || '').getTime() - new Date(com1.createdAt || '').getTime()
+ new Date(com2.createdAt || '').getTime() - new Date(com1.createdAt || '').getTime(),
);
return (
<div className="issue-comment-list-wrapper spacer-bottom">
renderLocation = (
index: number,
message: string | undefined,
- messageFormattings: MessageFormatting[] | undefined
+ messageFormattings: MessageFormatting[] | undefined,
) => {
return (
<SingleFileLocationNavigator
renderGroup = (
group: LocationGroup,
groupIndex: number,
- { onlyFirst = false, onlyLast = false } = {}
+ { onlyFirst = false, onlyLast = false } = {},
) => {
const { firstLocationIndex } = group;
const lastLocationIndex = group.locations.length - 1;
this.renderLocation(
firstLocationIndex,
group.locations[0].msg,
- group.locations[0].msgFormattings
+ group.locations[0].msgFormattings,
)}
{onlyLast &&
this.renderLocation(
firstLocationIndex + lastLocationIndex,
group.locations[lastLocationIndex].msg,
- group.locations[lastLocationIndex].msgFormattings
+ group.locations[lastLocationIndex].msgFormattings,
)}
{!onlyFirst &&
this.renderLocation(
firstLocationIndex + index,
location.msg,
- location.msgFormattings
- )
+ location.msgFormattings,
+ ),
)}
</div>
)}
<a className="location-file-more" href="#" onClick={this.handleMoreLocationsClick}>
{translateWithParameters(
'issues.x_more_locations',
- locations.length - nbLocationsAlwaysDisplayed
+ locations.length - nbLocationsAlwaysDisplayed,
)}
</a>
</div>
onLocationSelect={jest.fn()}
selectedLocationIndex={undefined}
{...props}
- />
+ />,
);
}
onLocationSelect={jest.fn()}
selectedLocationIndex={undefined}
{...overrides}
- />
+ />,
);
}
{rating === 1
? translateWithParameters(
'metric.sqale_rating.tooltip.A',
- formatMeasure(maintainabilityGrid[0] * PERCENT_MULTIPLIER, 'PERCENT')
+ formatMeasure(maintainabilityGrid[0] * PERCENT_MULTIPLIER, 'PERCENT'),
)
: translateWithParameters(
'metric.sqale_rating.tooltip',
ratingLetter,
- formatMeasure(maintainabilityRatingThreshold * PERCENT_MULTIPLIER, 'PERCENT')
+ formatMeasure(maintainabilityRatingThreshold * PERCENT_MULTIPLIER, 'PERCENT'),
)}
</>
);
it('renders trivial measure', () => {
expect(
- shallow(<Measure metricKey="coverage" metricType="PERCENT" value="73.0" />)
+ shallow(<Measure metricKey="coverage" metricType="PERCENT" value="73.0" />),
).toMatchSnapshot();
});
it('renders leak measure', () => {
expect(
- shallow(<Measure metricKey="new_coverage" metricType="PERCENT" value="36.0" />)
+ shallow(<Measure metricKey="new_coverage" metricType="PERCENT" value="36.0" />),
).toMatchSnapshot();
});
it('renders LEVEL', () => {
expect(
- shallow(<Measure metricKey="quality_gate_status" metricType="LEVEL" value="ERROR" />)
+ shallow(<Measure metricKey="quality_gate_status" metricType="LEVEL" value="ERROR" />),
).toMatchSnapshot();
});
it('renders RATING', () => {
expect(
- shallow(<Measure metricKey="sqale_rating" metricType="RATING" value="3" />)
+ shallow(<Measure metricKey="sqale_rating" metricType="RATING" value="3" />),
).toMatchSnapshot();
});
it('renders undefined measure', () => {
expect(
- shallow(<Measure metricKey="foo" metricType="PERCENT" value={undefined} />)
+ shallow(<Measure metricKey="foo" metricType="PERCENT" value={undefined} />),
).toMatchSnapshot();
});
it('renders correctly for coverage', () => {
render(
- <MeasureIndicator metricKey={MetricKey.coverage} metricType={MetricType.Percent} value="73.0" />
+ <MeasureIndicator
+ metricKey={MetricKey.coverage}
+ metricType={MetricType.Percent}
+ value="73.0"
+ />,
);
expect(screen.getByRole('img')).toMatchSnapshot();
});
expect(shallowRender()).toMatchSnapshot('sqale rating');
expect(shallowRender({ value: 1 })).toMatchSnapshot('sqale rating A');
expect(shallowRender({ appState: mockAppState({ settings: {} }) })).toMatchSnapshot(
- 'sqale rating default grid'
+ 'sqale rating default grid',
);
expect(
shallowRender({
appState: mockAppState({ settings: { [GlobalSettingKeys.RatingGrid]: '0,0.1' } }),
- })
+ }),
).toMatchSnapshot('sqale rating wrong grid');
});
it('should render other ratings correctly', () => {
expect(shallowRender({ metricKey: MetricKey.security_rating })).toMatchSnapshot(
- 'security rating'
+ 'security rating',
);
expect(shallowRender({ metricKey: MetricKey.new_security_rating })).toMatchSnapshot(
- 'new security rating'
+ 'new security rating',
);
});
metricKey={MetricKey.sqale_rating}
value={2}
{...overrides}
- />
+ />,
);
}
if (globalNcd.type === NewCodeDefinitionType.NumberOfDays) {
setting = `${translate('new_code_definition.number_days')} (${translateWithParameters(
'duration.days',
- globalNcd.value ?? '?'
+ globalNcd.value ?? '?',
)})`;
description = translate('new_code_definition.number_days.description');
useCase = translate('new_code_definition.number_days.usecase');
id: component.key,
}),
},
- [component, isGlobalBanner]
+ [component, isGlobalBanner],
);
const handleBannerDismiss = useCallback(async () => {
await setMessageDismissed(
isGlobalBanner
? { messageType: MessageTypes.GlobalNcd90 }
- : { messageType: MessageTypes.ProjectNcd90, projectKey: component.key }
+ : { messageType: MessageTypes.ProjectNcd90, projectKey: component.key },
);
setDismissed(true);
}, [component, isGlobalBanner]);
: {
messageType: MessageTypes.ProjectNcd90,
projectKey: component.key,
- }
+ },
);
setDismissed(messageStatus.dismissed);
}
: {
messageType: MessageTypes.GlobalNcdPage90,
- }
+ },
);
setNcdAutoUpdateBannerDismissed(messageStatus.dismissed);
}
{translateWithParameters(
'new_code_definition.number_days.invalid',
NUMBER_OF_DAYS_MIN_VALUE,
- NUMBER_OF_DAYS_MAX_VALUE
+ NUMBER_OF_DAYS_MAX_VALUE,
)}
</Note>
type: selectedNcdType,
value: days,
}),
- [selectedNcdType, days]
+ [selectedNcdType, days],
);
const handleNcdChanged = React.useCallback(
setIsChanged(true);
}
},
- [selectedNcdType]
+ [selectedNcdType],
);
React.useEffect(() => {
<div className="sw-flex sw-flex-col sw-my-4 sw-mr-4 sw-gap-4" role="radiogroup">
<NewCodeDefinitionPreviousVersionOption
disabled={Boolean(
- !selectedNcdType || selectedNcdType === NewCodeDefinitionType.Inherited
+ !selectedNcdType || selectedNcdType === NewCodeDefinitionType.Inherited,
)}
onSelect={handleNcdChanged}
selected={selectedNcdType === NewCodeDefinitionType.PreviousVersion}
<NewCodeDefinitionDaysOption
days={days}
disabled={Boolean(
- !selectedNcdType || selectedNcdType === NewCodeDefinitionType.Inherited
+ !selectedNcdType || selectedNcdType === NewCodeDefinitionType.Inherited,
)}
isChanged={isChanged}
isValid={isCompliant}
<SelectionCard
disabled={Boolean(
- !selectedNcdType || selectedNcdType === NewCodeDefinitionType.Inherited
+ !selectedNcdType || selectedNcdType === NewCodeDefinitionType.Inherited,
)}
onClick={() => handleNcdChanged(NewCodeDefinitionType.ReferenceBranch)}
selected={selectedNcdType === NewCodeDefinitionType.ReferenceBranch}
describe('Global NCD update notification banner', () => {
function renderGlobalMessage(
- currentUser = mockLoggedInUser({ permissions: { global: ['admin'] } })
+ currentUser = mockLoggedInUser({ permissions: { global: ['admin'] } }),
) {
return renderAppRoutes(
'/',
),
{
currentUser,
- }
+ },
);
}
),
{
currentUser,
- }
+ },
);
}
it('renders no project banner if user is not project admin', () => {
const { container } = renderProjectMessage(
- mockComponent({ configuration: { showSettings: false } })
+ mockComponent({ configuration: { showSettings: false } }),
);
expect(container).toBeEmptyDOMElement();
});
export type PreviouslyNonCompliantBranchNCD = PreviouslyNonCompliantNCD & NewCodeDefinitionBranch;
export function isPreviouslyNonCompliantDaysNCD(
- newCodeDefinition: NewCodeDefinition
+ newCodeDefinition: NewCodeDefinition,
): newCodeDefinition is PreviouslyNonCompliantNCD;
export function isPreviouslyNonCompliantDaysNCD(
- newCodeDefinition: NewCodeDefinitionBranch
+ newCodeDefinition: NewCodeDefinitionBranch,
): newCodeDefinition is PreviouslyNonCompliantBranchNCD;
export function isPreviouslyNonCompliantDaysNCD(
- newCodeDefinition: NewCodeDefinition | NewCodeDefinitionBranch
+ newCodeDefinition: NewCodeDefinition | NewCodeDefinitionBranch,
): newCodeDefinition is PreviouslyNonCompliantNCD | PreviouslyNonCompliantBranchNCD {
return (
newCodeDefinition.type === NewCodeDefinitionType.NumberOfDays &&
const { permissions, users, groups, loading, children, selectedPermission } = this.props;
const items = [...groups, ...users];
const [itemWithPermissions, itemWithoutPermissions] = partition(items, (item) =>
- this.getItemInitialPermissionsCount(item)
+ this.getItemInitialPermissionsCount(item),
);
return (
label={translateWithParameters(
'permission.assign_x_to_y',
permissionDefinition.name,
- permissionItem.name
+ permissionItem.name,
)}
onCheck={onCheck}
>
label={translateWithParameters(
'permission.assign_x_to_y',
permission.name,
- permissionItem.name
+ permissionItem.name,
)}
onCheck={onCheck}
/>
<Tooltip
overlay={translateWithParameters(
'global_permissions.filter_by_x_permission',
- permission.name
+ permission.name,
)}
>
<a href="#" onClick={this.handlePermissionClick}>
}
export default function usePermissionChange<T extends PermissionGroup | PermissionUser>(
- props: Props<T>
+ props: Props<T>,
) {
const { holder, removeOnly, permissions } = props;
const [loading, setLoading] = React.useState<string[]>([]);
const [confirmPermission, setConfirmPermission] = React.useState<PermissionDefinition | null>(
- null
+ null,
);
const stopLoading = (permission: string) => {
if (removeOnly) {
const flatPermissions = permissions.reduce<PermissionDefinition[]>(
(acc, p) => (isPermissionDefinitionGroup(p) ? [...acc, ...p.permissions] : [...acc, p]),
- []
+ [],
);
setConfirmPermission(flatPermissions.find((p) => p.key === permissionKey) ?? null);
} else {
setLoading((prevState) => [...prevState, permission]);
return props.onToggle(holder, permission).then(
() => stopLoading(permission),
- () => stopLoading(permission)
+ () => stopLoading(permission),
);
};
this.checkIfEducationPrinciplesAreVisible = debounce(
this.checkIfEducationPrinciplesAreVisible,
- DEBOUNCE_FOR_SCROLL
+ DEBOUNCE_FOR_SCROLL,
);
}
prevProps.ruleDetails !== ruleDetails ||
(prevProps.issue && issue && prevProps.issue.key !== issue.key) ||
prevProps.selectedFlowIndex !== selectedFlowIndex ||
- prevProps.selectedLocationIndex !== selectedLocationIndex
- )
+ prevProps.selectedLocationIndex !== selectedLocationIndex,
+ ),
);
}
// As we might tamper with the description later on, we clone to avoid any side effect
const descriptionSectionsByKey = cloneDeep(
- groupBy(descriptionSections, (section) => section.key)
+ groupBy(descriptionSections, (section) => section.key),
);
if (extendedDescription) {
const contexts = sections
.filter(
(
- section
+ section,
): section is RuleDescriptionSection & Required<Pick<RuleDescriptionSection, 'context'>> =>
- section.context != null
+ section.context != null,
)
.map((section) => ({
displayName: section.context.displayName || section.context.key,
<FlagMessage variant="info" className="sw-mb-4">
{translateWithParameters(
'coding_rules.description_context.default_information',
- defaultContext.displayName
+ defaultContext.displayName,
)}
</FlagMessage>
)}
<h2>
{translateWithParameters(
'coding_rules.description_context.subtitle',
- selectedContext.displayName
+ selectedContext.displayName,
)}
</h2>
)}
this.checkIfEducationPrinciplesAreVisible = debounce(
this.checkIfEducationPrinciplesAreVisible,
- DEBOUNCE_FOR_SCROLL
+ DEBOUNCE_FOR_SCROLL,
);
}
prevProps.ruleDetails !== ruleDetails ||
(prevProps.issue && issue && prevProps.issue.key !== issue.key) ||
prevProps.selectedFlowIndex !== selectedFlowIndex ||
- prevProps.selectedLocationIndex !== selectedLocationIndex
- )
+ prevProps.selectedLocationIndex !== selectedLocationIndex,
+ ),
);
}
// As we might tamper with the description later on, we clone to avoid any side effect
const descriptionSectionsByKey = cloneDeep(
- groupBy(descriptionSections, (section) => section.key)
+ groupBy(descriptionSections, (section) => section.key),
);
if (extendedDescription) {
type,
cleanCodeAttribute ? 'clean_code_attribute' : 'clean_code_attribute_category',
cleanCodeAttribute ?? cleanCodeAttributeCategory,
- 'title'
+ 'title',
)}
</p>
<p>
'issue',
cleanCodeAttribute ? 'clean_code_attribute' : 'clean_code_attribute_category',
cleanCodeAttribute ?? cleanCodeAttributeCategory,
- 'advice'
+ 'advice',
)}
</p>
</>
type,
'clean_code_attribute_category',
cleanCodeAttributeCategory,
- 'title_short'
+ 'title_short',
)}
</span>
{cleanCodeAttribute && (
return shallow<DrilldownLink>(
<DrilldownLink component="project123" metric="other" {...props}>
{label}
- </DrilldownLink>
+ </DrilldownLink>,
);
};
alt="" // Should be ignored by screen readers
className="sw-h-4 sw-w-4"
src={`${getBaseUrl()}/images/tutorials/jenkins.svg`}
- />
+ />,
)}
{showGitHubActions &&
alt="" // Should be ignored by screen readers
className="sw-h-4 sw-w-4"
src={`${getBaseUrl()}/images/tutorials/github-actions.svg`}
- />
+ />,
)}
{showBitbucketPipelines &&
alt="" // Should be ignored by screen readers
className="sw-h-4 sw-w-4"
src={`${getBaseUrl()}/images/alm/bitbucket.svg`}
- />
+ />,
)}
{showGitLabCICD &&
alt="" // Should be ignored by screen readers
className="sw-h-4 sw-w-4"
src={`${getBaseUrl()}/images/alm/gitlab.svg`}
- />
+ />,
)}
{showAzurePipelines &&
alt="" // Should be ignored by screen readers
className="sw-h-4 sw-w-4"
src={`${getBaseUrl()}/images/tutorials/azure-pipelines.svg`}
- />
+ />,
)}
{renderAlm(TutorialModes.OtherCI, component.key)}
await startLocalTutorial(user);
expect(
- screen.getByText('-Dsonar.host.url=http://sq.example.com', { exact: false })
+ screen.getByText('-Dsonar.host.url=http://sq.example.com', { exact: false }),
).toBeInTheDocument();
});
await startLocalTutorial(user);
expect(
- screen.getByText('-Dsonar.host.url=http://host.url', { exact: false })
+ screen.getByText('-Dsonar.host.url=http://host.url', { exact: false }),
).toBeInTheDocument();
});
function renderTutorialSelection(
props: Partial<ComponentPropsType<typeof TutorialSelection>> = {},
- navigateTo: string = 'tutorials?id=bar'
+ navigateTo: string = 'tutorials?id=bar',
) {
return renderApp(
'/tutorials',
currentUser={mockLoggedInUser({ permissions: { global: [Permissions.Scan] } })}
{...props}
/>,
- { featureList: [Feature.BranchSupport], navigateTo }
+ { featureList: [Feature.BranchSupport], navigateTo },
);
}
it('should generate a token with the given name', () => {
expect(
- getUniqueTokenName([mockUserToken({ name: initialTokenName })], 'Analyze "project"')
+ getUniqueTokenName([mockUserToken({ name: initialTokenName })], 'Analyze "project"'),
).toBe('Analyze "project"');
});
expect(
buildGithubLink(
mockAlmSettingsInstance({ url: 'https://github.company.com/api/v3' }),
- projectBinding
- )
+ projectBinding,
+ ),
).toBe('https://github.company.com/owner/reponame');
});
it('should work for github.com', () => {
expect(
- buildGithubLink(mockAlmSettingsInstance({ url: 'http://api.github.com/' }), projectBinding)
+ buildGithubLink(mockAlmSettingsInstance({ url: 'http://api.github.com/' }), projectBinding),
).toBe('https://github.com/owner/reponame');
});
expect(
buildBitbucketCloudLink(
mockAlmSettingsInstance({ url: 'http://bitbucket.org/workspace/' }),
- projectBinding
- )
+ projectBinding,
+ ),
).toBe('http://bitbucket.org/workspace/reponame');
});
it('should return null if there is no url defined', () => {
expect(
- buildBitbucketCloudLink(mockAlmSettingsInstance({ url: undefined }), projectBinding)
+ buildBitbucketCloudLink(mockAlmSettingsInstance({ url: undefined }), projectBinding),
).toBeNull();
expect(
buildBitbucketCloudLink(
mockAlmSettingsInstance(),
- mockProjectBitbucketCloudBindingResponse({ repository: undefined })
- )
+ mockProjectBitbucketCloudBindingResponse({ repository: undefined }),
+ ),
).toBeNull();
});
});
<TutorialStepList className="sw-mb-10">
<TutorialStep
title={translate(
- `onboarding.tutorial.with.azure_pipelines.${Steps.ExtensionInstallation}.title`
+ `onboarding.tutorial.with.azure_pipelines.${Steps.ExtensionInstallation}.title`,
)}
>
<ExtensionInstallationStepContent />
<TutorialStep
title={translate(
- `onboarding.tutorial.with.azure_pipelines.${Steps.ServiceEndpoint}.title`
+ `onboarding.tutorial.with.azure_pipelines.${Steps.ServiceEndpoint}.title`,
)}
>
<ServiceEndpointStepContent
<TutorialStep
title={translate(
- `onboarding.tutorial.with.azure_pipelines.${Steps.BranchAnalysis}.title`
+ `onboarding.tutorial.with.azure_pipelines.${Steps.BranchAnalysis}.title`,
)}
>
<BranchAnalysisStepContent component={component} onDone={setDone} />
<span>
<FormattedMessage
defaultMessage={translate(
- 'onboarding.tutorial.with.azure_pipelines.ExtensionInstallation.sentence'
+ 'onboarding.tutorial.with.azure_pipelines.ExtensionInstallation.sentence',
)}
id="onboarding.tutorial.with.azure_pipelines.ExtensionInstallation.sentence"
values={{
link: (
<Link to="https://marketplace.visualstudio.com/items?itemName=SonarSource.sonarqube">
{translate(
- 'onboarding.tutorial.with.azure_pipelines.ExtensionInstallation.sentence.link'
+ 'onboarding.tutorial.with.azure_pipelines.ExtensionInstallation.sentence.link',
)}
</Link>
),
button: (
<strong>
{translate(
- 'onboarding.tutorial.with.azure_pipelines.ExtensionInstallation.sentence.button'
+ 'onboarding.tutorial.with.azure_pipelines.ExtensionInstallation.sentence.button',
)}
</strong>
),
<FormattedMessage
id="onboarding.tutorial.with.azure_pipelines.BranchAnalysis.java_installer.sentence"
defaultMessage={translate(
- 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.java_installer.sentence'
+ 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.java_installer.sentence',
)}
values={{
field: <b className="sw-font-semibold">{field}</b>,
<ListItem>
{renderSentenceWithFieldAndValue({
field: translate(
- 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.java_installer.java_version'
+ 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.java_installer.java_version',
),
value: '17',
})}
{' ' /* explicit space between the two strings */}
{translate(
- 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.java_installer.or_higher'
+ 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.java_installer.or_higher',
)}
</ListItem>
<ListItem>
{renderSentenceWithFieldAndValue({
field: translate(
- 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.java_installer.java_architecture'
+ 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.java_installer.java_architecture',
),
value: 'x64',
})}
<ListItem>
{renderSentenceWithFieldAndValue({
field: translate(
- 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.java_installer.java_source'
+ 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.java_installer.java_source',
),
value: translate(
- 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.java_installer.pre-installed'
+ 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.java_installer.pre-installed',
),
})}
</ListItem>
<NumberedListItem className="sw-flex sw-items-center">
<FormattedMessage
defaultMessage={translate(
- 'onboarding.tutorial.with.azure_pipelines.ServiceEndpoint.step3.sentence'
+ 'onboarding.tutorial.with.azure_pipelines.ServiceEndpoint.step3.sentence',
)}
id="onboarding.tutorial.with.azure_pipelines.ServiceEndpoint.step3.sentence"
values={{
const user = userEvent.setup();
expect(
- screen.getByRole('heading', { name: 'onboarding.tutorial.with.azure_pipelines.title' })
+ screen.getByRole('heading', { name: 'onboarding.tutorial.with.azure_pipelines.title' }),
).toBeInTheDocument();
//// Default step.
expect(lastToken!.type).toBe(TokenType.Global);
expect(
- within(modal).getByText(`users.tokens.new_token_created.${lastToken!.token}`)
+ within(modal).getByText(`users.tokens.new_token_created.${lastToken!.token}`),
).toBeInTheDocument();
await clickButton(user, 'continue', modal);
expect(
screen.getByRole('heading', {
name: 'onboarding.tutorial.with.azure_pipelines.ExtensionInstallation.title',
- })
+ }),
).toBeInTheDocument();
}
expect(
screen.getByRole('heading', {
name: 'onboarding.tutorial.with.azure_pipelines.ServiceEndpoint.title',
- })
+ }),
).toBeInTheDocument();
expect(getCopyToClipboardValue(0, 'Copy to clipboard')).toBe('https://sonarqube.example.com/');
expect(
- screen.getByRole('button', { name: 'onboarding.token.generate.long' })
+ screen.getByRole('button', { name: 'onboarding.token.generate.long' }),
).toBeInTheDocument();
}
expect(
screen.getByRole('heading', {
name: 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.title',
- })
+ }),
).toBeInTheDocument();
expect(getCopyToClipboardValue(1, 'Copy to clipboard')).toBe('foo');
expect(getCopyToClipboardValue(0, 'Copy')).toMatchSnapshot(`cfamily ${os}, copy shell script`);
expect(getCopyToClipboardValue(1, 'Copy to clipboard')).toBe('foo');
expect(getCopyToClipboardValue(2, 'Copy to clipboard')).toMatchSnapshot(
- `cfamily ${os}, copy additional properties`
+ `cfamily ${os}, copy additional properties`,
);
expect(getCopyToClipboardValue(1, 'Copy')).toMatchSnapshot(
- `cfamily ${os}, copy build-wrapper command`
+ `cfamily ${os}, copy build-wrapper command`,
);
}
expect(
screen.getByRole('heading', {
name: 'onboarding.tutorial.ci_outro.done',
- })
+ }),
).toBeInTheDocument();
}
function renderAzurePipelinesTutorial(
props: Partial<AzurePipelinesTutorialProps> = {},
- { languages = { c: mockLanguage({ key: 'c' }) } }: RenderContext = {}
+ { languages = { c: mockLanguage({ key: 'c' }) } }: RenderContext = {},
) {
return renderApp(
'/',
willRefreshAutomatically
{...props}
/>,
- { languages }
+ { languages },
);
}
<NumberedListItem>
{translateWithParameters(
'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.java',
- translate('onboarding.build', BuildTools.Gradle)
+ translate('onboarding.build', BuildTools.Gradle),
)}
<UnorderedList ticks className="sw-ml-12 sw-mb-4">
<ListItem>
<NumberedListItem>
{translateWithParameters(
'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.java',
- translate('onboarding.build', BuildTools.Maven)
+ translate('onboarding.build', BuildTools.Maven),
)}
<UnorderedList ticks className="sw-ml-12 sw-mb-4">
<ListItem>
<FormattedMessage
id="onboarding.tutorial.with.azure_pipelines.BranchAnalysis.prepare.run_analysis"
defaultMessage={translate(
- 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.prepare.run_analysis'
+ 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.prepare.run_analysis',
)}
values={{
section: (
<b className="sw-font-semibold">
{translate(
- 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.prepare.run_analysis.section'
+ 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.prepare.run_analysis.section',
)}
</b>
),
<b className="sw-font-semibold">
{translate(
'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.prepare.run_analysis.values',
- buildTool
+ buildTool,
)}
</b>
),
<FormattedMessage
id="onboarding.tutorial.with.azure_pipelines.BranchAnalysis.run.key.sentence"
defaultMessage={translate(
- 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.run.key.sentence'
+ 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.run.key.sentence',
)}
values={{
project_key: (
<b className="sw-font-semibold sw-mx-1">
{translate(
- 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.run.key.sentence.project_key'
+ 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.run.key.sentence.project_key',
)}
</b>
),
<FormattedMessage
id="onboarding.tutorial.with.azure_pipelines.BranchAnalysis.prepare_additional.ccpp"
defaultMessage={translate(
- 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.prepare_additional.ccpp'
+ 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.prepare_additional.ccpp',
)}
values={{
advanced: (
<b className="sw-font-semibold sw-mx-1">
{translate(
- 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.prepare_additional.ccpp.advanced'
+ 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.prepare_additional.ccpp.advanced',
)}
</b>
),
additional: (
<b className="sw-font-semibold sw-mx-1">
{translate(
- 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.prepare_additional.ccpp.additional'
+ 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.prepare_additional.ccpp.additional',
)}
</b>
),
<FormattedMessage
id="onboarding.tutorial.with.azure_pipelines.BranchAnalysis.run.key.sentence"
defaultMessage={translate(
- 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.run.key.sentence'
+ 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.run.key.sentence',
)}
values={{
project_key: (
<b className="sw-font-semibold sw-mx-1">
{translate(
- 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.run.key.sentence.project_key'
+ 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.run.key.sentence.project_key',
)}
</b>
),
/>
<FlagMessage variant="info" className="sw-mt-2">
{translate(
- 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.publish_qg.info.sentence1'
+ 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.publish_qg.info.sentence1',
)}
</FlagMessage>
</NumberedListItem>
<FormattedMessage
id="onboarding.tutorial.with.azure_pipelines.BranchAnalysis.branch_protection"
defaultMessage={translate(
- 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.branch_protection'
+ 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.branch_protection',
)}
values={{
link: (
<Link to={docUrl(ALM_DOCUMENTATION_PATHS[AlmKeys.Azure])}>
{translate(
- 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.branch_protection.link'
+ 'onboarding.tutorial.with.azure_pipelines.BranchAnalysis.branch_protection.link',
)}
</Link>
),
branchesEnabled?: boolean,
mainBranchName?: string,
projectKey?: string,
- projectName?: string
+ projectName?: string,
) => string
> = {
[BuildTools.Gradle]: gradleExample,
branchSupportEnabled,
mainBranchName,
component.key,
- component.name
+ component.name,
);
return (
<StandoutLink
to={`${buildBitbucketCloudLink(
almBinding,
- projectBinding
+ projectBinding,
)}/admin/addon/admin/pipelines/repository-variables`}
target="_blank"
rel="noopener noreferrer"
expect(getCopyToClipboardValue(0, 'Copy to clipboard')).toMatchSnapshot('sonar token key');
expect(getCopyToClipboardValue(1, 'Copy to clipboard')).toMatchSnapshot('sonarqube host url key');
expect(getCopyToClipboardValue(2, 'Copy to clipboard')).toMatchSnapshot(
- 'sonarqube host url value'
+ 'sonarqube host url value',
);
// Create/update configuration file step
function renderBitbucketPipelinesTutorial(
overrides: Partial<BitbucketPipelinesTutorialProps> = {},
- { languages = { c: mockLanguage({ key: 'c' }) } }: RenderContext = {}
+ { languages = { c: mockLanguage({ key: 'c' }) } }: RenderContext = {},
) {
return renderApp(
'/',
currentUser={mockLoggedInUser()}
{...overrides}
/>,
- { languages, featureList: [Feature.BranchSupport] }
+ { languages, featureList: [Feature.BranchSupport] },
);
}
export default function dotNetExample(
branchesEnabled: boolean,
mainBranchName: string,
- projectKey: string
+ projectKey: string,
) {
return `image: mcr.microsoft.com/dotnet/sdk:7.0
branchesEnabled: boolean,
mainBranchName: string,
projectKey: string,
- projectName: string
+ projectName: string,
) {
return `image: maven:3-eclipse-temurin-17
}
options={tokenExpirationOptions}
value={tokenExpirationOptions.find(
- (option) => option.value === tokenExpiration
+ (option) => option.value === tokenExpiration,
)}
/>
<ButtonSecondary
};
export default function GithubCFamilyExampleRepositories(
- props: GithubCFamilyExampleRepositoriesProps
+ props: GithubCFamilyExampleRepositoriesProps,
) {
const { className, os, ci } = props;
const queryParams = ['sq', os ? OS_SEARCH_MAP[os] : undefined, ci ? CI_SEARCH_MAP[ci] : undefined]
const user = userEvent.setup();
expect(
- screen.getByRole('heading', { name: 'onboarding.token.generate.PROJECT_ANALYSIS_TOKEN' })
+ screen.getByRole('heading', { name: 'onboarding.token.generate.PROJECT_ANALYSIS_TOKEN' }),
).toBeInTheDocument();
expect(screen.getByText('onboarding.token.text.PROJECT_ANALYSIS_TOKEN')).toBeInTheDocument();
await typeInField(
user,
screen.getByLabelText('onboarding.token.name.label'),
- 'another token name'
+ 'another token name',
);
await clickButton(user, 'onboarding.token.generate');
currentUser={mockLoggedInUser()}
onClose={jest.fn()}
{...props}
- />
+ />,
);
}
renderGithubCFamilyExampleRepositories({ os, ci });
expect(await ui.cfamilyExamplesLink.find()).toHaveAttribute(
'href',
- `https://github.com/orgs/sonarsource-cfamily-examples/repositories?q=sq+${formattedOS}+${formattedCI}`
+ `https://github.com/orgs/sonarsource-cfamily-examples/repositories?q=sq+${formattedOS}+${formattedCI}`,
);
- }
+ },
);
function renderGithubCFamilyExampleRepositories(
- overrides: Partial<GithubCFamilyExampleRepositoriesProps> = {}
+ overrides: Partial<GithubCFamilyExampleRepositoriesProps> = {},
) {
return renderComponent(
- <GithubCFamilyExampleRepositories className="test-class" {...overrides} />
+ <GithubCFamilyExampleRepositories className="test-class" {...overrides} />,
);
}
expect(getCopyToClipboardValue(0, 'Copy to clipboard')).toMatchSnapshot('sonar token key');
expect(getCopyToClipboardValue(1, 'Copy to clipboard')).toMatchSnapshot('sonarqube host url key');
expect(getCopyToClipboardValue(2, 'Copy to clipboard')).toMatchSnapshot(
- 'sonarqube host url value'
+ 'sonarqube host url value',
);
// Create/update configuration file step
expect(getCopyToClipboardValue(0, 'Copy')).toMatchSnapshot('CFamily: sonar-project.properties');
await user.click(ui.linuxButton.get());
expect(getCopyToClipboardValue(1, 'Copy')).toMatchSnapshot(
- 'CFamily Linux: .github/workflows/build.yml'
+ 'CFamily Linux: .github/workflows/build.yml',
);
await user.click(ui.windowsButton.get());
expect(getCopyToClipboardValue(1, 'Copy')).toMatchSnapshot(
- 'CFamily Windows: .github/workflows/build.yml'
+ 'CFamily Windows: .github/workflows/build.yml',
);
await user.click(ui.macosButton.get());
expect(getCopyToClipboardValue(1, 'Copy')).toMatchSnapshot(
- 'CFamily MacOS: .github/workflows/build.yml'
+ 'CFamily MacOS: .github/workflows/build.yml',
);
// Other
function renderGithubActionTutorial(
overrides: Partial<GitHubActionTutorialProps> = {},
- { languages = { c: mockLanguage({ key: 'c' }) } }: RenderContext = {}
+ { languages = { c: mockLanguage({ key: 'c' }) } }: RenderContext = {},
) {
return renderApp(
'/',
currentUser={mockLoggedInUser()}
{...overrides}
/>,
- { languages, featureList: [Feature.BranchSupport] }
+ { languages, featureList: [Feature.BranchSupport] },
);
}
mainBranchName,
!!branchesEnabled,
'<image ready for your build toolchain>',
- STEPS[os]
+ STEPS[os],
)}
/>
<CompilationInfo />
mainBranchName,
!!branchesEnabled,
GITHUB_ACTIONS_RUNS_ON_WINDOWS,
- dotnetYamlSteps(component.key)
+ dotnetYamlSteps(component.key),
)}
/>
);
mainBranchName,
!!branchesEnabled,
GITHUB_ACTIONS_RUNS_ON_LINUX,
- GRADLE_YAML_STEPS
+ GRADLE_YAML_STEPS,
)}
/>
</>
mainBranchName,
!!branchesEnabled,
GITHUB_ACTIONS_RUNS_ON_LINUX,
- mavenYamlSteps(component.key, component.name)
+ mavenYamlSteps(component.key, component.name),
)}
/>
);
mainBranchName,
!!branchesEnabled,
GITHUB_ACTIONS_RUNS_ON_LINUX,
- otherYamlSteps(!!branchesEnabled)
+ otherYamlSteps(!!branchesEnabled),
)}
/>
</>
mainBranchName: string,
branchesEnabled: boolean,
runsOn: string,
- steps: string
+ steps: string,
) {
return `name: Build
}
const pipelineDescriptionLinkLabel = translate(
- 'onboarding.tutorial.with.gitlab_ci.variables.description.link'
+ 'onboarding.tutorial.with.gitlab_ci.variables.description.link',
);
export default function EnvironmentVariablesStep(props: EnvironmentVariablesStepProps) {
<FormattedMessage
defaultMessage={translate(
- 'onboarding.tutorial.with.gitlab_ci.variables.section.description'
+ 'onboarding.tutorial.with.gitlab_ci.variables.section.description',
)}
id="onboarding.tutorial.with.gitlab_ci.variables.section.description"
values={{
<ListItem>
<FormattedMessage
defaultMessage={translate(
- 'onboarding.tutorial.with.gitlab_ci.variables.section.step4'
+ 'onboarding.tutorial.with.gitlab_ci.variables.section.step4',
)}
id="onboarding.tutorial.with.gitlab_ci.variables.section.step4"
values={{
<FormattedMessage
defaultMessage={translate(
- 'onboarding.tutorial.with.gitlab_ci.variables.section2.description'
+ 'onboarding.tutorial.with.gitlab_ci.variables.section2.description',
)}
id="onboarding.tutorial.with.gitlab_ci.variables.section2.description"
values={{
<ListItem>
<FormattedMessage
defaultMessage={translate(
- 'onboarding.tutorial.with.gitlab_ci.variables.section2.step4'
+ 'onboarding.tutorial.with.gitlab_ci.variables.section2.step4',
)}
id="onboarding.tutorial.with.gitlab_ci.variables.section2.step4"
values={{
<NumberedListItem>
<FormattedMessage
defaultMessage={translate(
- `onboarding.tutorial.with.gitlab_ci.project_key.${buildTool}.step2`
+ `onboarding.tutorial.with.gitlab_ci.project_key.${buildTool}.step2`,
)}
id={`onboarding.tutorial.with.gitlab_ci.project_key.${buildTool}.step2`}
values={Object.assign(
</>
),
}
- : {}
+ : {},
)}
/>
{buildTool === BuildTools.Gradle ? (
expect(getCopyToClipboardValue(0, 'Copy to clipboard')).toMatchSnapshot('sonar token key');
expect(getCopyToClipboardValue(1, 'Copy to clipboard')).toMatchSnapshot('sonarqube host url key');
expect(getCopyToClipboardValue(2, 'Copy to clipboard')).toMatchSnapshot(
- 'sonarqube host url value'
+ 'sonarqube host url value',
);
// Create/update configuration file step
function renderGitLabTutorial(
overrides: Partial<GitLabCITutorialProps> = {},
- { languages = { c: mockLanguage({ key: 'c' }) } }: RenderContext = {}
+ { languages = { c: mockLanguage({ key: 'c' }) } }: RenderContext = {},
) {
return renderApp(
'/',
currentUser={mockLoggedInUser()}
{...overrides}
/>,
- { languages }
+ { languages },
);
}
<ListItem>
<strong>
{translate(
- 'onboarding.tutorial.with.jenkins.multi_branch_pipeline.step2.behaviors.label'
+ 'onboarding.tutorial.with.jenkins.multi_branch_pipeline.step2.behaviors.label',
)}
:
</strong>
<ListItem>
<strong>
{translate(
- 'onboarding.tutorial.with.jenkins.multi_branch_pipeline.step2.behaviors.ref_specs.label'
+ 'onboarding.tutorial.with.jenkins.multi_branch_pipeline.step2.behaviors.ref_specs.label',
)}
:
</strong>
</UnorderedList>
<p className="sw-ml-12">
{translate(
- 'onboarding.tutorial.with.jenkins.multi_branch_pipeline.step2.leave_defaults'
+ 'onboarding.tutorial.with.jenkins.multi_branch_pipeline.step2.leave_defaults',
)}
</p>
</NumberedListItem>
function buildUrlSnippet(
branchesEnabled: boolean,
isBitbucketcloud: boolean,
- ownUrl = '***BITBUCKET_URL***'
+ ownUrl = '***BITBUCKET_URL***',
) {
if (!branchesEnabled) {
return '***JENKINS_SERVER_URL***/job/***JENKINS_JOB_NAME***/build?token=***JENKINS_BUILD_TRIGGER_TOKEN***';
if (isBitbucketCloud && projectBinding?.repository) {
linkUrl = `${buildBitbucketCloudLink(
almBinding,
- projectBinding
+ projectBinding,
)}/admin/addon/admin/bitbucket-webhooks/bb-webhooks-repo-admin`;
} else if (projectBinding.slug) {
linkUrl = `${stripTrailingSlash(almBinding.url)}/plugins/servlet/webhooks/projects/${
await user.click(ui.windowsDotnetFrameworkButton.get());
expect(getCopyToClipboardValue(2, 'Copy')).toMatchSnapshot(
- `windows dotnet framework jenkinsfile`
+ `windows dotnet framework jenkinsfile`,
);
await user.click(ui.linuxDotnetCoreButton.get());
// Other
await user.click(ui.otherBuildButton.get());
expect(getCopyToClipboardValue(2, 'Copy')).toMatchSnapshot(
- `other build tools sonar-project.properties code`
+ `other build tools sonar-project.properties code`,
);
expect(getCopyToClipboardValue(3, 'Copy')).toMatchSnapshot(`other build tools jenkinsfile`);
expect(ui.allSetSentence.get()).toBeInTheDocument();
- }
+ },
);
it.each([AlmKeys.GitHub, AlmKeys.GitLab, AlmKeys.BitbucketCloud])(
expect(await ui.devopsPlatformTitle.find()).toBeInTheDocument();
await user.click(ui.devopsPlatformButton(alm).get());
expect(ui.pipelineIntroText.get()).toBeInTheDocument();
- }
+ },
);
it.each([AlmKeys.GitHub, AlmKeys.BitbucketCloud])(
expect(ui.webhookAlmLink(alm).get()).toBeInTheDocument();
await user.click(ui.mavenBuildButton.get());
expect(ui.allSetSentence.get()).toBeInTheDocument();
- }
+ },
);
it('navigates between steps', async () => {
{
featureList = [Feature.BranchSupport],
languages = { c: mockLanguage({ key: 'c' }) },
- }: RenderContext = {}
+ }: RenderContext = {},
) {
return renderApp(
'/',
<JenkinsTutorial baseUrl="http://localhost:9000" component={mockComponent()} {...overrides} />,
- { featureList, languages }
+ { featureList, languages },
);
}
<FormattedMessage
defaultMessage={translate(
'onboarding.tutorial.with.jenkins.jenkinsfile.gradle.step2',
- 'sentence'
+ 'sentence',
)}
id="onboarding.tutorial.with.jenkins.jenkinsfile.gradle.step2.sentence"
values={{
({ config }) => ({ config: { buildTool: config.buildTool, os } }),
() => {
this.props.onDone(this.state.config);
- }
+ },
);
};
<p className="sw-mt-4">
{isProjectAdmin
? translate(
- 'onboarding.analysis.auto_refresh_after_analysis.set_up_pr_deco_and_ci.admin'
+ 'onboarding.analysis.auto_refresh_after_analysis.set_up_pr_deco_and_ci.admin',
)
: translate('onboarding.analysis.auto_refresh_after_analysis.set_up_pr_deco_and_ci')}
</p>
<li>
<Link to={docUrl('/analyzing-source-code/branches/branch-analysis/')}>
{translate(
- 'onboarding.analysis.auto_refresh_after_analysis.check_these_links.branches'
+ 'onboarding.analysis.auto_refresh_after_analysis.check_these_links.branches',
)}
</Link>
</li>
<li>
<Link to={docUrl('/analyzing-source-code/pull-request-analysis')}>
{translate(
- 'onboarding.analysis.auto_refresh_after_analysis.check_these_links.pr_analysis'
+ 'onboarding.analysis.auto_refresh_after_analysis.check_these_links.pr_analysis',
)}
</Link>
</li>
options={tokenExpirationOptions}
size="full"
value={tokenExpirationOptions.find(
- (option) => option.value === tokenExpiration
+ (option) => option.value === tokenExpiration,
)}
/>
// Dotnet - Core
await user.click(ui.dotnetBuildButton.get());
expect(getCopyToClipboardValue(0, 'Copy')).toMatchSnapshot(
- 'dotnet core: install scanner globally'
+ 'dotnet core: install scanner globally',
);
expect(getCopyToClipboardValue(1, 'Copy')).toMatchSnapshot('dotnet core: execute command 1');
expect(getCopyToClipboardValue(2, 'Copy')).toMatchSnapshot('dotnet core: execute command 2');
await user.click(ui.cFamilyBuildButton.get());
await user.click(ui.linuxButton.get());
expect(getCopyToClipboardValue(0, 'Copy')).toMatchSnapshot(
- 'cfamily linux: execute build wrapper'
+ 'cfamily linux: execute build wrapper',
);
expect(getCopyToClipboardValue(1, 'Copy')).toMatchSnapshot('cfamily linux: execute scanner');
// C Family - Windows
await user.click(ui.windowsButton.get());
expect(getCopyToClipboardValue(0, 'Copy')).toMatchSnapshot(
- 'cfamily windows: execute build wrapper'
+ 'cfamily windows: execute build wrapper',
);
expect(getCopyToClipboardValue(1, 'Copy')).toMatchSnapshot('cfamily windows: execute scanner');
// C Family - MacOS
await user.click(ui.macosButton.get());
expect(getCopyToClipboardValue(0, 'Copy')).toMatchSnapshot(
- 'cfamily macos: execute build wrapper'
+ 'cfamily macos: execute build wrapper',
);
expect(getCopyToClipboardValue(1, 'Copy')).toMatchSnapshot('cfamily macos: execute scanner');
component={mockComponent()}
currentUser={mockLoggedInUser()}
/>,
- { languages }
+ { languages },
);
}
className="sw-px-4"
isOneLine
snippet={`${executables[os]} --out-dir bw-output ${translate(
- 'onboarding.analysis.build_wrapper.execute_build_command'
+ 'onboarding.analysis.build_wrapper.execute_build_command',
)}`}
/>
<p className="sw-mt-4">
export function buildGithubLink(
almBinding: AlmSettingsInstance,
- projectBinding: ProjectAlmBindingResponse
+ projectBinding: ProjectAlmBindingResponse,
) {
if (almBinding.url === undefined) {
return null;
export function buildBitbucketCloudLink(
almBinding: AlmSettingsInstance,
- projectBinding: ProjectAlmBindingResponse
+ projectBinding: ProjectAlmBindingResponse,
) {
if (almBinding.url === undefined || projectBinding.repository === undefined) {
return null;
type EllipsisPredicate = (
node: HTMLElement,
- props: Omit<AutoEllipsisProps, 'customShouldEllipsis'>
+ props: Omit<AutoEllipsisProps, 'customShouldEllipsis'>,
) => boolean;
interface AutoEllipsisProps {
},
// We don't want to apply this effect when ellipsis state change, only this effect can change it
// eslint-disable-next-line react-hooks/exhaustive-deps
- [props.customShouldEllipsis, props.maxHeight, props.maxWidth, props.useParent]
+ [props.customShouldEllipsis, props.maxHeight, props.maxWidth, props.useParent],
);
return [autoEllipsis, ref];
export const defaultShouldEllipsis: EllipsisPredicate = (
node,
- { useParent = true, maxWidth, maxHeight }
+ { useParent = true, maxWidth, maxHeight },
) => {
if (node.parentElement && useParent) {
maxWidth = maxWidth ?? node.parentElement.clientWidth;
`}
className={classNames(
className,
- 'page-shortcuts-tooltip note text-center display-inline-block'
+ 'page-shortcuts-tooltip note text-center display-inline-block',
)}
>
<div aria-hidden>
it('should render inline alert', () => {
expect(shallowRender({ display: 'inline' }).find('Styled(div)[isInline=true]').exists()).toBe(
- true
+ true,
);
});
it('should render banner alert', () => {
expect(shallowRender({ display: 'banner' }).find('Styled(div)[isBanner=true]').exists()).toBe(
- true
+ true,
);
});
return shallow(
<Alert className="alert-test" id="error-message" variant="error" {...props}>
This is an error!
- </Alert>
+ </Alert>,
);
}
const wrapper = shallow(
<AutoEllipsis maxWidth={5} useParent={false}>
<span className="medium">my test text</span>
- </AutoEllipsis>
+ </AutoEllipsis>,
);
expect(wrapper).toMatchSnapshot();
const wrapper = mount(
<AutoEllipsis customShouldEllipsis={() => true} maxWidth={5} useParent={false}>
<span className="medium">my test text</span>
- </AutoEllipsis>
+ </AutoEllipsis>,
);
expect(wrapper.find('span').hasClass('medium')).toBe(true);
expect(defaultShouldEllipsis(node10, { maxHeight: 5, useParent: false })).toBe(true);
expect(defaultShouldEllipsis(node10, { maxWidth: 5, maxHeight: 5, useParent: false })).toBe(true);
expect(defaultShouldEllipsis(node10, { maxWidth: 5, maxHeight: 10, useParent: false })).toBe(
- true
+ true,
);
expect(defaultShouldEllipsis(node10, { maxWidth: 10, maxHeight: 5, useParent: false })).toBe(
- true
+ true,
);
expect(defaultShouldEllipsis(node10, { maxWidth: 10, useParent: false })).toBe(false);
expect(defaultShouldEllipsis(node10, { maxHeight: 10, useParent: false })).toBe(false);
return shallow<DismissableAlertProps>(
<DismissableAlert alertKey="foo" variant="info" {...props}>
<div>My content</div>
- </DismissableAlert>
+ </DismissableAlert>,
);
}
return renderComponent(
<DismissableAlertComponent onDismiss={jest.fn()} variant="info" {...props}>
testing
- </DismissableAlertComponent>
+ </DismissableAlertComponent>,
);
}
hash="7daf6c79d4802916d83f6266e24850af"
name="Foo"
size={30}
- />
+ />,
);
expect(avatar).toMatchSnapshot();
});
it('falls back to dummy avatar', () => {
const avatar = shallow(
- <LegacyAvatar appState={mockAppState({ settings: {} })} name="Foo Bar" size={30} />
+ <LegacyAvatar appState={mockAppState({ settings: {} })} name="Foo Bar" size={30} />,
);
expect(avatar).toMatchSnapshot();
});
it('do not fail when name is missing', () => {
const avatar = shallow(
- <LegacyAvatar appState={mockAppState({ settings: {} })} name={undefined} size={30} />
+ <LegacyAvatar appState={mockAppState({ settings: {} })} name={undefined} size={30} />,
);
expect(avatar.getElement()).toBeNull();
});
expect(shallowRender({ muted: true, small: true })).toMatchSnapshot('muted and small');
expect(shallowRender({ 'aria-label': 'ARIA Label' })).toMatchSnapshot('with aria-label');
expect(shallowRender({ 'aria-labelledby': 'element-id' })).toMatchSnapshot(
- 'with aria-labelledby'
+ 'with aria-labelledby',
);
});
return shallow(
<NavBar height={42} {...props}>
<div className="my-navbar-content" />
- </NavBar>
+ </NavBar>,
);
}
return shallow(
<NewsBox onClose={jest.fn()} title="title" {...props}>
<div>description</div>
- </NewsBox>
+ </NewsBox>,
);
}
await user.hover(
screen.getByLabelText(
- 'shortcuts.on_page.intro shortcuts.on_page.up_down_x.up & down shortcuts.on_page.left_right_x.left & right shortcuts.on_page.left_x.left shortcuts.on_page.meta_x.meta'
- )
+ 'shortcuts.on_page.intro shortcuts.on_page.up_down_x.up & down shortcuts.on_page.left_right_x.left & right shortcuts.on_page.left_x.left shortcuts.on_page.meta_x.meta',
+ ),
);
expect(await screen.findByText(leftAndRightLabel)).toBeInTheDocument();
await user.hover(
screen.getByLabelText(
- 'shortcuts.on_page.intro shortcuts.on_page.left_right_x.left & right shortcuts.on_page.left_x.left'
- )
+ 'shortcuts.on_page.intro shortcuts.on_page.left_right_x.left & right shortcuts.on_page.left_x.left',
+ ),
);
expect(await screen.findByText(leftAndRightLabel)).toBeInTheDocument();
it('renders with a custom aria-label', () => {
expect(shallow(<Rating aria-label="custom" aria-hidden={false} value="2.0" />)).toMatchSnapshot();
expect(
- shallow(<Rating aria-label="custom" aria-hidden={false} value={undefined} />)
+ shallow(<Rating aria-label="custom" aria-hidden={false} value={undefined} />),
).toMatchSnapshot();
});
className="foo"
placement={PopupPlacement.LeftTop}
style={{ left: -5 }}
- />
- )
+ />,
+ ),
).toMatchSnapshot();
});
const wrapper = shallowRender({ arrowOffset: -2 });
expect(
- wrapper.instance().adjustArrowPosition(PopupPlacement.BottomLeft, { leftFix: 10, topFix: 10 })
+ wrapper
+ .instance()
+ .adjustArrowPosition(PopupPlacement.BottomLeft, { leftFix: 10, topFix: 10 }),
).toEqual({ marginLeft: -12 });
expect(
wrapper
.instance()
- .adjustArrowPosition(PopupPlacement.RightBottom, { leftFix: 10, topFix: 10 })
+ .adjustArrowPosition(PopupPlacement.RightBottom, { leftFix: 10, topFix: 10 }),
).toEqual({ marginTop: -12 });
});
return shallow<PortalPopup>(
<PortalPopup overlay={<span id="overlay" />} {...props}>
<div id="popup-trigger" />
- </PortalPopup>
+ </PortalPopup>,
);
}
});
'popup',
`is-${placement}`,
{ 'no-padding': props.noPadding },
- props.className
+ props.className,
)}
ref={ref || React.createRef()}
style={props.style}
adjustArrowPosition = (
placement: PopupPlacement,
- { leftFix, topFix }: { leftFix: number; topFix: number }
+ { leftFix, topFix }: { leftFix: number; topFix: number },
) => {
const { arrowOffset = 0 } = this.props;
switch (placement) {
{advancedDownloadUrl.label}
</a>
</span>
- )
+ ),
)}
{changeLogUrl && (
}
function isAdvancedDownloadUrlArray(
- downloadUrl: string | AdvancedDownloadUrl[] | undefined
+ downloadUrl: string | AdvancedDownloadUrl[] | undefined,
): downloadUrl is AdvancedDownloadUrl[] {
return !!downloadUrl && typeof downloadUrl !== 'string';
}
versionInformation: mockMetaDataVersionInformation({
downloadURL: [{ label: 'macos 64 bits', url: '' }],
}),
- })
+ }),
).toMatchSnapshot('with advanced downloadUrl');
expect(
shallowRender({
versionInformation: { version: '2.0' },
- })
+ }),
).toMatchSnapshot('with very few info');
});
function shallowRender(props?: Partial<MetaDataVersionProps>) {
return shallow(
- <MetaDataVersion versionInformation={mockMetaDataVersionInformation()} {...props} />
+ <MetaDataVersion versionInformation={mockMetaDataVersionInformation()} {...props} />,
);
}
mockMetaDataVersionInformation({ version: '1.0', archived: true }),
]}
{...props}
- />
+ />,
);
}
import { MetaDataInformation, MetaDataVersionInformation } from '../update-center-metadata';
export function mockMetaDataVersionInformation(
- overrides?: Partial<MetaDataVersionInformation>
+ overrides?: Partial<MetaDataVersionInformation>,
): MetaDataVersionInformation {
return {
version: '5.13',
}
export function mockMetaDataInformation(
- overrides?: Partial<MetaDataInformation>
+ overrides?: Partial<MetaDataInformation>,
): MetaDataInformation {
return {
name: 'SonarJava',
const [, major, minor] = parsedVersion;
const majoMinorVersion = `${major}.${minor}`;
patches = flatMap(systemUpgrades, (upgrades) =>
- filter(upgrades, (upgrade) => upgrade.version.startsWith(majoMinorVersion))
+ filter(upgrades, (upgrade) => upgrade.version.startsWith(majoMinorVersion)),
);
systemUpgradesWithPatch = systemUpgrades
.map((upgrades) =>
- upgrades.filter((upgrade) => !upgrade.version.startsWith(majoMinorVersion))
+ upgrades.filter((upgrade) => !upgrade.version.startsWith(majoMinorVersion)),
)
.filter(negate(isEmpty));
systemUpgradesWithPatch.push(patches);
const lastUpgrade = systemUpgrades[0];
const downloadUrl = getEditionDownloadUrl(
getEdition(edition || EditionKey.community),
- lastUpgrade
+ lastUpgrade,
);
let header = translate('system.latest_version');
if (isLTSVersion) {
function shallowRender(props: Partial<SystemUpgradeButton['props']> = {}) {
return shallow<SystemUpgradeButton['props']>(
- <SystemUpgradeButton systemUpgrades={[]} latestLTS="9.2" {...props} />
+ <SystemUpgradeButton systemUpgrades={[]} latestLTS="9.2" {...props} />,
);
}
systemUpgrades={UPGRADES}
latestLTS="9.1"
updateUseCase={updateUseCase}
- />
- )
+ />,
+ ),
).toMatchSnapshot();
- }
+ },
);
downloadUrl: 'http://download.url/community',
},
],
- })
+ }),
).toMatchSnapshot();
});
isPatch={false}
isLTSVersion={false}
{...props}
- />
+ />,
);
}
{ version: '5.10' },
{ version: '5.1' },
{ version: '5.4' },
- ] as SystemUpgrade[])
+ ] as SystemUpgrade[]),
).toEqual([{ version: '5.10' }, { version: '5.4.2' }, { version: '5.4' }, { version: '5.1' }]);
expect(
u.sortUpgrades([
{ version: '5.1.2' },
{ version: '6.0' },
{ version: '6.9' },
- ] as SystemUpgrade[])
+ ] as SystemUpgrade[]),
).toEqual([{ version: '6.9' }, { version: '6.0' }, { version: '5.10' }, { version: '5.1.2' }]);
});
});
{ version: '5.4.2' },
{ version: '5.4' },
{ version: '5.1' },
- ] as SystemUpgrade[])
+ ] as SystemUpgrade[]),
).toEqual([
[{ version: '5.10' }, { version: '5.4.2' }, { version: '5.4' }, { version: '5.1' }],
]);
{ version: '6.0' },
{ version: '5.10' },
{ version: '5.4.2' },
- ] as SystemUpgrade[])
+ ] as SystemUpgrade[]),
).toEqual([
[{ version: '6.9' }, { version: '6.7' }, { version: '6.0' }],
[{ version: '5.10' }, { version: '5.4.2' }],
try {
const data: any[] = JSON.parse(get(WORKSPACE) || '');
const components: ComponentDescriptor[] = data.filter(
- (x) => x[TYPE_KEY] === WorkspaceTypes.Component
+ (x) => x[TYPE_KEY] === WorkspaceTypes.Component,
);
return { components };
} catch {
// Do not save line number, next time the file is open, it should be open
// on the first line.
...this.state.components.map((x) =>
- omit({ ...x, [TYPE_KEY]: WorkspaceTypes.Component }, 'line')
+ omit({ ...x, [TYPE_KEY]: WorkspaceTypes.Component }, 'line'),
),
];
save(WORKSPACE, JSON.stringify(data));
const { key, name, qualifier } = details;
this.setState((state: State) => ({
components: state.components.map((component) =>
- component.key === key ? { ...component, name, qualifier } : component
+ component.key === key ? { ...component, name, qualifier } : component,
),
}));
}
if (this.container && this.props.component.line) {
const row = this.container.querySelector(
- `.it__source-line[data-line-number="${this.props.component.line}"]`
+ `.it__source-line[data-line-number="${this.props.component.line}"]`,
);
if (row) {
row.scrollIntoView({ block: 'center' });
expect(byText('previously opened file').get()).toBeInTheDocument();
expect(
- byRole('heading', { name: 'qualifier.FIL path/to/component/k1' }).query()
+ byRole('heading', { name: 'qualifier.FIL path/to/component/k1' }).query(),
).not.toBeInTheDocument();
await user.click(ui.componentOpenButton.get());
expect(
- byRole('heading', { name: 'qualifier.FIL path/to/component/k1' }).get()
+ byRole('heading', { name: 'qualifier.FIL path/to/component/k1' }).get(),
).toBeInTheDocument();
expect(save).toHaveBeenCalled();
});
return renderComponent(
<Workspace>
<TestComponent componentKey={componentKey} branchLike={branchLike} />
- </Workspace>
+ </Workspace>,
);
}
branch2Pr1,
branch1Pr2,
branch1Pr1,
- ])
+ ]),
).toEqual({
mainBranchTree: {
branch: main,
it('compares pull requests', () => {
expect(
- isSameBranchLike(mockPullRequest({ key: '1234' }), mockPullRequest({ key: '1234' }))
+ isSameBranchLike(mockPullRequest({ key: '1234' }), mockPullRequest({ key: '1234' })),
).toBe(true);
expect(
- isSameBranchLike(mockPullRequest({ key: '1234' }), mockPullRequest({ key: '5678' }))
+ isSameBranchLike(mockPullRequest({ key: '1234' }), mockPullRequest({ key: '5678' })),
).toBe(false);
});
applyCodeDifferences(container);
// eslint-disable-next-line testing-library/no-container, testing-library/no-node-access
expect(container.getElementsByClassName('code-difference-scrollable')).toMatchSnapshot(
- 'differenciatedCode'
+ 'differenciatedCode',
);
});
dangerouslySetInnerHTML={{
__html: codeSnippet,
}}
- />
+ />,
);
}
await expect(
throwGlobalError(response).then(() => {
throw new Error('Should throw');
- })
+ }),
).rejects.toBe(response);
});
addGlobalErrorMessage('test');
expect(listener1).toHaveBeenCalledWith(
- expect.objectContaining({ text: 'test', level: MessageLevel.Error })
+ expect.objectContaining({ text: 'test', level: MessageLevel.Error }),
);
listener1.mockClear();
addGlobalSuccessMessage('test');
expect(listener1).toHaveBeenCalledWith(
- expect.objectContaining({ text: 'test', level: MessageLevel.Success })
+ expect.objectContaining({ text: 'test', level: MessageLevel.Success }),
);
expect(listener2).toHaveBeenCalledWith(
- expect.objectContaining({ text: 'test', level: MessageLevel.Success })
+ expect.objectContaining({ text: 'test', level: MessageLevel.Success }),
);
});
const securityHotspot = mockIssue(false, { type: 'SECURITY_HOTSPOT', key: 'security_hotspot' });
expect(
- sortByType([bug1, codeSmell, bug2, securityHotspot, vulnerability1, vulnerability2])
+ sortByType([bug1, codeSmell, bug2, securityHotspot, vulnerability1, vulnerability2]),
).toEqual([bug1, bug2, vulnerability1, vulnerability2, codeSmell, securityHotspot]);
});
x_apples: '{0}: I have {2} apples in my {1} baskets - {3}',
});
expect(translateWithParameters('x_apples', 1, 2, 3, 4)).toBe(
- '1: I have 3 apples in my 2 baskets - 4'
+ '1: I have 3 apples in my 2 baskets - 4',
);
});
'metric.new_code.extra_short_name': 'metric.new_code.extra_short_name_t',
});
expect(getLocalizedCategoryMetricName({ key: 'new_code' })).toBe(
- 'metric.new_code.extra_short_name_t'
+ 'metric.new_code.extra_short_name_t',
);
});
const bundle = await loadL10nBundle();
expect(bundle).toEqual(
- expect.objectContaining({ locale: cachedBundle.locale, messages: cachedBundle.messages })
+ expect.objectContaining({ locale: cachedBundle.locale, messages: cachedBundle.messages }),
);
});
});
];
expect(
- enhanceConditionWithMeasure(mockQualityGateStatusCondition({ metric: 'bugs' }), measures)
+ enhanceConditionWithMeasure(mockQualityGateStatusCondition({ metric: 'bugs' }), measures),
).toMatchObject({
measure: expect.objectContaining({ metric: expect.objectContaining({ key: 'bugs' }) }),
});
expect(
- enhanceConditionWithMeasure(mockQualityGateStatusCondition({ metric: 'new_bugs' }), measures)
+ enhanceConditionWithMeasure(mockQualityGateStatusCondition({ metric: 'new_bugs' }), measures),
).toMatchObject({
measure: expect.objectContaining({
metric: expect.objectContaining({ key: 'new_bugs' }),
expect(isPeriodBestValue(mockMeasureEnhanced({ period: undefined }))).toBe(false);
expect(
isPeriodBestValue(
- mockMeasureEnhanced({ period: { index: 1, value: '1.0', bestValue: false } })
- )
+ mockMeasureEnhanced({ period: { index: 1, value: '1.0', bestValue: false } }),
+ ),
).toBe(false);
expect(
isPeriodBestValue(
- mockMeasureEnhanced({ period: { index: 1, value: '1.0', bestValue: true } })
- )
+ mockMeasureEnhanced({ period: { index: 1, value: '1.0', bestValue: true } }),
+ ),
).toBe(true);
});
});
expect(formatMeasure(50.89, 'PERCENT', { decimals: 2 })).toBe('50.89%');
expect(formatMeasure(50.89, 'PERCENT', { decimals: 3 })).toBe('50.890%');
expect(formatMeasure(50, 'PERCENT', { decimals: 0, omitExtraDecimalZeros: true })).toBe(
- '50.0%'
+ '50.0%',
);
expect(formatMeasure(50, 'PERCENT', { decimals: 1, omitExtraDecimalZeros: true })).toBe(
- '50.0%'
+ '50.0%',
);
expect(formatMeasure(50, 'PERCENT', { decimals: 3, omitExtraDecimalZeros: true })).toBe(
- '50.0%'
+ '50.0%',
);
expect(formatMeasure(50.89, 'PERCENT', { decimals: 3, omitExtraDecimalZeros: true })).toBe(
- '50.89%'
+ '50.89%',
);
});
'should test for new code definition compliance properly %s',
(newCodePeriod: NewCodeDefinition, result: boolean) => {
expect(isNewCodeDefinitionCompliant(newCodePeriod)).toEqual(result);
- }
+ },
);
});
(
globalNewCodeDefinition: NewCodeDefinition | null,
inheritedNewCodeDefinition: NewCodeDefinition | null,
- result: string
+ result: string,
) => {
expect(
- getNumberOfDaysDefaultValue(globalNewCodeDefinition, inheritedNewCodeDefinition)
+ getNumberOfDaysDefaultValue(globalNewCodeDefinition, inheritedNewCodeDefinition),
).toEqual(result);
- }
+ },
);
});
it('should handle date', () => {
expect(getNewCodePeriodLabel(mockPeriod({ mode: 'date' }), formatter)).toBe(
- 'overview.period.date.'
+ 'overview.period.date.',
);
expect(
getNewCodePeriodLabel(
mockPeriod({ mode: 'date', parameter: '2019-02-21T01:11:21+0100' }),
- formatter
- )
+ formatter,
+ ),
).toBe('overview.period.date.2019-02-21T01:11:21+0100');
expect(formatter).toHaveBeenCalledTimes(1);
});
it('should handle days', () => {
expect(getNewCodePeriodLabel(mockPeriod({ mode: 'days', modeParam: '12' }), formatter)).toBe(
- 'overview.period.days.12'
+ 'overview.period.days.12',
);
expect(formatter).not.toHaveBeenCalled();
});
expect(
getNewCodePeriodLabel(
mockPeriod({ mode: 'previous_analysis', parameter: 'param' }),
- formatter
- )
+ formatter,
+ ),
).toBe('overview.period.previous_analysis.param');
expect(formatter).not.toHaveBeenCalled();
});
it('should handle previous version', () => {
expect(getNewCodePeriodLabel(mockPeriod({ mode: 'previous_version' }), formatter)).toBe(
- 'overview.period.previous_version_only_date'
+ 'overview.period.previous_version_only_date',
);
expect(
- getNewCodePeriodLabel(mockPeriod({ mode: 'previous_version', parameter: '7.9' }), formatter)
+ getNewCodePeriodLabel(mockPeriod({ mode: 'previous_version', parameter: '7.9' }), formatter),
).toBe('overview.period.previous_version.7.9');
expect(formatter).not.toHaveBeenCalled();
});
it('should handle version', () => {
expect(
- getNewCodePeriodLabel(mockPeriod({ mode: 'version', modeParam: '7.2' }), formatter)
+ getNewCodePeriodLabel(mockPeriod({ mode: 'version', modeParam: '7.2' }), formatter),
).toBe('overview.period.version.7.2');
expect(
- getNewCodePeriodLabel(mockPeriod({ mode: 'previous_version', parameter: '7.9' }), formatter)
+ getNewCodePeriodLabel(mockPeriod({ mode: 'previous_version', parameter: '7.9' }), formatter),
).toBe('overview.period.previous_version.7.9');
expect(formatter).not.toHaveBeenCalled();
});
expect(
getNewCodePeriodLabel(
mockPeriod({ mode: 'manual_baseline', modeParam: 'A658678DE' }),
- formatter
- )
+ formatter,
+ ),
).toBe('overview.period.manual_baseline.A658678DE');
expect(getNewCodePeriodLabel(mockPeriod({ mode: 'manual_baseline' }), formatter)).toBe(
- 'overview.period.manual_baseline.2019-04-23T02:12:32+0100'
+ 'overview.period.manual_baseline.2019-04-23T02:12:32+0100',
);
expect(formatter).toHaveBeenCalledTimes(1);
});
expect(
getNewCodePeriodLabel(
mockPeriod({ mode: NewCodeDefinitionType.SpecificAnalysis, parameter: '7.1' }),
- formatter
- )
+ formatter,
+ ),
).toBe('overview.period.specific_analysis.2019-04-23T02:12:32+0100');
expect(
- getNewCodePeriodLabel(mockPeriod({ mode: NewCodeDefinitionType.SpecificAnalysis }), formatter)
+ getNewCodePeriodLabel(
+ mockPeriod({ mode: NewCodeDefinitionType.SpecificAnalysis }),
+ formatter,
+ ),
).toBe('overview.period.specific_analysis.2019-04-23T02:12:32+0100');
expect(formatter).toHaveBeenCalledTimes(2);
});
expect(
getNewCodePeriodLabel(
mockPeriod({ mode: NewCodeDefinitionType.PreviousVersion, modeParam: 'A658678DE' }),
- formatter
- )
+ formatter,
+ ),
).toBe('overview.period.previous_version.A658678DE');
expect(
- getNewCodePeriodLabel(mockPeriod({ mode: NewCodeDefinitionType.PreviousVersion }), formatter)
+ getNewCodePeriodLabel(mockPeriod({ mode: NewCodeDefinitionType.PreviousVersion }), formatter),
).toBe('overview.period.previous_version.2019-04-23T02:12:32+0100');
expect(formatter).toHaveBeenCalledTimes(1);
});
it('should cut long path', () => {
expect(collapsedDirFromPath('src/main/js/components/navigator/app/models/state.js')).toBe(
- 'src/.../js/components/navigator/app/models/'
+ 'src/.../js/components/navigator/app/models/',
);
});
it('should cut very long path', () => {
expect(
- collapsedDirFromPath('src/main/another/js/components/navigator/app/models/state.js')
+ collapsedDirFromPath('src/main/another/js/components/navigator/app/models/state.js'),
).toBe('src/.../js/components/navigator/app/models/');
});
});
describe('#cutLongWords', () => {
it('should cut the long work in the middle', () => {
expect(cutLongWords('This is a reallylongwordthatdontexistforthe test')).toBe(
- 'This is a reallylongwordthatdontexistfor... test'
+ 'This is a reallylongwordthatdontexistfor... test',
);
});
expect(validateProjectKey('123')).toBe(ProjectKeyValidationResult.OnlyDigits);
// Cannot be more than 400 chars long.
expect(validateProjectKey(new Array(PROJECT_KEY_MAX_LEN + 1).fill('a').join(''))).toBe(
- ProjectKeyValidationResult.TooLong
+ ProjectKeyValidationResult.TooLong,
);
// Cannot be empty.
expect(validateProjectKey('')).toBe(ProjectKeyValidationResult.Empty);
it('should correclty extract the conditions for the application child project status', () => {
expect(
extractStatusConditionsFromApplicationStatusChildProject(
- mockQualityGateApplicationStatus().projects[0]
- )
+ mockQualityGateApplicationStatus().projects[0],
+ ),
).toEqual([
{
actual: '10',
getJSON(url, { data: 'test' });
expect(window.fetch).toHaveBeenCalledWith(
url + '?data=test',
- expect.objectContaining({ method: 'GET' })
+ expect.objectContaining({ method: 'GET' }),
);
});
});
getText(url, { data: 'test' });
expect(window.fetch).toHaveBeenCalledWith(
url + '?data=test',
- expect.objectContaining({ method: 'GET' })
+ expect.objectContaining({ method: 'GET' }),
);
});
});
it('should parse error and return concatenated messages', async () => {
const response = new Response(
JSON.stringify({ errors: [{ msg: 'Error1' }, { msg: 'Error2' }] }),
- { status: HttpStatus.BadRequest }
+ { status: HttpStatus.BadRequest },
);
await expect(parseError(response)).resolves.toBe('Error1. Error2');
});
postJSON(url, { data: 'test' });
expect(window.fetch).toHaveBeenCalledWith(
url,
- expect.objectContaining({ body: 'data=test', method: 'POST' })
+ expect.objectContaining({ body: 'data=test', method: 'POST' }),
);
});
});
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: '{"nested":{"data":"test","withArray":[1,2]}}',
method: 'POST',
- })
+ }),
);
});
});
expect(window.fetch).toHaveBeenCalledWith(
url,
- expect.objectContaining({ body: 'data=test', method: 'POST' })
+ expect.objectContaining({ body: 'data=test', method: 'POST' }),
);
expect(response.json).not.toHaveBeenCalled();
expect(response.text).not.toHaveBeenCalled();
expect(window.fetch).toHaveBeenCalledWith(
url,
- expect.objectContaining({ body: 'dataArray=1&dataArray=2', method: 'POST' })
+ expect.objectContaining({ body: 'dataArray=1&dataArray=2', method: 'POST' }),
);
});
});
const promiseResult = requestTryAndRepeatUntil(
apiCall,
{ max: -1, slowThreshold: -20 },
- stopRepeat
+ stopRepeat,
);
for (let i = 1; i < 5; i++) {
apiCall,
{ max: -1, slowThreshold: -20 },
stopRepeat,
- [HttpStatus.GatewayTimeout]
+ [HttpStatus.GatewayTimeout],
);
for (let i = 1; i < 5; i++) {
const promiseResult = requestTryAndRepeatUntil(
apiCall,
{ max: 3, slowThreshold: 0 },
- stopRepeat
+ stopRepeat,
);
for (let i = 1; i < 3; i++) {
const promiseResult = requestTryAndRepeatUntil(
apiCall,
{ max: 5, slowThreshold: 3 },
- stopRepeat
+ stopRepeat,
);
for (let i = 1; i < 3; i++) {
as well. This is <b>Amazing</b> and this <strong>bold</strong> <br>
and <code>code.is.accepted too</code>
</p>
- `)
+ `),
).toBe(`
Hi <a target="_blank" href="http://example.com">this</a> is <i>in italics</i> and <ul>
<li> lists </li>
<span title=malformed attribs' do=don't id=foo checked onclick="a<b">Bar</span>`);
expect(clean.replace(/\s+/g, '')).toBe(
- `Clickyalert("<b>hi</b>");<divid=notarealtagonclick=notcode()><notatag<<<allinonetextblock>>><%#somephpcodeherewrite("$horriblySyntacticConstruct1");%>*/alert('hi');*/alert('hi');-->*/alert('hi');-->'}-->--><!--Zoicks-->sectioninHTML]]><ahref=""></a><ahref="/">Bar</a>`
+ `Clickyalert("<b>hi</b>");<divid=notarealtagonclick=notcode()><notatag<<<allinonetextblock>>><%#somephpcodeherewrite("$horriblySyntacticConstruct1");%>*/alert('hi');*/alert('hi');-->*/alert('hi');-->'}-->--><!--Zoicks-->sectioninHTML]]><ahref=""></a><ahref="/">Bar</a>`,
);
});
});
};
it('should render cwe categories correctly', () => {
expect(renderCWECategory(standards, '1004')).toEqual(
- "CWE-1004 - Sensitive Cookie Without 'HttpOnly' Flag"
+ "CWE-1004 - Sensitive Cookie Without 'HttpOnly' Flag",
);
expect(renderCWECategory(standards, '124')).toEqual('CWE-124');
expect(renderCWECategory(standards, 'unknown')).toEqual('No CWE associated');
};
it('should render Pci Dss 3.2 correctly', () => {
expect(renderPciDss32Category(standards, '1')).toEqual(
- '1 - Install and maintain a firewall configuration to protect cardholder data'
+ '1 - Install and maintain a firewall configuration to protect cardholder data',
);
expect(renderPciDss32Category(standards, '1.1')).toEqual('1.1');
});
};
it('should render Pci Dss 4.0 correctly', () => {
expect(renderPciDss40Category(standards, '1')).toEqual(
- '1 - Install and maintain a firewall configuration to protect cardholder data'
+ '1 - Install and maintain a firewall configuration to protect cardholder data',
);
expect(renderPciDss40Category(standards, '1.1')).toEqual('1.1');
});
};
it('should render sonarsource categories correctly', () => {
expect(renderSonarSourceSecurityCategory(standards, 'xss')).toEqual(
- 'Cross-Site Scripting (XSS)'
+ 'Cross-Site Scripting (XSS)',
);
expect(renderSonarSourceSecurityCategory(standards, 'xss', true)).toEqual(
- 'SONAR Cross-Site Scripting (XSS)'
+ 'SONAR Cross-Site Scripting (XSS)',
);
expect(renderSonarSourceSecurityCategory(standards, 'others')).toEqual('Others');
expect(renderSonarSourceSecurityCategory(standards, 'others', true)).toEqual('Others');
};
expect(stringify(obj)).toEqual(
- 'prop1=a%20string&prop2=123&prop3=true&prop4=&prop5=9&prop5=8&prop5=7&prop6='
+ 'prop1=a%20string&prop2=123&prop3=true&prop4=&prop5=9&prop5=8&prop5=7&prop6=',
);
});
};
expect(
decodeJwt(
- 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhcmk6Y2xvdWQ6Yml0YnVja2V0OjphcHAvezMyNzcxM2VkLWYxYjItNDY1OS05YzkxLWM4ZWNmOGJlN2YzZX0vc29uYXJjbG91ZC1ncmVnIiwiaWF0IjoxNTQxMDU4NjA1LCJxc2giOiJhNmM5M2FkZGQ5NzFjMDVkMDhkYTFlMTY2OWMyNjQwZmJhNTI5ZTk4ZmJiNWIyYjllZmZhZGYwMGJmNDg0Mjc3IiwiYXVkIjoiYXJpOmNsb3VkOmJpdGJ1Y2tldDo6YXBwL3szMjc3MTNlZC1mMWIyLTQ2NTktOWM5MS1jOGVjZjhiZTdmM2V9L3NvbmFyY2xvdWQtZ3JlZyIsImV4cCI6MTU0MTA2MjIwNX0.5_0dFh_TPT_UorDewu2JEErgQE2ZnzBjvCDrOThseRo'
- )
+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhcmk6Y2xvdWQ6Yml0YnVja2V0OjphcHAvezMyNzcxM2VkLWYxYjItNDY1OS05YzkxLWM4ZWNmOGJlN2YzZX0vc29uYXJjbG91ZC1ncmVnIiwiaWF0IjoxNTQxMDU4NjA1LCJxc2giOiJhNmM5M2FkZGQ5NzFjMDVkMDhkYTFlMTY2OWMyNjQwZmJhNTI5ZTk4ZmJiNWIyYjllZmZhZGYwMGJmNDg0Mjc3IiwiYXVkIjoiYXJpOmNsb3VkOmJpdGJ1Y2tldDo6YXBwL3szMjc3MTNlZC1mMWIyLTQ2NTktOWM5MS1jOGVjZjhiZTdmM2V9L3NvbmFyY2xvdWQtZ3JlZyIsImV4cCI6MTU0MTA2MjIwNX0.5_0dFh_TPT_UorDewu2JEErgQE2ZnzBjvCDrOThseRo',
+ ),
).toEqual(claims);
expect(
decodeJwt(
- 'eyJpc3MiOiJhcmk6Y2xvdWQ6Yml0YnVja2V0OjphcHAvezMyNzcxM2VkLWYxYjItNDY1OS05YzkxLWM4ZWNmOGJlN2YzZX0vc29uYXJjbG91ZC1ncmVnIiwiaWF0IjoxNTQxMDU4NjA1LCJxc2giOiJhNmM5M2FkZGQ5NzFjMDVkMDhkYTFlMTY2OWMyNjQwZmJhNTI5ZTk4ZmJiNWIyYjllZmZhZGYwMGJmNDg0Mjc3IiwiYXVkIjoiYXJpOmNsb3VkOmJpdGJ1Y2tldDo6YXBwL3szMjc3MTNlZC1mMWIyLTQ2NTktOWM5MS1jOGVjZjhiZTdmM2V9L3NvbmFyY2xvdWQtZ3JlZyIsImV4cCI6MTU0MTA2MjIwNX0'
- )
+ 'eyJpc3MiOiJhcmk6Y2xvdWQ6Yml0YnVja2V0OjphcHAvezMyNzcxM2VkLWYxYjItNDY1OS05YzkxLWM4ZWNmOGJlN2YzZX0vc29uYXJjbG91ZC1ncmVnIiwiaWF0IjoxNTQxMDU4NjA1LCJxc2giOiJhNmM5M2FkZGQ5NzFjMDVkMDhkYTFlMTY2OWMyNjQwZmJhNTI5ZTk4ZmJiNWIyYjllZmZhZGYwMGJmNDg0Mjc3IiwiYXVkIjoiYXJpOmNsb3VkOmJpdGJ1Y2tldDo6YXBwL3szMjc3MTNlZC1mMWIyLTQ2NTktOWM5MS1jOGVjZjhiZTdmM2V9L3NvbmFyY2xvdWQtZ3JlZyIsImV4cCI6MTU0MTA2MjIwNX0',
+ ),
).toEqual(claims);
});
});
describe('#latinize', () => {
it('should remove diacritics and replace them with normal letters', () => {
expect(latinize('âêîôûŵŷäëïöüẅÿàèìòùẁỳáéíóúẃýøāēīūčģķļņšž')).toBe(
- 'aeiouwyaeiouwyaeiouwyaeiouwyoaeiucgklnsz'
+ 'aeiouwyaeiouwyaeiouwyaeiouwyoaeiucgklnsz',
);
expect(latinize('ASDFGhjklQWERTz')).toBe('ASDFGhjklQWERTz');
});
value,
label: `users.tokens.expiration.${value.toString()}`,
};
- }
- )
+ },
+ ),
);
});
value,
label: `users.tokens.expiration.${value.toString()}`,
};
- })
+ }),
);
});
it('should correctly convert a GitHub API URL to a Web URL', () => {
expect(convertGithubApiUrlToLink('https://api.github.com')).toBe('https://github.com');
expect(convertGithubApiUrlToLink('https://company.github.com/api/v3')).toBe(
- 'https://company.github.com'
+ 'https://company.github.com',
);
});
});
expect.objectContaining({
pathname: '/project/issues',
search: queryToSearch({ id: SIMPLE_COMPONENT_KEY }),
- })
+ }),
);
});
expect.objectContaining({
pathname: '/project/issues',
search: queryToSearch({ resolved: 'false', id: SIMPLE_COMPONENT_KEY }),
- })
+ }),
);
});
});
expect.objectContaining({
pathname: '/security_hotspots',
search: queryToSearch({ id: SIMPLE_COMPONENT_KEY }),
- })
+ }),
);
});
[SecurityStandard.PCI_DSS_3_2]: '4.2',
[SecurityStandard.PCI_DSS_4_0]: '4.1',
ignoredParam: '1234',
- })
+ }),
).toEqual(
expect.objectContaining({
pathname: '/security_hotspots',
[SecurityStandard.PCI_DSS_3_2]: '4.2',
[SecurityStandard.PCI_DSS_4_0]: '4.1',
}),
- })
+ }),
);
});
});
expect.objectContaining({
pathname: '/portfolio',
search: queryToSearch({ id: SIMPLE_COMPONENT_KEY }),
- })
+ }),
);
});
it('should return a portfolio url for a subportfolio', () => {
expect.objectContaining({
pathname: '/portfolio',
search: queryToSearch({ id: SIMPLE_COMPONENT_KEY }),
- })
+ }),
);
});
it('should return a dashboard url for a project', () => {
expect.objectContaining({
pathname: '/dashboard',
search: queryToSearch({ id: SIMPLE_COMPONENT_KEY }),
- })
+ }),
);
});
it('should return correct dashboard url for a project when navigating from new code', () => {
SIMPLE_COMPONENT_KEY,
ComponentQualifier.Project,
undefined,
- CodeScope.New
- )
+ CodeScope.New,
+ ),
).toEqual(
expect.objectContaining({
pathname: '/dashboard',
search: queryToSearch({ id: SIMPLE_COMPONENT_KEY, code_scope: 'new' }),
- })
+ }),
);
});
it('should return correct dashboard url for a project when navigating from overall code', () => {
SIMPLE_COMPONENT_KEY,
ComponentQualifier.Project,
undefined,
- CodeScope.Overall
- )
+ CodeScope.Overall,
+ ),
).toEqual(
expect.objectContaining({
pathname: '/dashboard',
search: queryToSearch({ id: SIMPLE_COMPONENT_KEY, code_scope: 'overall' }),
- })
+ }),
);
});
it('should return a dashboard url for an app', () => {
expect.objectContaining({
pathname: '/dashboard',
search: queryToSearch({ id: SIMPLE_COMPONENT_KEY }),
- })
+ }),
);
});
});
describe('#getComponentDrilldownUrl', () => {
it('should return component drilldown url', () => {
expect(
- getComponentDrilldownUrl({ componentKey: SIMPLE_COMPONENT_KEY, metric: METRIC })
+ getComponentDrilldownUrl({ componentKey: SIMPLE_COMPONENT_KEY, metric: METRIC }),
).toEqual(
expect.objectContaining({
pathname: '/component_measures',
search: queryToSearch({ id: SIMPLE_COMPONENT_KEY, metric: METRIC }),
- })
+ }),
);
});
it('should not encode component key', () => {
expect(
- getComponentDrilldownUrl({ componentKey: COMPLEX_COMPONENT_KEY, metric: METRIC })
+ getComponentDrilldownUrl({ componentKey: COMPLEX_COMPONENT_KEY, metric: METRIC }),
).toEqual(
expect.objectContaining({
pathname: '/component_measures',
search: queryToSearch({ id: COMPLEX_COMPONENT_KEY, metric: METRIC }),
- })
+ }),
);
});
it('should add asc param only when its list view', () => {
expect(
- getComponentDrilldownUrl({ componentKey: SIMPLE_COMPONENT_KEY, metric: METRIC, asc: false })
+ getComponentDrilldownUrl({ componentKey: SIMPLE_COMPONENT_KEY, metric: METRIC, asc: false }),
).toEqual(
expect.objectContaining({
pathname: '/component_measures',
search: queryToSearch({ id: SIMPLE_COMPONENT_KEY, metric: METRIC }),
- })
+ }),
);
expect(
metric: METRIC,
listView: true,
asc: false,
- })
+ }),
).toEqual(
expect.objectContaining({
pathname: '/component_measures',
view: 'list',
asc: 'false',
}),
- })
+ }),
);
});
});
describe('#getComponentDrilldownUrlWithSelection', () => {
it('should return component drilldown url with selection', () => {
expect(
- getComponentDrilldownUrlWithSelection(SIMPLE_COMPONENT_KEY, COMPLEX_COMPONENT_KEY, METRIC)
+ getComponentDrilldownUrlWithSelection(SIMPLE_COMPONENT_KEY, COMPLEX_COMPONENT_KEY, METRIC),
).toEqual(
expect.objectContaining({
pathname: '/component_measures',
metric: METRIC,
selected: COMPLEX_COMPONENT_KEY,
}),
- })
+ }),
);
});
SIMPLE_COMPONENT_KEY,
COMPLEX_COMPONENT_KEY,
METRIC,
- mockBranch({ name: 'foo' })
- )
+ mockBranch({ name: 'foo' }),
+ ),
).toEqual(
expect.objectContaining({
pathname: '/component_measures',
branch: 'foo',
selected: COMPLEX_COMPONENT_KEY,
}),
- })
+ }),
);
});
COMPLEX_COMPONENT_KEY,
METRIC,
undefined,
- MeasurePageView.list
- )
+ MeasurePageView.list,
+ ),
).toEqual(
expect.objectContaining({
pathname: '/component_measures',
view: MeasurePageView.list,
selected: COMPLEX_COMPONENT_KEY,
}),
- })
+ }),
);
expect(
COMPLEX_COMPONENT_KEY,
METRIC,
mockMainBranch(),
- MeasurePageView.treemap
- )
+ MeasurePageView.treemap,
+ ),
).toEqual(
expect.objectContaining({
pathname: '/component_measures',
view: MeasurePageView.treemap,
selected: COMPLEX_COMPONENT_KEY,
}),
- })
+ }),
);
expect(
COMPLEX_COMPONENT_KEY,
METRIC,
mockPullRequest({ key: '1' }),
- MeasurePageView.tree
- )
+ MeasurePageView.tree,
+ ),
).toEqual(
expect.objectContaining({
pathname: '/component_measures',
pullRequest: '1',
selected: COMPLEX_COMPONENT_KEY,
}),
- })
+ }),
);
});
});
getPathUrlAsString({
pathname: '/dashboard',
search: queryToSearch({ id: SIMPLE_COMPONENT_KEY }),
- })
+ }),
).toBe('/dashboard?id=' + SIMPLE_COMPONENT_KEY);
});
getPathUrlAsString({
pathname: '/dashboard',
search: queryToSearch({ id: COMPLEX_COMPONENT_KEY }),
- })
+ }),
).toBe('/dashboard?id=' + COMPLEX_COMPONENT_KEY_ENCODED);
});
};
expect(queryToSearch(query)).toBe(
- '?b1=true&b2=false&normalString=hello&author=GRRM&author=JKR&author=Stross'
+ '?b1=true&b2=false&normalString=hello&author=GRRM&author=JKR&author=Stross',
);
});
type: 'APPLICATION',
branch: 'test-branch',
component: 'test-component',
- }
- )
+ },
+ ),
).toBe(true);
expect(
},
{
type: 'ISSUES',
- }
- )
+ },
+ ),
).toBe(false);
expect(
type: 'APPLICATION',
branch: 'test-branch-1',
component: 'test-component',
- }
- )
+ },
+ ),
).toBe(false);
expect(
type: 'APPLICATION',
branch: 'test-branch',
component: 'test-component-1',
- }
- )
+ },
+ ),
).toBe(false);
});
});
const mainBranch = branchLikes.find(isMainBranch);
const branches = orderBy(
branchLikes.filter(isBranch).filter((b) => !isMainBranch(b)),
- (b) => b.name
+ (b) => b.name,
);
const pullRequests = orderBy(branchLikes.filter(isPullRequest), (b) => parseInt(b.key, 10), [
'desc',
]);
const parentlessPullRequests = pullRequests.filter(
- (pr) => !pr.isOrphan && ![mainBranch, ...branches].find((b) => !!b && b.name === pr.base)
+ (pr) => !pr.isOrphan && ![mainBranch, ...branches].find((b) => !!b && b.name === pr.base),
);
const orphanPullRequests = pullRequests.filter((pr) => pr.isOrphan);
export function getBranchLikeQuery(
branchLike?: BranchLike,
- includeMainBranch = false
+ includeMainBranch = false,
): BranchParameters {
if (isBranch(branchLike) && (includeMainBranch || !isMainBranch(branchLike))) {
return { branch: branchLike.name };
// Create branch object from branch name or pull request key
export function fillBranchLike(
branch?: string,
- pullRequest?: string
+ pullRequest?: string,
): Branch | PullRequest | undefined {
if (branch) {
return {
}
const [markedNonCompliant, markedCompliantCode] = differentiateCode(
noncompliant.innerHTML,
- compliant.innerHTML
+ compliant.innerHTML,
);
replaceInDom(noncompliant, markedNonCompliant);
Object.values(
groupBy(
pres.filter((e) => e.getAttribute('data-diff-id') !== undefined),
- (e) => e.getAttribute('data-diff-id')
- )
+ (e) => e.getAttribute('data-diff-id'),
+ ),
)
// If we have 1 or 3+ example we can't display any differences
.filter((diffsBlock) => diffsBlock.length === NUMBER_OF_EXAMPLES)
.map(
(diffBlock) =>
- keyBy(diffBlock, (block) => block.getAttribute('data-diff-type')) as DiffBlock
+ keyBy(diffBlock, (block) => block.getAttribute('data-diff-type')) as DiffBlock,
)
);
}
import { ComponentMeasure, ComponentMeasureEnhanced } from '../types/types';
export function getComponentMeasureUniqueKey(
- component?: ComponentMeasure | ComponentMeasureEnhanced
+ component?: ComponentMeasure | ComponentMeasureEnhanced,
) {
return component ? [component.key, component.branch].filter((s) => !!s).join('/') : undefined;
}
export function getEditionUrl(
edition: Edition,
- data: { serverId?: string; ncloc?: number; sourceEdition?: EditionKey }
+ data: { serverId?: string; ncloc?: number; sourceEdition?: EditionKey },
) {
let url = edition.homeUrl;
const query = new URLSearchParams(omitNil(data)).toString();
id: uniqueId('global-message-'),
level,
text,
- })
+ }),
);
}
issue: Dict<any>,
source: any[] | undefined,
baseField: string,
- lookupField: string
+ lookupField: string,
) {
const newFields: Dict<any> = {};
const baseValue = issue[baseField];
function splitFlows(
issue: RawIssue,
- components: Component[] = []
+ components: Component[] = [],
): { secondaryLocations: FlowLocation[]; flows: FlowLocation[][]; flowsWithType: Flow[] } {
if (issue.flows?.some((flow) => flow.type !== undefined)) {
const flowsWithType = issue.flows.filter((flow) => flow.type !== undefined) as Flow[];
flow.map((location) => {
const component = components.find((component) => component.key === location.component);
return { ...location, componentName: component && component.name };
- })
+ }),
);
const onlySecondaryLocations = parsedFlows.every((flow) => flow.length === 1);
return sortBy(
locations,
(location) => location.textRange && location.textRange.startLine,
- (location) => location.textRange && location.textRange.startOffset
+ (location) => location.textRange && location.textRange.startOffset,
);
}
issue: RawIssue,
components?: Component[],
users?: UserBase[],
- rules?: Rule[]
+ rules?: Rule[],
): Issue {
return {
...issue,
}
export function isTextarea(
- event: KeyboardEvent
+ event: KeyboardEvent,
): event is KeyboardEvent & { target: HTMLTextAreaElement } {
return event.target instanceof HTMLTextAreaElement;
}
export function isInput(
- event: KeyboardEvent
+ event: KeyboardEvent,
): event is KeyboardEvent & { target: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement } {
return (
event.target instanceof HTMLInputElement ||
export function getLocalizedMetricName(
metric: { key: string; name?: string },
- short = false
+ short = false,
): string {
const bundleKey = `metric.${metric.key}.${short ? 'short_name' : 'name'}`;
locale: effectiveLocale,
messages,
},
- cache
+ cache,
);
return intl;
export function enhanceMeasuresWithMetrics(
measures: Measure[],
- metrics: Metric[]
+ metrics: Metric[],
): MeasureEnhanced[] {
return measures
.map((measure) => {
export function enhanceConditionWithMeasure(
condition: QualityGateStatusCondition,
- measures: MeasureEnhanced[]
+ measures: MeasureEnhanced[],
): QualityGateStatusConditionEnhanced | undefined {
const measure = measures.find((m) => m.metric.key === condition.metric);
export function formatMeasure(
value: string | number | undefined,
type: string,
- options?: any
+ options?: any,
): string {
const formatter = getFormatter(type);
// eslint-disable-next-line react-hooks/rules-of-hooks
function useFormatter(
value: string | number | undefined,
formatter: Formatter,
- options?: any
+ options?: any,
): string {
return value !== undefined && value !== '' ? formatter(value, options) : '';
}
function numberFormatter(
value: string | number,
minimumFractionDigits = 0,
- maximumFractionDigits = minimumFractionDigits
+ maximumFractionDigits = minimumFractionDigits,
) {
const { format } = new Intl.NumberFormat(getCurrentLocale(), {
minimumFractionDigits,
function shortIntFormatter(
value: string | number,
- option?: { roundingFunc?: (x: number) => number }
+ option?: { roundingFunc?: (x: number) => number },
): string {
const roundingFunc = (option && option.roundingFunc) || undefined;
if (typeof value === 'string') {
numberFormatter(
numberRound(value / formatUnit, Math.pow(10, fraction), roundingFunc),
0,
- fraction
+ fraction,
) + translate(suffix)
);
}
function numberRound(
value: number,
fraction: number = 1000,
- roundingFunc: (x: number) => number = Math.round
+ roundingFunc: (x: number) => number = Math.round,
) {
return roundingFunc(value * fraction) / fraction;
}
function percentFormatter(
value: string | number,
- { decimals, omitExtraDecimalZeros }: { decimals?: number; omitExtraDecimalZeros?: boolean } = {}
+ { decimals, omitExtraDecimalZeros }: { decimals?: number; omitExtraDecimalZeros?: boolean } = {},
): string {
if (typeof value === 'string') {
value = parseFloat(value);
formatted = addSpaceIfNeeded(formatted);
formatted += translateWithParameters(
'work_duration.x_hours',
- isNegative && formatted.length === 0 ? -1 * hours : hours
+ isNegative && formatted.length === 0 ? -1 * hours : hours,
);
}
if (shouldDisplayMinutes(days, hours, minutes)) {
formatted = addSpaceIfNeeded(formatted);
formatted += translateWithParameters(
'work_duration.x_minutes',
- isNegative && formatted.length === 0 ? -1 * minutes : minutes
+ isNegative && formatted.length === 0 ? -1 * minutes : minutes,
);
}
return formatted;
isNegative: boolean,
days: number,
hours: number,
- minutes: number
+ minutes: number,
): string {
if (shouldDisplayDaysInShortFormat(days)) {
const roundedDays = Math.round(days);
const roundedHours = Math.round(hours);
const formattedHours = formatMeasure(
isNegative ? -1 * roundedHours : roundedHours,
- 'SHORT_INT'
+ 'SHORT_INT',
);
return translateWithParameters('work_duration.x_hours', formattedHours);
}
}
export function mockBitbucketRepository(
- overrides: Partial<BitbucketRepository> = {}
+ overrides: Partial<BitbucketRepository> = {},
): BitbucketRepository {
return {
id: 1,
}
export function mockBitbucketCloudRepository(
- overrides: Partial<BitbucketCloudRepository> = {}
+ overrides: Partial<BitbucketCloudRepository> = {},
): BitbucketCloudRepository {
return {
uuid: 1,
} from '../../types/alm-settings';
export function mockAlmSettingsInstance(
- overrides: Partial<AlmSettingsInstance> = {}
+ overrides: Partial<AlmSettingsInstance> = {},
): AlmSettingsInstance {
return {
alm: AlmKeys.GitHub,
}
export function mockBitbucketCloudAlmSettingsInstance(
- overrides: Partial<AlmSettingsInstance> = {}
+ overrides: Partial<AlmSettingsInstance> = {},
): AlmSettingsInstance {
return {
alm: AlmKeys.BitbucketCloud,
}
export function mockAzureBindingDefinition(
- overrides: Partial<AzureBindingDefinition> = {}
+ overrides: Partial<AzureBindingDefinition> = {},
): AzureBindingDefinition {
return {
key: 'key',
}
export function mockBitbucketServerBindingDefinition(
- overrides: Partial<BitbucketServerBindingDefinition> = {}
+ overrides: Partial<BitbucketServerBindingDefinition> = {},
): BitbucketServerBindingDefinition {
return {
key: 'key',
}
export function mockBitbucketCloudBindingDefinition(
- overrides: Partial<BitbucketCloudBindingDefinition> = {}
+ overrides: Partial<BitbucketCloudBindingDefinition> = {},
): BitbucketCloudBindingDefinition {
return {
key: 'key',
}
export function mockGithubBindingDefinition(
- overrides: Partial<GithubBindingDefinition> = {}
+ overrides: Partial<GithubBindingDefinition> = {},
): GithubBindingDefinition {
return {
key: 'key',
}
export function mockGitlabBindingDefinition(
- overrides: Partial<GitlabBindingDefinition> = {}
+ overrides: Partial<GitlabBindingDefinition> = {},
): GitlabBindingDefinition {
return {
key: 'foo',
}
export function mockProjectAlmBindingResponse(
- overrides: Partial<ProjectAlmBindingResponse> = {}
+ overrides: Partial<ProjectAlmBindingResponse> = {},
): ProjectAlmBindingResponse {
return {
alm: AlmKeys.GitHub,
}
export function mockProjectBitbucketBindingResponse(
- overrides: Partial<ProjectBitbucketBindingResponse> = {}
+ overrides: Partial<ProjectBitbucketBindingResponse> = {},
): ProjectBitbucketBindingResponse {
return {
alm: AlmKeys.BitbucketServer,
}
export function mockProjectBitbucketCloudBindingResponse(
- overrides: Partial<ProjectBitbucketCloudBindingResponse> = {}
+ overrides: Partial<ProjectBitbucketCloudBindingResponse> = {},
): ProjectBitbucketCloudBindingResponse {
return {
alm: AlmKeys.BitbucketCloud,
}
export function mockProjectGithubBindingResponse(
- overrides: Partial<ProjectGitHubBindingResponse> = {}
+ overrides: Partial<ProjectGitHubBindingResponse> = {},
): ProjectGitHubBindingResponse {
return {
alm: AlmKeys.GitHub,
}
export function mockProjectGitLabBindingResponse(
- overrides: Partial<ProjectGitLabBindingResponse> = {}
+ overrides: Partial<ProjectGitLabBindingResponse> = {},
): ProjectGitLabBindingResponse {
return {
alm: AlmKeys.GitLab,
}
export function mockProjectAzureBindingResponse(
- overrides: Partial<ProjectAzureBindingResponse> = {}
+ overrides: Partial<ProjectAzureBindingResponse> = {},
): ProjectAzureBindingResponse {
return {
alm: AlmKeys.Azure,
}
export function mockAlmSettingsBindingStatus(
- overrides: Partial<AlmSettingsBindingStatus>
+ overrides: Partial<AlmSettingsBindingStatus>,
): AlmSettingsBindingStatus {
return {
alertSuccess: false,
}
export function mockProjectAlmBindingConfigurationErrors(
- overrides: Partial<ProjectAlmBindingConfigurationErrors> = {}
+ overrides: Partial<ProjectAlmBindingConfigurationErrors> = {},
): ProjectAlmBindingConfigurationErrors {
return {
scope: ProjectAlmBindingConfigurationErrorScope.Global,
import { ApplicationPeriod } from '../../types/application';
export function mockApplicationPeriod(
- overrides: Partial<ApplicationPeriod> = {}
+ overrides: Partial<ApplicationPeriod> = {},
): ApplicationPeriod {
return {
date: '2017-10-01',
import { ComponentReportStatus } from '../../types/component-report';
export function mockComponentReportStatus(
- props?: Partial<ComponentReportStatus>
+ props?: Partial<ComponentReportStatus>,
): ComponentReportStatus {
return {
canAdmin: true,
export function mockComponentMeasure(
file = false,
- overrides: Partial<ComponentMeasure> = {}
+ overrides: Partial<ComponentMeasure> = {},
): ComponentMeasure {
if (file) {
return {
}
export function mockComponentMeasureEnhanced(
- overrides: Partial<ComponentMeasureEnhanced> = {}
+ overrides: Partial<ComponentMeasureEnhanced> = {},
): ComponentMeasureEnhanced {
return {
...mockComponentMeasure(false, overrides as ComponentMeasure),
}
export function mockIssueChangelogDiff(
- overrides: Partial<IssueChangelogDiff> = {}
+ overrides: Partial<IssueChangelogDiff> = {},
): IssueChangelogDiff {
return {
key: 'assign',
}
export function mockNewCodePeriodBranch(
- overrides: Partial<NewCodeDefinitionBranch> = {}
+ overrides: Partial<NewCodeDefinitionBranch> = {},
): NewCodeDefinitionBranch {
return {
projectKey: 'pkey',
}
export function mockQualityGateStatus(
- overrides: Partial<QualityGateStatus> = {}
+ overrides: Partial<QualityGateStatus> = {},
): QualityGateStatus {
return {
ignoredConditions: false,
}
export function mockQualityGateProjectCondition(
- overrides: Partial<QualityGateProjectStatusCondition> = {}
+ overrides: Partial<QualityGateProjectStatusCondition> = {},
): QualityGateProjectStatusCondition {
return {
actualValue: '10',
}
export function mockQualityGateStatusCondition(
- overrides: Partial<QualityGateStatusCondition> = {}
+ overrides: Partial<QualityGateStatusCondition> = {},
): QualityGateStatusCondition {
return {
actual: '10',
}
export function mockQualityGateStatusConditionEnhanced(
- overrides: Partial<QualityGateStatusConditionEnhanced> = {}
+ overrides: Partial<QualityGateStatusConditionEnhanced> = {},
): QualityGateStatusConditionEnhanced {
return {
actual: '10',
}
export function mockQualityGateProjectStatus(
- overrides: Partial<QualityGateProjectStatus> = {}
+ overrides: Partial<QualityGateProjectStatus> = {},
): QualityGateProjectStatus {
return {
conditions: [
}
export function mockQualityGateApplicationStatus(
- overrides: Partial<QualityGateApplicationStatus> = {}
+ overrides: Partial<QualityGateApplicationStatus> = {},
): QualityGateApplicationStatus {
return {
metrics: [mockMetric(), mockMetric({ name: 'new_bugs', key: 'new_bugs', type: 'INT' })],
export function mockReactSelectOptionProps<
OptionType = unknown,
IsMulti extends boolean = boolean,
- GroupType extends GroupBase<OptionType> = GroupBase<OptionType>
+ GroupType extends GroupBase<OptionType> = GroupBase<OptionType>,
>(
data: OptionType,
- overrides?: OptionProps<OptionType, IsMulti, GroupType>
+ overrides?: OptionProps<OptionType, IsMulti, GroupType>,
): OptionProps<OptionType, IsMulti, GroupType> {
return {
...overrides,
export function mockReactSelectControlProps<
OptionType = unknown,
IsMulti extends boolean = boolean,
- GroupType extends GroupBase<OptionType> = GroupBase<OptionType>
+ GroupType extends GroupBase<OptionType> = GroupBase<OptionType>,
>(): ControlProps<OptionType, IsMulti, GroupType> {
return {} as ControlProps<OptionType, IsMulti, GroupType>;
}
export function mockReactSelectClearIndicatorProps<
OptionType = unknown,
IsMulti extends boolean = boolean,
- GroupType extends GroupBase<OptionType> = GroupBase<OptionType>
+ GroupType extends GroupBase<OptionType> = GroupBase<OptionType>,
>(_option: OptionType): ClearIndicatorProps<OptionType, IsMulti, GroupType> {
return { getStyles: () => {} } as unknown as ClearIndicatorProps<OptionType, IsMulti, GroupType>;
}
export function mockReactSelectDropdownIndicatorProps<
OptionType = unknown,
IsMulti extends boolean = boolean,
- GroupType extends GroupBase<OptionType> = GroupBase<OptionType>
+ GroupType extends GroupBase<OptionType> = GroupBase<OptionType>,
>(_option: OptionType): DropdownIndicatorProps<OptionType, IsMulti, GroupType> {
return {} as DropdownIndicatorProps<OptionType, IsMulti, GroupType>;
}
}
export function mockHotspotReviewHistoryElement(
- overrides?: Partial<ReviewHistoryElement>
+ overrides?: Partial<ReviewHistoryElement>,
): ReviewHistoryElement {
return {
date: '2019-09-13T17:55:42+0200',
} from '../../types/settings';
export function mockDefinition(
- overrides: Partial<ExtendedSettingDefinition> = {}
+ overrides: Partial<ExtendedSettingDefinition> = {},
): ExtendedSettingDefinition {
return {
key: 'foo',
}
export function mockSettingFieldDefinition(
- overrides: Partial<SettingFieldDefinition> = {}
+ overrides: Partial<SettingFieldDefinition> = {},
): SettingFieldDefinition {
return { key: 'name', name: 'Name', options: [], ...overrides };
}
}
export function mockSettingWithCategory(
- overrides: Partial<SettingWithCategory> = {}
+ overrides: Partial<SettingWithCategory> = {},
): SettingWithCategory {
return {
key: 'foo',
export function mockSourceViewerFile(
name = 'foo/bar.ts',
project = 'project',
- override?: Partial<SourceViewerFile>
+ override?: Partial<SourceViewerFile>,
): SourceViewerFile {
return {
measures: {
export function mockSnippetsByComponent(
file = 'main.js',
project = 'project',
- lines: number[] = [16]
+ lines: number[] = [16],
): SnippetsByComponent {
const sources = lines.reduce((lines: { [key: number]: SourceLine }, line) => {
lines[line] = mockSourceLine({ line });
export function getNumberOfDaysDefaultValue(
globalNewCodeDefinition?: NewCodeDefinition | null,
- inheritedNewCodeDefinition?: NewCodeDefinition | null
+ inheritedNewCodeDefinition?: NewCodeDefinition | null,
) {
if (
inheritedNewCodeDefinition &&
export function getNewCodePeriodLabel(
period: Period | undefined,
- dateFormatter: (date: string) => string
+ dateFormatter: (date: string) => string,
) {
if (!period) {
return undefined;
}
export function isApplicationNewCodePeriod(
- period: Period | ApplicationPeriod
+ period: Period | ApplicationPeriod,
): period is ApplicationPeriod {
return (period as ApplicationPeriod).project !== undefined;
}
export function filterPermissions(
permissions: Array<Permissions | { category: string; permissions: Permissions[] }>,
hasApplicationsEnabled: boolean,
- hasPortfoliosEnabled: boolean
+ hasPortfoliosEnabled: boolean,
) {
return permissions.map((permission) => {
if (typeof permission === 'object' && permission.category === 'creator') {
export function convertToPermissionDefinitions(
permissions: Array<string | { category: string; permissions: string[] }>,
- l10nPrefix: string
+ l10nPrefix: string,
): Array<PermissionDefinition | PermissionDefinitionGroup> {
return permissions.map((permission) => {
if (typeof permission === 'object') {
return {
category: permission.category,
permissions: permission.permissions.map((permission) =>
- convertToPermissionDefinition(permission, l10nPrefix)
+ convertToPermissionDefinition(permission, l10nPrefix),
),
};
}
}
export function isPermissionDefinitionGroup(
- permission?: PermissionDefinition | PermissionDefinitionGroup
+ permission?: PermissionDefinition | PermissionDefinitionGroup,
): permission is PermissionDefinitionGroup {
return Boolean(permission && (permission as PermissionDefinitionGroup).category);
}
} from '../types/quality-gates';
export function extractStatusConditionsFromProjectStatus(
- projectStatus: QualityGateProjectStatus
+ projectStatus: QualityGateProjectStatus,
): QualityGateStatusCondition[] {
const { conditions } = projectStatus;
return conditions
}
export function extractStatusConditionsFromApplicationStatusChildProject(
- projectStatus: QualityGateApplicationStatusChildProject
+ projectStatus: QualityGateApplicationStatusChildProject,
): QualityGateStatusCondition[] {
const { conditions } = projectStatus;
return conditions
export function parseAsOptionalArray<T>(
value: string | undefined,
- itemParser: (x: string) => T
+ itemParser: (x: string) => T,
): T[] | undefined {
return value ? parseAsArray(value, itemParser) : undefined;
}
export function serializeDate(
value?: Date,
- serializer = toISO8601WithOffsetString
+ serializer = toISO8601WithOffsetString,
): string | undefined {
if (value != null) {
return serializer(value);
export const mapReactQueryResult = <T, R>(
res: UseQueryResult<T>,
- mapper: (data: T) => R
+ mapper: (data: T) => R,
): UseQueryResult<R> => {
return {
...res,
private isJSON = false;
// eslint-disable-next-line no-useless-constructor
- constructor(private readonly url: string, private readonly options: { method?: string } = {}) {}
+ constructor(
+ private readonly url: string,
+ private readonly options: { method?: string } = {},
+ ) {}
getSubmitData(customHeaders: any = {}): { url: string; options: RequestInit } {
let { url } = this;
export function getText(
url: string,
data?: RequestData,
- bypassRedirect?: boolean
+ bypassRedirect?: boolean,
): Promise<string> {
return get(url, data, bypassRedirect).then(parseText);
}
export function postJSONBody(
url: string,
data?: RequestData,
- bypassRedirect?: boolean
+ bypassRedirect?: boolean,
): Promise<any> {
return request(url)
.setMethod('POST')
tries: { max: number; slowThreshold: number },
stopRepeat: (response: T) => boolean,
repeatErrors: number[] = [],
- lastError?: Response
+ lastError?: Response,
) {
tries.max--;
if (tries.max !== 0) {
return new Promise<T>((resolve) => {
setTimeout(
() => resolve(requestTryAndRepeatUntil(repeatAPICall, tries, stopRepeat, repeatErrors)),
- tries.max > tries.slowThreshold ? 500 : 3000
+ tries.max > tries.slowThreshold ? 500 : 3000,
);
});
}
repeatAPICall: () => Promise<T>,
tries: { max: number; slowThreshold: number },
stopRepeat: (response: T) => boolean,
- repeatErrors: number[] = []
+ repeatErrors: number[] = [],
) {
return repeatAPICall().then(
(r) => {
return tryRequestAgain(repeatAPICall, tries, stopRepeat, repeatErrors, error);
}
return Promise.reject(error);
- }
+ },
);
}
export function renderOwaspTop10Category(
standards: Standards,
category: string,
- withPrefix = false
+ withPrefix = false,
): string {
return renderOwaspCategory('owaspTop10', standards, category, withPrefix);
}
export function renderOwaspTop102021Category(
standards: Standards,
category: string,
- withPrefix = false
+ withPrefix = false,
): string {
return renderOwaspCategory('owaspTop10-2021', standards, category, withPrefix);
}
type: 'owaspTop10' | 'owaspTop10-2021',
standards: Standards,
category: string,
- withPrefix: boolean
+ withPrefix: boolean,
) {
const record = standards[type][category];
if (!record) {
export function renderSonarSourceSecurityCategory(
standards: Standards,
category: string,
- withPrefix = false
+ withPrefix = false,
): string {
const record = standards.sonarsourceSecurity[category];
if (!record) {
const { ideName, description } = json;
return { port: p, ideName, description } as Ide;
})
- .catch(() => undefined)
+ .catch(() => undefined),
);
const results = await Promise.all(probeRequests);
return results.filter((r) => r !== undefined) as Ide[];
defaultDiacriticsRemovalap.forEach((defaultDiacritic) =>
defaultDiacritic.letters.split('').forEach((letter) => {
diacriticsMap[letter] = defaultDiacritic.base;
- })
+ }),
);
// "what?" version ... http://jsperf.com/diacritics/12
export function initAppVariables() {
const appVariablesDiv = document.querySelector<AppVariablesElement>(
- getReactDomContainerSelector()
+ getReactDomContainerSelector(),
);
if (appVariablesDiv === null) {
throw new Error('Failed to get app variables');
}
export function mockQualityProfileInheritance(
- overrides: Partial<ProfileInheritanceDetails> = {}
+ overrides: Partial<ProfileInheritanceDetails> = {},
): ProfileInheritanceDetails {
return {
activeRuleCount: 4,
}
export function mockQualityProfileChangelogEvent(
- eventOverride?: Partial<ProfileChangelogEvent>
+ eventOverride?: Partial<ProfileChangelogEvent>,
): ProfileChangelogEvent {
return {
action: 'ACTIVATED',
overrides: {
push?: (loc: To) => void;
replace?: (loc: To) => void;
- } = {}
+ } = {},
) {
return {
createHref: jest.fn(),
}
export function mockDocumentationMarkdown(
- overrides: Partial<{ content: string; title: string; key: string }> = {}
+ overrides: Partial<{ content: string; title: string; key: string }> = {},
): string {
const content =
overrides.content ||
}
export function mockRef(
- overrides: Partial<React.RefObject<Partial<HTMLElement>>> = {}
+ overrides: Partial<React.RefObject<Partial<HTMLElement>>> = {},
): React.RefObject<HTMLElement> {
return {
current: {
indexPath: string,
routes: () => JSX.Element,
context: RenderContext = {},
- overrides: { systemStatus?: SysStatus; adminPages?: Extension[] } = {}
+ overrides: { systemStatus?: SysStatus; adminPages?: Extension[] } = {},
): RenderResult {
function MockAdminContainer() {
return (
{routes()}
</Route>,
indexPath,
- context
+ context,
);
}
export function renderComponent(
component: React.ReactElement,
pathname = '/',
- { appState = mockAppState(), featureList = [] }: RenderContext = {}
+ { appState = mockAppState(), featureList = [] }: RenderContext = {},
) {
function Wrapper({ children }: { children: React.ReactElement }) {
const queryClient = new QueryClient();
indexPath: string,
routes: () => JSX.Element,
context: RenderContext = {},
- componentContext: Partial<ComponentContextShape> = {}
+ componentContext: Partial<ComponentContextShape> = {},
) {
function MockComponentContainer() {
const [realComponent, setRealComponent] = React.useState(
- componentContext?.component ?? mockComponent()
+ componentContext?.component ?? mockComponent(),
);
return (
<ComponentContext.Provider
return renderRoutedApp(
<Route element={<MockComponentContainer />}>{routes()}</Route>,
indexPath,
- context
+ context,
);
}
export function renderApp(
indexPath: string,
component: JSX.Element,
- context: RenderContext = {}
+ context: RenderContext = {},
): RenderResult {
return renderRoutedApp(<Route path={indexPath} element={component} />, indexPath, context);
}
export function renderAppRoutes(
indexPath: string,
routes: () => JSX.Element,
- context?: RenderContext
+ context?: RenderContext,
): RenderResult {
return renderRoutedApp(routes(), indexPath, context);
}
appState = mockAppState(),
featureList = [],
languages = {},
- }: RenderContext = {}
+ }: RenderContext = {},
): RenderResult {
const path = parsePath(navigateTo);
path.pathname = `/${path.pathname}`;
</LanguagesContext.Provider>
</MetricsContext.Provider>
</IntlWrapper>
- </HelmetProvider>
+ </HelmetProvider>,
);
}
await user.selectOptions(
await screen.findByRole('combobox', { name: 'Month:' }),
- formatter.format(date)
+ formatter.format(date),
);
await user.selectOptions(
screen.getByRole('combobox', { name: 'Year:' }),
- String(date.getFullYear())
+ String(date.getFullYear()),
);
await user.click(screen.getByRole('gridcell', { name: String(date.getDate()) }));
export function findTooltipWithContent(
text: Matcher,
target?: HTMLElement,
- selector = 'svg > desc'
+ selector = 'svg > desc',
) {
// eslint-disable-next-line no-console
console.warn(`The usage of findTooltipWithContent() is deprecated; use expect.toHaveATooltipWithContent() instead.
export interface ReactTestingQuery {
find<T extends HTMLElement = HTMLElement>(
container?: HTMLElement,
- waitForOptions?: waitForOptions
+ waitForOptions?: waitForOptions,
): Promise<T>;
findAll<T extends HTMLElement = HTMLElement>(
container?: HTMLElement,
- waitForOptions?: waitForOptions
+ waitForOptions?: waitForOptions,
): Promise<T[]>;
get<T extends HTMLElement = HTMLElement>(container?: HTMLElement): T;
getAll<T extends HTMLElement = HTMLElement>(container?: HTMLElement): T[];
findAt<T extends HTMLElement = HTMLElement>(
index: number,
container?: HTMLElement,
- waitForOptions?: waitForOptions
+ waitForOptions?: waitForOptions,
): Promise<T>;
queryAt<T extends HTMLElement = HTMLElement>(index: number, container?: HTMLElement): T | null;
abstract class ChainingQuery implements ReactTestingQuery {
abstract find<T extends HTMLElement = HTMLElement>(
container?: HTMLElement,
- waitForOptions?: waitForOptions
+ waitForOptions?: waitForOptions,
): Promise<T>;
abstract findAll<T extends HTMLElement = HTMLElement>(
container?: HTMLElement,
- waitForOptions?: waitForOptions
+ waitForOptions?: waitForOptions,
): Promise<T[]>;
abstract get<T extends HTMLElement = HTMLElement>(container?: HTMLElement): T;
async findAt<T extends HTMLElement = HTMLElement>(
index: number,
container?: HTMLElement,
- waitForOptions?: waitForOptions
+ waitForOptions?: waitForOptions,
): Promise<T> {
return (await this.findAll<T>(container, waitForOptions))[index];
}
async find<T extends HTMLElement = HTMLElement>(
container?: HTMLElement,
- waitForOptions?: waitForOptions
+ waitForOptions?: waitForOptions,
) {
return this.elementQuery.find<T>(await this.insideQuery.find(container, waitForOptions));
}
async findAll<T extends HTMLElement = HTMLElement>(
container?: HTMLElement,
- waitForOptions?: waitForOptions
+ waitForOptions?: waitForOptions,
) {
return this.elementQuery.findAll<T>(await this.insideQuery.find(container, waitForOptions));
}
const containers = this.insideQuery.getAll(container);
return containers.reduce(
(acc, item) => [...acc, ...(this.elementQuery.queryAll<T>(item) ?? [])],
- []
+ [],
);
}
find<T extends HTMLElement = HTMLElement>(
container?: HTMLElement,
- waitForOptions?: waitForOptions
+ waitForOptions?: waitForOptions,
) {
return maybeScreen(container).findByText<T>(...this.args, waitForOptions);
}
findAll<T extends HTMLElement = HTMLElement>(
container?: HTMLElement,
- waitForOptions?: waitForOptions
+ waitForOptions?: waitForOptions,
) {
return maybeScreen(container).findAllByText<T>(...this.args, waitForOptions);
}
find<T extends HTMLElement = HTMLElement>(
container?: HTMLElement,
- waitForOptions?: waitForOptions
+ waitForOptions?: waitForOptions,
) {
return maybeScreen(container).findByLabelText<T>(...this.args, waitForOptions);
}
findAll<T extends HTMLElement = HTMLElement>(
container?: HTMLElement,
- waitForOptions?: waitForOptions
+ waitForOptions?: waitForOptions,
) {
return maybeScreen(container).findAllByLabelText<T>(...this.args, waitForOptions);
}
find<T extends HTMLElement = HTMLElement>(
container?: HTMLElement,
- waitForOptions?: waitForOptions
+ waitForOptions?: waitForOptions,
) {
return maybeScreen(container).findByRole<T>(...this.args, waitForOptions);
}
findAll<T extends HTMLElement = HTMLElement>(
container?: HTMLElement,
- waitForOptions?: waitForOptions
+ waitForOptions?: waitForOptions,
) {
return maybeScreen(container).findAllByRole<T>(...this.args, waitForOptions);
}
find<T extends HTMLElement = HTMLElement>(
container?: HTMLElement,
- waitForOptions?: waitForOptions
+ waitForOptions?: waitForOptions,
) {
return maybeScreen(container).findByTestId<T>(...this.args, waitForOptions);
}
findAll<T extends HTMLElement = HTMLElement>(
container?: HTMLElement,
- waitForOptions?: waitForOptions
+ waitForOptions?: waitForOptions,
) {
return maybeScreen(container).findAllByTestId<T>(...this.args, waitForOptions);
}
find<T extends HTMLElement = HTMLElement>(
container?: HTMLElement,
- waitForOptions?: waitForOptions
+ waitForOptions?: waitForOptions,
) {
return maybeScreen(container).findByDisplayValue<T>(...this.args, waitForOptions);
}
findAll<T extends HTMLElement = HTMLElement>(
container?: HTMLElement,
- waitForOptions?: waitForOptions
+ waitForOptions?: waitForOptions,
) {
return maybeScreen(container).findAllByDisplayValue<T>(...this.args, waitForOptions);
}
find<T extends HTMLElement = HTMLElement>(
container?: HTMLElement,
- waitForOptions?: waitForOptions
+ waitForOptions?: waitForOptions,
) {
return maybeScreen(container).findByPlaceholderText<T>(...this.args, waitForOptions);
}
findAll<T extends HTMLElement = HTMLElement>(
container?: HTMLElement,
- waitForOptions?: waitForOptions
+ waitForOptions?: waitForOptions,
) {
return maybeScreen(container).findAllByPlaceholderText<T>(...this.args, waitForOptions);
}
export function change(
element: ShallowWrapper | ReactWrapper,
value: string | object,
- event = {}
+ event = {},
): void {
// `type()` returns a component constructor for a composite element and string for DOM nodes
if (typeof element.type() === 'function') {
return EXPIRATION_OPTIONS.filter(
(option) =>
option.value <= SETTINGS_EXPIRATION_MAP[maxTokenLifetime] &&
- option.value !== TokenExpiration.NoExpiration
+ option.value !== TokenExpiration.NoExpiration,
);
}
componentKey: string,
componentQualifier: ComponentQualifier | string,
branchParameters?: BranchParameters,
- codeScope?: CodeScopeType
+ codeScope?: CodeScopeType,
) {
return isPortfolioLike(componentQualifier)
? getPortfolioUrl(componentKey)
export function getComponentAdminUrl(
componentKey: string,
- componentQualifier: ComponentQualifier | string
+ componentQualifier: ComponentQualifier | string,
) {
if (isPortfolioLike(componentQualifier)) {
return getPortfolioAdminUrl(componentKey);
export function getProjectUrl(
project: string,
branch?: string,
- codeScope?: CodeScopeType
+ codeScope?: CodeScopeType,
): Partial<Path> {
return {
pathname: PROJECT_BASE_URL,
export function getProjectQueryUrl(
project: string,
branchParameters?: BranchParameters,
- codeScope?: CodeScopeType
+ codeScope?: CodeScopeType,
): To {
return {
pathname: PROJECT_BASE_URL,
export function getComponentBackgroundTaskUrl(
componentKey: string,
status?: string,
- taskType?: string
+ taskType?: string,
): Path {
return {
pathname: '/project/background_tasks',
selectionKey: string,
metric: string,
branchLike?: BranchLike,
- view?: MeasurePageView
+ view?: MeasurePageView,
): To {
return getComponentDrilldownUrl({
componentKey,
*/
export function getProjectTutorialLocation(
project: string,
- selectedTutorial?: string
+ selectedTutorial?: string,
): Partial<Path> {
return {
pathname: '/tutorials',
export function getGlobalSettingsUrl(
category?: string,
- query?: Dict<string | undefined | number>
+ query?: Dict<string | undefined | number>,
): Partial<Path> {
return {
pathname: '/admin/settings',
project: string,
branchLike?: BranchLike,
selected?: string,
- line?: number
+ line?: number,
): Partial<Path> {
return {
pathname: '/code',
export default function useIntersectionObserver<T extends Element>(
ref: RefObject<T>,
- options: Options = {}
+ options: Options = {},
) {
const { root = null, rootMargin = '0px', threshold = 0, freezeOnceVisible = false } = options;
const [entry, setEntry] = useState<IntersectionObserverEntry>();
const observer = new IntersectionObserver(
([entry]) => setEntry(entry),
- { root, rootMargin, threshold }
+ { root, rootMargin, threshold },
);
observer.observe(ref.current);
export function useBadgeTokenQuery(componentKey: string) {
return useQuery(['badges-token', componentKey] as const, ({ queryKey: [_, key] }) =>
- getProjectBadgesToken(key)
+ getProjectBadgesToken(key),
);
}
prOrBranch === 'pull-request'
? branchLikes.find((b) => isPullRequest(b) && b.key === name)
: branchLikes.find(
- (b) => isBranch(b) && (prOrBranch === 'branch' ? b.name === name : b.isMain)
+ (b) => isBranch(b) && (prOrBranch === 'branch' ? b.name === name : b.isMain),
);
return { branchLikes, branchLike };
},
queryKey: invalidateDetailsKey,
});
}, DELAY_REFRECH),
- [invalidateDetailsKey, invalidateStatusKey]
+ [invalidateDetailsKey, invalidateStatusKey],
);
}
export function withBranchLikes<P extends { component?: Component }>(
WrappedComponent: React.ComponentType<
P & { branchLikes?: BranchLike[]; branchLike?: BranchLike; isFetchingBranch?: boolean }
- >
+ >,
): React.ComponentType<Omit<P, 'branchLike' | 'branchLikes'>> {
return function WithBranchLike(p: P) {
const { data, isFetching } = useBranchesQuery(p.component);
}
export function withBranchStatusRefresh<
- P extends { refreshBranchStatus: ReturnType<typeof useRefreshBranchStatus> }
+ P extends { refreshBranchStatus: ReturnType<typeof useRefreshBranchStatus> },
>(WrappedComponent: React.ComponentType<P>): React.ComponentType<Omit<P, 'refreshBranchStatus'>> {
return function WithBranchStatusRefresh(props: P) {
const refresh = useRefreshBranchStatus();
unknown,
T,
['devops_integration', string, 'binding']
- >
+ >,
) {
const keyFromUrl = useProjectKeyFromLocation();
staleTime: 60_000,
retry: false,
...options,
- }
+ },
);
}
export function useGitHubSyncStatusQuery(options: GithubSyncStatusOptions = {}) {
const hasGithubProvisioning = useContext(AvailableFeaturesContext).includes(
- Feature.GithubProvisioning
+ Feature.GithubProvisioning,
);
return useQuery(['identity_provider', 'github_sync', 'status'], fetchGithubProvisioningStatus, {
enabled: hasGithubProvisioning,
return useQuery(
getNewCodeDefinitionQueryKey(params?.projectKey, params?.branchName),
() => getNewCodeDefinition({ branch: params?.branchName, project: params?.projectKey }),
- { enabled: params?.enabled ?? true, refetchOnWindowFocus: false }
+ { enabled: params?.enabled ?? true, refetchOnWindowFocus: false },
);
}
values: {
newValue?: SettingValue;
definition: ExtendedSettingDefinition;
- }[]
+ }[],
) => {
return Promise.all(
values
} catch (error) {
return { key: definition.key, success: false };
}
- })
+ }),
);
},
onSuccess: () => {
export function useUsersQueries<U extends RestUserBase>(
getParams: Omit<Parameters<typeof getUsers>[0], 'pageSize' | 'pageIndex'>,
- numberOfPages: number
+ numberOfPages: number,
) {
type QueryKey = [
'user',
'list',
number,
- Omit<Parameters<typeof getUsers>[0], 'pageSize' | 'pageIndex'>
+ Omit<Parameters<typeof getUsers>[0], 'pageSize' | 'pageIndex'>,
];
const results = useQueries({
queries: range(1, numberOfPages + 1).map((page: number) => ({
total: data?.page.total,
isLoading: acc.isLoading || isLoading,
}),
- { users: [] as U[], total: 0, isLoading: false }
+ { users: [] as U[], total: 0, isLoading: false },
);
}
mutationFn: (data: Parameters<typeof revokeToken>[0]) => revokeToken(data),
onSuccess(_, data) {
queryClient.setQueryData<UserToken[]>(['user', data.login, 'tokens'], (oldData) =>
- oldData ? oldData.filter((token) => token.name !== data.name) : undefined
+ oldData ? oldData.filter((token) => token.name !== data.name) : undefined,
);
},
});
mutationFn: (data: Parameters<typeof addUserToGroup>[0]) => addUserToGroup(data),
onSuccess(_, data) {
queryClient.setQueryData<number>(['user', data.login, 'groups', 'total'], (oldData) =>
- oldData !== undefined ? oldData + 1 : undefined
+ oldData !== undefined ? oldData + 1 : undefined,
);
},
});
mutationFn: (data: Parameters<typeof removeUserFromGroup>[0]) => removeUserFromGroup(data),
onSuccess(_, data) {
queryClient.setQueryData<number>(['user', data.login, 'groups', 'total'], (oldData) =>
- oldData !== undefined ? oldData - 1 : undefined
+ oldData !== undefined ? oldData - 1 : undefined,
);
},
});
export function withQueryClient<P>(
Component:
| ComponentClass<P & { queryClient: QueryClient }>
- | VFC<P & { queryClient: QueryClient }>
+ | VFC<P & { queryClient: QueryClient }>,
): VFC<Omit<P, 'queryClient'>> {
return function WithQueryClient(props: P) {
const queryClient = useQueryClient();
(utilityMethod: (componentQualifier: ComponentQualifier) => void) => {
const results = Object.values(ComponentQualifier).reduce(
(prev, qualifier) => ({ ...prev, [qualifier]: utilityMethod(qualifier) }),
- {}
+ {},
);
expect(results).toMatchSnapshot();
- }
+ },
);
}
export function isProjectBitbucketBindingResponse(
- binding: ProjectAlmBindingResponse
+ binding: ProjectAlmBindingResponse,
): binding is ProjectBitbucketBindingResponse {
return binding.alm === AlmKeys.BitbucketServer;
}
export function isProjectBitbucketCloudBindingResponse(
- binding: ProjectAlmBindingResponse
+ binding: ProjectAlmBindingResponse,
): binding is ProjectBitbucketBindingResponse {
return binding.alm === AlmKeys.BitbucketCloud;
}
export function isProjectGitHubBindingResponse(
- binding: ProjectAlmBindingResponse
+ binding: ProjectAlmBindingResponse,
): binding is ProjectGitHubBindingResponse {
return binding.alm === AlmKeys.GitHub;
}
export function isProjectGitLabBindingResponse(
- binding: ProjectAlmBindingResponse
+ binding: ProjectAlmBindingResponse,
): binding is ProjectGitLabBindingResponse {
return binding.alm === AlmKeys.GitLab;
}
export function isProjectAzureBindingResponse(
- binding: ProjectAlmBindingResponse
+ binding: ProjectAlmBindingResponse,
): binding is ProjectAzureBindingResponse {
return binding.alm === AlmKeys.Azure;
}
export function isBitbucketBindingDefinition(
- binding?: AlmBindingDefinitionBase & { url?: string }
+ binding?: AlmBindingDefinitionBase & { url?: string },
): binding is BitbucketServerBindingDefinition {
return binding !== undefined && binding.url !== undefined;
}
export function isBitbucketCloudBindingDefinition(
- binding?: AlmBindingDefinitionBase & { clientId?: string; workspace?: string }
+ binding?: AlmBindingDefinitionBase & { clientId?: string; workspace?: string },
): binding is BitbucketCloudBindingDefinition {
return binding !== undefined && binding.clientId !== undefined && binding.workspace !== undefined;
}
export function isGithubBindingDefinition(
- binding?: AlmBindingDefinitionBase & { appId?: string; url?: string }
+ binding?: AlmBindingDefinitionBase & { appId?: string; url?: string },
): binding is GithubBindingDefinition {
return binding !== undefined && binding.appId !== undefined && binding.url !== undefined;
}
export function isGitLabBindingDefinition(
- binding?: AlmBindingDefinitionBase | GithubBindingDefinition | BitbucketCloudBindingDefinition
+ binding?: AlmBindingDefinitionBase | GithubBindingDefinition | BitbucketCloudBindingDefinition,
): binding is GitlabBindingDefinition {
// There's too much overlap with the others. We must not only validate that certain fields are
// present, we must also validate that others are NOT present. And even so, we cannot be 100%
}
export function isPortfolioLike(
- componentQualifier?: string | ComponentQualifier
+ componentQualifier?: string | ComponentQualifier,
): componentQualifier is ComponentQualifier.Portfolio | ComponentQualifier.SubPortfolio {
return (
componentQualifier === ComponentQualifier.Portfolio ||
}
export function isApplication(
- componentQualifier?: string | ComponentQualifier
+ componentQualifier?: string | ComponentQualifier,
): componentQualifier is ComponentQualifier.Application {
return componentQualifier === ComponentQualifier.Application;
}
export function isProject(
- componentQualifier?: string | ComponentQualifier
+ componentQualifier?: string | ComponentQualifier,
): componentQualifier is ComponentQualifier.Project {
return componentQualifier === ComponentQualifier.Project;
}
export function isFile(
- componentQualifier?: string | ComponentQualifier
+ componentQualifier?: string | ComponentQualifier,
): componentQualifier is ComponentQualifier.File {
return [ComponentQualifier.File, ComponentQualifier.TestFile].includes(
- componentQualifier as ComponentQualifier
+ componentQualifier as ComponentQualifier,
);
}
export function isView(
- componentQualifier?: string | ComponentQualifier
+ componentQualifier?: string | ComponentQualifier,
): componentQualifier is
| ComponentQualifier.Application
| ComponentQualifier.Portfolio