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

fix: accept no options-folder when fetching usage #14409

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

standeren
Copy link
Contributor

@standeren standeren commented Jan 13, 2025

Description

If an app does not have any option lists yet, and opening the content library, an toast error will occur. This error is triggered by backend responding with 500 when fetching usages of code lists.

This happens since the code that finds usage references fetches all option ids. When the app does not have any option lists in the options-folder, this method throws DirectoryNotFound exception which the usages endpoint does not handle.

To fix the issue, this PR returns an empty list from the GetOptionsListIds method instead of throwing an error. Then the method that iterates over the layouts to find usage will be able to handle apps that has no option lists.

Related Issue(s)

  • #{issue number}

Verification

  • Your code builds clean without any errors or warnings
  • Manual testing done (required)
  • Relevant automated test added (if you find this hard, leave it and we'll help out)

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Improved handling of option lists when no options are present in an application
    • API now returns a 200 OK status with an empty array instead of throwing an exception
  • Tests

    • Added new test cases to validate API behavior when no options are defined
    • Updated existing tests to align with new option list handling approach

The changes enhance the robustness of option list retrieval, providing a more consistent and predictable API response when no options are available.

@standeren standeren added skip-releasenotes Issues that do not make sense to list in our release notes backend area/content-library Area: Related to library for shared resources team/studio-domain1 skip-documentation Issues where updating documentation is not relevant labels Jan 13, 2025
Copy link

coderabbitai bot commented Jan 13, 2025

📝 Walkthrough

Walkthrough

The pull request introduces changes to the error handling and repository interaction in the Altinn App Development system. The modifications primarily focus on the AppDevelopmentController and AltinnAppGitRepository classes, with corresponding updates to the tests to validate the new behavior. The changes aim to improve the handling of scenarios where option lists are not present, replacing exception-based error handling with a more graceful approach of returning empty arrays or NoContent responses.

Changes

File Change Summary
backend/src/Designer/Controllers/AppDevelopmentController.cs - Modified GetOptionListIds method to check for empty option list IDs
- Removed try-catch block
- Added direct return of option list IDs or NoContent response
backend/src/Designer/Infrastructure/GitRepository/AltinnAppGitRepository.cs - Updated GetOptionsListIds method to return empty array instead of throwing NotFoundException
- Simplified error handling for non-existent options folder
backend/tests/Designer.Tests/Controllers/OptionsController/GetOptionListsReferencesTests.cs - Added new test method GetOptionListsReferences_Returns200Ok_WithEmptyOptionsReferences_WhenAppDoesNotHaveOptions
- Validates API behavior when no options are present in the application
backend/tests/Designer.Tests/Infrastructure/GitRepository/AltinnAppGitRepositoryTests.cs - Updated method GetOptionListIds_WithAppThatHasNoOptionLists to return empty list instead of throwing exception
- Changed method signature from Task to void

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added solution/studio/designer Issues related to the Altinn Studio Designer solution. quality/testing Tests that are missing, needs to be created or could be improved. labels Jan 13, 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

🧹 Nitpick comments (2)
backend/src/Designer/Infrastructure/GitRepository/AltinnAppGitRepository.cs (1)

801-801: Consider documenting the behavior change

The method now returns an empty array instead of throwing a NotFoundException when the options folder doesn't exist. This is a breaking change that should be documented in the method's XML documentation to inform callers of the new behavior.

     /// <summary>
     /// Gets a list of file names from the Options folder representing the available options lists.
     /// </summary>
+    /// <remarks>
+    /// If the options folder doesn't exist, returns an empty array instead of throwing an exception.
+    /// </remarks>
     /// <returns>A list of option list names.</returns>
     public string[] GetOptionsListIds()
backend/tests/Designer.Tests/Controllers/OptionsController/GetOptionListsReferencesTests.cs (1)

92-111: LGTM! Well-structured test for the new behavior

The test effectively validates the API's behavior when no options are present. Consider extracting the JSON layout string to a constant for better readability.

+    private const string EmptyLayout = @"{ ""data"": {""layout"": []}}";
+
     [Fact]
     public async Task GetOptionListsReferences_Returns200Ok_WithEmptyOptionsReferences_WhenAppDoesNotHaveOptions()
     {
         string targetRepository = TestDataHelper.GenerateTestRepoName();
         await CopyRepositoryForTest("ttd", RepoWithoutOptions, "testUser", targetRepository);
         string repoPath = TestDataHelper.GetTestDataRepositoryDirectory("ttd", targetRepository, "testUser");
-        string exampleLayout = @"{ ""data"": {""layout"": []}}";
         string filePath = Path.Combine(repoPath, "App/ui/form/layouts");
         Directory.CreateDirectory(filePath);
-        await File.WriteAllTextAsync(Path.Combine(filePath, "exampleLayout.json"), exampleLayout);
+        await File.WriteAllTextAsync(Path.Combine(filePath, "exampleLayout.json"), EmptyLayout);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aa46b72 and 6b734e8.

📒 Files selected for processing (3)
  • backend/src/Designer/Controllers/AppDevelopmentController.cs (1 hunks)
  • backend/src/Designer/Infrastructure/GitRepository/AltinnAppGitRepository.cs (1 hunks)
  • backend/tests/Designer.Tests/Controllers/OptionsController/GetOptionListsReferencesTests.cs (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Run dotnet build and test (macos-latest)
  • GitHub Check: Build environment and run e2e test
  • GitHub Check: Run dotnet build and test (windows-latest)
  • GitHub Check: Analyze
  • GitHub Check: Run dotnet build and test (ubuntu-latest)
  • GitHub Check: Run integration tests against actual gitea and db
🔇 Additional comments (1)
backend/src/Designer/Controllers/AppDevelopmentController.cs (1)

550-557: LGTM! Clean implementation of the empty options case

The implementation correctly handles the case where no options are available by returning a 204 No Content response.

@standeren standeren force-pushed the 500-from-usage-when-app-lacks-option-lists branch from 6b734e8 to 8df70a0 Compare January 13, 2025 13:11
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

🧹 Nitpick comments (1)
backend/tests/Designer.Tests/Controllers/OptionsController/GetOptionListsReferencesTests.cs (1)

92-111: Good test coverage for the empty options scenario.

The test effectively validates the behavior when an app has no options, which directly addresses the PR objective.

Consider these improvements:

  1. Add cleanup code to remove the test repository after the test completes
  2. Move the hardcoded layout JSON to a constant or test data file
  3. Add a test case for invalid repository scenario

Example cleanup implementation:

 public async Task GetOptionListsReferences_Returns200Ok_WithEmptyOptionsReferences_WhenAppDoesNotHaveOptions()
 {
     string targetRepository = TestDataHelper.GenerateTestRepoName();
+    try
+    {
         await CopyRepositoryForTest("ttd", RepoWithoutOptions, "testUser", targetRepository);
         string repoPath = TestDataHelper.GetTestDataRepositoryDirectory("ttd", targetRepository, "testUser");
         string exampleLayout = @"{ ""data"": {""layout"": []}}";
         string filePath = Path.Combine(repoPath, "App/ui/form/layouts");
         Directory.CreateDirectory(filePath);
         await File.WriteAllTextAsync(Path.Combine(filePath, "exampleLayout.json"), exampleLayout);

         string apiUrl = $"/designer/api/ttd/{targetRepository}/options/usage";
         using HttpRequestMessage httpRequestMessage = new(HttpMethod.Get, apiUrl);

         using HttpResponseMessage response = await HttpClient.SendAsync(httpRequestMessage);
         string responseBody = await response.Content.ReadAsStringAsync();

         Assert.Equal(StatusCodes.Status200OK, (int)response.StatusCode);
         Assert.Equivalent("[]", responseBody);
+    }
+    finally
+    {
+        // Clean up the test repository
+        string repoPath = TestDataHelper.GetTestDataRepositoryDirectory("ttd", targetRepository, "testUser");
+        if (Directory.Exists(repoPath))
+        {
+            Directory.Delete(repoPath, recursive: true);
+        }
+    }
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6b734e8 and 8df70a0.

📒 Files selected for processing (4)
  • backend/src/Designer/Controllers/AppDevelopmentController.cs (1 hunks)
  • backend/src/Designer/Infrastructure/GitRepository/AltinnAppGitRepository.cs (1 hunks)
  • backend/tests/Designer.Tests/Controllers/OptionsController/GetOptionListsReferencesTests.cs (3 hunks)
  • backend/tests/Designer.Tests/Infrastructure/GitRepository/AltinnAppGitRepositoryTests.cs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/src/Designer/Controllers/AppDevelopmentController.cs
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Build environment and run e2e test
  • GitHub Check: Run dotnet build and test (macos-latest)
  • GitHub Check: Run dotnet build and test (windows-latest)
  • GitHub Check: Run integration tests against actual gitea and db
  • GitHub Check: Run dotnet build and test (ubuntu-latest)
  • GitHub Check: Analyze
🔇 Additional comments (3)
backend/tests/Designer.Tests/Infrastructure/GitRepository/AltinnAppGitRepositoryTests.cs (1)

299-306: LGTM! Test correctly validates the new behavior.

The test has been properly updated to verify that GetOptionsListIds returns an empty array when no options folder exists, which aligns with the PR's objective of handling missing options gracefully.

backend/src/Designer/Infrastructure/GitRepository/AltinnAppGitRepository.cs (1)

801-801: LGTM! Implementation correctly handles missing options folder.

The change to return an empty array instead of throwing an exception when the options folder doesn't exist is a good improvement in error handling. This aligns with the principle that the absence of options is a valid state, not an error condition.

backend/tests/Designer.Tests/Controllers/OptionsController/GetOptionListsReferencesTests.cs (1)

19-19: LGTM! Clear and consistent constant naming.

The constant follows the existing naming pattern and clearly indicates its purpose.

@ErlingHauan ErlingHauan self-assigned this Jan 13, 2025
Copy link
Contributor

@ErlingHauan ErlingHauan left a comment

Choose a reason for hiding this comment

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

Nice 🙌

@ErlingHauan ErlingHauan removed their assignment Jan 13, 2025
Copy link

codecov bot commented Jan 15, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 95.66%. Comparing base (60ea6c6) to head (5d51b31).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14409   +/-   ##
=======================================
  Coverage   95.66%   95.66%           
=======================================
  Files        1880     1880           
  Lines       24446    24446           
  Branches     2810     2810           
=======================================
  Hits        23386    23386           
  Misses        800      800           
  Partials      260      260           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area/content-library Area: Related to library for shared resources backend quality/testing Tests that are missing, needs to be created or could be improved. skip-documentation Issues where updating documentation is not relevant skip-releasenotes Issues that do not make sense to list in our release notes solution/studio/designer Issues related to the Altinn Studio Designer solution. team/studio-domain1
Projects
Status: 🧪 Test
Development

Successfully merging this pull request may close these issues.

2 participants