Skip to content

Copy of PR #22493: fix: resolve unique constraint violations in listWithTeam integration test#22499

Closed
dakshgup wants to merge 1 commit intocalcom:mainfrom
dakshgup:copy-pr-22493-devin/1752527545-fix-integration-test-unique-constraints
Closed

Copy of PR #22493: fix: resolve unique constraint violations in listWithTeam integration test#22499
dakshgup wants to merge 1 commit intocalcom:mainfrom
dakshgup:copy-pr-22493-devin/1752527545-fix-integration-test-unique-constraints

Conversation

@dakshgup
Copy link

@dakshgup dakshgup commented Jul 14, 2025

This is a copy of #22493

Originally by: zomars

fix: resolve unique constraint violations in listWithTeam integration test

Summary

Fixed a failing integration test in listWithTeam.handler.integration-test.ts that was causing unique constraint violations. The test was using hardcoded email addresses and slugs that persisted between test runs, causing failures when the same test data already existed in the database.

Key changes:

  • Added timestamp-based unique identifiers for usernames, emails, team slugs, and event type slugs
  • Implemented robust error handling in test cleanup with null checks and try-catch blocks
  • Test success rate improved from 113/114 to 114/114 (100% pass rate)

Root cause: The test used static values like testuser-lwt-1@example.com and team-1-lwt that violated unique constraints on subsequent test runs.

Review & Testing Checklist for Human

  • Verify test passes consistently - Run TZ=UTC yarn test -- --integrationTestsOnly multiple times to ensure the fix is robust
  • Check timestamp uniqueness approach - Confirm that Date.now() provides sufficient uniqueness for concurrent test scenarios
  • Validate cleanup logic - Ensure the new error handling in afterAll properly cleans up test data without masking real errors
  • Test multiple rapid runs - Execute the test suite several times in quick succession to verify no race conditions exist

Diagram

%%{ init : { "theme" : "default" }}%%
graph TD
    Test["packages/trpc/server/routers/viewer/eventTypes/<br/>listWithTeam.handler.integration-test.ts"]:::major-edit
    Handler["listWithTeam.handler"]:::context
    UserModel["User (Prisma Model)"]:::context
    TeamModel["Team (Prisma Model)"]:::context
    EventTypeModel["EventType (Prisma Model)"]:::context
    
    Test --> Handler
    Test --> UserModel
    Test --> TeamModel
    Test --> EventTypeModel
    
    Test -- "creates with unique timestamps" --> UserModel
    Test -- "creates with unique slugs" --> TeamModel
    Test -- "creates with unique slugs" --> EventTypeModel
    
    subgraph Legend
        L1[Major Edit]:::major-edit
        L2[Minor Edit]:::minor-edit
        L3[Context/No Edit]:::context
    end
    
    classDef major-edit fill:#90EE90
    classDef minor-edit fill:#87CEEB
    classDef context fill:#FFFFFF
Loading

Notes

  • This fix addresses the PrismaClientKnownRequestError: Unique constraint failed on the fields: (email) that was preventing the integration test suite from achieving 100% pass rate
  • The solution maintains test isolation by ensuring each test run creates truly unique database records
  • Session requested by @zomars: https://app.devin.ai/sessions/3d62b140e87c424ab80c9ed76ac298ca

Summary by CodeRabbit

  • Tests
    • Improved reliability of integration tests by ensuring unique test data and more robust cleanup handling.

… listWithTeam integration test

Originally by: zomars

# fix: resolve unique constraint violations in listWithTeam integration test

## Summary

Fixed a failing integration test in `listWithTeam.handler.integration-test.ts` that was causing unique constraint violations. The test was using hardcoded email addresses and slugs that persisted between test runs, causing failures when the same test data already existed in the database.

**Key changes:**
- Added timestamp-based unique identifiers for usernames, emails, team slugs, and event type slugs
- Implemented robust error handling in test cleanup with null checks and try-catch blocks
- Test success rate improved from 113/114 to 114/114 (100% pass rate)

**Root cause:** The test used static values like `testuser-lwt-1@example.com` and `team-1-lwt` that violated unique constraints on subsequent test runs.

## Review & Testing Checklist for Human

- [ ] **Verify test passes consistently** - Run `TZ=UTC yarn test -- --integrationTestsOnly` multiple times to ensure the fix is robust
- [ ] **Check timestamp uniqueness approach** - Confirm that `Date.now()` provides sufficient uniqueness for concurrent test scenarios
- [ ] **Validate cleanup logic** - Ensure the new error handling in `afterAll` properly cleans up test data without masking real errors
- [ ] **Test multiple rapid runs** - Execute the test suite several times in quick succession to verify no race conditions exist

---

### Diagram

```mermaid
%%{ init : { "theme" : "default" }}%%
graph TD
    Test["packages/trpc/server/routers/viewer/eventTypes/<br/>listWithTeam.handler.integration-test.ts"]:::major-edit
    Handler["listWithTeam.handler"]:::context
    UserModel["User (Prisma Model)"]:::context
    TeamModel["Team (Prisma Model)"]:::context
    EventTypeModel["EventType (Prisma Model)"]:::context

    Test --> Handler
    Test --> UserModel
    Test --> TeamModel
    Test --> EventTypeModel

    Test -- "creates with unique timestamps" --> UserModel
    Test -- "creates with unique slugs" --> TeamModel
    Test -- "creates with unique slugs" --> EventTypeModel

    subgraph Legend
        L1[Major Edit]:::major-edit
        L2[Minor Edit]:::minor-edit
        L3[Context/No Edit]:::context
    end

    classDef major-edit fill:#90EE90
    classDef minor-edit fill:#87CEEB
    classDef context fill:#FFFFFF
```

### Notes

- This fix addresses the PrismaClientKnownRequestError: Unique constraint failed on the fields: (`email`) that was preventing the integration test suite from achieving 100% pass rate
- The solution maintains test isolation by ensuring each test run creates truly unique database records
- Session requested by @zomars: https://app.devin.ai/sessions/3d62b140e87c424ab80c9ed76ac298ca

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->

## Summary by CodeRabbit

* **Tests**
  * Improved test reliability by ensuring unique test data for each run and enhancing cleanup procedures for better error handling.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
@vercel
Copy link

vercel bot commented Jul 14, 2025

@dakshgup is attempting to deploy a commit to the cal Team on Vercel.

A member of the Team first needs to authorize it.

@graphite-app graphite-app bot added the community Created by Linear-GitHub Sync label Jul 14, 2025
@graphite-app graphite-app bot requested a review from a team July 14, 2025 22:42
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 14, 2025

Walkthrough

The integration test setup and cleanup logic were updated to ensure unique entity creation by appending timestamps to identifiers. Cleanup procedures were enhanced with conditional existence checks, error handling, and logging to prevent issues when entities are missing or already deleted.

Changes

Files Change Summary
packages/trpc/server/routers/viewer/eventTypes/listWithTeam.handler.integration-test.ts Improved test setup for unique entity creation; enhanced cleanup with conditional checks and error handling.

Poem

A rabbit hops through tests anew,
With timestamps fresh on all it grew.
Cleanup’s gentle, errors caught,
No missing data left to rot.
Each test now hops without a care—
Unique and tidy everywhere!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/trpc/server/routers/viewer/eventTypes/listWithTeam.handler.integration-test.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-playwright".

(The package "eslint-plugin-playwright" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-playwright@latest --save-dev

The plugin "eslint-plugin-playwright" was referenced from the config file in ".eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

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

@CLAassistant
Copy link

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@github-actions
Copy link
Contributor

github-actions bot commented Jul 14, 2025

Hey there and thank you for opening this pull request! 👋🏼

We require pull request titles to follow the Conventional Commits specification and it looks like your proposed title needs to be adjusted.

Details:

No release type found in pull request title "Copy of PR #22493: fix: resolve unique constraint violations in listWithTeam integration test". Add a prefix to indicate what kind of release this pull request corresponds to. For reference, see https://www.conventionalcommits.org/

Available types:
 - feat: A new feature
 - fix: A bug fix
 - docs: Documentation only changes
 - style: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
 - refactor: A code change that neither fixes a bug nor adds a feature
 - perf: A code change that improves performance
 - test: Adding missing tests or correcting existing tests
 - build: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)
 - ci: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)
 - chore: Other changes that don't modify src or test files
 - revert: Reverts a previous commit

@dosubot dosubot bot added the automated-tests area: unit tests, e2e tests, playwright label Jul 14, 2025
@graphite-app
Copy link

graphite-app bot commented Jul 14, 2025

Graphite Automations

"Add consumer team as reviewer" took an action on this PR • (07/14/25)

1 reviewer was added to this PR based on Keith Williams's automation.

"Add community label" took an action on this PR • (07/14/25)

1 label was added to this PR based on Keith Williams's automation.

Copy link
Contributor

@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 (1)
packages/trpc/server/routers/viewer/eventTypes/listWithTeam.handler.integration-test.ts (1)

21-21: Consider potential race conditions with timestamp-based uniqueness.

While Date.now() provides good uniqueness for most scenarios, there's a theoretical risk of race conditions if multiple test instances run simultaneously and generate the same timestamp.

Consider using crypto.randomUUID() or a combination of timestamp + random suffix for stronger uniqueness guarantees:

-    const timestamp = Date.now();
+    const uniqueId = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;

Then update the identifier usage throughout the test setup.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fe4946a and 875c38f.

📒 Files selected for processing (1)
  • packages/trpc/server/routers/viewer/eventTypes/listWithTeam.handler.integration-test.ts (6 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Install dependencies / Yarn install & cache
  • GitHub Check: Security Check
🔇 Additional comments (3)
packages/trpc/server/routers/viewer/eventTypes/listWithTeam.handler.integration-test.ts (3)

24-25: LGTM! Timestamp-based email and username uniqueness.

The addition of timestamps to usernames and emails effectively prevents unique constraint violations while maintaining readable test data.

Also applies to: 31-32


40-40: LGTM! Consistent timestamp approach for all slug fields.

The timestamp suffix has been consistently applied to all slug fields (team slugs and event type slugs), ensuring comprehensive uniqueness across test runs.

Also applies to: 54-54, 61-61, 70-70, 80-80, 89-89


98-128: Excellent improvement to cleanup logic with robust error handling.

The enhanced cleanup implementation addresses several important concerns:

  • Conditional existence checks: Prevents unnecessary database calls when entities don't exist
  • Error handling: Try-catch block prevents cleanup failures from masking real test errors
  • Null safety: filter(Boolean) removes undefined IDs from deletion arrays
  • Graceful failure: Warning logs provide visibility without failing tests

One minor suggestion for improved debugging:

    } catch (error) {
-      console.warn("Test cleanup failed:", error);
+      console.warn("Test cleanup failed - this may cause issues in subsequent test runs:", error);
    }

@hbjORbj hbjORbj closed this Jul 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

automated-tests area: unit tests, e2e tests, playwright community Created by Linear-GitHub Sync

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants