Skip to content
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

test: CGS commit and detach negative tests #38173

Merged
merged 2 commits into from
Dec 16, 2024
Merged

Conversation

nidhi-nair
Copy link
Contributor

@nidhi-nair nidhi-nair commented Dec 16, 2024

Description

Tip

Add a TL;DR when the description is longer than 500 words or extremely technical (helps the content, marketing, and DevRel team).

Please also include relevant motivation and context. List any dependencies that are required for this change. Add links to Notion, Figma or any other documents that might be relevant to the PR.

Fixes #Issue Number
or
Fixes Issue URL

Warning

If no issue exists, please create an issue first, and check with the maintainers if the issue is valid.

Automation

/ok-to-test tags=""

🔍 Cypress test results

Warning

Tests have not run on the HEAD c7743a7 yet


Mon, 16 Dec 2024 07:21:41 UTC

Communication

Should the DevRel and Marketing teams inform users about this change?

  • Yes
  • No

Summary by CodeRabbit

  • New Features

    • Introduced unit tests for Git commit functionality, covering scenarios such as empty commit messages and invalid configurations.
    • Added unit tests for Git detach functionality, validating error handling and permission checks.
  • Tests

    • New test classes created to enhance testing coverage for Git operations.

@nidhi-nair nidhi-nair requested a review from a team as a code owner December 16, 2024 06:39
Copy link
Contributor

coderabbitai bot commented Dec 16, 2024

Walkthrough

This pull request introduces two new test classes in the Appsmith server's Git operations testing suite: GitCommitTests.java and GitDetachTests.java. These classes are designed to comprehensively test the CentralGitService class, focusing on Git commit and detach operations. The tests cover various scenarios including error handling, permission checks, and edge cases related to Git repository interactions.

Changes

File Change Summary
app/server/appsmith-server/src/test/java/.../GitCommitTests.java New test class for CentralGitService commit operations, covering scenarios like empty local changes, Git configuration validation, and repository availability.
app/server/appsmith-server/src/test/java/.../GitDetachTests.java New test class for CentralGitService detach operations, testing error handling and permission-related scenarios.

Possibly related PRs

Suggested labels

ok-to-test

Suggested reviewers

  • sondermanish

Poem

🌿 Git's dance of code and test,
Commits and detaches with zest,
Mocking the flow, catching each sway,
Ensuring no bug gets away!
🚀 Quality's guardian, standing tall!


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e0cd7d0 and c7743a7.

📒 Files selected for processing (1)
  • app/server/appsmith-server/src/test/java/com/appsmith/server/git/ops/GitCommitTests.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/server/appsmith-server/src/test/java/com/appsmith/server/git/ops/GitCommitTests.java

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.

@github-actions github-actions bot added skip-changelog Adding this label to a PR prevents it from being listed in the changelog Test labels Dec 16, 2024
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: 1

🧹 Nitpick comments (6)
app/server/appsmith-server/src/test/java/com/appsmith/server/git/ops/GitDetachTests.java (3)

61-86: Consider enhancing test robustness.

While the test logic is sound, consider these improvements:

  1. Add a more descriptive error message in the StepVerifier
  2. Add test cleanup to remove the created workspace and application
 StepVerifier.create(applicationMono)
         .expectErrorMatches(throwable -> throwable instanceof AppsmithException
-                & throwable.getMessage().contains("Git configuration is invalid"))
+                & throwable.getMessage().contains("Git configuration is invalid"),
+                "Should fail when Git data is empty")
         .verify();
+
+ // Clean up
+ workspaceService.archiveById(workspace.getId()).block();

88-101: Add explicit exception type verification.

The test verifies the error message but should also explicitly verify the exception type for better test coverage.

 StepVerifier.create(applicationMono)
+        .expectError(AppsmithException.class)
         .expectErrorMessage(
                 AppsmithError.ACL_NO_RESOURCE_FOUND.getMessage(FieldName.APPLICATION, application.getId()))
         .verify();

109-130: Consider using reactive chains instead of blocking operations.

While blocking operations are acceptable in tests, consider using reactive chains for consistency with the production code style.

-User apiUser = userService.findByEmail("api_user").block();
+return userService.findByEmail("api_user")
+        .flatMap(apiUser -> {
+            Workspace toCreate = new Workspace();
+            toCreate.setName("Workspace_" + UUID.randomUUID());
+            return workspaceService.create(toCreate, apiUser, Boolean.FALSE);
+        })
+        .flatMap(workspace -> {
+            Application testApplication = new Application();
+            testApplication.setWorkspaceId(workspace.getId());
+            testApplication.setName("Test App");
+            return applicationPageService.createApplication(testApplication);
+        })
+        .flatMap(application -> {
+            application.getPolicyMap().remove(permission.getValue());
+            return applicationRepository.save(application);
+        });
app/server/appsmith-server/src/test/java/com/appsmith/server/git/ops/GitCommitTests.java (3)

46-48: Add class-level documentation

Add Javadoc to describe the test class's purpose and the scenarios it covers.

 @SpringBootTest
 @TestInstance(TestInstance.Lifecycle.PER_CLASS)
+/**
+ * Tests for Git commit operations in CentralGitService, covering:
+ * - Empty commit scenarios
+ * - Invalid Git configuration
+ * - Repository not found cases
+ */
 public class GitCommitTests {

71-109: Extract test setup to improve readability

Consider extracting the workspace and application setup into a separate helper method since it's likely to be reused in other tests.

+    private Workspace createTestWorkspace(String prefix) {
+        User apiUser = userService.findByEmail("api_user").block();
+        Workspace toCreate = new Workspace();
+        toCreate.setName(prefix + "_" + UUID.randomUUID());
+        return workspaceService.create(toCreate, apiUser, Boolean.FALSE).block();
+    }

     @Test
     @WithUserDetails(value = "api_user")
     public void commitArtifact_whenNoChangesInLocal_returnsWithEmptyCommitMessage() {
         CommitDTO commitDTO = new CommitDTO();
         commitDTO.setMessage("empty commit");
 
-        User apiUser = userService.findByEmail("api_user").block();
-        Workspace toCreate = new Workspace();
-        toCreate.setName("Workspace_" + UUID.randomUUID());
-        Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block();
+        Workspace workspace = createTestWorkspace("Workspace");

198-203: Use more precise error validation

Instead of using expectErrorMatches, consider using expectErrorSatisfies for more precise error validation.

-        StepVerifier.create(commitMono)
-                .expectErrorMatches(throwable -> throwable instanceof AppsmithException
-                        && throwable
-                                .getMessage()
-                                .equals(AppsmithError.INVALID_GIT_CONFIGURATION.getMessage(GIT_CONFIG_ERROR)))
-                .verify();
+        StepVerifier.create(commitMono)
+                .expectErrorSatisfies(throwable -> {
+                    assertThat(throwable).isInstanceOf(AppsmithException.class);
+                    assertThat(throwable.getMessage())
+                            .isEqualTo(AppsmithError.INVALID_GIT_CONFIGURATION.getMessage(GIT_CONFIG_ERROR));
+                })
+                .verify();
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e2916b2 and e0cd7d0.

📒 Files selected for processing (2)
  • app/server/appsmith-server/src/test/java/com/appsmith/server/git/ops/GitCommitTests.java (1 hunks)
  • app/server/appsmith-server/src/test/java/com/appsmith/server/git/ops/GitDetachTests.java (1 hunks)
🔇 Additional comments (1)
app/server/appsmith-server/src/test/java/com/appsmith/server/git/ops/GitDetachTests.java (1)

1-60: Well-structured test class with proper dependency injection.

The class follows Spring Boot testing best practices with appropriate annotations and dependency injection setup.

Comment on lines +111 to +173
private Application createApplicationConnectedToGit(String name, String branchName, String workspaceId)
throws IOException {

if (StringUtils.isEmpty(branchName)) {
branchName = "foo";
}
Mockito.doReturn(Mono.just(branchName))
.when(fsGitHandler)
.cloneRemoteIntoArtifactRepo(any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
Mockito.doReturn(Mono.just("commit"))
.when(fsGitHandler)
.commitArtifact(
any(Path.class),
Mockito.anyString(),
Mockito.anyString(),
Mockito.anyString(),
Mockito.anyBoolean(),
Mockito.anyBoolean());
Mockito.doReturn(Mono.just(true)).when(fsGitHandler).checkoutToBranch(any(Path.class), Mockito.anyString());
Mockito.doReturn(Mono.just("success"))
.when(fsGitHandler)
.pushApplication(any(Path.class), any(), any(), any(), any());
Mockito.doReturn(Mono.just(true)).when(commonGitFileUtils).checkIfDirectoryIsEmpty(any(Path.class));
Mockito.doReturn(Mono.just(Paths.get("textPath")))
.when(commonGitFileUtils)
.initializeReadme(any(Path.class), Mockito.anyString(), Mockito.anyString());
Mockito.doReturn(Mono.just(Paths.get("path")))
.when(commonGitFileUtils)
.saveArtifactToLocalRepoWithAnalytics(any(Path.class), any(), Mockito.anyString());

Application testApplication = new Application();
testApplication.setName(name);
testApplication.setWorkspaceId(workspaceId);
Application application1 =
applicationPageService.createApplication(testApplication).block();

GitArtifactMetadata gitArtifactMetadata = new GitArtifactMetadata();
GitAuth gitAuth = new GitAuth();
gitAuth.setPublicKey("testkey");
gitAuth.setPrivateKey("privatekey");
gitArtifactMetadata.setGitAuth(gitAuth);
gitArtifactMetadata.setDefaultApplicationId(application1.getId());
gitArtifactMetadata.setRepoName("testRepo");
application1.setGitApplicationMetadata(gitArtifactMetadata);
application1 = applicationService.save(application1).block();

PageDTO page = new PageDTO();
page.setName("New Page");
page.setApplicationId(application1.getId());
applicationPageService.createPage(page).block();

GitProfile gitProfile = new GitProfile();
gitProfile.setAuthorEmail("[email protected]");
gitProfile.setAuthorName("testUser");
GitConnectDTO gitConnectDTO = new GitConnectDTO();
gitConnectDTO.setRemoteUrl("[email protected]:test/testRepo.git");
gitConnectDTO.setGitProfile(gitProfile);
return centralGitService
.connectArtifactToGit(
application1.getId(), gitConnectDTO, "baseUrl", ArtifactType.APPLICATION, GitType.FILE_SYSTEM)
.map(artifact -> (Application) artifact)
.block();
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Split helper method into smaller focused methods

The helper method is doing too much. Consider splitting it into:

  1. Application creation
  2. Git metadata setup
  3. Mock configuration
+    private void configureMocks(String branchName) {
+        Mockito.doReturn(Mono.just(branchName))
+                .when(fsGitHandler)
+                .cloneRemoteIntoArtifactRepo(any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
+        // ... other mock configurations
+    }
+
+    private Application setupGitMetadata(Application application) {
+        GitArtifactMetadata gitArtifactMetadata = new GitArtifactMetadata();
+        GitAuth gitAuth = new GitAuth();
+        gitAuth.setPublicKey("testkey");
+        gitAuth.setPrivateKey("privatekey");
+        // ... rest of the metadata setup
+        return applicationService.save(application).block();
+    }

Committable suggestion skipped: line range outside the PR's diff.

Copy link

Failed server tests

  • com.appsmith.server.git.ops.GitCommitTests#commitArtifact_whenLocalRepoNotAvailable_throwsRepoNotFoundException

@nidhi-nair nidhi-nair merged commit a3e9967 into release Dec 16, 2024
20 checks passed
@nidhi-nair nidhi-nair deleted the test/cgs-commit0detach branch December 16, 2024 18:37
@coderabbitai coderabbitai bot mentioned this pull request Dec 17, 2024
2 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
skip-changelog Adding this label to a PR prevents it from being listed in the changelog Test
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants