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: Git integration tests #38237

Open
wants to merge 3 commits into
base: release
Choose a base branch
from
Open

test: Git integration tests #38237

wants to merge 3 commits into from

Conversation

nidhi-nair
Copy link
Contributor

@nidhi-nair nidhi-nair commented Dec 18, 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 2e2d2d4 yet


Fri, 20 Dec 2024 09:42:44 UTC

Communication

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

  • Yes
  • No

Summary by CodeRabbit

  • New Features

    • Introduced a method to set the name of artifacts.
    • Enhanced error handling for branch deletion and merge operations.
    • Added integration tests for validating Git workflows, including artifact connection, repository state verification, and branch management.
    • Implemented utilities for managing artifact tests and Git server lifecycle.
  • Bug Fixes

    • Improved error management during branch operations.
  • Documentation

    • Added comments and formatting improvements for clarity.
  • Tests

    • Created new integration test suite and utility classes for Git-related functionalities.

Copy link
Contributor

coderabbitai bot commented Dec 18, 2024

Walkthrough

This pull request introduces a comprehensive set of changes to the Appsmith server's Git-related functionality, focusing on enhancing Git workflow testing and error handling. The modifications include adding new interfaces, utility classes, and test extensions to improve the robustness of Git operations, particularly around branch management, artifact connection, and repository interactions.

Changes

File Change Summary
ArtifactCE.java Added setName() method to artifact interface
CommonGitServiceCEImpl.java Improved error handling for branch deletion and merge operations
GitBranchesIT.java New integration test suite for Git workflow validation
GitContext.java New context class for Git-related test template management
GitBranchesTestTemplateProvider.java New Spring component for test template provider
ArtifactBuilderContext.java New interface for artifact management in tests
ArtifactBuilderExtension.java JUnit extension for artifact and workspace setup/teardown
GitArtifactTestUtils.java Utility class for creating test artifacts with diff
GitServerInitializerExtension.java JUnit extension for Git server environment management
GitTestUtils.java Utility class for creating diffs across artifact types

Suggested Labels

git-product, task, ok-to-test

Suggested Reviewers

Poem

🌿 Git branches dance and sway,
Code commits painting a new day,
Extensions weave their testing spell,
Artifacts singing their version's tale!
Refactoring magic unfurls with glee 🚀

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 18, 2024
@nidhi-nair nidhi-nair marked this pull request as ready for review December 20, 2024 15:27
@nidhi-nair nidhi-nair requested a review from a team as a code owner December 20, 2024 15:27
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: 8

🧹 Nitpick comments (14)
app/server/appsmith-server/src/test/it/com/appsmith/server/git/GitBranchesIT.java (2)

167-170: Consider consolidating or removing TODO comments.
The TODOs at lines 167-170 mention potentially restructuring file paths and possibly using controller layer calls. These are valid considerations, but keeping TODOs unaddressed may lead to technical debt. It might be prudent to create an actionable work item or issue, so the team can prioritize it accordingly.


210-227: Ensure auto-commit does not stall.
While waiting for auto-commit to complete, the loop uses Thread.sleep with a 2-second upper limit. If auto-commit unexpectedly takes longer (e.g., under heavy load), this may cause intermittent test failures. Consider either using a more robust polling mechanism with configurable timeouts or asynchronous callbacks to make tests more reliable.

app/server/appsmith-server/src/test/it/com/appsmith/server/git/templates/providers/ce/GitBranchesTestTemplateProviderCE.java (1)

21-30: Clarify single test context usage.
The code always provides a single test context in provideTestTemplateInvocationContexts. If you intend to run multiple contexts or data sets, consider returning multiple contexts in the stream or applying dynamic logic based on extensionContext.

app/server/appsmith-server/src/test/utils/com/appsmith/server/git/GitServerInitializerExtension.java (4)

42-44: Consider using constructor-based injection rather than field injection.
This approach is generally preferred in Spring for better testability and immutability.


66-67: Consider making repository names more dynamic.
"test" is hardcoded and could cause collisions or confusion if multiple tests run concurrently or if different tests require distinct repository names. A random or parameterized name might help.


69-69: Address TODO for key management.
The comment "Move this to artifact service to enable packages" indicates future plans. Ensure this TODO is tracked in an issue or task so it doesn't remain overlooked.

Would you like me to open a follow-up GitHub issue linking to this line?


82-94: Handle errors and timeouts in chained web requests.
When chaining Mono operations, implement robust error handling or timeouts to ensure that a failure in key attachment or repo creation does not break subsequent tests silently.

app/server/appsmith-server/src/test/utils/com/appsmith/server/git/GitArtifactTestUtils.java (3)

20-27: Consider removing unused generic type parameter

The class is parameterized with <T extends Artifact> but the type parameter is never used. The createADiff method uses the base Artifact type directly.

-public class GitArtifactTestUtils<T extends Artifact> {
+public class GitArtifactTestUtils {

35-39: Extract constants for magic strings and default values

Consider moving the hardcoded strings to constants for better maintainability.

+    private static final String REST_API_PLUGIN_NAME = "restapi-plugin";
+    private static final String DEFAULT_ACTION_NAME_PREFIX = "aGetAction_";

48-50: Consider adding error handling for action creation

The error handling for action creation could be more explicit.

-        return layoutActionService
-            .createSingleAction(action, Boolean.FALSE)
-            .then();
+        return layoutActionService
+            .createSingleAction(action, Boolean.FALSE)
+            .onErrorResume(error -> 
+                Mono.error(new RuntimeException("Failed to create test action", error)))
+            .then();
app/server/appsmith-server/src/test/utils/com/appsmith/server/git/ArtifactBuilderContext.java (2)

7-8: Add Javadoc to document the interface's purpose

Consider adding Javadoc to explain how this interface is used in the Git integration testing framework and its relationship with JUnit extensions.

+/**
+ * Context interface for building artifacts during Git integration tests.
+ * Extends JUnit's ExtensionContext to provide artifact-specific test configuration.
+ */
 public interface ArtifactBuilderContext extends ExtensionContext {

15-22: Consider adding validation and documentation for ID fields

The workspace and artifact ID setters should include validation to prevent null or invalid values. Also, consider documenting any format requirements or constraints.

+    /**
+     * @return the workspace ID associated with this artifact
+     */
     String getWorkspaceId();

+    /**
+     * @param workspaceId must not be null or empty
+     * @throws IllegalArgumentException if workspaceId is null or empty
+     */
     void setWorkspaceId(String workspaceId);

+    /**
+     * @return the unique identifier of this artifact
+     */
     String getArtifactId();

+    /**
+     * @param artifactId must not be null or empty
+     * @throws IllegalArgumentException if artifactId is null or empty
+     */
     void setArtifactId(String artifactId);
app/server/appsmith-server/src/test/utils/com/appsmith/server/git/ArtifactBuilderExtension.java (2)

63-86: Improve test setup reliability and debugging

The setup code has several areas for improvement:

  1. Consider moving assertions to separate verification methods
  2. Add timeout to blocking operations to prevent test hangs
 @Override
 public void beforeEach(ExtensionContext extensionContext) throws Exception {
+    Duration timeout = Duration.ofSeconds(30);
     ExtensionContext.Store parentContextStore = extensionContext.getParent().get().getStore(ExtensionContext.Namespace.create(ArtifactBuilderExtension.class));
     Class<? extends ArtifactExchangeJson> aClass = parentContextStore.get(ArtifactExchangeJson.class, Class.class);
     String filePath = parentContextStore.get("filePath", String.class);
     ExtensionContext.Store contextStore = extensionContext.getStore(ExtensionContext.Namespace.create(ArtifactBuilderExtension.class));

-    ArtifactExchangeJson artifactExchangeJson = createArtifactJson(filePath, aClass).block();
+    ArtifactExchangeJson artifactExchangeJson = createArtifactJson(filePath, aClass).block(timeout);
     assertThat(artifactExchangeJson).isNotNull();

     artifactExchangeJson.getArtifact().setName(aClass.getSimpleName() + "_" + UUID.randomUUID());

-    User apiUser = userService.findByEmail("api_user").block();
+    User apiUser = userService.findByEmail("api_user").block(timeout);

106-116: Improve error handling and document mapper configuration

The JSON file handling needs better error messages and documentation about the mapper configuration.

+    /**
+     * Creates an ArtifactExchangeJson from a JSON file.
+     * MapperFeature.USE_ANNOTATIONS is disabled to allow flexible deserialization
+     * of test data that might not match production schema exactly.
+     */
     private Mono<? extends ArtifactExchangeJson> createArtifactJson(String filePath, Class<? extends ArtifactExchangeJson> exchangeJsonType) throws IOException {
+        if (!filePath.endsWith(".json")) {
+            return Mono.error(new IllegalArgumentException("File must be a JSON file: " + filePath));
+        }
         ClassPathResource classPathResource = new ClassPathResource(filePath);
+        if (!classPathResource.exists()) {
+            return Mono.error(new IOException("File not found: " + filePath));
+        }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 836b544 and 2e2d2d4.

📒 Files selected for processing (11)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/ArtifactCE.java (1 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/common/CommonGitServiceCEImpl.java (1 hunks)
  • app/server/appsmith-server/src/test/it/com/appsmith/server/git/GitBranchesIT.java (1 hunks)
  • app/server/appsmith-server/src/test/it/com/appsmith/server/git/templates/contexts/GitContext.java (1 hunks)
  • app/server/appsmith-server/src/test/it/com/appsmith/server/git/templates/providers/GitBranchesTestTemplateProvider.java (1 hunks)
  • app/server/appsmith-server/src/test/it/com/appsmith/server/git/templates/providers/ce/GitBranchesTestTemplateProviderCE.java (1 hunks)
  • app/server/appsmith-server/src/test/utils/com/appsmith/server/git/ArtifactBuilderContext.java (1 hunks)
  • app/server/appsmith-server/src/test/utils/com/appsmith/server/git/ArtifactBuilderExtension.java (1 hunks)
  • app/server/appsmith-server/src/test/utils/com/appsmith/server/git/GitArtifactTestUtils.java (1 hunks)
  • app/server/appsmith-server/src/test/utils/com/appsmith/server/git/GitServerInitializerExtension.java (1 hunks)
  • app/server/appsmith-server/src/test/utils/com/appsmith/server/git/GitTestUtils.java (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • app/server/appsmith-server/src/test/it/com/appsmith/server/git/templates/providers/GitBranchesTestTemplateProvider.java
🔇 Additional comments (10)
app/server/appsmith-server/src/test/it/com/appsmith/server/git/GitBranchesIT.java (2)

425-434: Validate branch checkout before deletion.
You manually switch branches (line 435) to avoid deleting the currently checked-out branch. Consider handling this condition more gracefully in the service code itself, or providing clear error messaging by verifying (and if needed, auto-checking out) a safe branch first.


528-532: Address TODO for leftover uncommitted changes after branch creation.
The comment implies that changes remain on the source branch after creation. This may indicate a flow issue or mismatch between local and remote synchronization. Investigating and resolving it will make the test suite more reliable and transparent.

app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/ArtifactCE.java (1)

16-17: Good addition of the setter method.
Providing a setter for the artifact name is helpful for dynamic naming in advanced scenarios. No immediate issues are detected here.

app/server/appsmith-server/src/main/java/com/appsmith/server/git/common/CommonGitServiceCEImpl.java (1)

2190-2200: Improved error handling with proper lock release!

Good improvement to release file locks before throwing exceptions, preventing potential lock leaks. The error messages are clear and descriptive.

app/server/appsmith-server/src/test/utils/com/appsmith/server/git/GitServerInitializerExtension.java (2)

48-52: Ensure test container isolation for parallel test scenarios.
Since gitContainer is defined as a static field, multiple test classes running in parallel might conflict if they share the same container. Evaluate if a per-instance container is more appropriate or if parallel test runs are coordinated.


100-106: Ensure directory cleanup is safe for multiple test runs.
Consider whether parallel test runs or concurrent teardown calls may cause concurrency issues when deleting the directory. You might also want to log any failures if the directory does not exist.

app/server/appsmith-server/src/test/utils/com/appsmith/server/git/GitArtifactTestUtils.java (1)

1-19: LGTM - Clean imports structure

All imports are properly organized and utilized.

app/server/appsmith-server/src/test/utils/com/appsmith/server/git/ArtifactBuilderContext.java (2)

1-6: LGTM! Clean and well-organized imports

Package structure and imports are appropriate for a test utility interface.


9-13: Document methods and verify implementation requirements

The artifact type and JSON-related methods would benefit from documentation explaining their purpose and requirements.

app/server/appsmith-server/src/test/it/com/appsmith/server/git/templates/contexts/GitContext.java (1)

15-21: LGTM! Well-structured test context class.

The class properly implements JUnit 5 interfaces and uses appropriate field modifiers.

Comment on lines +493 to +495
// There is an on page load that gets triggered here that is causing a diff
// This should ideally have already been fixed on initial artifact import
// assertThat(discardedStatus.getIsClean()).isTrue();
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

Revisit the "on page load" causing diffs.
The TODO indicates unexpected diffs appear after discarding changes, which may be linked to application triggers. If left unresolved, it could lead to misleading or frequent test failures. A deeper investigation would help ensure stable test runs.

Comment on lines +1 to +27
package com.appsmith.server.git;

import com.appsmith.server.constants.ArtifactType;
import com.appsmith.server.domains.Application;
import com.appsmith.server.domains.Artifact;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

@RequiredArgsConstructor
@Component
public class GitTestUtils {

private final GitArtifactTestUtils<Application> gitApplicationTestUtils;

private GitArtifactTestUtils<?> getArtifactSpecificUtils(ArtifactType artifactType) {
// TODO For now just work with apps
return gitApplicationTestUtils;
}


public Mono<Void> createADiffInArtifact(Artifact artifact) {
GitArtifactTestUtils<?> artifactSpecificUtils = getArtifactSpecificUtils(artifact.getArtifactType());

return artifactSpecificUtils.createADiff(artifact);
}
}
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

Streamline artifact-specific utilities.
Currently, the method getArtifactSpecificUtils always returns gitApplicationTestUtils. If you plan to support other artifact types, consider implementing a switch or strategy pattern for different artifact utilities. This will reduce future refactors when non-Application artifacts are handled.

Comment on lines +75 to +81
// Attach public key on TED git server
Mono<ResponseEntity<Void>> createRepoMono = WebClient.create(tedGitApiPath + "repos")
.post()
.bodyValue(Map.of("name", repoName, "private", false))
.retrieve()
.toBodilessEntity();

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 when creating the repository.
If the repository creation fails for any reason, the code may continue to attach SSH keys and potentially mask underlying problems. Consider adding error handling or a fallback strategy here.


Mono<Void> createADiff(Artifact artifact) {

Application application = (Application) artifact;
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

Add type safety check before casting

The unchecked cast could lead to runtime errors if a non-Application artifact is passed.

-        Application application = (Application) artifact;
+        if (!(artifact instanceof Application)) {
+            return Mono.error(new IllegalArgumentException("Artifact must be an Application"));
+        }
+        Application application = (Application) artifact;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Application application = (Application) artifact;
if (!(artifact instanceof Application)) {
return Mono.error(new IllegalArgumentException("Artifact must be an Application"));
}
Application application = (Application) artifact;

Comment on lines +32 to +33
String pageId = application.getPages().get(0).getId();
Plugin plugin = pluginService.findByPackageName("restapi-plugin").block();
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

Add null checks and avoid blocking calls

The code assumes the application has pages and uses a blocking call to find the plugin.

-        String pageId = application.getPages().get(0).getId();
-        Plugin plugin = pluginService.findByPackageName("restapi-plugin").block();
+        if (application.getPages() == null || application.getPages().isEmpty()) {
+            return Mono.error(new IllegalStateException("Application must have at least one page"));
+        }
+        String pageId = application.getPages().get(0).getId();
+        return pluginService.findByPackageName("restapi-plugin")
+            .switchIfEmpty(Mono.error(new IllegalStateException("REST API plugin not found")))
+            .flatMap(plugin -> {

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

Comment on lines +22 to +30
public GitContext(
ExtensionContext extensionContext, String fileName, Class<? extends ArtifactExchangeJson> artifactExchangeJsonType, ArtifactType artifactType) {
this.artifactType = artifactType;
ExtensionContext.Store contextStore = extensionContext.getStore(ExtensionContext.Namespace.create(ArtifactBuilderExtension.class));
contextStore.put(ArtifactExchangeJson.class, artifactExchangeJsonType);
contextStore.put("filePath", fileName);
this.fileName = fileName;
this.artifactExchangeJsonType = artifactExchangeJsonType;
}
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 parameter validation in constructor

Consider adding null checks and fileName validation to prevent issues during test execution.

 public GitContext(
     ExtensionContext extensionContext, String fileName, Class<? extends ArtifactExchangeJson> artifactExchangeJsonType, ArtifactType artifactType) {
+    if (extensionContext == null || fileName == null || artifactExchangeJsonType == null || artifactType == null) {
+        throw new IllegalArgumentException("All parameters must be non-null");
+    }
+    if (fileName.trim().isEmpty()) {
+        throw new IllegalArgumentException("fileName must not be empty");
+    }
     this.artifactType = artifactType;
     ExtensionContext.Store contextStore = extensionContext.getStore(ExtensionContext.Namespace.create(ArtifactBuilderExtension.class));
     contextStore.put(ArtifactExchangeJson.class, artifactExchangeJsonType);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public GitContext(
ExtensionContext extensionContext, String fileName, Class<? extends ArtifactExchangeJson> artifactExchangeJsonType, ArtifactType artifactType) {
this.artifactType = artifactType;
ExtensionContext.Store contextStore = extensionContext.getStore(ExtensionContext.Namespace.create(ArtifactBuilderExtension.class));
contextStore.put(ArtifactExchangeJson.class, artifactExchangeJsonType);
contextStore.put("filePath", fileName);
this.fileName = fileName;
this.artifactExchangeJsonType = artifactExchangeJsonType;
}
public GitContext(
ExtensionContext extensionContext, String fileName, Class<? extends ArtifactExchangeJson> artifactExchangeJsonType, ArtifactType artifactType) {
if (extensionContext == null || fileName == null || artifactExchangeJsonType == null || artifactType == null) {
throw new IllegalArgumentException("All parameters must be non-null");
}
if (fileName.trim().isEmpty()) {
throw new IllegalArgumentException("fileName must not be empty");
}
this.artifactType = artifactType;
ExtensionContext.Store contextStore = extensionContext.getStore(ExtensionContext.Namespace.create(ArtifactBuilderExtension.class));
contextStore.put(ArtifactExchangeJson.class, artifactExchangeJsonType);
contextStore.put("filePath", fileName);
this.fileName = fileName;
this.artifactExchangeJsonType = artifactExchangeJsonType;
}

Comment on lines +50 to +64
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
return true;
}

@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
if (parameterContext.getParameter().getType().equals(ExtensionContext.class)) {
return extensionContext;
}

return this;
}
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

Restrict parameter resolution to supported types

The current implementation of supportsParameter is too permissive. It should only return true for types that can actually be resolved.

 @Override
 public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
     throws ParameterResolutionException {
-    return true;
+    Class<?> type = parameterContext.getParameter().getType();
+    return type.equals(ExtensionContext.class) || type.equals(GitContext.class);
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
return true;
}
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
if (parameterContext.getParameter().getType().equals(ExtensionContext.class)) {
return extensionContext;
}
return this;
}
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
Class<?> type = parameterContext.getParameter().getType();
return type.equals(ExtensionContext.class) || type.equals(GitContext.class);
}
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
if (parameterContext.getParameter().getType().equals(ExtensionContext.class)) {
return extensionContext;
}
return this;
}

Comment on lines +89 to +104
@Override
public void afterEach(ExtensionContext extensionContext) {

ExtensionContext.Store contextStore = extensionContext.getStore(ExtensionContext.Namespace.create(ArtifactBuilderExtension.class));
String workspaceId = contextStore.get(FieldName.WORKSPACE_ID, String.class);

// Because right now we only have checks for apps
// Move this to artifact based model when we fix that
applicationService
.findByWorkspaceId(workspaceId, applicationPermission.getDeletePermission())
.flatMap(remainingApplication -> applicationPageService.deleteApplication(remainingApplication.getId()))
.collectList()
.block();
workspaceService.archiveById(workspaceId).block();

}
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

Add error handling and timeouts to cleanup

The cleanup code should handle errors gracefully to ensure test resources are properly released.

 @Override
 public void afterEach(ExtensionContext extensionContext) {
+    Duration timeout = Duration.ofSeconds(30);
     ExtensionContext.Store contextStore = extensionContext.getStore(ExtensionContext.Namespace.create(ArtifactBuilderExtension.class));
     String workspaceId = contextStore.get(FieldName.WORKSPACE_ID, String.class);

-    // Because right now we only have checks for apps
-    // Move this to artifact based model when we fix that
-    applicationService
-        .findByWorkspaceId(workspaceId, applicationPermission.getDeletePermission())
-        .flatMap(remainingApplication -> applicationPageService.deleteApplication(remainingApplication.getId()))
-        .collectList()
-        .block();
-    workspaceService.archiveById(workspaceId).block();
+    try {
+        applicationService
+            .findByWorkspaceId(workspaceId, applicationPermission.getDeletePermission())
+            .flatMap(remainingApplication -> applicationPageService.deleteApplication(remainingApplication.getId()))
+            .collectList()
+            .block(timeout);
+        workspaceService.archiveById(workspaceId).block(timeout);
+    } catch (Exception e) {
+        // Log the error but don't fail the test
+        System.err.println("Error during test cleanup: " + e.getMessage());
+    }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@Override
public void afterEach(ExtensionContext extensionContext) {
ExtensionContext.Store contextStore = extensionContext.getStore(ExtensionContext.Namespace.create(ArtifactBuilderExtension.class));
String workspaceId = contextStore.get(FieldName.WORKSPACE_ID, String.class);
// Because right now we only have checks for apps
// Move this to artifact based model when we fix that
applicationService
.findByWorkspaceId(workspaceId, applicationPermission.getDeletePermission())
.flatMap(remainingApplication -> applicationPageService.deleteApplication(remainingApplication.getId()))
.collectList()
.block();
workspaceService.archiveById(workspaceId).block();
}
@Override
public void afterEach(ExtensionContext extensionContext) {
Duration timeout = Duration.ofSeconds(30);
ExtensionContext.Store contextStore = extensionContext.getStore(ExtensionContext.Namespace.create(ArtifactBuilderExtension.class));
String workspaceId = contextStore.get(FieldName.WORKSPACE_ID, String.class);
try {
applicationService
.findByWorkspaceId(workspaceId, applicationPermission.getDeletePermission())
.flatMap(remainingApplication -> applicationPageService.deleteApplication(remainingApplication.getId()))
.collectList()
.block(timeout);
workspaceService.archiveById(workspaceId).block(timeout);
} catch (Exception e) {
// Log the error but don't fail the test
System.err.println("Error during test cleanup: " + e.getMessage());
}
}

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.

1 participant