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: Migrate test run module to signals, inject and standalone #9914

Merged
merged 20 commits into from
Jan 26, 2025

Conversation

coolchock
Copy link
Contributor

@coolchock coolchock commented Nov 29, 2024

Checklist

General

Client

Description

This pull request migrates test runs module to signals, inject and standalone.

Steps for Testing

Prerequisites:

  • 1 Instructor
  • 1 Exam
  1. Log in to Artemis
  2. Navigate to Course Administration -> Select a course -> Exams -> Test Runs
  3. Click Create a Test Run
  4. Verify that modal works and it's possible to create a test run
  5. Verify that buttons and links on Test Run Management page work

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

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

Manual Tests

  • Test 1
  • Test 2

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced dependency management in the Create Test Run and Test Run Management components using Angular's modern inject function.
    • Added translation capabilities to the Test Run Ribbon component.
  • Bug Fixes

    • Streamlined initialization processes for components, improving overall readability and maintainability.
  • Refactor

    • Removed constructor parameters in favor of direct property assignment for injected services, reducing boilerplate code.
    • Marked components as standalone for improved modularity.
    • Adjusted module configurations to reflect the removal and addition of components.
    • Updated template logic to utilize function calls for dynamic property evaluation.
  • Tests

    • Enhanced the test suite for the Test Run Management component, improving clarity and functionality.

@github-actions github-actions bot added the client Pull requests that update TypeScript code. (Added Automatically!) label Nov 29, 2024
@coolchock coolchock changed the title Chore: Migrate test run module to signals, inject and standalone General: Migrate test run module to signals, inject and standalone Nov 29, 2024
@coolchock coolchock temporarily deployed to artemis-test1.artemis.cit.tum.de November 30, 2024 17:26 — with GitHub Actions Inactive
@coolchock coolchock marked this pull request as ready for review December 2, 2024 08:56
@coolchock coolchock requested a review from a team as a code owner December 2, 2024 08:56
Copy link

coderabbitai bot commented Dec 2, 2024

Caution

Review failed

The head commit changed during the review from 1f24262 to 8727157.

Walkthrough

The pull request modifies the CreateTestRunModalComponent, TestRunManagementComponent, and TestRunRibbonComponent in the Angular application. It transitions both CreateTestRunModalComponent and TestRunManagementComponent from constructor-based dependency injection to using the inject function for service initialization. Both components are marked as standalone, enhancing their modularity. The TestRunManagementComponent introduces reactive state management using signals and computed properties. Additionally, the TestRunRibbonComponent is updated to include translation capabilities. The ArtemisExamManagementModule and ArtemisParticipationSummaryModule are updated to reflect the removal and addition of components, respectively.

Changes

File Path Change Summary
src/main/webapp/app/exam/manage/test-runs/create-test-run-modal.component.ts Removed constructor; added private activeModal and private artemisDurationFromSecondsPipe; marked as standalone; imported ReactiveFormsModule and TranslateDirective.
src/main/webapp/app/exam/manage/test-runs/test-run-management.component.ts Removed constructor; added services using inject; marked as standalone; imported ArtemisTranslatePipe, FaIconComponent, and ArtemisSharedModule; updated state management to use signals and computed properties.
src/main/webapp/app/exam/manage/test-runs/test-run-ribbon.component.ts Added TranslateDirective; marked as standalone.
src/main/webapp/app/exam/manage/exam-management.module.ts Removed TestRunManagementComponent and CreateTestRunModalComponent from declarations.
src/main/webapp/app/exam/participate/exam-participation.module.ts Added TestRunRibbonComponent to imports.
src/main/webapp/app/exam/participate/summary/exam-result-summary.module.ts Removed TestRunRibbonComponent from declarations and exports.
src/test/javascript/spec/component/exam/test-run/test-run-management.component.spec.ts Streamlined imports; added ArtemisTestModule and MockNgbModalService; adjusted test setups and cases for asynchronous operations.
src/main/webapp/app/exam/manage/test-runs/test-run-management.component.html Converted property accesses to function calls for reactive updates in the template.

Possibly related PRs

Suggested labels

refactoring

Suggested reviewers

  • JohannesStoehr
  • SimonEntholzer
  • az108
  • HawKhiem
  • krusche

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 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 (4)
src/main/webapp/app/exam/manage/test-runs/create-test-run-modal.component.ts (1)

19-24: Consider implementing OnDestroy for proper cleanup

While the component looks good, it's handling exam data and form controls which should be properly cleaned up.

Consider implementing OnDestroy:

-export class CreateTestRunModalComponent implements OnInit {
+export class CreateTestRunModalComponent implements OnInit, OnDestroy {
+    private destroy$ = new Subject<void>();
+
+    ngOnDestroy(): void {
+        this.destroy$.next();
+        this.destroy$.complete();
+    }
src/main/webapp/app/exam/manage/test-runs/test-run-management.component.ts (3)

Line range hint 38-39: Implement proper cleanup for dialogErrorSource Subject

The dialogErrorSource Subject needs proper cleanup to prevent memory leaks.

Add cleanup in ngOnDestroy:

+    private destroy$ = new Subject<void>();
     private dialogErrorSource = new Subject<string>();
     dialogError$ = this.dialogErrorSource.asObservable();

+    ngOnDestroy(): void {
+        this.dialogErrorSource.complete();
+        this.destroy$.next();
+        this.destroy$.complete();
+    }

Line range hint 51-67: Use destroy$ Subject to manage subscription cleanup

The HTTP subscriptions in ngOnInit should be properly managed to prevent memory leaks.

Implement proper subscription management:

     ngOnInit(): void {
-        this.examManagementService.find(/*...*/).subscribe({
+        this.examManagementService.find(/*...*/)
+            .pipe(takeUntil(this.destroy$))
+            .subscribe({
             next: (response: HttpResponse<Exam>) => {
                 this.exam = response.body!;
                 this.isExamStarted = this.exam.started!;
                 this.course = this.exam.course!;
                 this.course.isAtLeastInstructor = this.accountService.isAtLeastInstructorInCourse(this.course);
-                this.examManagementService.findAllTestRunsForExam(/*...*/).subscribe({
+                this.examManagementService.findAllTestRunsForExam(/*...*/)
+                    .pipe(takeUntil(this.destroy$))
+                    .subscribe({
                     next: (res: HttpResponse<StudentExam[]>) => {
                         this.testRuns = res.body!;
                     },

Line range hint 89-93: Consider using async pipe for dialogError$

Since you're using an Observable for dialog errors, consider leveraging the async pipe in the template for automatic subscription management.

Update the template to use async pipe:

<div *ngIf="dialogError$ | async as error" class="alert alert-danger">
    {{ error }}
</div>
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2611d04 and c255253.

📒 Files selected for processing (2)
  • src/main/webapp/app/exam/manage/test-runs/create-test-run-modal.component.ts (2 hunks)
  • src/main/webapp/app/exam/manage/test-runs/test-run-management.component.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
src/main/webapp/app/exam/manage/test-runs/create-test-run-modal.component.ts (1)

Pattern src/main/webapp/**/*.ts: angular_style:https://angular.io/guide/styleguide;methods_in_html:false;lazy_loading:true;code_reuse:true;tests:meaningful;types:PascalCase;enums:PascalCase;funcs:camelCase;props:camelCase;no_priv_prefix:true;strings:single_quotes;localize:true;btns:functionality;links:navigation;icons_text:newline;labels:associate;code_style:arrow_funcs,curly_braces,open_braces_same_line,indent_4;memory_leak_prevention:true;routes:naming_schema;chart_framework:ngx-charts;responsive_layout:true

src/main/webapp/app/exam/manage/test-runs/test-run-management.component.ts (1)

Pattern src/main/webapp/**/*.ts: angular_style:https://angular.io/guide/styleguide;methods_in_html:false;lazy_loading:true;code_reuse:true;tests:meaningful;types:PascalCase;enums:PascalCase;funcs:camelCase;props:camelCase;no_priv_prefix:true;strings:single_quotes;localize:true;btns:functionality;links:navigation;icons_text:newline;labels:associate;code_style:arrow_funcs,curly_braces,open_braces_same_line,indent_4;memory_leak_prevention:true;routes:naming_schema;chart_framework:ngx-charts;responsive_layout:true

🔇 Additional comments (2)
src/main/webapp/app/exam/manage/test-runs/create-test-run-modal.component.ts (1)

1-1: LGTM: Clean migration to inject() pattern

The migration from constructor injection to the new inject() pattern is well implemented. This change:

  • Reduces boilerplate code
  • Follows modern Angular practices
  • Maintains proper encapsulation with private members

Also applies to: 17-18

src/main/webapp/app/exam/manage/test-runs/test-run-management.component.ts (1)

23-28: LGTM: Clean service injection implementation

The migration to inject() for all services is well implemented and follows a consistent pattern.

coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 2, 2024
HawKhiem
HawKhiem previously approved these changes Dec 2, 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. Test Run works as described

Screenshot 2024-12-03 001900
Screenshot 2024-12-03 001921
Screenshot 2024-12-03 001944

Copy link
Contributor

@SimonEntholzer SimonEntholzer left a comment

Choose a reason for hiding this comment

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

injection change lgtm, but you still need to migrate to standalone and use signals

Copy link
Member

@krusche krusche left a comment

Choose a reason for hiding this comment

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

we prefer undefined over null in the client code, see the client coding guidelines

@krusche krusche removed this from the 7.8.2 milestone Jan 5, 2025
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 comments (3)
src/main/webapp/app/exam/manage/test-runs/test-run-management.component.ts (3)

Line range hint 63-82: Improve initialization with proper error handling and cleanup

Consider these improvements:

  1. Replace non-null assertions with proper null checks
  2. Use RxJS operators to flatten nested subscriptions
  3. Consider cleanup for HTTP subscriptions
ngOnInit(): void {
-   this.examManagementService.find(Number(this.route.snapshot.paramMap.get('courseId')), Number(this.route.snapshot.paramMap.get('examId')), false, true).subscribe({
+   const courseId = Number(this.route.snapshot.paramMap.get('courseId'));
+   const examId = Number(this.route.snapshot.paramMap.get('examId'));
+   if (isNaN(courseId) || isNaN(examId)) {
+       this.alertService.error('artemisApp.exam.error.invalidIds');
+       return;
+   }
+   this.examManagementService.find(courseId, examId, false, true).pipe(
+       switchMap(response => {
+           if (!response.body) {
+               throw new Error('No exam data received');
+           }
+           this.exam.set(response.body);
+           const examData = response.body;
+           this.course.set(examData.course);
+           const course = examData.course;
+           if (!course) {
+               throw new Error('No course data available');
+           }
+           course.isAtLeastInstructor = this.accountService.isAtLeastInstructorInCourse(course);
+           return this.examManagementService.findAllTestRunsForExam(course.id, examData.id);
+       })
+   ).subscribe({
+       next: (res: HttpResponse<StudentExam[]>) => {
+           if (res.body) {
+               this.testRuns.set(res.body);
+           }
+       },
+       error: (error: HttpErrorResponse) => onError(this.alertService, error),
+   });
}

Line range hint 88-104: Improve modal handling with better type safety

The modal handling uses unsafe type assertions and non-null assertions. Consider these improvements:

openCreateTestRunModal() {
-   const modalRef: NgbModalRef = this.modalService.open(CreateTestRunModalComponent as Component, { size: 'lg', backdrop: 'static' });
+   const modalRef = this.modalService.open(CreateTestRunModalComponent, { size: 'lg', backdrop: 'static' });
-   modalRef.componentInstance.exam = this.exam();
+   const currentExam = this.exam();
+   if (!currentExam) {
+       this.alertService.error('artemisApp.exam.error.noExamData');
+       return;
+   }
+   modalRef.componentInstance.exam = currentExam;
    modalRef.result
        .then((testRunConfiguration: StudentExam) => {
-           this.examManagementService.createTestRun(this.course()?.id!, this.exam()?.id!, testRunConfiguration)
+           const courseId = this.course()?.id;
+           const examId = this.exam()?.id;
+           if (!courseId || !examId) {
+               this.alertService.error('artemisApp.exam.error.invalidIds');
+               return;
+           }
+           this.examManagementService.createTestRun(courseId, examId, testRunConfiguration)
🧰 Tools
🪛 GitHub Check: client-style

[warning] 93-93:
Optional chain expressions can return undefined by design - using a non-null assertion is unsafe and wrong


[warning] 93-93:
Optional chain expressions can return undefined by design - using a non-null assertion is unsafe and wrong


Line range hint 111-118: Improve error handling in deleteTestRun

Consider adding proper null checks and error handling:

deleteTestRun(testRunId: number) {
+   const courseId = this.course()?.id;
+   const examId = this.exam()?.id;
+   if (!courseId || !examId) {
+       this.dialogErrorSource.next('artemisApp.exam.error.invalidIds');
+       return;
+   }
-   this.examManagementService.deleteTestRun(this.course()!.id!, this.exam()!.id!, testRunId)
+   this.examManagementService.deleteTestRun(courseId, examId, testRunId)
🧹 Nitpick comments (3)
src/main/webapp/app/exam/manage/test-runs/test-run-management.component.ts (3)

Line range hint 1-19: Consider organizing imports by category

While the imports are functional, consider organizing them into categories for better maintainability:

  1. Angular core
  2. Angular features
  3. Application models
  4. Application services
  5. Third-party libraries
  6. Shared components/modules

35-53: Consider strengthening signal typing

The signal implementation looks good, but consider adding more specific types for better type safety:

-    course = signal<Course | undefined>(undefined);
+    readonly course = signal<Course | undefined>(undefined);
-    exam = signal<Exam | undefined>(undefined);
+    readonly exam = signal<Exam | undefined>(undefined);
-    isLoading = signal(false);
+    readonly isLoading = signal<boolean>(false);
-    testRuns = signal<StudentExam[]>([]);
+    readonly testRuns = signal<readonly StudentExam[]>([]);

The readonly modifier prevents accidental reassignment of the signal itself, while using readonly arrays prevents accidental mutations of the array reference.


130-132: LGTM with a minor suggestion

The sorting implementation is good. Consider adding type safety to the predicate:

-predicate = signal<string>('id');
+type SortPredicate = 'id' | 'user' | 'submitted';
+predicate = signal<SortPredicate>('id');
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3336f60 and a4c5605.

📒 Files selected for processing (1)
  • src/main/webapp/app/exam/manage/test-runs/test-run-management.component.ts (6 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/main/webapp/app/exam/manage/test-runs/test-run-management.component.ts (1)

Pattern src/main/webapp/**/*.ts: angular_style:https://angular.io/guide/styleguide;methods_in_html:false;lazy_loading:true;code_reuse:true;tests:meaningful;types:PascalCase;enums:PascalCase;funcs:camelCase;props:camelCase;no_priv_prefix:true;strings:single_quotes;localize:true;btns:functionality;links:navigation;icons_text:newline;labels:associate;code_style:arrow_funcs,curly_braces,open_braces_same_line,indent_4;memory_leak_prevention:true;routes:naming_schema;chart_framework:ngx-charts;responsive_layout:true

🪛 GitHub Check: client-style
src/main/webapp/app/exam/manage/test-runs/test-run-management.component.ts

[warning] 93-93:
Optional chain expressions can return undefined by design - using a non-null assertion is unsafe and wrong


[warning] 93-93:
Optional chain expressions can return undefined by design - using a non-null assertion is unsafe and wrong

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: server-tests
  • GitHub Check: client-tests
  • GitHub Check: Analyse
🔇 Additional comments (1)
src/main/webapp/app/exam/manage/test-runs/test-run-management.component.ts (1)

28-33: Well-implemented dependency injection using inject()!

Good use of the modern inject() function for dependency injection, which aligns with current Angular best practices and reduces boilerplate code.

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 5, 2025
@krusche
Copy link
Member

krusche commented Jan 12, 2025

We postpone this PR until #10124 is merged

# Conflicts:
#	src/main/webapp/app/exam/manage/test-runs/create-test-run-modal.component.ts
#	src/main/webapp/app/exam/manage/test-runs/test-run-management.component.html
#	src/main/webapp/app/exam/manage/test-runs/test-run-management.component.ts
#	src/main/webapp/app/exam/manage/test-runs/test-run-ribbon.component.ts
#	src/main/webapp/app/exam/participate/exam-participation.module.ts
#	src/test/javascript/spec/component/exam/test-run/create-test-run-modal.component.spec.ts
Copy link
Contributor

@SimonEntholzer SimonEntholzer left a comment

Choose a reason for hiding this comment

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

Code

Copy link
Contributor

@muradium muradium left a comment

Choose a reason for hiding this comment

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

Reapprove after merge conflict fixes

Copy link
Member

@BBesrour BBesrour left a comment

Choose a reason for hiding this comment

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

re-approve

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.

Reapprove

Copy link
Contributor

@ole-ve ole-ve left a comment

Choose a reason for hiding this comment

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

code-reapprove after adapting Angular 19 migration changes

@krusche krusche added this to the 7.9.1 milestone Jan 26, 2025
@krusche krusche merged commit 532157b into develop Jan 26, 2025
28 of 30 checks passed
@krusche krusche deleted the chore/test-run-module-client-migration branch January 26, 2025 10:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
client Pull requests that update TypeScript code. (Added Automatically!) ready to merge small tests
Projects
Status: Merged
Development

Successfully merging this pull request may close these issues.

9 participants