All files / modules/70-pipeline/pages/execution/ExecutionTestView TestsExecutionItem.tsx

91.06% Statements 112/123
73.64% Branches 176/239
86.96% Functions 20/23
91.06% Lines 112/123

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566              1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x                                     1x                         1x   1x       1x   1x 1x 1x 1x     1x                             624x 604x   20x 20x 5x   20x         1x                     1x                     2300x 460x 1840x 460x 1380x 460x                 920x 920x 920x                                                 2300x                       1x                       156x 156x 156x 156x 156x 156x 156x 156x           156x 156x   156x 77x   77x                                                               156x                 156x 156x 156x   1x 1x             156x   77x             780x 780x 2300x 2300x   2300x       2300x   2300x 40x     2300x                                 156x 156x 156x                                                                                                                                                   156x   156x 77x   77x           156x 92x 2x 2x 90x 6x       156x 77x 77x 77x   77x 77x   77x 77x   77x 77x   77x           77x       156x 77x 77x 7x     77x 77x   77x 77x       156x                                                                                                                                                                                           460x                                                                        
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React, { useEffect, useState, useCallback, useMemo, useRef, SetStateAction, Dispatch } from 'react'
import { Intent, ProgressBar } from '@blueprintjs/core'
import { useParams } from 'react-router-dom'
import { get, omit } from 'lodash-es'
import { Button, Icon, Container, Text, useIsMounted, Layout, TableV2 } from '@wings-software/uicore'
import cx from 'classnames'
import { Color } from '@harness/design-system'
import type { CellProps, Column, Renderer } from 'react-table'
import type { orderType, sortType, serverSortProps } from '@common/components/Table/react-table-config'
import { TestSuite, useTestCaseSummary, TestCase, TestCaseSummaryQueryParams } from 'services/ti-service'
import { useStrings } from 'framework/strings'
import { CopyText } from '@common/components/CopyText/CopyText'
import { Duration } from '@common/exports'
import useExpandErrorModal from '@pipeline/components/ExpandErrorModal/useExpandErrorModal'
import { getOptionalQueryParamKeys, renderFailureRate } from './TestsUtils'
import { TestsFailedPopover } from './TestsFailedPopover'
import css from './BuildTests.module.scss'
 
const NOW = Date.now()
const PAGE_SIZE = 10
const COPY_CLIPBOARD_ICON_WIDTH = 16
const SAFETY_TABLE_WIDTH = 216
 
interface SortByObjInterface {
  sort?: sortType
  order?: orderType
}
export interface TestExecutionEntryProps {
  buildIdentifier: string
  serviceToken: string
  executionSummary: TestSuite
  expanded?: boolean
  status?: 'failed'
  onExpand?: () => void
  stageId: string
  stepId: string
  onShowCallGraphForClass?: (classname: string) => void
  isUngroupedList: boolean
}
 
const getServerSort = ({
  queryParams,
  sort,
  sortByObj,
  setSortByObj,
  refetchData
}: {
  queryParams: TestCaseSummaryQueryParams
  sort?: any //'name' | 'class_name' | 'status' | 'duration_ms'
  sortByObj: SortByObjInterface
  setSortByObj: Dispatch<SetStateAction<SortByObjInterface>>
  refetchData: (queryParams: TestCaseSummaryQueryParams) => void
}): void => {
  const newQueryParams = { ...queryParams }
  let newOrder: orderType | undefined
  Iif (sort === sortByObj.sort && sortByObj.order) {
    newOrder = sortByObj.order === 'DESC' ? 'ASC' : 'DESC'
  } else {
    // no saved state for sortBy of the same sort type
    newOrder = 'ASC'
  }
  setSortByObj({ sort, order: newOrder })
  newQueryParams.sort = sort
  newQueryParams.order = newOrder
  refetchData(newQueryParams)
}
 
const getServerSortProps = ({
  enableServerSort,
  accessor,
  sortByObj,
  queryParams,
  refetchData,
  setSortByObj
}: {
  enableServerSort: boolean
  accessor: string
  sortByObj: SortByObjInterface
  queryParams: TestCaseSummaryQueryParams
  refetchData: (queryParams: TestCaseSummaryQueryParams) => void
  setSortByObj: Dispatch<SetStateAction<SortByObjInterface>>
}): serverSortProps => {
  if (!enableServerSort) {
    return { enableServerSort: false }
  } else {
    let sortName = accessor
    if (sortName === 'result') {
      sortName = 'status'
    }
    return {
      enableServerSort: true,
      isServerSorted: sortByObj.sort === sortName,
      isServerSortedDesc: sortByObj.order === 'DESC',
      getSortedColumn: ({ sort }: { sort?: sortType }) =>
        getServerSort({
          queryParams,
          sort: sort === 'result' ? 'status' : sort,
          sortByObj,
          setSortByObj,
          refetchData
        })
    }
  }
}
 
const getColumnText = ({
  col,
  pageIndex,
  itemOrderNumber,
  row
}: {
  col: keyof TestCase | 'order'
  pageIndex: number
  itemOrderNumber: number
  row: { original: TestCase }
}): string | JSX.Element => {
  if (col === 'order') {
    return PAGE_SIZE * pageIndex + itemOrderNumber + '.'
  } else if (col === 'result') {
    return row.original[col]?.status || ''
  } else if (col === 'duration_ms') {
    return (
      <Duration
        icon={undefined}
        durationText=" "
        startTime={NOW}
        endTime={NOW + (row.original[col] || 0)}
        showMsLessThanOneSecond={true}
      />
    )
  } else Eif (col === 'name' || col === 'class_name') {
    const textToCopy = row.original[col] || ''
    return (
      <CopyText iconName="clipboard-alt" textToCopy={textToCopy}>
        {row.original[col]}
      </CopyText>
    )
  } else {
    return row.original[col] || ''
  }
}
 
function ColumnText({
  tooltip,
  failed,
  col,
  pageIndex,
  itemOrderNumber,
  row
}: {
  tooltip?: JSX.Element
  failed: boolean
  col: keyof TestCase | 'order'
  pageIndex: number
  itemOrderNumber: number
  row: { original: TestCase }
}): JSX.Element {
  return (
    <Text
      className={cx(css.text, tooltip && css.failed)}
      color={failed && col !== 'order' ? Color.RED_700 : Color.GREY_700}
      lineClamp={!tooltip ? 1 : undefined}
      tooltip={tooltip}
    >
      {getColumnText({ col, pageIndex, itemOrderNumber, row })}
    </Text>
  )
}
 
export function TestsExecutionItem({
  buildIdentifier,
  serviceToken,
  executionSummary,
  expanded,
  status,
  onExpand,
  stageId,
  stepId,
  onShowCallGraphForClass,
  isUngroupedList
}: TestExecutionEntryProps): React.ReactElement {
  const containerRef = useRef<HTMLElement>(null)
  const rightSideContainerRef = useRef<HTMLElement>(null)
  const tableRef = useRef<HTMLDivElement>(null)
  const [titleWidth, setTitleWidth] = useState<number>()
  const [tableWidth, setTableWidth] = useState<number>()
  const [sortByObj, setSortByObj] = useState<SortByObjInterface>({})
  const { getString } = useStrings()
  const { accountId, orgIdentifier, projectIdentifier, pipelineIdentifier } = useParams<{
    projectIdentifier: string
    orgIdentifier: string
    accountId: string
    pipelineIdentifier: string
  }>()
  const [pageIndex, setPageIndex] = useState(0)
  const { openErrorModal } = useExpandErrorModal({})
 
  const queryParams = useMemo(() => {
    const optionalKeys = getOptionalQueryParamKeys({ stageId, stepId })
 
    return Object.assign(
      {
        accountId,
        orgId: orgIdentifier,
        projectId: projectIdentifier,
        buildId: buildIdentifier,
        pipelineId: pipelineIdentifier,
        report: 'junit' as const,
        suite_name: executionSummary.name,
        status,
        sort: 'status',
        order: 'ASC',
        pageIndex,
        pageSize: PAGE_SIZE
      },
      isUngroupedList ? { suite_name: executionSummary.name } : {},
      optionalKeys
    )
  }, [
    accountId,
    orgIdentifier,
    projectIdentifier,
    buildIdentifier,
    pipelineIdentifier,
    executionSummary.name,
    status,
    pageIndex,
    stageId,
    stepId,
    isUngroupedList
  ]) as TestCaseSummaryQueryParams
 
  const { data, error, loading, refetch } = useTestCaseSummary({
    queryParams,
    lazy: true,
    requestOptions: {
      headers: {
        'X-Harness-Token': serviceToken
      }
    }
  })
  const isMounted = useIsMounted()
  const [selectedRow, setSelectedRow] = useState<TestCase>()
  const refetchData = useCallback(
    (params: TestCaseSummaryQueryParams) => {
      setTimeout(() => {
        Iif (isMounted.current) {
          refetch({ queryParams: params })
        }
      }, 250)
    },
    [isMounted, refetch]
  )
  const renderColumn = useMemo(
    () =>
      ({
        col,
        openTestsFailedModal
      }: {
        col: keyof TestCase | 'order'
        openTestsFailedModal?: (errorContent: JSX.Element) => void
      }) => {
        let itemOrderNumber = 0
        return (props => {
          const { row, rows } = props
          const failed = ['error', 'failed'].includes(row.original?.result?.status || '')
          const tooltip =
            failed && col === 'name' ? (
              <TestsFailedPopover testCase={row.original} openTestsFailedModal={openTestsFailedModal} />
            ) : undefined
 
          itemOrderNumber++
 
          if (itemOrderNumber > rows.length) {
            itemOrderNumber = 1
          }
 
          return (
            <Container width="90%" className={css.testCell}>
              <ColumnText
                tooltip={tooltip}
                failed={failed}
                col={col}
                pageIndex={pageIndex}
                itemOrderNumber={itemOrderNumber}
                row={row}
              />
            </Container>
          )
        }) as Renderer<CellProps<TestCase>>
      },
    [pageIndex]
  )
 
  const columns: Column<TestCase>[] = useMemo(() => {
    const nameClassNameWidth = tableWidth ? tableWidth * 0.5 - 185 : SAFETY_TABLE_WIDTH
    return [
      {
        Header: '#',
        accessor: 'order' as 'name',
        width: 50,
        Cell: renderColumn({ col: 'order' }),
        disableSortBy: true
      },
      {
        Header: getString('pipeline.testsReports.testCaseName').toUpperCase(),
        accessor: 'name',
        width: nameClassNameWidth,
        Cell: renderColumn({
          col: 'name',
          openTestsFailedModal: openErrorModal
        }),
        disableSortBy: data?.content?.length === 1,
        openErrorModal,
        serverSortProps: getServerSortProps({
          enableServerSort: isUngroupedList,
          accessor: 'name',
          sortByObj,
          queryParams,
          refetchData,
          setSortByObj
        })
      },
      {
        Header: getString('pipeline.testsReports.className').toUpperCase(),
        accessor: 'class_name',
        width: nameClassNameWidth,
        Cell: renderColumn({ col: 'class_name' }),
        disableSortBy: data?.content?.length === 1,
        serverSortProps: getServerSortProps({
          enableServerSort: isUngroupedList,
          accessor: 'class_name',
          sortByObj,
          queryParams,
          refetchData,
          setSortByObj
        })
      },
      {
        Header: getString('pipeline.testsReports.result'),
        accessor: 'result',
        width: 100,
        Cell: renderColumn({ col: 'result' }),
        disableSortBy: data?.content?.length === 1,
        serverSortProps: getServerSortProps({
          enableServerSort: isUngroupedList,
          accessor: 'result',
          sortByObj,
          queryParams,
          refetchData,
          setSortByObj
        })
      },
      {
        Header: getString('pipeline.duration').toUpperCase(),
        accessor: 'duration_ms',
        width: 100,
        Cell: renderColumn({ col: 'duration_ms' }),
        disableSortBy: data?.content?.length === 1,
        serverSortProps: getServerSortProps({
          enableServerSort: isUngroupedList,
          accessor: 'duration_ms',
          sortByObj,
          queryParams,
          refetchData,
          setSortByObj
        })
      }
    ]
  }, [getString, renderColumn, data?.content?.length])
  const failureRate = (executionSummary.failed_tests || 0) / (executionSummary.total_tests || 1)
 
  useEffect(() => {
    Iif (expanded && !data) {
      refetchData(queryParams)
    } else Iif (isUngroupedList && !data) {
      const newQueryParams = { ...omit(queryParams, ['suite_name']) }
      refetchData(newQueryParams)
    }
  }, [expanded, queryParams, refetchData, data])
 
  useEffect(() => {
    if (!loading && expanded && data?.content?.length && onShowCallGraphForClass) {
      setSelectedRow(data.content[0])
      onShowCallGraphForClass(data.content[0].class_name as string)
    } else if (!loading && expanded && data?.content?.length) {
      setSelectedRow(data.content[0])
    }
  }, [loading, expanded, data, onShowCallGraphForClass])
 
  useEffect(() => {
    Eif (containerRef.current && rightSideContainerRef.current) {
      const container = containerRef.current
      const containerWidth = container.offsetWidth
      const containerHorizontalPaddings =
        parseFloat(getComputedStyle(container).paddingLeft) + parseFloat(getComputedStyle(container).paddingRight)
      const containerWidthWithoutPaddings = containerWidth - containerHorizontalPaddings
 
      const rightSideContainer = rightSideContainerRef.current
      const rightSideContainerWidth = rightSideContainer.offsetWidth
 
      const CHEVRON_BUTTON_WIDTH = 40
      const SIDES_SPACING = 25
      const newTitleWidth =
        containerWidthWithoutPaddings -
        rightSideContainerWidth -
        CHEVRON_BUTTON_WIDTH -
        SIDES_SPACING -
        COPY_CLIPBOARD_ICON_WIDTH
 
      setTitleWidth(newTitleWidth)
    }
  }, [])
 
  useEffect(() => {
    const onResize = (): void => {
      if (tableRef?.current) {
        setTableWidth(tableRef.current.clientWidth)
      }
    }
    onResize()
    window.addEventListener('resize', onResize)
 
    return () => {
      window.removeEventListener('resize', onResize)
    }
  }, [])
 
  return (
    <Container className={cx(css.widget, css.testSuite, expanded && css.expanded)} padding="medium" ref={containerRef}>
      <Container flex className={css.headingContainer}>
        <Text
          className={cx(css.testSuiteHeading, css.main)}
          color={Color.GREY_500}
          style={{ flexGrow: 1, textAlign: 'left', justifyContent: 'flex-start' }}
        >
          {!isUngroupedList && (
            <>
              <Button minimal large icon={expanded ? 'chevron-down' : 'chevron-right'} onClick={() => onExpand?.()} />
              <Layout.Horizontal>
                <Text width={titleWidth} style={{ whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }}>
                  <CopyText iconName="clipboard-alt" textToCopy={executionSummary.name || ''}>
                    <Text tooltip={<Container padding="small">{executionSummary.name}</Container>}>
                      <span className={css.testSuiteName}>
                        {getString('pipeline.testsReports.testSuite')} {executionSummary.name}
                      </span>
                    </Text>
                  </CopyText>
                </Text>
              </Layout.Horizontal>
            </>
          )}
        </Text>
        <Container flex ref={rightSideContainerRef}>
          <Text
            className={cx(css.testSuiteHeading, css.withSeparator)}
            color={Color.GREY_500}
            font={{ size: 'small' }}
            padding={{ left: 'small', right: 'small' }}
          >
            <span style={{ whiteSpace: 'nowrap' }}>{getString('total')}</span>
            <span>{executionSummary.total_tests}</span>
          </Text>
          <Text
            className={cx(css.testSuiteHeading, css.withSeparator)}
            color={Color.GREY_500}
            font={{ size: 'small' }}
            padding={{ left: 'small', right: 'small' }}
          >
            <span style={{ whiteSpace: 'nowrap' }}>{getString('failed')}</span>
            <span>{executionSummary.failed_tests}</span>
          </Text>
          <Text
            className={cx(css.testSuiteHeading, css.withSeparator)}
            color={Color.GREY_500}
            font={{ size: 'small' }}
            padding={{ left: 'small', right: 'small' }}
          >
            <span style={{ whiteSpace: 'nowrap' }}>{getString('common.failureRate')}</span>
            <span>{renderFailureRate(failureRate)}%</span>
          </Text>
          <Layout.Vertical spacing="xsmall" style={{ marginRight: 'var(--spacing-large)' }} flex>
            <Duration
              icon="time"
              durationText=" "
              startTime={NOW}
              endTime={NOW + (executionSummary.duration_ms || 0)}
              font={{ size: 'small' }}
              color={Color.GREY_500}
              iconProps={{ color: Color.GREY_500, size: 12 }}
              showZeroSecondsResult
            />
            <ProgressBar
              className={css.progressBar}
              animate={false}
              intent={failureRate > 0 ? Intent.DANGER : Intent.SUCCESS}
              stripes={false}
              value={failureRate || 1}
            />
          </Layout.Vertical>
        </Container>
      </Container>
      {expanded && (
        <>
          {loading && (
            <Container flex={{ align: 'center-center' }} padding="xlarge">
              <Icon name="spinner" size={24} color="blue500" />
            </Container>
          )}
          {!loading && error && (
            <Container flex={{ align: 'center-center' }} padding="large">
              <Text icon="error" color={Color.RED_500} iconProps={{ size: 16, color: Color.RED_500 }}>
                {get(error, 'data.error_msg', error?.message)}
              </Text>
            </Container>
          )}
          {!loading && !error && (
            <Container ref={tableRef}>
              <TableV2<TestCase>
                className={cx(css.testSuiteTable, !!onShowCallGraphForClass && css.clickable)}
                columns={columns}
                data={data?.content || []}
                getRowClassName={row => (row.original === selectedRow ? css.rowSelected : '')}
                sortable
                resizable={true}
                onRowClick={
                  onShowCallGraphForClass
                    ? row => {
                        setSelectedRow(row)
                        onShowCallGraphForClass(row.class_name as string)
                      }
                    : undefined
                }
                pagination={
                  (data?.data?.totalItems || 0) > PAGE_SIZE
                    ? {
                        itemCount: data?.data?.totalItems || 0,
                        pageSize: data?.data?.pageSize || 0,
                        pageCount: data?.data?.totalPages || 0,
                        pageIndex,
                        gotoPage: pageIdx => {
                          setPageIndex(pageIdx)
                          refetchData({
                            ...queryParams,
                            pageIndex: pageIdx
                          })
                        }
                      }
                    : undefined
                }
              />
            </Container>
          )}
        </>
      )}
    </Container>
  )
}