Skip to content

[INS 328] Create tests for contributors dependency#139

Merged
borfast merged 1 commit intomainfrom
improvement/ins-328-create-tests-for-contributors-dependency
Mar 27, 2025
Merged

[INS 328] Create tests for contributors dependency#139
borfast merged 1 commit intomainfrom
improvement/ins-328-create-tests-for-contributors-dependency

Conversation

@borfast
Copy link
Copy Markdown
Contributor

@borfast borfast commented Mar 26, 2025

This fixes the tests for the Contributors Dependency data source.

It just takes care of the most basic test. The goal is simply to have a basic security harness so we can refactor things without fear of breaking stuff.

Summary by CodeRabbit

  • Tests
    • Introduced new unit tests to verify the proper handling of contributor dependency data under simulated API responses.
    • Added a comprehensive mock data set to emulate realistic contributor metrics, ensuring robust verification of counts, percentages, and performance details.

@borfast borfast added the feature New feature or request label Mar 26, 2025
@borfast borfast self-assigned this Mar 26, 2025
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 26, 2025

Walkthrough

This pull request introduces a new test file for the fetchContributorDependency function, utilizing the Vitest framework and a mocked implementation of the fetchFromTinybird function to simulate API responses. The test verifies that the function is called with the correct parameters and returns data with the expected structure. In addition, a new mock data structure named mockTimeseries is added to represent API responses for contributor timeseries data, including metadata, contributor details, and performance metrics. A placeholder for future edge case tests is also included.

Changes

File(s) Change Summary
frontend/server/data/tinybird/contributors-dependency-data-source.test.ts Added unit tests for the fetchContributorDependency function using Vitest. The tests setup a mock for fetchFromTinybird, verify the function's endpoint calls and response structure, and include a placeholder for additional edge case tests.
frontend/server/mocks/tinybird-contributors-dependency-response.mock.ts Introduced a new mock data structure mockTimeseries containing metadata, contributor data, and performance statistics to simulate Tinybird API responses.

Sequence Diagram(s)

sequenceDiagram
    participant T as Test Runner
    participant F as fetchContributorDependency
    participant M as fetchFromTinybird (Mock)

    T->>F: Invoke fetchContributorDependency(filter)
    F->>M: Call fetchFromTinybird (first endpoint)
    M-->>F: Return mocked response data
    F->>M: Call fetchFromTinybird (second endpoint)
    M-->>F: Return mocked response data
    F-->>T: Return aggregated contributor data
Loading

Suggested Reviewers

  • gaspergrom
  • emlimlf
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@borfast borfast force-pushed the improvement/ins-328-create-tests-for-contributors-dependency branch from 757d8fb to c14a12d Compare March 26, 2025 15:14
@borfast borfast requested review from emlimlf and gaspergrom March 26, 2025 15:22
@borfast borfast changed the base branch from improvement/add-github-action-for-tests to improvement/ins-330-create-tests-for-contributors-leaderboard March 26, 2025 15:25
@borfast borfast force-pushed the improvement/ins-330-create-tests-for-contributors-leaderboard branch 2 times, most recently from 89e46f3 to 3e789b4 Compare March 27, 2025 16:17
Base automatically changed from improvement/ins-330-create-tests-for-contributors-leaderboard to main March 27, 2025 16:26
Signed-off-by: Raúl Santos <4837+borfast@users.noreply.github.com>
@borfast borfast force-pushed the improvement/ins-328-create-tests-for-contributors-dependency branch from c14a12d to dc1964e Compare March 27, 2025 17:08
Copy link
Copy Markdown

@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: 0

🧹 Nitpick comments (4)
frontend/server/mocks/tinybird-contributors-dependency-response.mock.ts (1)

1-103: Good job creating a comprehensive mock data structure.

The mockTimeseries structure provides a realistic representation of Tinybird API response data, including metadata, contributor information, and performance statistics. The mock includes a variety of contributors with different contribution percentages, which will be useful for testing various scenarios.

One observation: there's a slight inconsistency in the contributionPercentageRunningTotal values. For example, Christian Brauner has 16% (line 78), followed by Krzysztof Kozlowski at 15% (line 85), then Bjorn Andersson at 17% (line 92). This suggests the data isn't sorted by running total. This may be intentional for testing purposes, but if the API typically returns data in a specific order, consider adjusting the mock to match that behavior.

frontend/server/data/tinybird/contributors-dependency-data-source.test.ts (3)

15-18: Update the comment reference to match this test file.

The comment refers to "active-contributors-data-source.ts" but should refer to "contributors-dependency-data-source.ts" since that's the module being tested in this file.

- // This means that the import for tinybird.ts inside active-contributors-data-source.ts would still be used,
+ // This means that the import for tinybird.ts inside contributors-dependency-data-source.ts would still be used,

80-80: Consider implementing the mentioned edge case tests.

The TODO comment identifies important edge cases to test (invalid dates, invalid data, SQL injections). Since this PR aims to "fix the existing tests" and "implement the most fundamental test to establish a basic security harness," adding at least basic validation for these edge cases would strengthen the testing framework before future refactoring.

Example implementation:

  // TODO: Add checks for invalid dates, invalid data, sql injections, and other edge cases.
+  
+  test('should handle invalid dates gracefully', async () => {
+    const { fetchContributorDependency } = await import("~~/server/data/tinybird/contributors-dependency-data-source");
+    
+    mockFetchFromTinybird.mockResolvedValueOnce({ data: [], meta: [], statistics: {} });
+    mockFetchFromTinybird.mockResolvedValueOnce({ data: [], meta: [], statistics: {} });
+    
+    const filter = {
+      project: 'the-linux-kernel-organization',
+      startDate: DateTime.utc(2025, 3, 20),
+      endDate: DateTime.utc(2024, 3, 20) // End date before start date
+    };
+    
+    const result = await fetchContributorDependency(filter);
+    
+    // Expect valid but empty response structure
+    expect(result).toEqual({
+      topContributors: { count: 0, percentage: 0 },
+      otherContributors: { count: 0, percentage: 100 },
+      list: []
+    });
+  });
+  
+  test('should sanitize project name to prevent SQL injection', async () => {
+    const { fetchContributorDependency } = await import("~~/server/data/tinybird/contributors-dependency-data-source");
+    
+    mockFetchFromTinybird.mockResolvedValueOnce(mockTimeseries).mockResolvedValueOnce(mockLeaderboardTimeseries);
+    
+    const filter = {
+      project: "project'; DROP TABLE contributors; --",
+      startDate: DateTime.utc(2024, 3, 20),
+      endDate: DateTime.utc(2025, 3, 20)
+    };
+    
+    await fetchContributorDependency(filter);
+    
+    // Check if the project name is passed directly to the API or if it's sanitized
+    const firstCallArgs = mockFetchFromTinybird.mock.calls[0][1];
+    expect(firstCallArgs.project).toBe("project'; DROP TABLE contributors; --");
+    
+    // This test would fail if the implementation doesn't properly handle SQL injection attempts
+    // Note: A more comprehensive test would check if the actual implementation sanitizes the input
+  });

55-59: Consider adding a check for empty data handling.

The current implementation extracts values like topContributorsPercentage and totalContributorCount from the mock data without fully handling the case where that data might be empty. While the optional chaining helps prevent errors, it would be good to add a test case that explicitly verifies behavior with empty data responses.

// Add a test case in the file:

+ test('should handle empty data responses gracefully', async () => {
+   const { fetchContributorDependency } = await import("~~/server/data/tinybird/contributors-dependency-data-source");
+   
+   // Mock empty responses
+   mockFetchFromTinybird.mockResolvedValueOnce({ 
+     data: [], 
+     meta: mockTimeseries.meta,
+     statistics: mockTimeseries.statistics 
+   }).mockResolvedValueOnce({ 
+     data: [], 
+     meta: mockLeaderboardTimeseries.meta,
+     statistics: mockLeaderboardTimeseries.statistics 
+   });
+   
+   const filter = {
+     project: 'the-linux-kernel-organization',
+     startDate: DateTime.utc(2024, 3, 20),
+     endDate: DateTime.utc(2025, 3, 20)
+   };
+   
+   const result = await fetchContributorDependency(filter);
+   
+   // Expected result with empty data
+   const expectedResult: ContributorDependencyResponse = {
+     topContributors: {
+       count: 0,
+       percentage: 0
+     },
+     otherContributors: {
+       count: 0,
+       percentage: 100
+     },
+     list: []
+   };
+   
+   expect(result).toEqual(expectedResult);
+ });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9e4afcd and dc1964e.

📒 Files selected for processing (2)
  • frontend/server/data/tinybird/contributors-dependency-data-source.test.ts (1 hunks)
  • frontend/server/mocks/tinybird-contributors-dependency-response.mock.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
frontend/server/data/tinybird/contributors-dependency-data-source.test.ts (1)
Learnt from: borfast
PR: LF-Engineering/insights#76
File: frontend/server/data/tinybird/active-contributors-data-source.test.ts:10-10
Timestamp: 2025-03-27T11:19:30.505Z
Learning: The tests in the frontend/server/data/tinybird directory became broken due to changes introduced in another branch and will need to be revisited later as part of the data sources refactoring.
🧬 Code Definitions (1)
frontend/server/data/tinybird/contributors-dependency-data-source.test.ts (1)
frontend/server/mocks/tinybird-contributors-dependency-response.mock.ts (1)
  • mockTimeseries (1-103)
🔇 Additional comments (2)
frontend/server/data/tinybird/contributors-dependency-data-source.test.ts (2)

24-78: Well-structured test with good verification of parameters and response.

The test effectively validates that the fetchContributorDependency function calls the Tinybird API with the correct parameters and properly formats the response. Good job calculating the expected values based on the mock data.


1-81: Great first implementation of the test structure for Contributors Dependency.

This is a good start for testing the contributors dependency feature. The test covers the basic functionality and establishes a solid foundation for future tests. I see this aligns with the PR objective to "implement the most fundamental test to establish a basic security harness."

Based on the retrieved learning that "tests in the frontend/server/data/tinybird directory became broken due to changes introduced in another branch," it's important that these new tests remain robust during future refactoring efforts.

@borfast borfast merged commit 6c9d27e into main Mar 27, 2025
4 checks passed
@borfast borfast deleted the improvement/ins-328-create-tests-for-contributors-dependency branch March 27, 2025 17:13
@borfast borfast assigned borfast and unassigned borfast May 2, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants