Skip to content

feat(tests): Add comprehensive test suite for the Project API#7252

Merged
sriramveeraghanta merged 8 commits intomakeplane:previewfrom
mohamedhayballa22:preview
Jul 2, 2025
Merged

feat(tests): Add comprehensive test suite for the Project API#7252
sriramveeraghanta merged 8 commits intomakeplane:previewfrom
mohamedhayballa22:preview

Conversation

@mohamedhayballa22
Copy link
Contributor

@mohamedhayballa22 mohamedhayballa22 commented Jun 22, 2025

Description

This pull request introduces a comprehensive API contract test suite for the Project resource to improve the test coverage and long-term health of this component and the overall codebase.

This covers all CRUD operations (POST, GET, PATCH, DELETE) and includes extensive checks for:

  • Core business logic and side-effects.
  • Detailed permission enforcement for different user roles.
  • Authentication requirements for all endpoints.
  • Validation for invalid data and uniqueness constraints.
  • Edge cases like retrieving non-existent or archived projects.

To support this and future tests, this PR also introduces a reusable workspace fixture in conftest.py.

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • Feature (non-breaking change which adds functionality)
  • Improvement (change that would cause existing functionality to not work as expected)
  • Code refactoring
  • Performance improvements
  • Documentation update

Test Scenarios

The changes in this PR consist entirely of new tests. All new and existing tests in the suite were run via pytest and passed successfully in the local development environment. The new tests themselves serve as the verification for the existing Project API functionality.

References

Closes #7229

Summary by CodeRabbit

  • Tests
    • Added new contract tests for Project API endpoints, covering project creation, retrieval, updating, and deletion within a workspace context.
    • Tests include scenarios for permissions, required and optional fields, conflict handling, and access control for different user roles.
    • Introduced a new fixture to streamline workspace setup in tests.

Introduces a new `workspace` fixture in `conftest.py` to provide a
consistent and reusable setup for tests that require a workspace.
This commit introduces a comprehensive test suite for the project creation API endpoint.

The suite covers a wide range of scenarios, including:
- Successful creation and verification of side-effects (default states, project members, user properties).
- Validation for invalid or missing data (400 Bad Request).
- Permission checks for different user roles (e.g., guests are forbidden).
- Authentication requirements (401 Unauthorized).
- Uniqueness constraints for project names and identifiers (409 Conflict).
- Successful creation with all optional fields populated.

It leverages the `workspace`, `session_client` and `create_user` fixtures for a consistent test setup.
To avoid code duplication in upcoming tests, this commit introduces a `TestProjectBase` class.

The `get_project_url` helper method is moved into this shared base class, and the existing `TestProjectAPIPost` class is updated to inherit from it. This ensures the URL generation logic is defined in a single place and preparing the suite for the upcoming GET tests.
This commit adds a suite for the GET method. It leverages the previously created `TestProjectBase` class for URL generation.

The new test suite covers:
- Listing projects:
  - Verifies that administrators see all projects.
  - Confirms guests only see projects they are members of.
  - Tests the separate detailed project list endpoint.
- Retrieving a single project:
  - Checks for successful retrieval of a project by its ID.
  - Handles edge cases for non-existent and archived projects (404 Not Found).
- Authentication:
  - Ensures authentication is required (401 Unauthorized).
Key scenarios tested for PATCH:
- Successful partial updates by project administrators.
- Forbidden access for non-admin members (403).
- Conflict errors for duplicate names or identifiers on update (409).
- Validation errors for invalid data (400).

Key scenarios tested for DELETE:
- Successful deletion by both project admins and workspace admins.
- Forbidden access for non-admin members (403).
- Authentication checks for unauthenticated users (401).
@CLAassistant
Copy link

CLAassistant commented Jun 22, 2025

CLA assistant check
All committers have signed the CLA.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 22, 2025

"""

Walkthrough

A new pytest fixture for creating workspaces was added to the test configuration, and a comprehensive contract test suite for the Project API endpoints within a workspace context was introduced. The tests cover project creation, retrieval, update, and deletion, verifying permissions, data validation, and correct API behavior.

Changes

File(s) Change Summary
apiserver/plane/tests/conftest.py Added a pytest fixture workspace for creating and retrieving a workspace for use in tests.
apiserver/plane/tests/contract/app/test_project_app.py Added comprehensive contract tests for Project API: POST, GET, PATCH, DELETE, covering permissions, validation, and expected behaviors.

Sequence Diagram(s)

sequenceDiagram
    participant TestClient
    participant API_Server
    participant Database

    TestClient->>API_Server: POST /api/workspace/ (create workspace)
    API_Server->>Database: Insert Workspace
    API_Server-->>TestClient: 201 Created + workspace ID

    TestClient->>API_Server: POST /api/workspace/{slug}/project/ (create project)
    API_Server->>Database: Insert Project, ProjectMember, IssueUserProperty
    API_Server-->>TestClient: 201 Created / 400 Bad Request / 409 Conflict

    TestClient->>API_Server: GET /api/workspace/{slug}/project/
    API_Server->>Database: Query Projects (filter by permissions)
    API_Server-->>TestClient: 200 OK + project list

    TestClient->>API_Server: PATCH /api/workspace/{slug}/project/{id}/
    API_Server->>Database: Update Project (if permitted)
    API_Server-->>TestClient: 200 OK / 403 Forbidden / 409 Conflict

    TestClient->>API_Server: DELETE /api/workspace/{slug}/project/{id}/
    API_Server->>Database: Delete Project (if permitted)
    API_Server-->>TestClient: 204 No Content / 403 Forbidden
Loading

Assessment against linked issues

Objective Addressed Explanation
Add test coverage for backend API endpoints, focusing on core modules like project API (#7229)
Follow established testing architecture and use of base classes for consistency (#7229)
Ensure tests verify permissions, data validation, and expected API behaviors for project endpoints (#7229)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes found.

Suggested reviewers

  • pablohashescobar
  • aheckmann

Poem

In the garden of code where the test bunnies roam,
New fixtures and checks now make their home.
Projects are guarded, permissions are tight,
APIs tested by day and by night.
With every assertion, bugs take flight—
Hippity-hop, all systems are right! 🐇✨
"""


📜 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 e93a6d7 and 62405be.

📒 Files selected for processing (1)
  • apiserver/plane/tests/conftest.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apiserver/plane/tests/conftest.py
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

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

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 (3)
apiserver/plane/tests/conftest.py (2)

6-6: Remove unused imports.

The patch and MagicMock imports from unittest.mock are not used in this file and should be removed to keep the codebase clean.

-from unittest.mock import patch, MagicMock

143-144: Fix line length violation.

The assertion message exceeds the project's line length limit (96 > 88 characters).

-    assert response.status_code == status.HTTP_201_CREATED, \
-        f"Failed to create workspace. Status: {response.status_code}, Response: {response.data}"
+    assert response.status_code == status.HTTP_201_CREATED, (
+        f"Failed to create workspace. Status: {response.status_code}, "
+        f"Response: {response.data}"
+    )
apiserver/plane/tests/contract/app/test_project_app.py (1)

54-54: Remove debug print statement.

The print(url) statement should be removed as it's not needed in production test code.

-        print(url)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7045a1f and 8bece84.

📒 Files selected for processing (2)
  • apiserver/plane/tests/conftest.py (2 hunks)
  • apiserver/plane/tests/contract/app/test_project_app.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.11.9)
apiserver/plane/tests/conftest.py

6-6: unittest.mock.patch imported but unused

Remove unused import

(F401)


6-6: unittest.mock.MagicMock imported but unused

Remove unused import

(F401)


144-144: Line too long (96 > 88)

(E501)

🪛 Pylint (3.3.7)
apiserver/plane/tests/contract/app/test_project_app.py

[refactor] 16-16: Too few public methods (1/2)

(R0903)

🔇 Additional comments (5)
apiserver/plane/tests/conftest.py (1)

125-148: Well-implemented workspace fixture!

The workspace fixture is properly implemented with:

  • Correct API endpoint usage via reverse()
  • Proper error handling with descriptive assertion message
  • Returns the actual model instance for test usage
  • Good documentation explaining its purpose

This fixture will provide excellent reusability for the comprehensive test suite.

apiserver/plane/tests/contract/app/test_project_app.py (4)

16-42: Excellent URL helper method implementation!

The get_project_url method is well-designed with:

  • Clear documentation and parameter descriptions
  • Flexible URL construction for different endpoint types
  • Proper handling of optional parameters
  • Good reasoning for avoiding reverse() due to duplicate URL names

This provides a clean abstraction for URL generation across all tests.


45-253: Comprehensive POST operation test coverage!

The POST tests excellently cover:

  • ✅ Empty data validation
  • ✅ Valid project creation with all side effects (ProjectMember, IssueUserProperty, States)
  • ✅ Project lead assignment scenarios
  • ✅ Permission enforcement (guest forbidden, unauthenticated denied)
  • ✅ Duplicate name/identifier conflict handling
  • ✅ Required field validation
  • ✅ Optional field handling

The tests verify both API responses and database state changes, which is crucial for contract testing.


255-403: Thorough GET operation test coverage!

The GET tests comprehensively cover:

  • ✅ Admin vs guest user access patterns
  • ✅ Project visibility based on membership
  • ✅ Unauthenticated access denial
  • ✅ Detailed project listing
  • ✅ Individual project retrieval
  • ✅ 404 handling for non-existent projects
  • ✅ Archived project exclusion

The permission testing ensures guests only see projects they belong to, which is critical for data security.


406-619: Complete PATCH/DELETE operation test suite!

The PATCH/DELETE tests provide excellent coverage of:

  • ✅ Successful partial updates with field verification
  • ✅ Permission enforcement (only admins can update/delete)
  • ✅ Duplicate name/identifier conflict handling
  • ✅ Invalid data rejection
  • ✅ Both project admin and workspace admin deletion rights
  • ✅ Unauthenticated access denial

The tests properly verify database state changes and ensure proper authorization controls.



@pytest.fixture
def workspace(session_client):
Copy link
Member

Choose a reason for hiding this comment

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

@mohamedhayballa22 I suggest you to directly create the workspace for this fixture using the Workspace model instead of the API.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@dheeru0198 Done!

Updates the `workspace` fixture to create the model instance directly via the ORM using the `Workspace` model instead of the API, as requested during code review.
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)
apiserver/plane/tests/conftest.py (1)

4-4: Clean up unused imports flagged by static analysis.

The static analysis correctly identifies several unused imports in this file. These should be removed to keep the codebase clean.

-from rest_framework import status
-from unittest.mock import patch, MagicMock
-from django.urls import reverse

Also applies to: 6-7

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8bece84 and e93a6d7.

📒 Files selected for processing (2)
  • apiserver/plane/tests/conftest.py (2 hunks)
  • apiserver/plane/tests/contract/app/test_project_app.py (1 hunks)
🧰 Additional context used
🪛 Pylint (3.3.7)
apiserver/plane/tests/contract/app/test_project_app.py

[refactor] 16-16: Too few public methods (1/2)

(R0903)

🪛 Ruff (0.11.9)
apiserver/plane/tests/conftest.py

4-4: rest_framework.status imported but unused

Remove unused import: rest_framework.status

(F401)


6-6: unittest.mock.patch imported but unused

Remove unused import

(F401)


6-6: unittest.mock.MagicMock imported but unused

Remove unused import

(F401)


7-7: django.urls.reverse imported but unused

Remove unused import: django.urls.reverse

(F401)

🔇 Additional comments (5)
apiserver/plane/tests/conftest.py (1)

125-142: Excellent workspace fixture implementation!

The fixture correctly follows the previous review feedback by creating the workspace directly using the model instead of the API. The implementation properly:

  • Creates a workspace with the authenticated user as owner
  • Establishes workspace membership with admin role (20)
  • Returns the workspace instance for use in tests

This provides a solid foundation for the comprehensive Project API tests.

apiserver/plane/tests/contract/app/test_project_app.py (4)

16-42: Well-designed URL helper method!

The get_project_url() method elegantly handles URL construction while avoiding the reverse() function issues with duplicate names. The method signature and logic clearly support all the different URL patterns needed for the tests.


45-252: Comprehensive POST operation test coverage!

The test suite excellently covers all critical POST scenarios:

  • Data validation (empty, missing fields, invalid data)
  • Success cases with proper side effects (project creation, member roles, default states)
  • Permission enforcement (guest forbidden, unauthenticated blocked)
  • Conflict handling (duplicate names/identifiers)
  • Edge cases (project lead assignment, optional fields)

The assertions verify both response codes and database state changes, ensuring complete validation of the API behavior.


254-402: Thorough GET operation test coverage!

The test suite comprehensively validates GET operations:

  • Authentication and authorization (admin vs guest vs unauthenticated)
  • Data filtering (guests only see projects they belong to)
  • Different endpoint variations (list, details, specific project)
  • Edge cases (non-existent projects, archived projects)

The tests properly verify both access control and data correctness.


405-618: Complete PATCH and DELETE operation test coverage!

The test suite thoroughly validates update and delete operations:

  • Permission enforcement (only admins can modify/delete)
  • Conflict detection (duplicate names/identifiers on updates)
  • Data validation (invalid update data)
  • Success scenarios with proper database state verification
  • Authentication requirements

The tests ensure proper access control and data integrity for destructive operations.

Removes imports that I added while working on the test suite for the Project API but were ultimately not used. Note that other unused imports still exist from the state of the codebase when this branch was created/forked.
@sriramveeraghanta sriramveeraghanta merged commit 6000639 into makeplane:preview Jul 2, 2025
2 of 3 checks passed
lifeiscontent pushed a commit that referenced this pull request Aug 18, 2025
* feat(tests): Add reusable workspace fixture

Introduces a new `workspace` fixture in `conftest.py` to provide a
consistent and reusable setup for tests that require a workspace.

* feat(tests): Add tests for project creation (POST)

This commit introduces a comprehensive test suite for the project creation API endpoint.

The suite covers a wide range of scenarios, including:
- Successful creation and verification of side-effects (default states, project members, user properties).
- Validation for invalid or missing data (400 Bad Request).
- Permission checks for different user roles (e.g., guests are forbidden).
- Authentication requirements (401 Unauthorized).
- Uniqueness constraints for project names and identifiers (409 Conflict).
- Successful creation with all optional fields populated.

It leverages the `workspace`, `session_client` and `create_user` fixtures for a consistent test setup.

* refactor(tests): Centralize project URL helper into a base class

To avoid code duplication in upcoming tests, this commit introduces a `TestProjectBase` class.

The `get_project_url` helper method is moved into this shared base class, and the existing `TestProjectAPIPost` class is updated to inherit from it. This ensures the URL generation logic is defined in a single place and preparing the suite for the upcoming GET tests.

* feat(tests): Add tests for project listing and retrieval (GET)

This commit adds a suite for the GET method. It leverages the previously created `TestProjectBase` class for URL generation.

The new test suite covers:
- Listing projects:
  - Verifies that administrators see all projects.
  - Confirms guests only see projects they are members of.
  - Tests the separate detailed project list endpoint.
- Retrieving a single project:
  - Checks for successful retrieval of a project by its ID.
  - Handles edge cases for non-existent and archived projects (404 Not Found).
- Authentication:
  - Ensures authentication is required (401 Unauthorized).

* feat(tests): Add tests for project update (PATCH) and deletion (DELETE)

Key scenarios tested for PATCH:
- Successful partial updates by project administrators.
- Forbidden access for non-admin members (403).
- Conflict errors for duplicate names or identifiers on update (409).
- Validation errors for invalid data (400).

Key scenarios tested for DELETE:
- Successful deletion by both project admins and workspace admins.
- Forbidden access for non-admin members (403).
- Authentication checks for unauthenticated users (401).

* Remove unnecessary print statement

* refactor(tests): Update workspace fixture to use ORM

Updates the `workspace` fixture to create the model instance directly via the ORM using the `Workspace` model instead of the API, as requested during code review.

* Refactor: Remove some unused imports

Removes imports that I added while working on the test suite for the Project API but were ultimately not used. Note that other unused imports still exist from the state of the codebase when this branch was created/forked.
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.

[feature]: [tests] Proposal to add test coverage for backend API endpoints

4 participants