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

Development: Add check for public methods in controllers that are not endpoints #9729

Draft
wants to merge 2 commits into
base: develop
Choose a base branch
from

Conversation

MaximilianAnzinger
Copy link
Contributor

@MaximilianAnzinger MaximilianAnzinger commented Nov 10, 2024

Checklist

General

Motivation and Context

To maintain good code quality REST controllers should not provide any functionality for the service layer or other controllers. Thus all public methods should be endpoints. Thus developers are not tempted to call methods of the web layer from any other layer.

Description

Adds architecture test to ensure REST controllers only contain public methods that are endpoints

Review Progress

Performance Review

  • I (as a reviewer) confirm that the client changes (in particular related to REST calls and UI responsiveness) are implemented with a very good performance even for very large courses with more than 2000 students.
  • I (as a reviewer) confirm that the server changes (in particular related to database calls) are implemented with a very good performance even for very large courses with more than 2000 students.

Code Review

  • Code Review 1
  • Code Review 2

Summary by CodeRabbit

  • New Features

    • Introduced a new test method to ensure public methods in REST controllers are properly annotated as endpoints.
    • Added a method to identify endpoint methods within the module architecture.
  • Bug Fixes

    • Updated existing tests for improved accuracy in checking request mapping annotations.
  • Refactor

    • Changed visibility of a method to indicate internal usage only.

@MaximilianAnzinger MaximilianAnzinger marked this pull request as ready for review November 11, 2024 22:08
@MaximilianAnzinger MaximilianAnzinger requested a review from a team as a code owner November 11, 2024 22:08
@MaximilianAnzinger MaximilianAnzinger marked this pull request as draft November 11, 2024 22:09
Copy link

coderabbitai bot commented Nov 11, 2024

Walkthrough

The changes in this pull request enhance the testing capabilities for REST controller conventions within the AbstractModuleResourceArchitectureTest and ModuleArchitectureTest classes. A new test method is added to check that public methods in RestController classes are properly annotated as endpoints. Additionally, modifications include updating a method's visibility and introducing a new method to identify endpoint methods specifically. These changes collectively strengthen the architectural rules governing REST controllers.

Changes

File Change Summary
src/test/java/de/tum/cit/aet/artemis/shared/architecture/module/AbstractModuleResourceArchitectureTest.java - Added method void shouldHaveNoPublicMethodsExceptForEndpoints().
- Changed visibility of protected ArchCondition<JavaMethod> useKebabCaseForRestAnnotations(Class<?> annotationClass) to private.
- Introduced private method beAnnotatedWithRequestMapping.
src/test/java/de/tum/cit/aet/artemis/shared/architecture/module/ModuleArchitectureTest.java - Added method default GivenMethodsConjunction endpointsOfThisModule().
- Included import for RestController.

Possibly related PRs

Suggested labels

ready for review, core, programming

Suggested reviewers

  • JohannesStoehr
  • SimonEntholzer
  • krusche

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.

🔧 pmd
src/test/java/de/tum/cit/aet/artemis/shared/architecture/module/AbstractModuleResourceArchitectureTest.java

The following rules are missing or misspelled in your ruleset file category/vm/bestpractices.xml: BooleanInstantiation, DontImportJavaLang, DuplicateImports, EmptyFinallyBlock, EmptyIfStmt, EmptyInitializer, EmptyStatementBlock, EmptyStatementNotInLoop, EmptySwitchStatements, EmptySynchronizedBlock, EmptyTryBlock, EmptyWhileStmt, ExcessiveClassLength, ExcessiveMethodLength, ImportFromSamePackage, MissingBreakInSwitch, SimplifyBooleanAssertion. Please check your ruleset configuration.

src/test/java/de/tum/cit/aet/artemis/shared/architecture/module/ModuleArchitectureTest.java

The following rules are missing or misspelled in your ruleset file category/vm/bestpractices.xml: BooleanInstantiation, DontImportJavaLang, DuplicateImports, EmptyFinallyBlock, EmptyIfStmt, EmptyInitializer, EmptyStatementBlock, EmptyStatementNotInLoop, EmptySwitchStatements, EmptySynchronizedBlock, EmptyTryBlock, EmptyWhileStmt, ExcessiveClassLength, ExcessiveMethodLength, ImportFromSamePackage, MissingBreakInSwitch, SimplifyBooleanAssertion. Please check your ruleset configuration.


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 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 or @coderabbitai title 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.

Copy link

@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

🧹 Outside diff range and nitpick comments (3)
src/test/java/de/tum/cit/aet/artemis/shared/architecture/module/ModuleArchitectureTest.java (2)

55-58: LGTM! Consider adding Javadoc.

The implementation correctly identifies endpoints and aligns with the PR objective. Consider adding Javadoc to document:

  • The purpose of this method
  • What constitutes an endpoint
  • The return value and its usage

Example Javadoc:

/**
 * Returns a rule conjunction that matches all public endpoint methods in REST controllers within this module.
 * An endpoint is a public method in a class annotated with @RestController.
 *
 * @return ArchUnit rule conjunction for matching endpoint methods
 */

55-58: Consider a more flexible implementation for future extensibility.

The current implementation only checks for @RestController. Consider making it more flexible to handle different types of controllers or endpoint annotations.

Example enhancement:

-    default GivenMethodsConjunction endpointsOfThisModule() {
+    default GivenMethodsConjunction endpointsOfThisModule(Class<?>... controllerAnnotations) {
+        var conjunction = methodsOfThisModuleThat();
+        for (Class<?> annotation : controllerAnnotations.length > 0 ? controllerAnnotations 
+            : new Class<?>[]{ RestController.class }) {
+            conjunction = conjunction.areDeclaredInClassesThat().areAnnotatedWith(annotation).or();
+        }
+        return conjunction.and().arePublic();
     }
src/test/java/de/tum/cit/aet/artemis/shared/architecture/module/AbstractModuleResourceArchitectureTest.java (1)

90-103: Enhance error message for better debugging

The implementation correctly checks for request mapping annotations, but the error message could be more descriptive to help developers quickly identify and fix issues.

Consider enhancing the error message:

-                events.add(violated(item, createMessage(item, "Method should be annotated with @RequestMapping")));
+                events.add(violated(item, createMessage(item, 
+                    String.format("Public method '%s' in REST controller should be annotated with one of: %s", 
+                    item.getName(), 
+                    annotationClasses.stream()
+                        .map(Class::getSimpleName)
+                        .collect(joining(", "))))));
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between de36813 and 62d1255.

📒 Files selected for processing (2)
  • src/test/java/de/tum/cit/aet/artemis/shared/architecture/module/AbstractModuleResourceArchitectureTest.java (1 hunks)
  • src/test/java/de/tum/cit/aet/artemis/shared/architecture/module/ModuleArchitectureTest.java (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
src/test/java/de/tum/cit/aet/artemis/shared/architecture/module/AbstractModuleResourceArchitectureTest.java (1)

Pattern src/test/java/**/*.java: test_naming: descriptive; test_size: small_specific; fixed_data: true; junit5_features: true; assert_use: assertThat; assert_specificity: true; archunit_use: enforce_package_rules; db_query_count_tests: track_performance; util_service_factory_pattern: true; avoid_db_access: true; mock_strategy: static_mocks; context_restart_minimize: true

src/test/java/de/tum/cit/aet/artemis/shared/architecture/module/ModuleArchitectureTest.java (1)

Pattern src/test/java/**/*.java: test_naming: descriptive; test_size: small_specific; fixed_data: true; junit5_features: true; assert_use: assertThat; assert_specificity: true; archunit_use: enforce_package_rules; db_query_count_tests: track_performance; util_service_factory_pattern: true; avoid_db_access: true; mock_strategy: static_mocks; context_restart_minimize: true

🪛 GitHub Check: Java Architecture Tests
src/test/java/de/tum/cit/aet/artemis/shared/architecture/module/AbstractModuleResourceArchitectureTest.java

[failure] 87-87: de.tum.cit.aet.artemis.buildagent.architecture.BuildAgentResourceArchitectureTest ► shouldHaveNoPublicMethodsExceptForEndpoints()
Failed test found in:
build/test-results/test/TEST-de.tum.cit.aet.artemis.buildagent.architecture.BuildAgentResourceArchitectureTest.xml
Error:
java.lang.AssertionError: Rule 'methods that are declared in classes that reside in a package 'de.tum.cit.aet.artemis.buildagent..' and are declared in classes that are annotated with @RestController and are public should be annotated with request mapping annotation, because all public methods should be endpoints' failed to check any classes. This means either that no classes have been passed to the rule at all, or that no classes passed to the rule matched the that() clause. To allow rules being evaluated without checking any classes you can either use ArchRule.allowEmptyShould(true) on a single rule or set the configuration property archRule.failOnEmptyShould = false to change the behavior globally.


[failure] 87-87: de.tum.cit.aet.artemis.core.architecture.CoreResourceArchitectureTest ► shouldHaveNoPublicMethodsExceptForEndpoints()
Failed test found in:
build/test-results/test/TEST-de.tum.cit.aet.artemis.core.architecture.CoreResourceArchitectureTest.xml
Error:
java.lang.AssertionError: Architecture Violation [Priority: MEDIUM] - Rule 'methods that are declared in classes that reside in a package 'de.tum.cit.aet.artemis.core..' and are declared in classes that are annotated with @RestController and are public should be annotated with request mapping annotation, because all public methods should be endpoints' was violated (2 times):

🔇 Additional comments (3)
src/test/java/de/tum/cit/aet/artemis/shared/architecture/module/ModuleArchitectureTest.java (1)

8-8: LGTM!

The import is correctly placed and necessary for the new functionality.

src/test/java/de/tum/cit/aet/artemis/shared/architecture/module/AbstractModuleResourceArchitectureTest.java (2)

112-112: LGTM: Improved encapsulation

The visibility change from protected to private is appropriate as the method is only used within this class.


79-79: LGTM: Improved test scoping

The change from methods() to methodsOfThisModuleThat() correctly scopes the test to the current module, improving test isolation.

Let's verify that this change doesn't miss any important checks:

Comment on lines +83 to +88
@Test
void shouldHaveNoPublicMethodsExceptForEndpoints() {
ArchRule rule = methodsOfThisModuleThat().areDeclaredInClassesThat().areAnnotatedWith(RestController.class).and().arePublic().should(beAnnotatedWithRequestMapping())
.because("all public methods should be endpoints");
rule.check(productionClasses);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add allowEmptyShould for modules without REST controllers

The test is correctly enforcing that all public methods in REST controllers must be endpoints. However, the static analysis shows failures in BuildAgent and Core modules, likely because they don't have REST controllers or have public methods that aren't endpoints.

Apply this change to handle modules without REST controllers:

     @Test
     void shouldHaveNoPublicMethodsExceptForEndpoints() {
         ArchRule rule = methodsOfThisModuleThat().areDeclaredInClassesThat().areAnnotatedWith(RestController.class).and().arePublic().should(beAnnotatedWithRequestMapping())
                 .because("all public methods should be endpoints");
-        rule.check(productionClasses);
+        rule.allowEmptyShould(true).check(productionClasses);
     }
📝 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
@Test
void shouldHaveNoPublicMethodsExceptForEndpoints() {
ArchRule rule = methodsOfThisModuleThat().areDeclaredInClassesThat().areAnnotatedWith(RestController.class).and().arePublic().should(beAnnotatedWithRequestMapping())
.because("all public methods should be endpoints");
rule.check(productionClasses);
}
@Test
void shouldHaveNoPublicMethodsExceptForEndpoints() {
ArchRule rule = methodsOfThisModuleThat().areDeclaredInClassesThat().areAnnotatedWith(RestController.class).and().arePublic().should(beAnnotatedWithRequestMapping())
.because("all public methods should be endpoints");
rule.allowEmptyShould(true).check(productionClasses);
}
🧰 Tools
🪛 GitHub Check: Java Architecture Tests

[failure] 87-87: de.tum.cit.aet.artemis.buildagent.architecture.BuildAgentResourceArchitectureTest ► shouldHaveNoPublicMethodsExceptForEndpoints()
Failed test found in:
build/test-results/test/TEST-de.tum.cit.aet.artemis.buildagent.architecture.BuildAgentResourceArchitectureTest.xml
Error:
java.lang.AssertionError: Rule 'methods that are declared in classes that reside in a package 'de.tum.cit.aet.artemis.buildagent..' and are declared in classes that are annotated with @RestController and are public should be annotated with request mapping annotation, because all public methods should be endpoints' failed to check any classes. This means either that no classes have been passed to the rule at all, or that no classes passed to the rule matched the that() clause. To allow rules being evaluated without checking any classes you can either use ArchRule.allowEmptyShould(true) on a single rule or set the configuration property archRule.failOnEmptyShould = false to change the behavior globally.


[failure] 87-87: de.tum.cit.aet.artemis.core.architecture.CoreResourceArchitectureTest ► shouldHaveNoPublicMethodsExceptForEndpoints()
Failed test found in:
build/test-results/test/TEST-de.tum.cit.aet.artemis.core.architecture.CoreResourceArchitectureTest.xml
Error:
java.lang.AssertionError: Architecture Violation [Priority: MEDIUM] - Rule 'methods that are declared in classes that reside in a package 'de.tum.cit.aet.artemis.core..' and are declared in classes that are annotated with @RestController and are public should be annotated with request mapping annotation, because all public methods should be endpoints' was violated (2 times):

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: Ready For Review
Development

Successfully merging this pull request may close these issues.

1 participant