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

Programming exercises: Fix an issue with access tokens for team exercises #9802

Merged
merged 7 commits into from
Nov 24, 2024

Conversation

SimonEntholzer
Copy link
Contributor

@SimonEntholzer SimonEntholzer commented Nov 17, 2024

Checklist

General

  • I tested all changes and their related features with all corresponding user types on a test server.
  • This is a small issue that I tested locally and was confirmed by another developer on a test server.
  • I chose a title conforming to the naming conventions for pull requests.

Server

  • Important: I implemented the changes with a very good performance and prevented too many (unnecessary) and too complex database calls.
  • I strictly followed the principle of data economy for all database calls.
  • I strictly followed the server coding and design guidelines.
  • I added multiple integration tests (Spring) related to the features (with a high test coverage).
  • I added pre-authorization annotations according to the guidelines and checked the course groups for all new REST Calls (security).
  • I documented the Java code using JavaDoc style.

Changes affecting Programming Exercises

  • High priority: I tested all changes and their related features with all corresponding user types on a test server configured with the integrated lifecycle setup (LocalVC and LocalCI).

Motivation and Context

For programming team exercises, the vcs access token did not load, as the team's students were not loaded when fetching the participation.

Description

Fix the issue by loading the team's students, when the exercise is a team exercise.

Steps for Testing

Prerequisites:

  1. As an instructor create a team programming exercise
  2. Create a team and add at least one student
  3. With the student account, login and navigate to the exercise
  4. Make sure the clone link in the code button is displayed with the VCS-access token.

Testserver States

Note

These badges show the state of the test servers.
Green = Currently available, Red = Currently locked
Click on the badges to get to the test servers.







Review Progress

Code Review

  • Code Review 1
  • Code Review 2

Manual Tests

  • Test 1
  • Test 2

Test Coverage

Server

Class/File Line Coverage Confirmation (assert/expect)
ParticipationVcsAccessTokenService.java 92% ✅ ❌

Screenshots

image
image

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced functionality to manage team exercises, including loading team student data and creating access tokens for team participation.
    • Added methods to handle programming submissions specifically for team exercises.
    • Implemented a method to delete specific teams from the repository.
  • Bug Fixes

    • Enhanced logic for retrieving and creating VCS access tokens to ensure team data is accurately processed.
  • Tests

    • Added new test methods to verify the functionality related to team exercises and VCS access tokens.

@SimonEntholzer SimonEntholzer requested a review from a team as a code owner November 17, 2024 12:09
@github-actions github-actions bot added tests server Pull requests that update Java code. (Added Automatically!) core Pull requests that affect the corresponding module exercise Pull requests that affect the corresponding module programming Pull requests that affect the corresponding module labels Nov 17, 2024
@SimonEntholzer SimonEntholzer changed the title Programming exercise: Fix VCS access tokens for team exercises Programming exercises: Fix VCS access tokens for team exercises Nov 17, 2024
Copy link

coderabbitai bot commented Nov 17, 2024

Walkthrough

The changes in this pull request involve modifications to several classes to enhance the handling of team exercises and VCS access tokens. The ParticipationVcsAccessTokenService class now has a dependency on TeamRepository and includes a method to load team students. New test methods have been added to the UserAccountLocalVcsIntegrationTest and UserTestService classes to verify functionalities related to team exercises. Additionally, the TeamUtilService has a method for deleting a team, and the ProgrammingExerciseUtilService includes a method for adding submissions to team exercises.

Changes

File Change Summary
src/main/java/de/tum/cit/aet/artemis/programming/service/ParticipationVcsAccessTokenService.java - Constructor updated to include TeamRepository.
- Added method loadTeamStudentsForTeamExercise.
src/test/java/de/tum/cit/aet/artemis/core/authentication/UserAccountLocalVcsIntegrationTest.java - Added test method getParticipationVcsAccessTokenByUserForTeamExercise.
src/test/java/de/tum/cit/aet/artemis/core/user/util/UserTestService.java - Added fields TeamUtilService and ExerciseTestRepository.
- Added method getAndCreateParticipationVcsAccessTokenForTeamExercise.
src/test/java/de/tum/cit/aet/artemis/exercise/team/TeamUtilService.java - Added method deleteTeam(Team team).
src/test/java/de/tum/cit/aet/artemis/programming/util/ProgrammingExerciseUtilService.java - Added method addProgrammingSubmissionToTeamExercise.

Possibly related PRs

Suggested reviewers

  • dfuchss
  • Hialus
  • b-fein
  • JohannesStoehr

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

🧹 Outside diff range and nitpick comments (5)
src/test/java/de/tum/cit/aet/artemis/core/authentication/UserAccountLocalVcsIntegrationTest.java (1)

41-46: Consider enhancing test method naming and documentation

While the test implementation follows the class's consistent pattern, consider these improvements:

  1. Rename the method to be more specific about what it verifies:
-void getParticipationVcsAccessTokenByUserForTeamExercise() throws Exception {
+void shouldGetVcsAccessTokenForTeamExerciseParticipation() throws Exception {
  1. Add JavaDoc to document the test's purpose and scenario:
/**
 * Verifies that VCS access tokens can be retrieved for team exercise participations.
 * This test ensures that students associated with the team are properly loaded
 * when fetching participation data for team exercises.
 */
src/main/java/de/tum/cit/aet/artemis/programming/service/ParticipationVcsAccessTokenService.java (1)

31-35: LGTM: Constructor properly updated

The constructor is correctly modified to include the new dependency while maintaining clean code principles.

Consider breaking the long parameter list into multiple lines for better readability:

-    public ParticipationVcsAccessTokenService(ParticipationVCSAccessTokenRepository participationVCSAccessTokenRepository,
-            ProgrammingExerciseStudentParticipationRepository programmingExerciseStudentParticipationRepository, TeamRepository teamRepository) {
+    public ParticipationVcsAccessTokenService(
+            ParticipationVCSAccessTokenRepository participationVCSAccessTokenRepository,
+            ProgrammingExerciseStudentParticipationRepository programmingExerciseStudentParticipationRepository,
+            TeamRepository teamRepository) {
src/test/java/de/tum/cit/aet/artemis/programming/util/ProgrammingExerciseUtilService.java (1)

745-758: Fix JavaDoc parameter description for team parameter.

The implementation looks good and follows the established patterns for test utility methods. However, the JavaDoc parameter description for team is incorrect as it describes it as "The login of the user" when it's actually a Team object.

Apply this diff to fix the JavaDoc:

     /**
      * Adds programming submission to provided programming exercise. The provided login is used to access or create a participation.
      *
      * @param exercise   The exercise to which the submission should be added.
      * @param submission The submission which should be added to the programming exercise.
-     * @param team       The login of the user used to access or create an exercise participation.
+     * @param team       The team object used to access or create a team participation.
      * @return The created programming submission.
      */
src/test/java/de/tum/cit/aet/artemis/core/user/util/UserTestService.java (2)

928-956: Add test annotation and documentation.

The test method is missing:

  1. The @Test annotation
  2. JavaDoc documentation explaining the test's purpose and steps

Add the following before the method:

+    /**
+     * Test that verifies the creation and retrieval of VCS access tokens for team exercises:
+     * 1. Creates a team exercise and adds a user to a team
+     * 2. Verifies that token is not found initially
+     * 3. Creates a new token and verifies it can be retrieved
+     * 4. Cleans up all created entities
+     */
+    @Test
     public void getAndCreateParticipationVcsAccessTokenForTeamExercise() throws Exception {

928-956: Consider extracting common setup and cleanup logic.

The test shares similar setup and cleanup patterns with getAndCreateParticipationVcsAccessToken. Consider extracting these into helper methods to improve maintainability and reduce code duplication.

Consider creating the following helper methods:

private ProgrammingSubmission setupTeamExerciseSubmission(User user) {
    var course = courseUtilService.addEmptyCourse();
    var exercise = programmingExerciseUtilService.addProgrammingExerciseToCourse(course);
    exercise.setMode(ExerciseMode.TEAM);
    exerciseTestRepository.save(exercise);
    courseRepository.save(course);
    
    User tutor = userTestRepository.findOneByLogin(TEST_PREFIX + "tutor1").orElseThrow();
    Team team = teamUtilService.createTeam(Set.of(user), tutor, exercise, "team1");
    
    var submission = (ProgrammingSubmission) new ProgrammingSubmission()
        .commitHash("abc")
        .type(SubmissionType.MANUAL)
        .submitted(true);
    return programmingExerciseUtilService.addProgrammingSubmissionToTeamExercise(exercise, submission, team);
}

private void cleanupSubmission(ProgrammingSubmission submission) {
    submissionRepository.delete(submission);
    participationVCSAccessTokenRepository.deleteAll();
    participationRepository.deleteById(submission.getParticipation().getId());
    teamUtilService.deleteAll();
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1786886 and c8d2c7d.

📒 Files selected for processing (5)
  • src/main/java/de/tum/cit/aet/artemis/programming/service/ParticipationVcsAccessTokenService.java (5 hunks)
  • src/test/java/de/tum/cit/aet/artemis/core/authentication/UserAccountLocalVcsIntegrationTest.java (1 hunks)
  • src/test/java/de/tum/cit/aet/artemis/core/user/util/UserTestService.java (4 hunks)
  • src/test/java/de/tum/cit/aet/artemis/exercise/team/TeamUtilService.java (1 hunks)
  • src/test/java/de/tum/cit/aet/artemis/programming/util/ProgrammingExerciseUtilService.java (2 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
src/main/java/de/tum/cit/aet/artemis/programming/service/ParticipationVcsAccessTokenService.java (1)

Pattern src/main/java/**/*.java: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,delegate_logic,http_only,minimal_dtos}; dtos:{java_records,no_entities,min_data,single_resp}; di:constructor_injection; kiss:simple_code; file_handling:os_indep_paths; practices:{least_access,avoid_transactions,code_reuse,static_member_ref,prefer_primitives}; sql:{param_annotation,uppercase,avoid_subqueries};java:avoid_star_imports

src/test/java/de/tum/cit/aet/artemis/core/authentication/UserAccountLocalVcsIntegrationTest.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/core/user/util/UserTestService.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/exercise/team/TeamUtilService.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/programming/util/ProgrammingExerciseUtilService.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

📓 Learnings (1)
src/test/java/de/tum/cit/aet/artemis/core/authentication/UserAccountLocalVcsIntegrationTest.java (1)
Learnt from: SimonEntholzer
PR: ls1intum/Artemis#8929
File: src/test/java/de/tum/in/www1/artemis/authentication/UserLocalVcIntegrationTest.java:29-33
Timestamp: 2024-11-12T12:51:51.200Z
Learning: When addressing missing test coverage, ensure that new tests specifically validate the functionality introduced in the PR, such as token-based authentication.
🔇 Additional comments (10)
src/test/java/de/tum/cit/aet/artemis/core/authentication/UserAccountLocalVcsIntegrationTest.java (2)

44-44: Verify test service implementation follows guidelines

Please ensure that UserTestService.getAndCreateParticipationVcsAccessTokenForTeamExercise() follows these test guidelines:

  1. Uses AssertJ's assertThat() for assertions
  2. Tracks database query count for performance monitoring

Let's verify the implementation:

#!/bin/bash
# Description: Check UserTestService implementation

# Check for assertThat usage
rg -A 5 "getAndCreateParticipationVcsAccessTokenForTeamExercise" src/test/java

# Check for query count tracking
rg "TestTransaction|@Sql" src/test/java/de/tum/cit/aet/artemis/core/user/util/UserTestService.java

41-46: 🛠️ Refactor suggestion

Consider adding edge case tests for team exercises

Given that this PR fixes issues with VCS token loading for team exercises, consider adding additional test cases to verify edge scenarios:

  1. Token retrieval when a student is part of multiple teams
  2. Token retrieval when a team has no students
  3. Token retrieval after team membership changes

Let's check if these scenarios are covered elsewhere:

src/main/java/de/tum/cit/aet/artemis/programming/service/ParticipationVcsAccessTokenService.java (4)

13-13: LGTM: Clean dependency addition

The TeamRepository dependency is properly added following the constructor injection pattern and immutability principles.

Also applies to: 29-30


Line range hint 1-100: Verify test coverage for team exercise scenarios

The implementation aligns with the PR objective of fixing VCS token loading for team exercises. However, let's verify the test coverage mentioned in the PR description.

#!/bin/bash
# Look for related test files and coverage
rg -l "ParticipationVcsAccessTokenService.*team" --type java --glob "*Test.java"

90-99: 🛠️ Refactor suggestion

Improve robustness and performance of team student loading

The current implementation has several potential issues:

  1. Possible NPE if findWithStudentsById returns empty Optional
  2. Potential N+1 query problem if called for multiple participations
  3. Complex nested Optional handling

Consider this safer and more efficient implementation:

     private void loadTeamStudentsForTeamExercise(StudentParticipation participation) {
-        if (participation.getTeam().isPresent()) {
-            participation.getTeam().get().setStudents(teamRepository.findWithStudentsById(participation.getTeam().get().getId()).get().getStudents());
-        }
+        participation.getTeam().ifPresent(team -> 
+            teamRepository.findWithStudentsById(team.getId())
+                .ifPresent(loadedTeam -> team.setStudents(loadedTeam.getStudents()))
+        );
     }

Let's check for similar patterns in the codebase that might need similar improvements:

#!/bin/bash
# Look for similar Optional unwrapping patterns that might need improvement
ast-grep --pattern 'if ($x.isPresent()) {
  $$$
  $x.get()
  $$$
}'

62-62: Consider transaction boundaries for team loading

While the placement of loadTeamStudentsForTeamExercise calls is correct, loading team data might require explicit transaction handling to prevent LazyInitializationException.

Let's check if there are any transaction annotations in the codebase:

Consider adding @Transactional(readOnly = true) to these methods if not already handled at a higher level.

Also applies to: 81-81

src/test/java/de/tum/cit/aet/artemis/exercise/team/TeamUtilService.java (2)

Line range hint 1-253: Consider enhancing test isolation and data management

While the class provides good utility for test data generation, consider these architectural improvements:

  1. Implement a TestContext pattern to track and clean up created entities
  2. Add methods to verify the state after operations
  3. Consider using builder pattern for more flexible team creation

Example TestContext implementation:

@TestComponent
public class TeamTestContext {
    private final Set<Team> createdTeams = new HashSet<>();
    
    public void trackTeam(Team team) {
        createdTeams.add(team);
    }
    
    @AfterEach
    public void cleanup() {
        // Clean up only teams created in the current test
        createdTeams.forEach(team -> {
            team.getStudents().clear();
            team.setOwner(null);
            team.setExercise(null);
        });
        teamRepo.deleteAll(createdTeams);
        createdTeams.clear();
    }
}

Let's analyze the current test patterns:

#!/bin/bash
# Description: Analyze test patterns and isolation

# Find test classes using this utility
echo "Test classes using TeamUtilService:"
rg "class.*extends.*Test.*\{" -A 10 -B 2 $(rg -l "TeamUtilService" --type java)

# Check for potential test isolation issues
echo "\nPotential test isolation issues:"
rg "@Test" -A 20 -B 2 $(rg -l "TeamUtilService" --type java) | rg -v "@AfterEach|@After"

247-253: 🛠️ Refactor suggestion

Consider revising the database access approach

The deleteAll() method has several concerns that should be addressed:

  1. Direct database access violates the test guidelines. Consider using a mock repository or moving this logic to a dedicated cleanup service.
  2. Missing transaction management could lead to inconsistent state.
  3. Potential test isolation issues if other tests are running concurrently.

Consider this alternative implementation:

-    public void deleteAll() {
-        teamRepo.deleteAll();
-    }
+    @Transactional
+    public void deleteAll() {
+        // First, clean up related entities to prevent foreign key violations
+        var teams = teamRepo.findAll();
+        teams.forEach(team -> {
+            team.getStudents().clear();
+            team.setOwner(null);
+            team.setExercise(null);
+        });
+        teamRepo.saveAll(teams);
+        teamRepo.deleteAll();
+    }

Let's verify the usage context and potential impact:

src/test/java/de/tum/cit/aet/artemis/core/user/util/UserTestService.java (2)

49-53: LGTM!

The new imports are properly organized and necessary for implementing team exercise functionality.


98-100: LGTM!

The new autowired fields are properly annotated and follow the class's organization pattern.

Also applies to: 138-140

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 17, 2024
HawKhiem
HawKhiem previously approved these changes Nov 17, 2024
Copy link

@HawKhiem HawKhiem left a comment

Choose a reason for hiding this comment

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

Tested on TS3. Token appeared as described

image

EneaGore
EneaGore previously approved these changes Nov 17, 2024
Copy link
Contributor

@EneaGore EneaGore left a comment

Choose a reason for hiding this comment

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

Tested on TS3. works as expected. code also lgtm

alekspetrov9e
alekspetrov9e previously approved these changes Nov 17, 2024
Copy link

@alekspetrov9e alekspetrov9e left a comment

Choose a reason for hiding this comment

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

Tested on TS1. Works fine.

Copy link

@HawKhiem HawKhiem left a comment

Choose a reason for hiding this comment

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

Tested on TS3. Reapprove

Copy link

@flbrgit flbrgit left a comment

Choose a reason for hiding this comment

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

Tested on TS3. Everything works as expected
Screenshot 2024-11-23 231148

@krusche krusche added this to the 7.7.2 milestone Nov 24, 2024
@krusche krusche changed the title Programming exercises: Fix VCS access tokens for team exercises Programming exercises: Fix an issue with access tokens for team exercises Nov 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bugfix core Pull requests that affect the corresponding module exercise Pull requests that affect the corresponding module programming Pull requests that affect the corresponding module ready for review server Pull requests that update Java code. (Added Automatically!) tests
Projects
Archived in project
Development

Successfully merging this pull request may close these issues.