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 discard tests #38206

Merged
merged 1 commit into from
Dec 18, 2024
Merged

test: CGS discard tests #38206

merged 1 commit into from
Dec 18, 2024

Conversation

nidhi-nair
Copy link
Contributor

@nidhi-nair nidhi-nair commented Dec 17, 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

Caution

If you modify the content in this section, you are likely to disrupt the CI result for your PR.

Communication

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

  • Yes
  • No

Summary by CodeRabbit

  • Tests
    • Introduced a new test suite for the Git discard functionality, covering various scenarios to ensure application integrity during Git operations.

@nidhi-nair nidhi-nair requested a review from a team as a code owner December 17, 2024 09:19
Copy link
Contributor

coderabbitai bot commented Dec 17, 2024

Walkthrough

The pull request introduces a new test class GitDiscardTests.java in the Appsmith server project, focusing on unit testing the Git discard functionality. The test suite validates the behavior of the CentralGitService when discarding changes in Git-connected applications. It covers two primary scenarios: successful discard with upstream changes and handling of mid-operation cancellations, utilizing Mockito for mocking and Spring's testing framework for comprehensive test coverage.

Changes

File Change Summary
app/server/appsmith-server/src/test/java/com/appsmith/server/git/ops/GitDiscardTests.java New test class added to validate Git discard functionality with two test methods covering different discard scenarios

Sequence Diagram

sequenceDiagram
    participant Developer
    participant GitDiscardTests
    participant CentralGitService
    participant ApplicationService

    Developer->>GitDiscardTests: Trigger Discard Test
    GitDiscardTests->>CentralGitService: Invoke Discard Changes
    CentralGitService->>ApplicationService: Update Application State
    CentralGitService-->>GitDiscardTests: Return Discard Result
    GitDiscardTests->>GitDiscardTests: Verify Discard Outcome
Loading

Possibly related PRs

Suggested labels

skip-changelog, Test

Suggested reviewers

  • sondermanish

Poem

🌿 Git's wild dance of change and test,
Discard and verify with zest!
Mockito's magic, Spring's embrace,
Code flows with algorithmic grace 🚀
Refactoring's rhythmic quest!

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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 17, 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: 2

🧹 Nitpick comments (2)
app/server/appsmith-server/src/test/java/com/appsmith/server/git/ops/GitDiscardTests.java (2)

91-157: Consider adding parameter validation and error handling.

The utility method could benefit from:

  1. Validating the workspaceId parameter
  2. Adding error handling for the application creation block() operation
 private Application createApplicationConnectedToGit(String name, String branchName, String workspaceId)
         throws IOException {
+    if (StringUtils.isEmpty(workspaceId)) {
+        throw new IllegalArgumentException("workspaceId cannot be empty");
+    }
     // ... rest of the method
     Application application1 =
-            applicationPageService.createApplication(testApplication).block();
+            applicationPageService.createApplication(testApplication)
+                    .onErrorMap(error -> new RuntimeException("Failed to create application: " + error.getMessage()))
+                    .block();

173-216: Enhance test assertions for better coverage.

The assertion only checks if pages are not equal. Consider adding more specific assertions:

  1. Verify the exact number of pages
  2. Verify the page content
  3. Verify the Git status after discard
 StepVerifier.create(applicationMono)
         .assertNext(application1 -> {
-            assertThat(application1.getPages()).isNotEqualTo(application.getPages());
+            assertThat(application1.getPages()).isNotNull();
+            assertThat(application1.getPages()).hasSize(1);
+            assertThat(application1.getGitApplicationMetadata().getIsRepoPrivate()).isTrue();
         })
         .verifyComplete();
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 979acc9 and eb313bd.

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

54-90: LGTM! Test class setup follows best practices.

The test class is properly configured with Spring Boot test annotations and appropriate dependency injection setup.

Comment on lines +159 to +171
private Mono<? extends ArtifactExchangeJson> createArtifactJson(String filePath) throws IOException {

ClassPathResource classPathResource = new ClassPathResource(filePath);

String artifactJson = classPathResource.getContentAsString(Charset.defaultCharset());

Class<? extends ArtifactExchangeJson> exchangeJsonType = ApplicationJson.class;

ArtifactExchangeJson artifactExchangeJson =
objectMapper.copy().disable(MapperFeature.USE_ANNOTATIONS).readValue(artifactJson, exchangeJsonType);

return jsonSchemaMigration.migrateArtifactExchangeJsonToLatestSchema(artifactExchangeJson, null, null);
}
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

Add error handling for file not found scenario.

The method should handle the case where the specified file is not found in the classpath.

 private Mono<? extends ArtifactExchangeJson> createArtifactJson(String filePath) throws IOException {
+    if (StringUtils.isEmpty(filePath)) {
+        return Mono.error(new IllegalArgumentException("filePath cannot be empty"));
+    }
     ClassPathResource classPathResource = new ClassPathResource(filePath);
+    if (!classPathResource.exists()) {
+        return Mono.error(new IOException("File not found: " + filePath));
+    }
     // ... rest of the method

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

Comment on lines +218 to +292
@Test
@WithUserDetails(value = "api_user")
public void discardChanges_whenCancelledMidway_discardsSuccessfully() throws IOException, GitAPIException {
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();
assertThat(workspace).isNotNull();

Application application = createApplicationConnectedToGit(
"discard-changes-midway", "discard-change-midway-branch", workspace.getId());
MergeStatusDTO mergeStatusDTO = new MergeStatusDTO();
mergeStatusDTO.setStatus("Nothing to fetch from remote. All changes are upto date.");
mergeStatusDTO.setMergeAble(true);

ArtifactExchangeJson artifactExchangeJson = createArtifactJson(
"test_assets/ImportExportServiceTest/valid-application-without-action-collection.json")
.block();
((Application) artifactExchangeJson.getArtifact()).setName("discard-changes-midway");

GitStatusDTO gitStatusDTO = new GitStatusDTO();
gitStatusDTO.setAheadCount(0);
gitStatusDTO.setBehindCount(0);
gitStatusDTO.setIsClean(true);

Mockito.doReturn(Mono.just(Paths.get("path")))
.when(commonGitFileUtils)
.saveArtifactToLocalRepoWithAnalytics(any(Path.class), any(), Mockito.anyString());
Mockito.doReturn(Mono.just(artifactExchangeJson))
.when(gitHandlingService)
.recreateArtifactJsonFromLastCommit(Mockito.any());
Mockito.doReturn(Mono.just(mergeStatusDTO))
.when(fsGitHandler)
.pullApplication(
any(Path.class),
Mockito.anyString(),
Mockito.anyString(),
Mockito.anyString(),
Mockito.anyString());
Mockito.doReturn(Mono.just(gitStatusDTO)).when(fsGitHandler).getStatus(any(Path.class), Mockito.anyString());
Mockito.doReturn(Mono.just("fetched"))
.when(fsGitHandler)
.fetchRemote(
any(Path.class),
Mockito.anyString(),
Mockito.anyString(),
eq(true),
Mockito.anyString(),
Mockito.anyBoolean());

centralGitService
.discardChanges(application.getId(), ArtifactType.APPLICATION, GitType.FILE_SYSTEM)
.map(artifact -> (Application) artifact)
.timeout(Duration.ofNanos(100))
.subscribe();

// Wait for git clone to complete
Mono<Application> applicationFromDbMono = Mono.just(application).flatMap(application1 -> {
try {
// Before fetching the git connected application, sleep for 5 seconds to ensure that the clone
// completes
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return applicationService.getById(application1.getId());
});

StepVerifier.create(applicationFromDbMono)
.assertNext(application1 -> {
assertThat(application1).isNotEqualTo(application);
})
.verifyComplete();
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Replace Thread.sleep with proper test synchronization.

Using Thread.sleep for test synchronization is unreliable and can lead to flaky tests. Consider:

  1. Using TestPublisher for controlled emission
  2. Using StepVerifier's virtual time capabilities
- Thread.sleep(5000);
+ return applicationService.getById(application1.getId())
+         .retryWhen(Retry.fixedDelay(3, Duration.ofSeconds(1))
+                 .filter(error -> error instanceof IllegalStateException));

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


StepVerifier.create(applicationFromDbMono)
.assertNext(application1 -> {
assertThat(application1).isNotEqualTo(application);
Copy link
Contributor

@sondermanish sondermanish Dec 17, 2024

Choose a reason for hiding this comment

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

how is this equality check working?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Just that it is not the same object. We're only checking for completion here

@nidhi-nair nidhi-nair merged commit 774c8ca into release Dec 18, 2024
17 checks passed
@nidhi-nair nidhi-nair deleted the test/cgs-discard branch December 18, 2024 09:04
NandanAnantharamu pushed a commit that referenced this pull request Dec 27, 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
<!-- This is an auto-generated comment: Cypress test results  -->
> [!CAUTION]  
> If you modify the content in this section, you are likely to disrupt
the CI result for your PR.

<!-- end of auto-generated comment: Cypress test results  -->


## Communication
Should the DevRel and Marketing teams inform users about this change?
- [ ] Yes
- [ ] No


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

## Summary by CodeRabbit

- **Tests**
- Introduced a new test suite for the Git discard functionality,
covering various scenarios to ensure application integrity during Git
operations.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
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