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: add helper method to check if version is below or equal to a specific version #14812

Conversation

Jondyr
Copy link
Member

@Jondyr Jondyr commented Feb 26, 2025

Description

Adds a new helper function to check if semantic version is below or equal to a version, and only returns empty string for 8.0.0-preview.15 or below.

Related Issue(s)

Issue thread from slack: https://digdir.slack.com/archives/C0760NPT2BE/p1740395650522149

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)

Documentation

  • User documentation is updated with a separate linked PR in altinn-studio-docs. (if applicable)

Summary by CodeRabbit

  • New Features
    • Introduced a new helper that standardizes package version outputs.
  • Refactor
    • Streamlined version handling by removing deprecated logic.
  • Tests
    • Added comprehensive tests to validate the version output across various scenarios.

Copy link
Contributor

coderabbitai bot commented Feb 26, 2025

📝 Walkthrough

Walkthrough

The pull request removes version-handling constants and a method from the PreviewController and updates its logic to delegate NuGet version processing to a new helper class. A new static class, NugetVersionHelper, is introduced to encapsulate the version validation and mocking functionality. Additionally, a corresponding test class, NugetVersionHelperTests, verifies that the helper returns the expected outputs for various version strings.

Changes

File(s) Change Summary
backend/src/.../PreviewController.cs Removed constants MINIMUM_NUGET_VERSION, MINIMUM_PREVIEW_NUGET_VERSION and the method GetMockedAltinnNugetBuildFromVersion. Updated to call NugetVersionHelper.GetMockedAltinnNugetBuildFromVersion instead.
backend/src/.../NugetVersionHelper.cs Added a new static helper class NugetVersionHelper with the method GetMockedAltinnNugetBuildFromVersion and private methods for version validation and comparison.
backend/tests/.../NugetVersionHelperTests.cs Added a new test class NugetVersionHelperTests containing tests to assert correct behavior of the version helper method with various version strings.

Suggested labels

solution/platform

Suggested reviewers

  • Ahmed-Ghanam
  • SandGrainOne

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c5f58d9 and 8bcbb4b.

📒 Files selected for processing (1)
  • backend/tests/Designer.Tests/Helpers/Preview/NugetVersionHelperTests.cs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/tests/Designer.Tests/Helpers/Preview/NugetVersionHelperTests.cs
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • 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 dotnet build and test (ubuntu-latest)

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.
  • @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 area/app-preview Area: Related to test and preview of apps that are developed in Altinn Studio. 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. backend labels Feb 26, 2025
@Jondyr Jondyr added team/studio-core kind/bug Used when there is a defect / something is not working as it should. backend and removed area/app-preview Area: Related to test and preview of apps that are developed in Altinn Studio. 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. backend labels Feb 26, 2025
Copy link
Contributor

coderabbitai bot commented Feb 26, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@github-actions github-actions bot added area/app-preview Area: Related to test and preview of apps that are developed in Altinn Studio. 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 Feb 26, 2025
@Jondyr Jondyr marked this pull request as ready for review February 26, 2025 10:54
@Jondyr Jondyr force-pushed the fix/applicationmetadata-version-mock-breaks-for-preview-after-v4 branch from c5f58d9 to 8bcbb4b Compare February 26, 2025 10:56
Copy link
Contributor

@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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently, please check "Code review limits" under "Moderation" settings.

Actionable comments posted: 5

🧹 Nitpick comments (4)
backend/tests/Designer.Tests/Helpers/Preview/NugetVersionHelperTests.cs (2)

10-11: Add summary documentation to test method.

The test method name is descriptive, but adding an XML documentation comment would improve clarity about what's being tested and why.

         [Fact]
+        /// <summary>
+        /// Tests that GetMockedAltinnNugetBuildFromVersion returns an empty string for versions below or equal to 8.0.0-preview.14,
+        /// and returns "8.0.0.0" for versions above that threshold.
+        /// </summary>
         public void GetMockedAltinnNugetBuildFromVersion_ShouldReturnEmptyStringForVersionsBelowBreakpoint()

12-22: Remove duplicated assertion and improve test organization.

There's a duplicated assertion on line 18, and the test mixes assertions for different outcomes (empty string vs "8.0.0.0"). Consider restructuring the test for better clarity.

         {
-            Assert.Equal("", NugetVersionHelper.GetMockedAltinnNugetBuildFromVersion("1.1.1"));
-            Assert.Equal("", NugetVersionHelper.GetMockedAltinnNugetBuildFromVersion("1.1.1-preview.150"));
-            Assert.Equal("", NugetVersionHelper.GetMockedAltinnNugetBuildFromVersion("1.1.1-preview.0"));
-            Assert.Equal("8.0.0.0", NugetVersionHelper.GetMockedAltinnNugetBuildFromVersion("8.1.1-preview.14"));
-            Assert.Equal("8.0.0.0", NugetVersionHelper.GetMockedAltinnNugetBuildFromVersion("8.8.8-preview.0"));
-            Assert.Equal("8.0.0.0", NugetVersionHelper.GetMockedAltinnNugetBuildFromVersion("8.18.1238"));
-            Assert.Equal("8.0.0.0", NugetVersionHelper.GetMockedAltinnNugetBuildFromVersion("8.18.1238"));
-            Assert.Equal("8.0.0.0", NugetVersionHelper.GetMockedAltinnNugetBuildFromVersion("8.8.8-preview.342"));
-            Assert.Equal("8.0.0.0", NugetVersionHelper.GetMockedAltinnNugetBuildFromVersion("8.0.0-preview.15"));
-            Assert.Equal("", NugetVersionHelper.GetMockedAltinnNugetBuildFromVersion("8.0.0-preview.14"));
+            // Versions that should return an empty string
+            string[] versionsExpectingEmpty = new[]
+            {
+                "1.1.1",
+                "1.1.1-preview.150",
+                "1.1.1-preview.0",
+                "8.0.0-preview.14"
+            };
+            
+            foreach (string version in versionsExpectingEmpty)
+            {
+                Assert.Equal("", NugetVersionHelper.GetMockedAltinnNugetBuildFromVersion(version), $"Version {version} should return empty string");
+            }
+            
+            // Versions that should return the minimum nuget version
+            string[] versionsExpectingMinimumVersion = new[]
+            {
+                "8.1.1-preview.14",
+                "8.8.8-preview.0",
+                "8.18.1238",
+                "8.8.8-preview.342",
+                "8.0.0-preview.15"
+            };
+            
+            foreach (string version in versionsExpectingMinimumVersion)
+            {
+                Assert.Equal("8.0.0.0", NugetVersionHelper.GetMockedAltinnNugetBuildFromVersion(version), $"Version {version} should return minimum nuget version");
+            }
         }
backend/src/Designer/Helpers/Preview/NugetVersionHelper.cs (2)

38-41: Improve version validation to handle edge cases.

The current validation only checks for minimum length and major version, but doesn't verify if the version parts are valid integers.

        private static bool IsValidSemVerVersion(string[] versionParts)
        {
-            return versionParts.Length >= 3 && Convert.ToInt32(versionParts[0]) >= 8;
+            if (versionParts.Length < 3)
+            {
+                return false;
+            }
+            
+            // Check if first part (major version) is valid and >= 8
+            if (!int.TryParse(versionParts[0], out int majorVersion) || majorVersion < 8)
+            {
+                return false;
+            }
+            
+            // Check if other required parts are valid integers
+            return versionParts.Take(3).All(part => int.TryParse(part.Split('-')[0], out _));
        }

43-57: Consider modern validation approach instead of Code Contracts.

The Contract.Requires statements are part of Code Contracts which is not being actively developed. Consider using guard clauses instead.

        // <exception cref="FormatException"></exception>
        // <exception cref="OverflowException"></exception>
        private static bool IsVersionOrBelow(int[] versionParts, int[] breakpoint)
        {
-            Contract.Requires(versionParts.Length == 3);
-            Contract.Requires(breakpoint.Length == 3);
+            if (versionParts.Length != 3 || breakpoint.Length != 3)
+            {
+                throw new ArgumentException("Version arrays must have exactly 3 elements");
+            }
+            
            for (int i = 0; i < 3; i++)
            {
                if (versionParts[i] > breakpoint[i])
                {
                    return false;
                }
            }
            return true;
        }
🛑 Comments failed to post (5)
backend/tests/Designer.Tests/Helpers/Preview/NugetVersionHelperTests.cs (1)

1-3: ⚠️ Potential issue

Fix imports ordering to comply with code style.

The pipeline failure indicates an issue with imports ordering.

-using Xunit;
-using Altinn.Studio.Designer.Helpers.Preview;
+using Altinn.Studio.Designer.Helpers.Preview;
+using Xunit;
📝 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.

using Altinn.Studio.Designer.Helpers.Preview;
using Xunit;
🧰 Tools
🪛 GitHub Actions: Dotnet format check

[error] 1-1: IMPORTS: Fix imports ordering.

backend/src/Designer/Helpers/Preview/NugetVersionHelper.cs (4)

64-67: ⚠️ Potential issue

Add error handling to GetPreviewVersion.

The method assumes the preview version number is always in the fourth element and is a valid integer.

        private static int GetPreviewVersion(string[] versionParts)
        {
-            return Convert.ToInt32(versionParts[3]);
+            if (versionParts.Length < 4)
+            {
+                return 0; // Default to 0 if preview version not specified
+            }
+
+            try
+            {
+                return Convert.ToInt32(versionParts[3]);
+            }
+            catch (FormatException)
+            {
+                return 0; // Return default if conversion fails
+            }
+            catch (OverflowException)
+            {
+                return 0; // Return default if number is too large
+            }
        }
📝 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.

        private static int GetPreviewVersion(string[] versionParts)
        {
            if (versionParts.Length < 4)
            {
                return 0; // Default to 0 if preview version not specified
            }

            try
            {
                return Convert.ToInt32(versionParts[3]);
            }
            catch (FormatException)
            {
                return 0; // Return default if conversion fails
            }
            catch (OverflowException)
            {
                return 0; // Return default if number is too large
            }
        }

19-26: ⚠️ Potential issue

Add null check for the version parameter.

The method doesn't handle null or empty version strings, which could cause a NullReferenceException.

        public static string GetMockedAltinnNugetBuildFromVersion(string version)
        {
+            if (string.IsNullOrEmpty(version))
+            {
+                return string.Empty;
+            }

            string[] versionParts = version.Split('.');
            if (!IsValidSemVerVersion(versionParts))
            {
                return string.Empty;
            }
📝 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.

        public static string GetMockedAltinnNugetBuildFromVersion(string version)
        {
            if (string.IsNullOrEmpty(version))
            {
                return string.Empty;
            }

            string[] versionParts = version.Split('.');
            if (!IsValidSemVerVersion(versionParts))
            {
                return string.Empty;
            }

59-62: 🛠️ Refactor suggestion

Make IsPreviewVersion more robust.

The current implementation assumes specific structure and doesn't handle edge cases.

        private static bool IsPreviewVersion(string[] versionParts)
        {
-            return versionParts[2].Contains("-preview") && versionParts.Length == 4;
+            // Check if we have enough parts and third part contains preview designation
+            return versionParts.Length >= 3 && 
+                  versionParts[2].Contains("-preview") && 
+                  versionParts.Length == 4; // Last check ensures we have preview number
        }
📝 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.

        private static bool IsPreviewVersion(string[] versionParts)
        {
            // Check if we have enough parts and third part contains preview designation
            return versionParts.Length >= 3 && 
                  versionParts[2].Contains("-preview") && 
                  versionParts.Length == 4; // Last check ensures we have preview number
        }

28-36: 🛠️ Refactor suggestion

Consider breaking down complex condition and adding exception handling for the conversion.

The current implementation has a complex condition and lacks error handling for the numeric conversion, which could lead to runtime exceptions.

            string normalVersion = version.Split('-').First();
-            int[] numberVersion = [.. normalVersion.Split('.').Take(3).Select((split) => Convert.ToInt32(split))];
-            if (IsVersionOrBelow(numberVersion, [8, 0, 0]) && IsPreviewVersion(versionParts) && GetPreviewVersion(versionParts) < MINIMUM_PREVIEW_NUGET_VERSION)
+            
+            try 
+            {
+                int[] numberVersion = normalVersion.Split('.')
+                    .Take(3)
+                    .Select(split => Convert.ToInt32(split))
+                    .ToArray();
+                
+                bool isBelowOrEqualToBreakpoint = IsVersionOrBelow(numberVersion, new int[] { 8, 0, 0 });
+                bool isPreviewVersion = IsPreviewVersion(versionParts);
+                bool isBelowMinimumPreviewVersion = isPreviewVersion && GetPreviewVersion(versionParts) < MINIMUM_PREVIEW_NUGET_VERSION;
+                
+                if (isBelowOrEqualToBreakpoint && isBelowMinimumPreviewVersion)
+                {
+                    return string.Empty;
+                }
+            }
+            catch (FormatException)
+            {
+                // Invalid version format, return empty
+                return string.Empty;
+            }
+            catch (OverflowException)
+            {
+                // Version number too large, return empty
+                return string.Empty;
+            }
            {
                return string.Empty;
            }

            return MINIMUM_NUGET_VERSION;

Committable suggestion skipped: line range outside the PR's diff.

@framitdavid framitdavid added the skip-manual-testing PRs that do not need to be tested manually label Feb 26, 2025
@framitdavid framitdavid merged commit d5e44f1 into main Feb 26, 2025
22 checks passed
@framitdavid framitdavid deleted the fix/applicationmetadata-version-mock-breaks-for-preview-after-v4 branch February 26, 2025 14:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area/app-preview Area: Related to test and preview of apps that are developed in Altinn Studio. backend kind/bug Used when there is a defect / something is not working as it should. quality/testing Tests that are missing, needs to be created or could be improved. skip-manual-testing PRs that do not need to be tested manually solution/studio/designer Issues related to the Altinn Studio Designer solution. team/studio-core
Projects
Status: ✅ Done
Development

Successfully merging this pull request may close these issues.

2 participants