Skip to content

Test: src/graphql/types/FundCampaignPledge/updater.ts #3190

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 9 commits into from
Feb 12, 2025
Merged

Test: src/graphql/types/FundCampaignPledge/updater.ts #3190

merged 9 commits into from
Feb 12, 2025

Conversation

JXP25
Copy link

@JXP25 JXP25 commented Feb 9, 2025

Goal

This PR improves the code coverage for the file src/graphql/types/FundCampaignPledge/updater.ts, ensuring 100% coverage across lines, functions, statements, and branches.

image

Tasks Completed

  • Reviewed updater.ts to identify untested logic.
  • Added/Updated Test Cases to cover all branches and conditions.
  • Removed /* istanbul ignore */ statements where applicable.
  • Refactored Test Cases for better readability and efficiency.
  • Ensured Tests Pass all checks and CI/CD pipelines.

Issue

This PR addresses #3036

Note

Resolver was extracted carefully to make it available in test file, it wouldn't cause breaking changes.

Summary by CodeRabbit

  • New Features

    • Introduced enhanced campaign pledge update handling that improves user verification, permission checks, and overall reliability.
  • Tests

    • Added comprehensive test coverage to validate various user scenarios, ensuring robust error management and consistent behavior.

Copy link

coderabbitai bot commented Feb 9, 2025

Walkthrough

This pull request extracts the resolver logic for the FundCampaignPledge type into a new function named resolveUpdater. The function enforces authentication, performs concurrent queries for the current user and related fund campaign data, and includes comprehensive error handling and role authorization checks. A new ContextType is defined to support the updated context. A corresponding test suite has been added using Vitest, covering scenarios such as unauthenticated access, missing campaign or user data, null updater IDs, and proper user lookup and authorization.

Changes

File(s) Change Summary
src/graphql/types/FundCampaignPledge/updater.ts Introduced a new function resolveUpdater encapsulating the resolver logic for the updater field; defined a new type ContextType combining ExplicitGraphQLContext and ImplicitMercuriusContext; maintained authentication, error handling, and authorization logic.
test/graphql/types/FundCampaignPledge/updater.test.ts Added a comprehensive Vitest test suite for resolveUpdater, covering authentication checks, campaign existence, role-based authorization, handling of null updater IDs, and proper resolution or error-throwing in various scenarios.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Resolver as resolveUpdater
  participant UserDB
  participant CampaignDB

  Client->>Resolver: Call resolveUpdater(parent, _args, ctx)
  Resolver->>Resolver: Check if ctx.currentClient.isAuthenticated
  alt Not authenticated
    Resolver-->>Client: Throw TalawaGraphQLError
  else Authenticated
    Resolver->>UserDB: Query for current user and, if needed, updater user concurrently
    Resolver->>CampaignDB: Query for existing fund campaign (using parent.campaignId)
    alt updaterId is null
      Resolver-->>Client: Return null
    else updaterId equals currentUserId
      Resolver-->>Client: Return currentUser
    else
      Resolver->>UserDB: Fetch user by updaterId
      alt User found
        Resolver-->>Client: Return fetched updater
      else User not found
        Resolver-->>Client: Log error and throw TalawaGraphQLError
      end
    end
  end
Loading

Possibly related issues

Possibly related PRs

Suggested labels

ignore-sensitive-files-pr

Suggested reviewers

  • palisadoes

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9892675 and 7213d46.

📒 Files selected for processing (2)
  • src/graphql/types/FundCampaignPledge/updater.ts (1 hunks)
  • test/graphql/types/FundCampaignPledge/updater.test.ts (1 hunks)
🔇 Additional comments (13)
src/graphql/types/FundCampaignPledge/updater.ts (6)

9-10: Encapsulating Context Type Looks Good.
Defining a dedicated ContextType to merge ExplicitGraphQLContext & ImplicitMercuriusContext keeps the codebase organized and type-safe.


16-22: Use of "unauthenticated" error code is consistent.
This helps clearly distinguish between missing session vs. other errors. No issues here.


69-79: Consider using a more specific error code for missing campaign.
Using "unexpected" when the campaign doesn't exist can obscure the real error. A more descriptive code like "campaign_not_found" would improve clarity.


105-121: Consider using a clearer error code for missing updater user.
This repeats a past suggestion to differentiate between truly “unexpected” errors and cases where the updater user record is not found.


81-95: Administrator role check is well-structured.
The combined check for both global admin and organization membership is properly handled.


126-134: Implementation within FundCampaignPledge is appropriately wired.
Referencing the new resolver function enriches testability without complicating the existing type definitions.

test/graphql/types/FundCampaignPledge/updater.test.ts (7)

1-9: Well-rounded test imports.
Vitest, utility types, and the direct import of the resolver maintain clarity and ensure coverage.


30-41: Mocking drizzle client and context is cleanly set up.
This arrangement streamlines testing while keeping dependencies isolated.


60-75: Comprehensive unauthenticated checks.
Both "not authenticated" and "user not found" scenarios are fully addressed, boosting coverage and preventing regressions.


94-114: Unauthorized user role scenario is tested thoroughly.
Validates that only admins can proceed, aligning with the production logic in the resolver.


158-176: Robust handling of non-existent updater user.
Covers the edge case that the updater ID might not point to a valid user, ensuring an appropriately thrown error.


194-205: Validates correct user lookups.
Ensures the query uses the right userID and that the function returns the expected user.


255-293: Membership condition check thoroughly verified.
The test ensures that the where condition for membershipsWhereOrganization is invoked correctly, satisfying coverage goals.

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

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

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9892675 and aa8b50a.

📒 Files selected for processing (2)
  • src/graphql/types/FundCampaignPledge/updater.ts (1 hunks)
  • test/graphql/types/FundCampaignPledge/FundCampaignPledge.test.ts (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: Pull request workflow
src/graphql/types/FundCampaignPledge/updater.ts

[warning] 1-1: Import statements could be sorted.


[warning] 4-4: Formatter would have printed the following content.

test/graphql/types/FundCampaignPledge/FundCampaignPledge.test.ts

[warning] 1-1: Import statements could be sorted.


[warning] 1-1: Formatter would have printed the following content.

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (4)
src/graphql/types/FundCampaignPledge/updater.ts (2)

9-77: Well-structured resolver with proper error handling and concurrent data fetching!

The implementation shows good practices:

  • Concurrent data fetching using Promise.all
  • Descriptive error messages
  • Type-safe context handling

94-131: Efficient updater resolution logic with proper error handling!

The implementation shows good practices:

  • Early return for null updaterId
  • Optimization by returning currentUser when possible
  • Proper error handling for non-existent updater
test/graphql/types/FundCampaignPledge/FundCampaignPledge.test.ts (2)

1-52: Well-structured test setup with comprehensive mocks!

The test setup shows good practices:

  • Complete mock coverage of dependencies
  • Realistic test data
  • Clear type definitions
🧰 Tools
🪛 GitHub Actions: Pull request workflow

[warning] 1-1: Import statements could be sorted.


[warning] 1-1: Formatter would have printed the following content.


132-214: Thorough query validation tests!

The tests effectively verify:

  • Correct query parameters
  • Proper membership validation
  • Query construction accuracy

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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: 3

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aa8b50a and 349955e.

📒 Files selected for processing (1)
  • src/graphql/types/FundCampaignPledge/updater.ts (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: Pull request workflow
src/graphql/types/FundCampaignPledge/updater.ts

[warning] 1-1: Import statements could be sorted.


[warning] 1-1: Formatter would have printed the following content.

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (6)
src/graphql/types/FundCampaignPledge/updater.ts (6)

1-4: Sort import statements to address pipeline warning.
This suggestion has already been made in a previous review. Below is the same diff for reference:

-import { User } from "~/src/graphql/types/User/User";
-import { TalawaGraphQLError } from "~/src/utilities/TalawaGraphQLError";
-import { FundCampaignPledge } from "./FundCampaignPledge";
-import type { ExplicitGraphQLContext, ImplicitMercuriusContext } from '~/src/graphql/context';
+import type { ExplicitGraphQLContext, ImplicitMercuriusContext } from '~/src/graphql/context';
+import { FundCampaignPledge } from "./FundCampaignPledge";
+import { TalawaGraphQLError } from "~/src/utilities/TalawaGraphQLError";
+import { User } from "~/src/graphql/types/User/User";
🧰 Tools
🪛 GitHub Actions: Pull request workflow

[warning] 1-1: Import statements could be sorted.


[warning] 1-1: Formatter would have printed the following content.


6-6: Type alias for combined context looks good.
Defining and using a unified context type helps ensure type safety and clarity across resolvers.


9-57: Clean resolver structure and concurrent data fetching.
Your approach using Promise.all() to fetch both the current user and campaign simultaneously is efficient. The surrounding conditions (e.g., checking authentication) are logically sound.


82-92: Enhance error message for unauthorized access.
As mentioned in a prior review, consider adding a descriptive message in addition to the error code to clarify why the request was denied.


94-100: Simple and intuitive updaterId check.
Returning null when no updater exists, or the current user object when IDs match, is clear and logical.


123-131: Nicely integrated resolver assignment.
Registering the new resolver function within the FundCampaignPledge type is straightforward and fits well with your project’s patterns.

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 9, 2025
@JXP25
Copy link
Author

JXP25 commented Feb 9, 2025

@coderabbitai full review

Copy link

coderabbitai bot commented Feb 9, 2025

✅ Actions performed

Full review triggered.

@JXP25 JXP25 changed the title 100% Code Coverage in updater.ts Test: src/graphql/types/FundCampaignPledge/updater.ts Feb 9, 2025
Copy link
Contributor

@palisadoes palisadoes left a comment

Choose a reason for hiding this comment

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

  1. Why was this code removed? Pledges are an important feature of the app
  2. You have reduced the functionality

image
image

@JXP25
Copy link
Author

JXP25 commented Feb 12, 2025

@palisadoes I haven't removed any code, just shifted a block of code above the component and called it back in, the comparison git is making looks messed up, but the code is same
Here is the approach

FundCampaignPledge.implement({
fields: (t) => ({
updater: t.field({
description: "User who last updated the fund campaign pledge.",
resolve: resolveUpdater,
type: User,
}),
}),
});

this resolveUpdater is extracted from pledge and called back here and also in test file.

@PalisadoesFoundation PalisadoesFoundation deleted a comment from codecov bot Feb 12, 2025
@JXP25
Copy link
Author

JXP25 commented Feb 12, 2025

Screenshot 2025-02-12 at 8 31 06 AM

Sir line number 11 and 16 can be compared directly for more clarity

Screenshot 2025-02-12 at 8 31 25 AM

Copy link

codecov bot commented Feb 12, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 42.38%. Comparing base (da81d6e) to head (2872a1c).
Report is 1 commits behind head on develop-postgres.

Additional details and impacted files
@@                 Coverage Diff                  @@
##           develop-postgres    #3190      +/-   ##
====================================================
+ Coverage             42.08%   42.38%   +0.29%     
====================================================
  Files                   455      455              
  Lines                 33647    33648       +1     
  Branches                563      578      +15     
====================================================
+ Hits                  14161    14261     +100     
+ Misses                19486    19387      -99     

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

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