Skip to content

event-creator-test #3181

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

Conversation

Piyushk8
Copy link

@Piyushk8 Piyushk8 commented Feb 8, 2025

What kind of change does this PR introduce?

Added tests for Event creator

Issue Number:

Fixes #3067

Snapshots/Videos:
image
image

If relevant, did you update the documentation?
no

Summary
Added test cases for event creator

Does this PR introduce a breaking change?
no

Checklist

CodeRabbit AI Review

  • I have reviewed and addressed all critical issues flagged by CodeRabbit AI
  • I have implemented or provided justification for each non-critical suggestion
  • I have documented my reasoning in the PR comments where CodeRabbit AI suggestions were not implemented

Test Coverage

  • I have written tests for all new changes/features
  • I have verified that test coverage meets or exceeds 95%
  • I have run the test suite locally and all tests pass

Have you read the contributing guide?

Yes

Summary by CodeRabbit

  • Refactor

    • Enhanced how the event creator is determined by restructuring the validation and error handling, ensuring more consistent responses when user permissions or data inconsistencies are encountered.
  • Tests

    • Introduced extensive tests covering authentication, permission checks, and error cases to ensure reliable and predictable behavior when retrieving event creator details.

Copy link

coderabbitai bot commented Feb 8, 2025

Walkthrough

This PR refactors the event creator resolver by extracting its logic into a dedicated asynchronous function. The new function performs authentication, authorization, and error handling before returning the creator information. In addition, a comprehensive test suite is added to validate various scenarios such as missing authentication, insufficient permissions, and database anomalies, ensuring full coverage of the resolver's behavior.

Changes

File(s) Change Summary
src/graphql/types/Event/creator.ts Refactored the event creator resolver by extracting its logic into an asynchronous function (eventCreatorResolver) with added authentication checks, role validation, database queries, and improved error handling. Added necessary type imports and exported the new function.
test/graphql/types/Event/creator.test.ts Introduced a comprehensive test suite using Vitest to validate authentication, authorization, error handling, and database interaction scenarios for the eventCreatorResolver.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant R as eventCreatorResolver
    participant DB as Database

    C->>R: Request event creator
    R->>R: Check authentication
    alt Not authenticated
        R-->>C: Throw "unauthenticated" error
    else Authenticated
        R->>DB: Query current user & memberships
        alt User not found
            R-->>C: Throw "unauthenticated" error
        else
            R->>R: Verify administrator role
            alt Not an administrator
                R-->>C: Throw "unauthorized_action" error
            else
                R->>R: Check if creatorId is null or matches current user
                alt creatorId is null
                    R-->>C: Return null
                else creatorId equals current user
                    R-->>C: Return current user
                else
                    R->>DB: Fetch user by creatorId
                    alt User not found
                        R-->>C: Log error and throw "unexpected" error
                    else
                        R-->>C: Return fetched user
                    end
                end
            end
        end
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Improve test coverage for src/graphql/types/Event/creator.ts (#3067)

Possibly related issues

Possibly related PRs

  • Test: src/graphql/types/tag/creator.ts #3170: Introduces a parallel resolver function (tagCreatorResolver) with similar authentication and authorization logic, indicating a consistent implementation approach between the two features.

Suggested labels

ignore-sensitive-files-pr

Suggested reviewers

  • palisadoes
✨ 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

github-actions bot commented Feb 8, 2025

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

Copy link

codecov bot commented Feb 8, 2025

Codecov Report

Attention: Patch coverage is 98.79518% with 1 line in your changes missing coverage. Please review.

Project coverage is 40.54%. Comparing base (3266337) to head (4cbfa62).
Report is 2 commits behind head on develop-postgres.

Files with missing lines Patch % Lines
src/graphql/types/Event/creator.ts 98.79% 1 Missing ⚠️
Additional details and impacted files
@@                 Coverage Diff                  @@
##           develop-postgres    #3181      +/-   ##
====================================================
+ Coverage             40.33%   40.54%   +0.21%     
====================================================
  Files                   455      455              
  Lines                 33558    33574      +16     
  Branches                446      465      +19     
====================================================
+ Hits                  13534    13613      +79     
+ Misses                20024    19961      -63     

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

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 5255740 and c444fed.

📒 Files selected for processing (2)
  • src/graphql/types/Event/creator.ts (1 hunks)
  • test/graphql/types/event/creator.test.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run tests for talawa api
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (17)
src/graphql/types/Event/creator.ts (7)

3-5: Imports appear correct and consistent.
No issues noted with the new type imports.


7-11: Distinct resolver function is a good design approach.
Separating the logic into its own function aids maintainability and clarity.


12-18: Clear unauthenticated check.
Throwing a TalawaGraphQLError for non-authenticated users is appropriate. Consider customizing the error message to provide more context if desired for debugging.


20-43: Robust retrieval of current user.
Accessing the database to confirm user presence is well-handled. Ensure that the role retrieval logic in lines 29-31 abides by the correct membership scoping for future expansions of the membership model.


59-65: Graceful handling of null creator ID or current user as creator.
These conditionals ensure consistent returns without unnecessary DB lookups. This is efficient and improves clarity.


86-99: Catch block ensures robust error rethrowing and logging.
Re-throwing TalawaGraphQLError preserves original error context while logging unknown errors helps with investigations. This approach is solid.


101-109: Event type implementation with the new resolver.
Registering the resolver for the “creator” field is straightforward and consistent with the extracted logic.

test/graphql/types/event/creator.test.ts (10)

1-23: Mock context and imports look solid.
Using vitest mocks for the context and the Drizzle client is a clean way to isolate the business logic for testing.


24-32: Well-defined MockUser type.
Clearly outlines the structure needed for testing user data, aiding readability.


54-119: Comprehensive authentication and authorization test coverage.
Covering both unauthenticated and unauthorized users is thorough. Consider using parameterized tests to reduce duplication.


121-137: Null creator ID test is precise.
Verifies correct handling of null references, preventing NPE-like issues.


139-158: Accurate test for returning the current user as creator.
Confirms the resolver correctly identifies and returns the currentUser if IDs match.


160-188: Fetching a different user from the DB.
This test ensures the resolver retrieves a separate creator, reinforcing that the logic is not incorrectly hard-coded to the current user.


190-208: Catching the missing user scenario.
Helps confirm that the resolver raises an "unexpected" error when the selected creator doesn't exist.


210-273: Handling various database query errors.
From connection failures to constraint violations and syntax errors, these tests ensure consistent error handling and logging.


276-336: Concurrent access tests are valuable.
Simulating parallel event/creator updates or deletions helps confirm the resolver logs and returns errors consistently.


338-370: Ensuring error pass-through for TalawaGraphQLError.
This preserves the original error properties and is a good approach for layering custom error handling without inadvertently masking known exceptions.

Copy link

github-actions bot commented Feb 8, 2025

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c444fed and 493827c.

📒 Files selected for processing (1)
  • test/graphql/types/Event/creator.test.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run tests for talawa api
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (2)
test/graphql/types/Event/creator.test.ts (2)

103-118: Address commented-out test case.

The commented-out test case appears to be important for testing admin authorization. Either implement it or remove it with a clear explanation of why it's not needed.

Please clarify if this test case is still needed. If it is, I can help implement it correctly.


33-371: LGTM! Comprehensive test coverage.

The test suite provides excellent coverage of various scenarios including:

  • Authentication and authorization
  • Error handling
  • Database interactions
  • Concurrent access
  • Edge cases

The tests are well-organized and follow good testing practices.

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.

Please make code rabbit ai approve your work

@Piyushk8
Copy link
Author

Piyushk8 commented Feb 9, 2025

Please make code rabbit ai approve your work

@palisadoes
sir , i need a suggestion

I noticed that some tests use mockContext, while others define custom GraphQL contexts in their files. This could lead to inconsistencies and require multiple updates if GRAPHQLCONTEXT in context.ts changes.

will creating a MockContextCreator factory function to ensure all tests use a single, consistent mock context. This will simplify maintenance and keep everything aligned. Let me know your thoughts.

should make a seperate PR for that ?
Thanks!

@palisadoes
Copy link
Contributor

palisadoes commented Feb 9, 2025

  1. How many files would need to be updated for this new approach?
  2. Is it practical to make the change all at once?
  3. What was the original approach used in this branch?

@Piyushk8
Copy link
Author

Piyushk8 commented Feb 9, 2025

  1. How many files would need to be updated for this new approach?
  2. Is it practical to make the change all at once?
  3. What was the original approach used in this branch?
    Here’s a more concise and structured version of your response with key points highlighted:

@palisadoes

  1. Files to Update:

    • All test files in graphql/types need updating.
    • This is based on the current unit testing pattern for resolvers.
    • Needs discussion, as many contributors are following this approach.
  2. Feasibility of Changing All at Once:

    • Yes, since the only required change is in the context logic.
    • Context will be exported from a context factory function (resolvers share the same context in GraphQL).
  3. Original Approach in This Branch:

    • Contributors were handling GraphQL context in two ways:
      A) Custom context per test
      B) Defining context inside test files
      So , might be some irregularities in future

    • Someone more familiar with the codebase should decide the best approach.

And I have resolved issues in this pr for now

@palisadoes
Copy link
Contributor

  1. The standardized MockContextCreator approach seems best.
  2. Would that be a separate PR?

@Piyushk8
Copy link
Author

Piyushk8 commented Feb 9, 2025

  1. The standardized MockContextCreator approach seems best.
  2. Would that be a separate PR?

@palisadoes
yes, new MockContextCreator approach need changes in several files so , making a seperate pr would be better for a solving them together

this one is for unit testing only with current approach

@PalisadoesFoundation PalisadoesFoundation deleted a comment from github-actions bot Feb 9, 2025
@palisadoes palisadoes merged commit 9892675 into PalisadoesFoundation:develop-postgres Feb 9, 2025
18 checks passed
@palisadoes
Copy link
Contributor

Please create another issue and PR to fix the factory

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