Skip to content

Clean up the test utils#138

Merged
5ouma merged 4 commits intomainfrom
test-utils
Dec 8, 2024
Merged

Clean up the test utils#138
5ouma merged 4 commits intomainfrom
test-utils

Conversation

@5ouma
Copy link
Owner

@5ouma 5ouma commented Dec 8, 2024

⚠️ Issue

close #


✏️ Description

Make objects to collect similar constants.


🔄 Type of the Change

  • 🎉 New Feature
  • 🧰 Bug
  • 🛡️ Security
  • 📖 Documentation
  • 🏎️ Performance
  • 🧹 Refactoring
  • 🧪 Testing
  • 🔧 Maintenance
  • 🎽 CI
  • 🧠 Meta

Make objects to collect similar constants.
Copilot AI review requested due to automatic review settings December 8, 2024 08:50
@prlabeler prlabeler bot added the 🧪 Testing Adding missing tests or correcting existing tests label Dec 8, 2024
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Copilot reviewed 4 out of 4 changed files in this pull request and generated no suggestions.

@codecov
Copy link

codecov bot commented Dec 8, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (f074200) to head (e393908).
Report is 2 commits behind head on main.

✅ All tests successful. No failed tests found.

Additional details and impacted files
@@            Coverage Diff            @@
##              main      #138   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            6         6           
  Lines           93        97    +4     
  Branches         6         6           
=========================================
+ Hits            93        97    +4     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@coderabbitai
Copy link

coderabbitai bot commented Dec 8, 2024

Walkthrough

The pull request introduces modifications to test cases across several files to adopt a behavior-driven development (BDD) style, utilizing describe and test from the @std/testing/bdd module. In content.test.ts and redirect.test.ts, function calls are updated to reference specific properties of the testRepo and testRef objects. The structure of these objects is altered in test_utils.ts to include normal and unknown properties for testRepo, and normal and slash properties for testRef. Additionally, the organization of test cases in server.test.ts is improved for clarity.

Changes

File Change Summary
src/libs/content.test.ts Updated test cases to use testRepo.normal and testRepo.unknown in various function calls.
src/libs/redirect.test.ts Modified parameters in checkRedirect and assertions to utilize testRepo.normal and testRef.normal.
src/libs/test_utils.ts Changed testRepo to an object with normal and unknown properties; transformed testRef to include normal and slash properties. Updated documentation comments accordingly.
src/server.test.ts Reorganized and renamed test cases for clarity; removed testRefSlash variable and improved structure of tests for paths.
deno.json Added new import for @std/testing module at version 1.0.6.

Possibly related PRs

  • Use Hono env adapter instead of the Deno.env() #64: Changes in src/libs/content.test.ts and src/libs/redirect.test.ts both involve updates to test cases that utilize the testRepo object, which is also referenced in the modifications made in src/libs/test_utils.ts.
  • Make reproxy workable on Bun and Cloudfalre Workers #67: Similar to the main PR, this PR also updates test cases to use specific properties of testRepo, indicating a shared focus on enhancing test specificity and structure.
  • Follow the Deno 2 #81: The changes in src/libs/content.ts and src/libs/redirect.ts enhance function signatures and parameter handling, relevant to the updates made in the main PR regarding test cases that call these functions.
  • Upload the test result to Codecov #103: The introduction of a step for uploading test results in the CI workflow aligns with the main PR's focus on improving test case structure and reporting.

Suggested labels

🧹 Refactoring, 🎉 New Feature


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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 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.

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

🧹 Outside diff range and nitpick comments (4)
src/libs/redirect.test.ts (1)

9-11: Consider adding test cases for edge cases.

While the updates to use testRepo.normal and testRef.normal are good, we could improve test coverage by adding test cases for:

  1. Unknown repository (testRepo.unknown)
  2. Slash-containing reference (testRef.slash)

This would ensure we're testing all the test data variations we've defined.

Also applies to: 15-21

src/server.test.ts (3)

14-32: Consider test isolation improvements

The exportRepo call affects both test steps but there's no cleanup. Consider:

  1. Moving exportRepo into each step for better isolation
  2. Adding cleanup after each step to prevent state leakage
 Deno.test("/", async (t: Deno.TestContext) => {
-  exportRepo(testRepo.normal);
   await t.step("Direct", async () => {
+    exportRepo(testRepo.normal);
     const res: Response = await app.request("/");
     assertEquals(res.status, STATUS_CODE.OK);
+    // Cleanup
+    await Deno.remove(testRepo.normal.path, { recursive: true });
   });

   await t.step("Redirect", async () => {
+    exportRepo(testRepo.normal);
     const res: Response = await app.request("/", {
       headers: { "User-Agent": testUserAgent.toString() },
     });
     assertEquals(
       res.headers.get("Location"),
       getGitHubUrl(testRepo.normal).toString(),
     );
     assertEquals(res.status, STATUS_CODE.PermanentRedirect);
+    // Cleanup
+    await Deno.remove(testRepo.normal.path, { recursive: true });
   });
 });

56-75: Well-structured test isolation!

This test block demonstrates good practices by:

  1. Placing exportRepo within each test step
  2. Using appropriate test data structures (testRef.slash)

Consider removing the extra newlines after the request calls (lines 60 and 69) for consistency with other test blocks.


13-75: Well-organized test structure improvements

The changes successfully:

  1. Organize tests into clear "Direct" and "Redirect" steps
  2. Use structured test data consistently (testRepo.normal, testRef.normal/slash)
  3. Improve readability and maintainability

This aligns well with the PR's objective of cleaning up test utilities.

Consider documenting these test patterns in a README or contributing guide to ensure consistent test organization across the codebase.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f074200 and 65304e7.

📒 Files selected for processing (4)
  • src/libs/content.test.ts (1 hunks)
  • src/libs/redirect.test.ts (1 hunks)
  • src/libs/test_utils.ts (1 hunks)
  • src/server.test.ts (1 hunks)
🔇 Additional comments (4)
src/libs/test_utils.ts (2)

18-28: LGTM! Well-structured organization of test repository data.

The restructuring of testRepo into an object with normal and unknown properties improves code organization and makes the intention of each test case clearer.


44-47: LGTM! Good separation of reference types.

The restructuring of testRef into an object with distinct properties for different reference formats (normal and slash) improves test case clarity.

src/libs/content.test.ts (1)

9-9: LGTM! Consistent usage of restructured test utilities.

The test cases have been properly updated to use the new structure, making it clearer which test data is being used in each scenario.

Also applies to: 16-16, 23-23

src/server.test.ts (1)

35-53: Apply consistent test isolation pattern

Similar to the root path test, consider moving exportRepo into individual steps and adding cleanup.

coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 8, 2024
Check null is returned when not accessed by a browser.
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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (2)
src/libs/content.test.ts (1)

Line range hint 8-28: LGTM! Well-structured BDD test organization.

The migration to BDD style using describe/test blocks improves readability and organization. The test cases properly utilize the new structured test objects.

Consider adding descriptions to test cases to document the expected behavior:

-  test("normal", async () => {
+  test("normal - should return OK status and content for valid repo", async () => {
-  test("with ref", async () => {
+  test("with ref - should return OK status and content for valid repo and ref", async () => {
-  test("not found", async () => {
+  test("not found - should return 404 status for unknown repo", async () => {
src/server.test.ts (1)

14-76: Consider reorganizing test structure for better maintainability.

The current structure has some redundancy in the Direct/Redirect test patterns. Consider extracting common test patterns into shared test factories.

Example approach:

const testEndpoint = (path: string, options: { ref?: string }) => {
  describe(`Endpoint: ${path}`, () => {
    beforeEach(() => {
      exportRepo(testRepo.normal);
    });

    test("Direct - should return OK status", async () => {
      const res = await app.request(path);
      assertEquals(res.status, STATUS_CODE.OK);
    });

    test("Redirect - should redirect to GitHub URL", async () => {
      const res = await app.request(path, {
        headers: { "User-Agent": testUserAgent.toString() },
      });
      assertEquals(
        res.headers.get("Location"),
        getGitHubUrl(testRepo.normal, options.ref).toString(),
      );
      assertEquals(res.status, STATUS_CODE.PermanentRedirect);
    });
  });
};

describe("Serve", () => {
  testEndpoint("/", {});
  testEndpoint(`/${testRef.normal}`, { ref: testRef.normal });
  testEndpoint(`/${testRef.slash}`, { ref: testRef.slash });
});
🛑 Comments failed to post (2)
src/server.test.ts (2)

16-16: 🛠️ Refactor suggestion

Refactor repeated exportRepo setup.

The exportRepo setup is duplicated across tests and could lead to flaky tests due to shared state. Consider using beforeEach for setup.

  describe("/", () => {
-    exportRepo(testRepo.normal);
+    beforeEach(() => {
+      exportRepo(testRepo.normal);
+    });
    
    test("Direct", async () => {

Apply similar pattern to other test blocks to ensure clean state for each test.

Also applies to: 37-37, 59-59, 66-66


36-36: ⚠️ Potential issue

Fix inconsistent test structure.

Using Deno.test here is inconsistent with the BDD style used elsewhere. Replace with describe to maintain consistency.

-  Deno.test("/:ref", () => {
+  describe("/:ref", () => {

Committable suggestion skipped: line range outside the PR's diff.

Deno.test() doesn't support tree-structure tests.
@5ouma
Copy link
Owner Author

5ouma commented Dec 8, 2024

@coderabbitai review

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

🧹 Outside diff range and nitpick comments (2)
src/server.test.ts (2)

19-36: Consider adding edge cases for root path tests

The current test coverage looks good but consider adding tests for:

  • Invalid User-Agent headers
  • Rate limiting scenarios
  • Error responses from GitHub

Example test structure:

test("with invalid User-Agent", async () => {
  const res = await app.request("/", {
    headers: { "User-Agent": "invalid" },
  });
  assertEquals(res.status, STATUS_CODE.BadRequest);
});

59-76: Add JSDoc comments explaining slash handling

Consider adding documentation to explain the expected behavior when handling references with slashes.

+ /**
+  * Tests handling of references containing slashes (e.g., feature/branch).
+  * GitHub URLs require special handling for such references.
+  */
  describe("/:ref (with Slash)", () => {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4503642 and e393908.

⛔ Files ignored due to path filters (1)
  • deno.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • deno.json (1 hunks)
  • src/libs/content.test.ts (1 hunks)
  • src/libs/redirect.test.ts (1 hunks)
  • src/server.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • deno.json
  • src/libs/redirect.test.ts
  • src/libs/content.test.ts
🔇 Additional comments (3)
src/server.test.ts (3)

3-3: LGTM! Good choice using BDD style testing

The addition of BDD testing utilities will help improve test organization and readability.


14-16: Consider adding afterEach hook for cleanup

While the beforeEach hook correctly sets up the test environment, consider adding an afterEach hook to clean up any test artifacts.

Let's verify the test utils being used:


39-56: Verify testRef property usage across codebase

The usage of testRef.normal looks good, but let's ensure consistency across the codebase.

✅ Verification successful

testRef usage is consistent and well-documented

The testRef object is properly defined in test utilities with two properties:

  • normal: "v1.0.0"
  • slash: "renovate/configure"

All usages across the codebase in server.test.ts, content.test.ts, and redirect.test.ts consistently use these properties as documented in the JSDoc examples.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify consistent usage of testRef properties

# Check all usages of testRef
rg "testRef\." --type typescript

Length of output: 69


Script:

#!/bin/bash
# Search for testRef usage without file type restriction
rg "testRef\."

# Also search for testRef declaration
ast-grep --pattern 'const testRef = $_'

Length of output: 987


Script:

#!/bin/bash
# Let's find the testRef declaration and its structure
rg "testRef\s*=\s*{" -A 5

# Also check if there are any other properties beyond normal and slash
rg "testRef\.[a-zA-Z]+" --only-matching | sort -u

Length of output: 396


Script:

#!/bin/bash
# Fix the regex to find testRef declaration
rg "testRef = " -A 5

Length of output: 22


Script:

#!/bin/bash
# Search for files that might contain test constants/fixtures
fd "test_" --type f --exec cat {}

Length of output: 1565

@5ouma 5ouma merged commit c26f7e4 into main Dec 8, 2024
@5ouma 5ouma deleted the test-utils branch December 8, 2024 10:08
@github-actions github-actions bot mentioned this pull request Dec 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🧪 Testing Adding missing tests or correcting existing tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants