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: Refactor file upload tests #9415

Merged
merged 111 commits into from
Oct 7, 2024

Conversation

MaximilianAnzinger
Copy link
Collaborator

@MaximilianAnzinger MaximilianAnzinger commented Oct 3, 2024

Checklist

General

Server

Motivation and Context

Description

Introduces AbstractFileUploadIntegrationTest.

Review Progress

Code Review

  • Code Review 1
  • Code Review 2

Test Coverage

unchanged

Summary by CodeRabbit

  • New Features

    • Introduced a new test class for validating the architecture of the file upload module.
  • Refactor

    • Restructured existing integration tests to extend a new base class, improving organization and maintainability.
    • Removed several dependencies from test classes to streamline testing processes.
  • Tests

    • Enhanced existing test cases and added new ones to ensure comprehensive coverage of file upload functionalities.

…ory and prevent unambiguous bean exception
@github-actions github-actions bot added tests fileupload Pull requests that affect the corresponding module labels Oct 3, 2024
Base automatically changed from chore/restructure-architecture-tests to develop October 4, 2024 16:00
@MaximilianAnzinger MaximilianAnzinger marked this pull request as ready for review October 6, 2024 04:25
@MaximilianAnzinger MaximilianAnzinger requested a review from a team as a code owner October 6, 2024 04:25
Copy link

coderabbitai bot commented Oct 6, 2024

Walkthrough

The changes introduce a new base integration test class, AbstractFileUploadIntegrationTest, which provides a structured approach for testing file upload functionalities. Several existing test classes have been refactored to extend this new base class, resulting in the removal of numerous autowired dependencies. Additionally, a new architecture test class for the file upload module has been created to facilitate module testing. These modifications aim to streamline the integration testing process and improve the organization of the test code.

Changes

File Change Summary
src/test/java/de/tum/cit/aet/artemis/fileupload/AbstractFileUploadIntegrationTest.java Class added: AbstractFileUploadIntegrationTest with multiple @Autowired fields for various repositories and services.
src/test/java/de/tum/cit/aet/artemis/fileupload/FileUploadAssessmentIntegrationTest.java Class signature updated to extend AbstractFileUploadIntegrationTest. Renamed variable from complaintRepo to complaintRepository. Several autowired dependencies removed.
src/test/java/de/tum/cit/aet/artemis/fileupload/FileUploadExerciseIntegrationTest.java Class signature updated to extend AbstractFileUploadIntegrationTest. Multiple autowired fields removed, indicating a shift in dependency handling.
src/test/java/de/tum/cit/aet/artemis/fileupload/FileUploadSubmissionIntegrationTest.java Class signature updated to extend AbstractFileUploadIntegrationTest. Several autowired fields removed, suggesting changes in dependency management.
src/test/java/de/tum/cit/aet/artemis/fileupload/architecture/FileUploadTestArchitectureTest.java Class added: FileUploadTestArchitectureTest with methods getModulePackage() and getAbstractModuleIntegrationTestClass() to establish a framework for testing the architecture of the file upload module.

Possibly related PRs

Suggested labels

ready for review, priority:high

Suggested reviewers

  • krusche
  • JohannesStoehr
  • SimonEntholzer

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
Contributor

@JohannesStoehr JohannesStoehr left a comment

Choose a reason for hiding this comment

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

Approve refactoring

Copy link
Contributor

@cremertim cremertim left a comment

Choose a reason for hiding this comment

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

Refactoring lgtm

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: 4

🧹 Outside diff range comments (6)
src/test/java/de/tum/cit/aet/artemis/fileupload/FileUploadSubmissionIntegrationTest.java (1)

Line range hint 713-717: Use consistent indentation for code readability

The indentation in the saveExercise_beforeDueDate test method is inconsistent. Ensure to use 4 spaces for indentation to maintain code readability and adhere to the project's coding style guidelines.

Apply this diff to correct the indentation:

 @Test
 @WithMockUser(username = TEST_PREFIX + "student3", roles = "USER")
 void saveExercise_beforeDueDate() throws Exception {
-   FileUploadSubmission storedSubmission = request.postWithMultipartFile("/api/exercises/" + releasedFileUploadExercise.getId() + "/file-upload-submissions",
+    FileUploadSubmission storedSubmission = request.postWithMultipartFile("/api/exercises/" + releasedFileUploadExercise.getId() + "/file-upload-submissions",
             notSubmittedFileUploadSubmission, "submission", validFile, FileUploadSubmission.class, HttpStatus.OK);
     assertThat(storedSubmission.isSubmitted()).isTrue();
 
 }
src/test/java/de/tum/cit/aet/artemis/fileupload/FileUploadExerciseIntegrationTest.java (5)

Line range hint 67-73: Add assertions to validate the expected failure

In the method createFileUploadExerciseFails(), there are no assertions to confirm that the API call fails as intended. Consider adding assertions to verify the response body or specific error messages to ensure the test accurately checks for the expected HttpStatus.BAD_REQUEST.

Apply this change to include assertions:

 @Test
 @WithMockUser(username = TEST_PREFIX + "instructor1", roles = "INSTRUCTOR")
 void createFileUploadExerciseFails() throws Exception {
     String filePattern = "Example file pattern";
     fileUploadExercise.setFilePattern(filePattern);
-    request.postWithResponseBody("/api/file-upload-exercises", fileUploadExercise, FileUploadExercise.class, HttpStatus.BAD_REQUEST);
+    var response = request.postWithResponseBody("/api/file-upload-exercises", fileUploadExercise, String.class, HttpStatus.BAD_REQUEST);
+    assertThat(response).contains("Specific error message or validation details");
 }

Line range hint 74-80: Include assertions to confirm the expected error condition

In createFileUploadExerciseFailsIfAlreadyCreated(), the test lacks assertions to verify that the exercise creation fails because it already exists. Adding assertions to check the response content will help ensure the test accurately reflects the expected behavior.

Consider applying this diff to add necessary assertions:

 @Test
 @WithMockUser(username = TEST_PREFIX + "instructor1", roles = "INSTRUCTOR")
 void createFileUploadExerciseFailsIfAlreadyCreated() throws Exception {
     String filePattern = "Example file pattern";
     fileUploadExercise.setFilePattern(filePattern);
     fileUploadExercise = fileUploadExerciseRepository.save(fileUploadExercise);
-    request.postWithResponseBody("/api/file-upload-exercises", fileUploadExercise, FileUploadExercise.class, HttpStatus.BAD_REQUEST);
+    var response = request.postWithResponseBody("/api/file-upload-exercises", fileUploadExercise, String.class, HttpStatus.BAD_REQUEST);
+    assertThat(response).contains("Exercise already exists error message");
 }

Line range hint 133-137: Avoid direct database access in tests

The method createFileUploadExerciseForExam() directly saves grading criteria to the repository:

gradingCriteria = exerciseUtilService.addGradingInstructionsToExercise(fileUploadExercise);
gradingCriterionRepository.saveAll(gradingCriteria);

According to the coding guidelines, tests should avoid direct database access. Consider using mock objects or test utilities to manage test data without directly interacting with the database.

Refactor the code to use test utilities:

-gradingCriteria = exerciseUtilService.addGradingInstructionsToExercise(fileUploadExercise);
-gradingCriterionRepository.saveAll(gradingCriteria);
+gradingCriteria = gradingCriterionUtilService.addGradingInstructionsToExercise(fileUploadExercise);

Line range hint 217-221: Use static mocks for dependency injection

The test utilizes Mockito for verifying interactions:

verify(examLiveEventsService, times(1)).createAndSendProblemStatementUpdateEvent(any(), any(), any());
verify(groupNotificationScheduleService, never()).checkAndCreateAppropriateNotificationsWhenUpdatingExercise(any(), any(), any());

As per the coding guidelines, the mock strategy should use static mocks. Ensure that all mocks are properly declared as static and that the mocking strategy aligns with the project's conventions.


Line range hint 356-361: Minimize context restarts in parameterized tests

The parameterized test testGetAllExercisesOnPageAsEditorSuccess() may cause unnecessary context restarts, impacting test performance. Consider restructuring the test to minimize context initialization by combining similar test cases or using different parameterization strategies.

Refactor the test method to reduce context restarts:

-@Test
-@WithMockUser(username = TEST_PREFIX + "editor1", roles = "EDITOR")
+@ParameterizedTest
+@WithMockUser(username = TEST_PREFIX + "editor1", roles = "EDITOR")
 void testGetAllExercisesOnPageAsEditorSuccess() throws Exception {
    // Test implementation
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between eee133f and 9bc870f.

📒 Files selected for processing (5)
  • src/test/java/de/tum/cit/aet/artemis/fileupload/AbstractFileUploadIntegrationTest.java (1 hunks)
  • src/test/java/de/tum/cit/aet/artemis/fileupload/FileUploadAssessmentIntegrationTest.java (2 hunks)
  • src/test/java/de/tum/cit/aet/artemis/fileupload/FileUploadExerciseIntegrationTest.java (1 hunks)
  • src/test/java/de/tum/cit/aet/artemis/fileupload/FileUploadSubmissionIntegrationTest.java (1 hunks)
  • src/test/java/de/tum/cit/aet/artemis/fileupload/architecture/FileUploadTestArchitectureTest.java (1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
src/test/java/de/tum/cit/aet/artemis/fileupload/AbstractFileUploadIntegrationTest.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/fileupload/FileUploadAssessmentIntegrationTest.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/fileupload/FileUploadExerciseIntegrationTest.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/fileupload/FileUploadSubmissionIntegrationTest.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/fileupload/architecture/FileUploadTestArchitectureTest.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

🔇 Additional comments (13)
src/test/java/de/tum/cit/aet/artemis/fileupload/architecture/FileUploadTestArchitectureTest.java (5)

1-5: LGTM: Package declaration and imports are correct.

The package declaration matches the file path, and the imports are appropriate for the class implementation.


6-6: LGTM: Class declaration and structure are appropriate.

The class name FileUploadTestArchitectureTest is descriptive and follows the naming convention for test classes. It correctly extends AbstractModuleTestArchitectureTest with the appropriate type parameter.


8-11: LGTM: getModulePackage() method is correctly implemented.

The method properly overrides the superclass method and returns the expected package name for the file upload module. It adheres to the small and specific test method guideline.


13-16: LGTM: getAbstractModuleIntegrationTestClass() method is correctly implemented.

The method properly overrides the superclass method and returns the correct class object for AbstractFileUploadIntegrationTest. It adheres to the small and specific test method guideline.


1-17: Overall, the FileUploadTestArchitectureTest class is well-implemented and follows best practices.

The class adheres to the provided coding guidelines:

  1. The test class name is descriptive.
  2. Methods are small and specific.
  3. It extends the appropriate abstract class for module testing.
  4. No database access or mocking is required, which is suitable for an architectural test.

The class structure and implementation provide a solid foundation for testing the architecture of the file upload module.

src/test/java/de/tum/cit/aet/artemis/fileupload/AbstractFileUploadIntegrationTest.java (2)

24-24: LGTM: Class structure and naming.

The class name AbstractFileUploadIntegrationTest is descriptive and follows the naming convention for abstract classes. Extending AbstractSpringIntegrationIndependentTest is a good practice for integration tests, providing a common base for file upload-related tests.


1-81: Overall assessment: Good foundation with room for improvement.

The AbstractFileUploadIntegrationTest class provides a solid foundation for file upload integration tests. It follows proper naming conventions, extends an appropriate base class, and adheres to the basic structure expected for test classes.

However, there are opportunities for improvement:

  1. Consider reducing the number of autowired dependencies to better adhere to the Single Responsibility Principle.
  2. Evaluate the possibility of using constructor injection instead of field injection.
  3. Add comments or documentation to guide developers on how to properly extend this class and adhere to all test-related coding guidelines.

These improvements will enhance the maintainability, readability, and overall quality of the test suite. Great job on establishing this base class for file upload tests!

src/test/java/de/tum/cit/aet/artemis/fileupload/FileUploadSubmissionIntegrationTest.java (4)

45-45: Extending AbstractFileUploadIntegrationTest for improved test structure

Changing the base class from AbstractSpringIntegrationIndependentTest to AbstractFileUploadIntegrationTest is appropriate. It helps in encapsulating common setup and utilities specific to file upload integration tests, promoting code reuse and maintainability.


Line range hint 400-405: Verify injection of participationRepository after removing @Autowired

In the method submitExercise_afterDueDate_forbidden(), participationRepository is used, but its @Autowired field declaration has been removed. Confirm that participationRepository is correctly injected via the base class or another method to avoid potential runtime exceptions.

Run the following script to check for the declaration of participationRepository:

#!/bin/bash
# Description: Verify that `participationRepository` is declared in parent classes.

# Search for the declaration of `participationRepository` in parent classes.
rg --type java 'private ParticipationTestRepository participationRepository' src/test/java/de/tum/cit/aet/artemis/fileupload/AbstractFileUploadIntegrationTest.java

This script will help you verify if participationRepository is declared in AbstractFileUploadIntegrationTest.java, ensuring that the dependency is appropriately managed.


Line range hint 62-81: Ensure utility services are accessible after removing @Autowired fields

Methods like initTestCase() use services such as userUtilService, fileUploadExerciseUtilService, and participationUtilService, which were previously injected via @Autowired. Verify that these services are now available through the base class or other means to prevent any NullPointerException.

Use the following script to check the declarations:

#!/bin/bash
# Description: Verify that utility services are declared or inherited.

# Check for declarations in the base class.
rg --type java 'protected UserUtilService userUtilService' src/test/java/de/tum/cit/aet/artemis/fileupload/AbstractFileUploadIntegrationTest.java
rg --type java 'protected FileUploadExerciseUtilService fileUploadExerciseUtilService' src/test/java/de/tum/cit/aet/artemis/fileupload/AbstractFileUploadIntegrationTest.java
rg --type java 'protected ParticipationUtilService participationUtilService' src/test/java/de/tum/cit/aet/artemis/fileupload/AbstractFileUploadIntegrationTest.java

This will confirm if the utility services are declared in the base class and accessible in the subclass.


Line range hint 84-93: Verify injection of fileUploadSubmissionRepository after removing @Autowired

In the testRepositoryMethods() method, fileUploadSubmissionRepository is used, but its @Autowired field declaration has been removed. Ensure that fileUploadSubmissionRepository is still properly injected, possibly through the new base class or another mechanism, to prevent NullPointerException at runtime.

You can run the following script to check if fileUploadSubmissionRepository is declared in the base classes:

This script searches for the declaration of fileUploadSubmissionRepository in AbstractFileUploadIntegrationTest.java. If the repository is declared there, it confirms that the dependency is properly injected through the base class.

src/test/java/de/tum/cit/aet/artemis/fileupload/FileUploadExerciseIntegrationTest.java (2)

52-52: Ensure the new base class provides necessary setup and utilities

The test class now extends AbstractFileUploadIntegrationTest instead of AbstractSpringIntegrationIndependentTest. Please verify that the new base class initializes all required dependencies and provides the necessary setup and utility methods that were previously available. This ensures that all tests function correctly with the updated inheritance.


Line range hint 400-406: Validate assertions for accurate test verification

In the method testGetFileUploadExercise_exampleSolutionVisibility(), ensure that the assertions accurately reflect the expected visibility of the example solution based on the user's role and the exampleSolutionPublicationDate.

Review the assertions and confirm they align with the expected outcomes in different scenarios.

@krusche krusche merged commit a0f7fd8 into develop Oct 7, 2024
35 of 39 checks passed
@krusche krusche deleted the chore/refactor-file-upload-tests branch October 7, 2024 18:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
fileupload Pull requests that affect the corresponding module ready to merge tests
Projects
Archived in project
Status: Done
Development

Successfully merging this pull request may close these issues.

5 participants