-
Notifications
You must be signed in to change notification settings - Fork 1
Add file utility functions with unit tests #48
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
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
cd8bdd1
Add file utility functions with unit tests
anatolyshipitz f851ca2
Refactor file utility functions by removing invalid path checks
anatolyshipitz fcd8826
Refactor JSON file handling in file utility functions
anatolyshipitz 6b86a64
Refactor weekly financial reports workflow (#47)
anatolyshipitz 7dc1340
Merge branch 'main' into feature/file-utils
killev 650030f
Merge branch 'main' into feature/file-utils
anatolyshipitz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export * from './weeklyFinancialReports'; |
148 changes: 148 additions & 0 deletions
148
workers/main/src/activities/weeklyFinancialReports/getTargetUnits.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,148 @@ | ||
| import { afterEach, beforeEach, describe, expect, it, Mock, vi } from 'vitest'; | ||
|
|
||
| import { AppError } from '../../common/errors'; | ||
| import { writeJsonFile } from '../../common/fileUtils'; | ||
| import { RedminePool } from '../../common/RedminePool'; | ||
| import { getTargetUnits } from './getTargetUnits'; | ||
|
|
||
| type TargetUnit = { | ||
| group_id: number; | ||
| group_name: string; | ||
| project_id: number; | ||
| project_name: string; | ||
| user_id: number; | ||
| username: string; | ||
| spent_on: string; | ||
| total_hours: number; | ||
| }; | ||
|
|
||
| interface TargetUnitRepositoryMock { | ||
| mockClear: () => void; | ||
| mockImplementation: ( | ||
| impl: () => { getTargetUnits: () => Promise<TargetUnit[]> }, | ||
| ) => void; | ||
| } | ||
|
|
||
| interface RedminePoolMock { | ||
| mockClear: () => void; | ||
| mockImplementation: ( | ||
| impl: () => { getPool: () => string; endPool: () => void }, | ||
| ) => void; | ||
| } | ||
|
|
||
| const defaultUnit: TargetUnit = { | ||
| group_id: 1, | ||
| group_name: 'Group', | ||
| project_id: 2, | ||
| project_name: 'Project', | ||
| user_id: 3, | ||
| username: 'User', | ||
| spent_on: '2024-06-01', | ||
| total_hours: 8, | ||
| }; | ||
|
|
||
| function createMockUnit(overrides: Partial<TargetUnit> = {}): TargetUnit { | ||
| return { ...defaultUnit, ...overrides }; | ||
| } | ||
|
|
||
| async function setupTargetUnitRepositoryMock(): Promise<TargetUnitRepositoryMock> { | ||
| const imported = await vi.importMock( | ||
| '../../services/TargetUnit/TargetUnitRepository', | ||
| ); | ||
| const repo = vi.mocked( | ||
| imported.TargetUnitRepository, | ||
| ) as TargetUnitRepositoryMock; | ||
|
|
||
| repo.mockClear(); | ||
|
|
||
| return repo; | ||
| } | ||
|
|
||
| function setupRedminePoolMock(endPool: Mock) { | ||
| (RedminePool as unknown as RedminePoolMock).mockClear(); | ||
| (RedminePool as unknown as RedminePoolMock).mockImplementation(() => ({ | ||
| getPool: vi.fn(() => 'mockPool'), | ||
| endPool, | ||
| })); | ||
| } | ||
|
|
||
| vi.mock('../../common/RedminePool', () => ({ | ||
| RedminePool: vi.fn().mockImplementation(() => ({ | ||
| getPool: vi.fn(() => 'mockPool'), | ||
| endPool: vi.fn(), | ||
| })), | ||
| })); | ||
| vi.mock('../../services/TargetUnit/TargetUnitRepository', () => ({ | ||
| TargetUnitRepository: vi.fn(), | ||
| })); | ||
| vi.mock('../../common/fileUtils', () => ({ | ||
| writeJsonFile: vi.fn(), | ||
| })); | ||
| vi.mock('../../configs/redmineDatabase', () => ({ | ||
| redmineDatabaseConfig: {}, | ||
| })); | ||
|
|
||
| describe('getTargetUnits', () => { | ||
| const mockUnits: TargetUnit[] = [createMockUnit()]; | ||
| const mockFile = | ||
| 'data/weeklyFinancialReportsWorkflow/getTargetUnits/target-units-123.json'; | ||
| let writeJsonFileMock: Mock; | ||
| let TargetUnitRepository: TargetUnitRepositoryMock; | ||
| let endPool: Mock; | ||
| let dateSpy: ReturnType<typeof vi.spyOn>; | ||
|
|
||
| beforeEach(async () => { | ||
| dateSpy = vi.spyOn(Date, 'now').mockReturnValue(123); | ||
| writeJsonFileMock = vi.mocked(writeJsonFile); | ||
| writeJsonFileMock.mockClear(); | ||
| TargetUnitRepository = await setupTargetUnitRepositoryMock(); | ||
| endPool = vi.fn(); | ||
| setupRedminePoolMock(endPool); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| dateSpy.mockRestore(); | ||
| }); | ||
|
|
||
| const mockRepo = (success = true) => { | ||
| TargetUnitRepository.mockImplementation(() => ({ | ||
| getTargetUnits: success | ||
| ? vi.fn().mockResolvedValue(mockUnits) | ||
| : vi.fn().mockRejectedValue(new Error('fail-get')), | ||
| })); | ||
| }; | ||
|
|
||
| it('returns fileLink when successful', async () => { | ||
| mockRepo(true); | ||
| writeJsonFileMock.mockResolvedValue(undefined); | ||
| const result = await getTargetUnits(); | ||
|
|
||
| expect(result).toEqual({ fileLink: mockFile }); | ||
| expect(writeJsonFile).toHaveBeenCalledWith(mockFile, mockUnits); | ||
| }); | ||
|
|
||
| it('throws AppError when repo.getTargetUnits throws', async () => { | ||
| mockRepo(false); | ||
| writeJsonFileMock.mockResolvedValue(undefined); | ||
| await expect(getTargetUnits()).rejects.toThrow(AppError); | ||
| await expect(getTargetUnits()).rejects.toThrow( | ||
| 'Failed to get Target Units', | ||
| ); | ||
| }); | ||
|
|
||
| it('throws AppError when writeJsonFile throws', async () => { | ||
| mockRepo(true); | ||
| writeJsonFileMock.mockRejectedValue(new Error('fail-write')); | ||
| await expect(getTargetUnits()).rejects.toThrow(AppError); | ||
| await expect(getTargetUnits()).rejects.toThrow( | ||
| 'Failed to get Target Units', | ||
| ); | ||
| }); | ||
|
|
||
| it('always ends the Redmine pool', async () => { | ||
| mockRepo(true); | ||
| writeJsonFileMock.mockResolvedValue(undefined); | ||
| await getTargetUnits(); | ||
| expect(endPool).toHaveBeenCalled(); | ||
| }); | ||
| }); |
31 changes: 31 additions & 0 deletions
31
workers/main/src/activities/weeklyFinancialReports/getTargetUnits.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| import { AppError } from '../../common/errors'; | ||
| import { writeJsonFile } from '../../common/fileUtils'; | ||
| import { RedminePool } from '../../common/RedminePool'; | ||
| import { redmineDatabaseConfig } from '../../configs/redmineDatabase'; | ||
| import { TargetUnitRepository } from '../../services/TargetUnit/TargetUnitRepository'; | ||
|
|
||
| interface GetTargetUnitsResult { | ||
| fileLink: string; | ||
| } | ||
|
|
||
| export const getTargetUnits = async (): Promise<GetTargetUnitsResult> => { | ||
| const redminePool = new RedminePool(redmineDatabaseConfig); | ||
|
|
||
| try { | ||
| const pool = redminePool.getPool(); | ||
|
|
||
| const repo = new TargetUnitRepository(pool); | ||
| const result = await repo.getTargetUnits(); | ||
| const filename = `data/weeklyFinancialReportsWorkflow/getTargetUnits/target-units-${Date.now()}.json`; | ||
|
|
||
| await writeJsonFile(filename, result); | ||
|
|
||
| return { fileLink: filename }; | ||
| } catch (err) { | ||
| const message = err instanceof Error ? err.message : String(err); | ||
|
|
||
| throw new AppError('Failed to get Target Units', message); | ||
| } finally { | ||
| await redminePool.endPool(); | ||
| } | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export * from './getTargetUnits'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| vi.mock('fs', () => ({ | ||
| promises: { | ||
| readFile: vi.fn(), | ||
| writeFile: vi.fn(), | ||
| mkdir: vi.fn(), | ||
| }, | ||
| })); | ||
|
|
||
| import { promises as fs } from 'fs'; | ||
| import path from 'path'; | ||
| import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; | ||
|
|
||
| import { FileUtilsError } from './errors'; | ||
| import { readJsonFile, writeJsonFile } from './fileUtils'; | ||
|
|
||
| describe('fileUtils', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| vi.restoreAllMocks(); | ||
| }); | ||
|
|
||
| describe('readJsonFile', () => { | ||
| test('reads and parses JSON file', async () => { | ||
| vi.mocked(fs.readFile).mockResolvedValueOnce('{"a":1}'); | ||
| const result = await readJsonFile<{ a: number }>('test.json'); | ||
|
|
||
| expect(result).toEqual({ a: 1 }); | ||
| expect(fs.readFile).toHaveBeenCalledWith('test.json', 'utf-8'); | ||
| }); | ||
|
|
||
| test('throws FileUtilsError for invalid JSON', async () => { | ||
| vi.mocked(fs.readFile).mockResolvedValueOnce('not-json'); | ||
| await expect(readJsonFile('bad.json')).rejects.toBeInstanceOf( | ||
| FileUtilsError, | ||
| ); | ||
| }); | ||
|
|
||
| test('throws FileUtilsError if fs.readFile throws', async () => { | ||
| vi.mocked(fs.readFile).mockRejectedValueOnce(new Error('fail')); | ||
| await expect(readJsonFile('fail.json')).rejects.toBeInstanceOf( | ||
| FileUtilsError, | ||
| ); | ||
| }); | ||
| }); | ||
|
|
||
| describe('writeJsonFile', () => { | ||
| test('writes JSON file and creates directory', async () => { | ||
| vi.mocked(fs.mkdir).mockResolvedValueOnce(undefined); | ||
| vi.mocked(fs.writeFile).mockResolvedValueOnce(undefined); | ||
| const filePath = 'dir/file.json'; | ||
| const data = { b: 2 }; | ||
|
|
||
| await writeJsonFile(filePath, data); | ||
| expect(fs.mkdir).toHaveBeenCalledWith(path.dirname(filePath), { | ||
| recursive: true, | ||
| }); | ||
| expect(fs.writeFile).toHaveBeenCalledWith( | ||
| filePath, | ||
| JSON.stringify(data, null, 2), | ||
| 'utf-8', | ||
| ); | ||
| }); | ||
|
|
||
| test('throws FileUtilsError if fs.mkdir throws', async () => { | ||
| vi.mocked(fs.mkdir).mockRejectedValueOnce(new Error('fail')); | ||
| await expect(writeJsonFile('fail.json', {})).rejects.toBeInstanceOf( | ||
| FileUtilsError, | ||
| ); | ||
| }); | ||
|
|
||
| test('throws FileUtilsError if fs.writeFile throws', async () => { | ||
| vi.mocked(fs.mkdir).mockResolvedValueOnce(undefined); | ||
| vi.mocked(fs.writeFile).mockRejectedValueOnce(new Error('fail')); | ||
| await expect(writeJsonFile('fail2.json', {})).rejects.toBeInstanceOf( | ||
| FileUtilsError, | ||
| ); | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| import { promises as fs } from 'fs'; | ||
| import path from 'path'; | ||
|
|
||
| import { FileUtilsError } from './errors'; | ||
|
|
||
| export async function readJsonFile<T = object>(filePath: string): Promise<T> { | ||
| try { | ||
| const content = await fs.readFile(filePath, 'utf-8'); | ||
| const parsed = JSON.parse(content) as T; | ||
|
|
||
| return parsed; | ||
| } catch { | ||
| throw new FileUtilsError( | ||
| `Failed to read or parse JSON file at "${filePath}"`, | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| export async function writeJsonFile<T = object>( | ||
| filePath: string, | ||
| data: T, | ||
| ): Promise<void> { | ||
| try { | ||
| const content = JSON.stringify(data, null, 2); | ||
| const dir = path.dirname(filePath); | ||
|
|
||
| await fs.mkdir(dir, { recursive: true }); | ||
| await fs.writeFile(filePath, content, 'utf-8'); | ||
| } catch { | ||
| throw new FileUtilsError(`Failed to write JSON file at "${filePath}"`); | ||
| } | ||
| } |
43 changes: 0 additions & 43 deletions
43
workers/main/src/workflows/weeklyFinancialReports/index.test.ts
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.