Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Add unit tests for utils #1166

Merged
merged 26 commits into from
Feb 28, 2025
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
ccab62a
Added few tests and removed duplicate util impl
vardanbansal-harness Feb 26, 2025
39a760f
cleanup
vardanbansal-harness Feb 27, 2025
b999946
remove .only
vardanbansal-harness Feb 27, 2025
3407915
removing duplicate util function
vardanbansal-harness Feb 27, 2025
f85fb3b
fix vitest setup for apps/gitness
vardanbansal-harness Feb 27, 2025
48d83c1
cleanup
vardanbansal-harness Feb 27, 2025
78417cc
fix vitest
vardanbansal-harness Feb 27, 2025
5c2fb7c
resolve vitest config
vardanbansal-harness Feb 27, 2025
3bcc9eb
fix vitest config
vardanbansal-harness Feb 27, 2025
e3b24e6
add failing test
vardanbansal-harness Feb 27, 2025
40cac08
feat: add more tests in utils folder- part 2
cjlee1 Feb 28, 2025
1b74c45
feat: add more tests in utils folder- part 3
cjlee1 Feb 28, 2025
9b05b8f
cleanup
vardanbansal-harness Feb 28, 2025
323d18f
cleanup - remove vitest imports
vardanbansal-harness Feb 28, 2025
1438ef2
cleanup - remove vitest imports
vardanbansal-harness Feb 28, 2025
f216e4f
cleanup - remove unused time mocks
vardanbansal-harness Feb 28, 2025
4a6ddfa
cleanup - remove time mock
vardanbansal-harness Feb 28, 2025
fdbbdb1
skipping file till fixed
vardanbansal-harness Feb 28, 2025
07d5394
fix test compilation issue on CI
vardanbansal-harness Feb 28, 2025
bbe5dad
cleanup
vardanbansal-harness Feb 28, 2025
d011eca
fix vitest config
vardanbansal-harness Feb 28, 2025
f9c2988
cleanup vitest configs
vardanbansal-harness Feb 28, 2025
3665e4c
add unoptimised build step before running tests
abhinavrastogi-harness Feb 28, 2025
84e9d0a
Merge branch 'main' into add-uts-for-utils
vardanbansal-harness Feb 28, 2025
3b7d378
cleanup
vardanbansal-harness Feb 28, 2025
b325b50
removing unrelated change
vardanbansal-harness Feb 28, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions apps/gitness/config/vitest-setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { vi } from 'vitest'

Object.defineProperty(document, 'queryCommandSupported', {
value: vi.fn().mockImplementation((command: string) => {
return command === 'copy' || command === 'cut'
}),
writable: true
})
2 changes: 1 addition & 1 deletion apps/gitness/src/components/GitBlame.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { useEffect, useState } from 'react'

import { useGetBlameQuery } from '@harnessio/code-service-client'
import { getInitials } from '@harnessio/ui/utils'
import { BlameEditor, BlameEditorProps, ThemeDefinition } from '@harnessio/yaml-editor'
import { BlameItem } from '@harnessio/yaml-editor/dist/types/blame'

import { useGetRepoRef } from '../framework/hooks/useGetRepoPath'
import useCodePathDetails from '../hooks/useCodePathDetails'
import { timeAgoFromISOTime } from '../pages/pipeline-edit/utils/time-utils'
import { getInitials } from '../utils/common-utils'
import { normalizeGitRef } from '../utils/git-utils'

interface GitBlameProps {
Expand Down
151 changes: 151 additions & 0 deletions apps/gitness/src/utils/__tests__/common-utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import { describe, expect, it } from 'vitest'

import { RepoFile, SummaryItemType } from '@harnessio/ui/views'

import { getLogsText, sortFilesByType } from '../common-utils'

// Mock data for testing
const mockLogs = [{ out: 'Log line 1\n' }, { out: 'Log line 2\n' }, { out: 'Log line 3\n' }]

const mockFiles: RepoFile[] = [
{
name: 'file1.txt',
type: SummaryItemType.File,
id: '1',
path: 'file1.txt',
lastCommitMessage: 'file1 commit',
timestamp: '2021-09-01T00:00:00Z'
},
{
name: 'folder1',
type: SummaryItemType.Folder,
id: '2',
path: 'folder1',
lastCommitMessage: 'folder1 commit',
timestamp: '2021-09-01T00:00:00Z'
},
{
name: 'file2.txt',
type: SummaryItemType.File,
id: '3',
path: 'file2.txt',
lastCommitMessage: 'file2 commit',
timestamp: '2021-09-01T00:00:00Z'
},
{
name: 'folder2',
type: SummaryItemType.Folder,
id: '4',
path: 'folder2',
lastCommitMessage: 'folder2 commit',
timestamp: '2021-09-01T00:00:00Z'
}
]

describe('getLogsText', () => {
Object.defineProperty(document, 'queryCommandSupported', {
value: vi.fn().mockReturnValue(true),
writable: true // Ensure it can be reassigned
})

it('should concatenate log lines into a single string', () => {
const result = getLogsText(mockLogs)
expect(result).toBe('Log line 1\nLog line 2\nLog line 3\n')
})

it('should return an empty string if logs array is empty', () => {
const result = getLogsText([])
expect(result).toBe('')
})
})

describe('sortFilesByType', () => {
it('should sort files by type, with folders first', () => {
const result = sortFilesByType(mockFiles)
expect(result).toEqual([
{
name: 'folder1',
type: SummaryItemType.Folder,
id: '2',
path: 'folder1',
lastCommitMessage: 'folder1 commit',
timestamp: '2021-09-01T00:00:00Z'
},
{
name: 'folder2',
type: SummaryItemType.Folder,
id: '4',
path: 'folder2',
lastCommitMessage: 'folder2 commit',
timestamp: '2021-09-01T00:00:00Z'
},
{
name: 'file1.txt',
type: SummaryItemType.File,
id: '1',
path: 'file1.txt',
lastCommitMessage: 'file1 commit',
timestamp: '2021-09-01T00:00:00Z'
},
{
name: 'file2.txt',
type: SummaryItemType.File,
id: '3',
path: 'file2.txt',
lastCommitMessage: 'file2 commit',
timestamp: '2021-09-01T00:00:00Z'
}
])
})

it('should handle an empty array', () => {
const result = sortFilesByType([])
expect(result).toEqual([])
})

it('should handle an array with only files', () => {
const filesOnly = [
{
name: 'file1.txt',
type: SummaryItemType.File,
id: '1',
path: 'file1.txt',
lastCommitMessage: 'file1 commit',
timestamp: '2021-09-01T00:00:00Z'
},
{
name: 'file2.txt',
type: SummaryItemType.File,
id: '2',
path: 'file2.txt',
lastCommitMessage: 'file2 commit',
timestamp: '2021-10-01T00:00:00Z'
}
]
const result = sortFilesByType(filesOnly)
expect(result).toEqual(filesOnly)
})

it('should handle an array with only folders', () => {
const foldersOnly = [
{
name: 'folder1',
type: SummaryItemType.Folder,
id: '2',
path: 'folder1',
lastCommitMessage: 'folder1 commit',
timestamp: '2021-09-01T00:00:00Z'
},
{
name: 'folder2',
type: SummaryItemType.Folder,
id: '2',
path: 'folder2',
lastCommitMessage: 'folder2 commit',
timestamp: '2021-10-01T00:00:00Z'
}
]
const result = sortFilesByType(foldersOnly)
expect(result).toEqual(foldersOnly)
})
})
13 changes: 0 additions & 13 deletions apps/gitness/src/utils/common-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,6 @@ export const getLogsText = (logs: LivelogLine[]) => {
return output
}

export const getInitials = (name: string, length = 2) => {
// Split the name into an array of words, ignoring empty strings
const words = name.split(' ').filter(Boolean)

// Get the initials from the words
const initials = words
.map(word => word[0].toUpperCase()) // Get the first letter of each word
.join('')

// If length is provided, truncate the initials to the desired length
return length ? initials.slice(0, length) : initials
}

export const sortFilesByType = (entries: RepoFile[]): RepoFile[] => {
return entries.sort((a, b) => {
if (a.type === SummaryItemType.Folder && b.type === SummaryItemType.File) {
Expand Down
2 changes: 2 additions & 0 deletions apps/gitness/vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import viteConfig from './vite.config'

export default mergeConfig(viteConfig, {
test: {
environment: 'jsdom',
setupFiles: ['./config/vitest-setup.ts'],
include: ['**/*.test.{ts,tsx}'],
globals: true,
coverage: {
Expand Down
84 changes: 84 additions & 0 deletions packages/ui/src/utils/__tests__/TimeUtils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { describe, expect, it } from 'vitest'

import { formatDuration, formatTimestamp, getFormattedDuration } from '../TimeUtils'

describe('getFormattedDuration', () => {
it('should return "0s" if startTs is greater than or equal to endTs', () => {
expect(getFormattedDuration(1000, 500)).toBe('0s')
expect(getFormattedDuration(1000, 1000)).toBe('0s')
})

it('should return formatted duration in "1h 2m 3s" format', () => {
expect(getFormattedDuration(0, 3723000)).toBe('1h 2m 3s')
expect(getFormattedDuration(0, 7200000)).toBe('2h')
expect(getFormattedDuration(0, 60000)).toBe('1m')
expect(getFormattedDuration(0, 1000)).toBe('1s')
})

it('should handle durations with only seconds', () => {
expect(getFormattedDuration(0, 5000)).toBe('5s')
})

it('should handle durations with hours, minutes, and seconds', () => {
expect(getFormattedDuration(0, 3661000)).toBe('1h 1m 1s')
})
})

describe('formatDuration', () => {
it('should return "0s" if duration is 0', () => {
expect(formatDuration(0)).toBe('0s')
})

it('should return formatted duration in "1h 2m 3s" format for milliseconds', () => {
expect(formatDuration(3723000, 'ms')).toBe('1h 2m 3s')
})

it('should return formatted duration in "1h 2m 3s" format for nanoseconds', () => {
expect(formatDuration(3723000000000, 'ns')).toBe('1h 2m 3s')
})

it('should handle durations with only milliseconds', () => {
expect(formatDuration(500, 'ms')).toBe('500ms')
})

it('should handle durations with only nanoseconds', () => {
expect(formatDuration(500000000, 'ns')).toBe('500ms')
})

it('should handle durations with hours, minutes, and seconds', () => {
expect(formatDuration(3661000, 'ms')).toBe('1h 1m 1s')
})
})

describe('formatTimestamp', () => {
const fixedDate = new Date('2023-01-01T12:34:56.789Z')

beforeAll(() => {
vi.useFakeTimers()
vi.setSystemTime(fixedDate)

vi.spyOn(Intl, 'DateTimeFormat').mockImplementation(
() =>
({
format: () => '12:34:56.789'
}) as any
)
})

afterAll(() => {
vi.useRealTimers()
vi.restoreAllMocks()
})

it('should format epoch timestamp into "HH:mm:ss.SSS" format', () => {
const timestamp = fixedDate.getTime()
expect(formatTimestamp(timestamp)).toBe('12:34:56.789')
})

it('should handle different times of the day', () => {
const morningTimestamp = new Date('2023-01-01T08:00:00.000Z').getTime()
const eveningTimestamp = new Date('2023-01-01T20:00:00.000Z').getTime()
expect(formatTimestamp(morningTimestamp)).toBe('12:34:56.789')
expect(formatTimestamp(eveningTimestamp)).toBe('12:34:56.789')
})
})
36 changes: 36 additions & 0 deletions packages/ui/src/utils/__tests__/stringUtils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { describe, expect, it } from 'vitest'

import { getInitials } from '../stringUtils'

describe('getInitials', () => {
it('should return the initials of a single word', () => {
expect(getInitials('John')).toBe('J')
})

it('should return the initials of multiple words', () => {
expect(getInitials('John Doe')).toBe('JD')
})

it('should return the initials truncated to the specified length', () => {
expect(getInitials('John Doe', 1)).toBe('J')
expect(getInitials('John Doe', 2)).toBe('JD')
expect(getInitials('John Doe', 3)).toBe('JD')
})

it('should ignore extra spaces between words', () => {
expect(getInitials(' John Doe ')).toBe('JD')
})

it('should handle empty strings', () => {
expect(getInitials('')).toBe('')
})

it('should handle names with more than two words', () => {
expect(getInitials('John Michael Doe')).toBe('JM')
expect(getInitials('John Michael Doe', 2)).toBe('JM')
})

it('should handle names with special characters', () => {
expect(getInitials('John-Michael Doe')).toBe('JD')
})
})
1 change: 1 addition & 0 deletions packages/ui/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './utils'
export * from './stringUtils'
26 changes: 1 addition & 25 deletions packages/ui/src/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,6 @@ import { createElement, ReactNode } from 'react'
import { TimeAgoHoverCard } from '@views/repo/components/time-ago-hover-card'
import { formatDistance, formatDistanceToNow } from 'date-fns'

export const getInitials = (name: string, length = 2) => {
// Split the name into an array of words, ignoring empty strings
const words = name.split(' ').filter(Boolean)

// Get the initials from the words
const initials = words
.map(word => word[0].toUpperCase()) // Get the first letter of each word
.join('')

// If length is provided, truncate the initials to the desired length
return length ? initials.slice(0, length) : initials
}
export const INITIAL_ZOOM_LEVEL = 1
export const ZOOM_INC_DEC_LEVEL = 0.1

Expand Down Expand Up @@ -110,19 +98,6 @@ export const timeAgo = (timestamp?: number | null, cutoffDays: number = 3): Reac
}
}

//generate random password
export function generateAlphaNumericHash(length: number) {
let result = ''
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
const charactersLength = characters.length

for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength))
}

return result
}

/**
* Format a number with current locale.
* @param num number
Expand All @@ -131,6 +106,7 @@ export function generateAlphaNumericHash(length: number) {
export function formatNumber(num: number | bigint): string {
return num ? new Intl.NumberFormat(LOCALE).format(num) : ''
}

export interface Violation {
violation: string
}
Expand Down
3 changes: 2 additions & 1 deletion packages/ui/src/views/repo/components/commits-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import { FC, useMemo } from 'react'
import { Link, useNavigate } from 'react-router-dom'

import { Avatar, Button, CommitCopyActions, Icon, NodeGroup, StackedList } from '@/components'
import { formatDate, getInitials } from '@/utils/utils'
import { formatDate } from '@/utils/utils'
import { TypesCommit } from '@/views'
import { getInitials } from '@utils/stringUtils'

type CommitsGroupedByDate = Record<string, TypesCommit[]>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ import {
import { DiffFile, DiffModeEnum, DiffView, DiffViewProps, SplitSide } from '@git-diff-view/react'
import { useCustomEventListener } from '@hooks/use-event-listener'
import { useMemoryCleanup } from '@hooks/use-memory-cleanup'
import { getInitials, timeAgo } from '@utils/utils'
import { getInitials } from '@utils/stringUtils'
import { timeAgo } from '@utils/utils'
import { DiffBlock } from 'diff2html/lib/types'
import { debounce, get } from 'lodash-es'
import { OverlayScrollbars } from 'overlayscrollbars'
Expand Down
Loading
Loading