Skip to content

fix: resolve unique constraint violations in listWithTeam integration test#22493

Merged
zomars merged 1 commit intomainfrom
devin/1752527545-fix-integration-test-unique-constraints
Jul 15, 2025
Merged

fix: resolve unique constraint violations in listWithTeam integration test#22493
zomars merged 1 commit intomainfrom
devin/1752527545-fix-integration-test-unique-constraints

Conversation

@zomars
Copy link
Contributor

@zomars zomars commented Jul 14, 2025

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 test reliability by ensuring unique test data for each run and enhancing cleanup procedures for better error handling.

… test

- Add timestamp-based unique identifiers for usernames, emails, team slugs, and event type slugs
- Implement proper error handling in test cleanup with null checks and try-catch blocks
- Prevents PrismaClientKnownRequestError: Unique constraint failed on email fields
- Fixes TypeError: Cannot read properties of undefined (reading 'id') in cleanup
- All 114 integration tests now pass (previously 113/114)

Co-Authored-By: zomars@cal.com <zomars@me.com>
@devin-ai-integration
Copy link
Contributor

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR that start with 'DevinAI'.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment and CI monitoring

@vercel
Copy link

vercel bot commented Jul 14, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

2 Skipped Deployments
Name Status Preview Comments Updated (UTC)
cal ⬜️ Ignored (Inspect) Visit Preview Jul 14, 2025 9:13pm
cal-eu ⬜️ Ignored (Inspect) Visit Preview Jul 14, 2025 9:13pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 14, 2025

Walkthrough

The integration test setup for event types was updated to ensure unique test data by appending timestamps to identifiers. Cleanup logic was improved with error handling, conditional deletions based on resource existence, and logging of cleanup failures to enhance test isolation and robustness.

Changes

File(s) Change Summary
packages/trpc/server/routers/viewer/eventTypes/listWithTeam.handler.integration-test.ts Improved test data uniqueness with timestamps; enhanced cleanup with error handling and logging.

Poem

A timestamp here, a slug anew,
For every test, uniqueness grew.
Cleanup now checks, deletes with care,
Logs a warning if errors are there.
In the warren of code, tests hop with glee—
Robust and tidy, as all should be! 🐇✨

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.


📜 Recent 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 6664aa2.

📒 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: Detect changes
  • GitHub Check: Security Check
🔇 Additional comments (5)
packages/trpc/server/routers/viewer/eventTypes/listWithTeam.handler.integration-test.ts (5)

21-21: Good approach for ensuring test data uniqueness.

Using Date.now() to create unique identifiers is an effective solution for preventing unique constraint violations in integration tests.


24-25: LGTM: Timestamp applied to user identifiers.

The username and email fields now include timestamps to ensure uniqueness across test runs, which should resolve the unique constraint violations mentioned in the PR objectives.

Also applies to: 31-32


40-40: LGTM: Timestamp applied to team slugs.

Team slugs now include timestamps to prevent collisions during parallel test execution or repeated test runs.

Also applies to: 54-54


61-61: LGTM: Timestamp applied to event type slugs.

Event type slugs now include timestamps for uniqueness, completing the comprehensive approach to prevent constraint violations.

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


98-128: Excellent cleanup logic improvements.

The enhanced cleanup logic addresses several important concerns:

  1. Error handling: Try-catch block prevents test failures due to cleanup errors
  2. Conditional deletions: Resources are only deleted if they exist, preventing unnecessary database operations
  3. Proper filtering: filter(Boolean) removes undefined values before deletion
  4. Logging: Warning logs provide visibility into cleanup failures without breaking tests

This is a robust implementation that should handle edge cases gracefully.

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

@graphite-app graphite-app bot requested a review from a team July 14, 2025 21:13
@keithwillcode keithwillcode added core area: core, team members only foundation labels Jul 14, 2025
@dosubot dosubot bot added the automated-tests area: unit tests, e2e tests, playwright label Jul 14, 2025
@delve-auditor
Copy link

delve-auditor bot commented Jul 14, 2025

No security or compliance issues detected. Reviewed everything up to 6664aa2.

Security Overview
  • 🔎 Scanned files: 1 changed file(s)
Detected Code Changes
Change Type Relevant files
Bug Fix ► listWithTeam.handler.integration-test.ts
    Add timestamp-based unique identifiers for test data
    Improve error handling in test cleanup

Reply to this PR with @delve-auditor followed by a description of what change you want and we'll auto-submit a change to this PR to implement it.

@graphite-app
Copy link

graphite-app bot commented Jul 14, 2025

Graphite Automations

"Add foundation 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.

@github-actions
Copy link
Contributor

E2E results are ready!

@zomars zomars enabled auto-merge (squash) July 14, 2025 22:23
dakshgup added a commit to dakshgup/cal.com that referenced this pull request Jul 14, 2025
… 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 -->
Copy link
Contributor

@anikdhabal anikdhabal left a comment

Choose a reason for hiding this comment

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

👍

@zomars zomars merged commit 202d248 into main Jul 15, 2025
105 of 110 checks passed
@zomars zomars deleted the devin/1752527545-fix-integration-test-unique-constraints branch July 15, 2025 02:21
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 core area: core, team members only foundation ready-for-e2e

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants