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

chore: Add parameter for soft wrapping in ASCII table #1232

Merged
merged 13 commits into from
Oct 7, 2024

Conversation

elsand
Copy link
Member

@elsand elsand commented Oct 7, 2024

Description

This introduces a soft-wrap parameter specifying the desired number of columns, and handling of linebreaks within the values in the tables. In short, instead of this:

o-------------o-----------o---------------o-------o----------------------------------------------------------------------------------------------------------------------------------------------------------------------------o
| Environment | Type      | SeverityLevel | Count | Details                                                                                                                                                                    |
o-------------o-----------o---------------o-------o----------------------------------------------------------------------------------------------------------------------------------------------------------------------------o
| test        | exception | Warning       | 4     | Infrastructure.Common.Exceptions.UpstreamServiceException at Infrastructure.Altinn.Authorization.AltinnAuthorizationClient+<PerformAuthorizedPartiesRequest>d__13.MoveNext |
| test        | exception |               | 4     | Infrastructure.Common.Exceptions.UpstreamServiceException at Infrastructure.Altinn.Authorization.AltinnAuthorizationClient+<PerformAuthorizedPartiesRequest>d__13.MoveNext |
| test        | trace     | Error         | 1     | HTTP POST /graphql responded 500 in 317.4673 ms                                                                                                                            |
| test        | trace     | Error         | 1     | HTTP POST /graphql responded 500 in 303.5542 ms                                                                                                                            |
| test        | trace     | Error         | 1     | HTTP POST /graphql responded 500 in 32.5378 ms                                                                                                                             |
| test        | trace     | Error         | 1     | HTTP POST /graphql responded 500 in 26.8092 ms                                                                                                                             |
o-------------o-----------o---------------o-------o----------------------------------------------------------------------------------------------------------------------------------------------------------------------------o

o-------------o-----------o---------------o-------o-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------o
| Environment | Type      | SeverityLevel | Count | Details                                                                                                                                                                                                                                   |
o-------------o-----------o---------------o-------o-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------o
|             | exception | Error         | 2     | Npgsql.PostgresException at Npgsql.Internal.NpgsqlConnector+<ReadMessageLong>d__233.MoveNext                                                                                                                                              |
|             | trace     | Error         | 2     | Failed executing DbCommand (18ms) [Parameters=[], CommandType='"Text"', CommandTimeout='30']
SELECT max(COALESCE(s."UpdatedAt", TIMESTAMPTZ '-infinity'))
FROM (
    SELECT NULL AS empty
) AS e
LEFT JOIN "SubjectResource" AS s ON TRUE |
o-------------o-----------o---------------o-------o-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------o

we get this:

o-------------o-----------o---------------o-------o---------------------------------------------------------------------------------------------------------------o
| Environment | Type      | SeverityLevel | Count | Details                                                                                                       |
o-------------o-----------o---------------o-------o---------------------------------------------------------------------------------------------------------------o
| test        | exception | Warning       |     4 | Infrastructure.Common.Exceptions.UpstreamServiceException at                                                  |
|             |           |               |       | Infrastructure.Altinn.Authorization.AltinnAuthorizationClient+<PerformAuthorizedPartiesRequest>d__13.MoveNext |
o-------------o-----------o---------------o-------o---------------------------------------------------------------------------------------------------------------o
| test        | exception |               |     4 | Infrastructure.Common.Exceptions.UpstreamServiceException at                                                  |
|             |           |               |       | Infrastructure.Altinn.Authorization.AltinnAuthorizationClient+<PerformAuthorizedPartiesRequest>d__13.MoveNext |
o-------------o-----------o---------------o-------o---------------------------------------------------------------------------------------------------------------o
| test        | trace     | Error         |     1 | HTTP POST /graphql responded 500 in 303.5542 ms                                                               |
o-------------o-----------o---------------o-------o---------------------------------------------------------------------------------------------------------------o
| test        | trace     | Error         |     1 | HTTP POST /graphql responded 500 in 32.5378 ms                                                                |
o-------------o-----------o---------------o-------o---------------------------------------------------------------------------------------------------------------o
| test        | trace     | Error         |     1 | HTTP POST /graphql responded 500 in 26.8092 ms                                                                |
o-------------o-----------o---------------o-------o---------------------------------------------------------------------------------------------------------------o

o-------------o-----------o---------------o-------o----------------------------------------------------------------------------------------------o
| Environment | Type      | SeverityLevel | Count | Details                                                                                      |
o-------------o-----------o---------------o-------o----------------------------------------------------------------------------------------------o
|             | exception | Error         |     2 | Npgsql.PostgresException at Npgsql.Internal.NpgsqlConnector+<ReadMessageLong>d__233.MoveNext |
o-------------o-----------o---------------o-------o----------------------------------------------------------------------------------------------o
|             | trace     | Error         |     1 | Failed executing DbCommand (17ms) [Parameters=[], CommandType='"Text"', CommandTimeout='30'] |
|             |           |               |       | SELECT                                                                                       |
|             |           |               |       | max(COALESCE(s."UpdatedAt", TIMESTAMPTZ '-infinity'))                                        |
|             |           |               |       | FROM (                                                                                       |
|             |           |               |       |     SELECT NULL AS empty                                                                     |
|             |           |               |       | ) AS e                                                                                       |
|             |           |               |       | LEFT                                                                                         |
|             |           |               |       | JOIN "SubjectResource" AS s ON TRUE                                                          |
o-------------o-----------o---------------o-------o----------------------------------------------------------------------------------------------o

This will make copy/pasting from Slack harder, but will increase readability. It is assumed that copy/pasting can be done from Application Insights.

Note that it will not break long words (strings) without spaces, regardless of column max width, so for the above examples the effective max col width is 109 (ie. the length of Infrastructure.Altinn.Authorization.AltinnAuthorizationClient+<PerformAuthorizedPartiesRequest>d__13.MoveNext)

Much of this code is courtesy of ChatGPT.

Related Issue(s)

  • N/A}

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

  • Documentation is updated (either in docs-directory, Altinnpedia or a separate linked PR in altinn-studio-docs., if applicable)

Summary by CodeRabbit

  • New Features

    • Enhanced ASCII table formatting with support for multi-line cell content.
    • Introduced a parameter to specify maximum column width for better table layout.
    • Added a new test project to validate the functionality of the ASCII table formatter.
  • Bug Fixes

    • Updated exception report generation to accommodate new column width settings, improving output formatting.
  • Tests

    • Implemented a comprehensive suite of unit tests for the AsciiTableFormatter class, covering various scenarios for the ToAsciiTable method.

@elsand elsand requested a review from a team as a code owner October 7, 2024 07:16
Copy link
Contributor

coderabbitai bot commented Oct 7, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request enhance the AsciiTableFormatter class's ToAsciiTable method by adding a maxColumnWidth parameter, which allows for better control over column widths when formatting ASCII tables. A new method, AddLineBreaks, has been introduced to handle multi-line cell content. The ToAsciiTableExceptionReport method in the Extensions class has been updated to call the modified ToAsciiTable method with the new parameter. Additionally, a new test project has been added to validate these changes through unit tests.

Changes

File Path Change Summary
src/Digdir.Tool.Dialogporten.SlackNotifier/Common/AsciiTableFormatter.cs Updated ToAsciiTable method to include maxColumnWidth parameter; modified internal logic for multi-line cell content; added AddLineBreaks method.
src/Digdir.Tool.Dialogporten.SlackNotifier/Common/Extensions.cs Updated ToAsciiTableExceptionReport method to call ToAsciiTable with maxColumnWidth set to 72.
Digdir.Domain.Dialogporten.sln Added new project Digdir.Tool.Dialogporten.SlackNotifier.Tests for unit testing.
tests/Digdir.Tool.Dialogporten.SlackNotifier.Tests/AsciiTableFormatterTests.cs Introduced unit tests for AsciiTableFormatter class covering various scenarios for the ToAsciiTable method.
tests/Digdir.Tool.Dialogporten.SlackNotifier.Tests/Digdir.Tool.Dialogporten.SlackNotifier.Tests.csproj Created project file for the test project targeting .NET 8.0 with necessary references for testing.

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

@elsand elsand changed the title Add parameter for soft wrapping in ASCII table chore: Add parameter for soft wrapping in ASCII table Oct 7, 2024
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.

Actionable comments posted: 4

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between ed85bc4 and a25cd20.

📒 Files selected for processing (2)
  • src/Digdir.Tool.Dialogporten.SlackNotifier/Common/AsciiTableFormatter.cs (3 hunks)
  • src/Digdir.Tool.Dialogporten.SlackNotifier/Common/Extensions.cs (1 hunks)
🧰 Additional context used
🔇 Additional comments (1)
src/Digdir.Tool.Dialogporten.SlackNotifier/Common/Extensions.cs (1)

14-14: Approve change and suggest improvements

The addition of maxColumnWidth: 72 to the ToAsciiTable method call aligns well with the PR objectives of introducing soft wrapping in ASCII tables. This change should improve readability by wrapping long text entries.

However, to ensure the robustness of this new feature, consider the following suggestions:

  1. Add unit tests to verify the new formatting behavior with various input scenarios, including edge cases.
  2. Update the documentation to reflect this new feature and its usage.
  3. Could you provide more context on why 72 was chosen as the max column width? Is this value configurable, and does it work well for all expected use cases?

To verify the impact of this change, let's check for any other usages of ToAsciiTable that might need similar updates:

✅ Verification successful

Consistent maxColumnWidth Usage Confirmed

The update to use maxColumnWidth: 72 in Extensions.cs is the only change found. All other usages of ToAsciiTable continue to use the default maxColumnWidth: 30, ensuring no unintended side effects in different parts of the codebase.

Consider documenting the rationale behind choosing 72 as the maximum column width to aid future maintenance and clarity.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other usages of ToAsciiTable method
rg --type csharp "ToAsciiTable\(" -C 3

Length of output: 2252

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.

Actionable comments posted: 5

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between a25cd20 and feaf015.

📒 Files selected for processing (1)
  • src/Digdir.Tool.Dialogporten.SlackNotifier/Common/AsciiTableFormatter.cs (3 hunks)
🧰 Additional context used

elsand and others added 4 commits October 7, 2024 09:25
…rmatter.cs

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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.

Actionable comments posted: 6

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between feaf015 and 7a50fbb.

📒 Files selected for processing (4)
  • Digdir.Domain.Dialogporten.sln (3 hunks)
  • src/Digdir.Tool.Dialogporten.SlackNotifier/Common/AsciiTableFormatter.cs (2 hunks)
  • tests/Digdir.Tool.Dialogporten.SlackNotifier.Tests/AsciiTableFormatterTests.cs (1 hunks)
  • tests/Digdir.Tool.Dialogporten.SlackNotifier.Tests/Digdir.Tool.Dialogporten.SlackNotifier.Tests.csproj (1 hunks)
🧰 Additional context used
📓 Learnings (1)
src/Digdir.Tool.Dialogporten.SlackNotifier/Common/AsciiTableFormatter.cs (2)
Learnt from: elsand
PR: digdir/dialogporten#1232
File: src/Digdir.Tool.Dialogporten.SlackNotifier/Common/AsciiTableFormatter.cs:0-0
Timestamp: 2024-10-07T07:45:33.970Z
Learning: The `ToAsciiTable` method creates a copy of the input `rows` and operates on it, so the original `rows` passed to the method remains unchanged.
Learnt from: elsand
PR: digdir/dialogporten#1232
File: src/Digdir.Tool.Dialogporten.SlackNotifier/Common/AsciiTableFormatter.cs:12-12
Timestamp: 2024-10-07T07:31:46.700Z
Learning: In C# 12, square brackets `[]` can be used for array initialization, e.g., `string[] array = [ "value" ];`.
🔇 Additional comments (9)
tests/Digdir.Tool.Dialogporten.SlackNotifier.Tests/Digdir.Tool.Dialogporten.SlackNotifier.Tests.csproj (3)

1-10: LGTM: Project configuration is well-structured.

The project is correctly set up as a .NET 8.0 test project with appropriate settings:

  • Implicit usings and nullable reference types are enabled, which are good practices.
  • The project is correctly marked as non-packable and a test project.

19-21: LGTM: Global using statement for xUnit is appropriate.

The global using statement for Xunit is a convenient approach, consistent with the project's use of implicit usings. This will make xUnit assertions available throughout the test project without requiring explicit imports in each file.


23-25: LGTM: Project reference to the main Slack Notifier project is included.

The project reference seems correct, allowing the test project to access and test the main project's code.

To ensure the project structure is correct, please run the following script:

✅ Verification successful

Verified: Referenced project file exists.

The project reference is confirmed to be valid.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence of the referenced project file

# Test: Check if the referenced project file exists
if fd -p "src/Digdir.Tool.Dialogporten.SlackNotifier/Digdir.Tool.Dialogporten.SlackNotifier.csproj"; then
    echo "Referenced project file found."
else
    echo "Warning: Referenced project file not found. Please verify the project structure."
fi

Length of output: 256

tests/Digdir.Tool.Dialogporten.SlackNotifier.Tests/AsciiTableFormatterTests.cs (2)

7-34: LGTM: Well-structured test for text wrapping

This test case effectively verifies the text wrapping functionality when the content exceeds the specified maximum column width. The arrangement, action, and assertion are clear and appropriate.


63-88: LGTM: Proper null handling test

This test case effectively verifies that null values in cells are handled gracefully. It's crucial for ensuring robustness in the ToAsciiTable method when dealing with potentially null data.

Digdir.Domain.Dialogporten.sln (2)

66-67: Summary of changes to the solution file

The changes to the Digdir.Domain.Dialogporten.sln file are minimal and focused:

  1. A new test project Digdir.Tool.Dialogporten.SlackNotifier.Tests has been added.
  2. The project is correctly configured with Debug and Release build settings.
  3. It's properly nested under the "tests" section of the solution.

These changes enhance the project structure by adding dedicated tests for the SlackNotifier tool, which is a positive step towards improving code quality and maintainability.

Also applies to: 158-161, 191-191


66-67: New test project added: Digdir.Tool.Dialogporten.SlackNotifier.Tests

The addition of a new test project for the SlackNotifier tool is a positive change. It suggests an improvement in test coverage, which aligns with best practices for maintaining code quality.

A few observations:

  1. The project is correctly added to the "tests" section of the solution.
  2. Both Debug and Release configurations are properly set up for the new project.
  3. The project GUID is unique, which is correct.

To ensure the new test project is properly set up, please run the following script:

This script will help verify that the new test project is properly structured and references the necessary components.

Also applies to: 158-161, 191-191

✅ Verification successful

Verification Successful: Digdir.Tool.Dialogporten.SlackNotifier.Tests

The new test project has been successfully added and properly configured. The project file exists, includes the necessary test framework reference, and correctly references the main SlackNotifier project.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the existence and basic structure of the new test project

# Check if the project file exists
fd -p "tests/Digdir.Tool.Dialogporten.SlackNotifier.Tests/Digdir.Tool.Dialogporten.SlackNotifier.Tests.csproj"

# Check for basic test setup (e.g., reference to test framework)
rg -i "Microsoft\.NET\.Test\.Sdk" "tests/Digdir.Tool.Dialogporten.SlackNotifier.Tests/Digdir.Tool.Dialogporten.SlackNotifier.Tests.csproj"

# Check for reference to the main project
rg -i "Digdir\.Tool\.Dialogporten\.SlackNotifier" "tests/Digdir.Tool.Dialogporten.SlackNotifier.Tests/Digdir.Tool.Dialogporten.SlackNotifier.Tests.csproj"

Length of output: 717

src/Digdir.Tool.Dialogporten.SlackNotifier/Common/AsciiTableFormatter.cs (2)

42-42: Correctly handle null cell values

Great job updating the code to safely handle null values by using the null-conditional operator ?.. This prevents potential NullReferenceException when processing cell content.


7-10: 💡 Codebase verification

Update Required for ToAsciiTable Usage in Extensions.cs

  • src/Digdir.Tool.Dialogporten.SlackNotifier/Common/Extensions.cs: The ToAsciiTable() method is called without specifying the maxColumnWidth parameter.
🔗 Analysis chain

Ensure all usages of ToAsciiTable are updated with the new parameter

The ToAsciiTable method now includes an optional maxColumnWidth parameter. Please verify that all calls to this method throughout the codebase are reviewed to determine if they need to specify this parameter explicitly, especially if they rely on a different column width.

Run the following script to find all usages of ToAsciiTable and check if the maxColumnWidth parameter is correctly handled:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all usages of ToAsciiTable and review if maxColumnWidth parameter is properly utilized.

# Search for calls to the ToAsciiTable extension method
rg --type csharp -A 2 -B 2 '\.ToAsciiTable\('

Length of output: 4160

⛔ Skipped due to learnings
Learnt from: elsand
PR: digdir/dialogporten#1232
File: src/Digdir.Tool.Dialogporten.SlackNotifier/Common/AsciiTableFormatter.cs:0-0
Timestamp: 2024-10-07T07:45:33.970Z
Learning: The `ToAsciiTable` method creates a copy of the input `rows` and operates on it, so the original `rows` passed to the method remains unchanged.
Learnt from: elsand
PR: digdir/dialogporten#1232
File: src/Digdir.Tool.Dialogporten.SlackNotifier/Common/AsciiTableFormatter.cs:12-12
Timestamp: 2024-10-07T07:31:46.700Z
Learning: In C# 12, square brackets `[]` can be used for array initialization, e.g., `string[] array = [ "value" ];`.

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.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (7)
tests/Digdir.Tool.Dialogporten.SlackNotifier.Tests/AsciiTableFormatterTests.cs (7)

7-34: LGTM: Well-structured test for text wrapping

This test effectively verifies that text exceeding the maximum column width is wrapped correctly. The expected output accurately represents the desired behavior.

Consider adding an additional assertion to explicitly check the width of each line:

Assert.True(result.Split('\n').All(line => line.Length <= maxColumnWidth + 2), "All lines should be within the maximum width (including border characters)");

This would provide an extra layer of validation for the wrapping behavior.


36-61: Consider adding a test for multiple long words

This test effectively verifies that a single long word is not broken when it exceeds the maximum column width. To further strengthen this test suite, consider adding a case with multiple long words in a single cell. This would ensure that the wrapping behavior is correct when dealing with a mix of long and short words.

Example:

var rows = new List<List<object>>
{
    new() { "Header1" },
    new() { "Supercalifragilisticexpialidocious is a long word" }
};

This addition would help verify that the method correctly handles complex scenarios with mixed word lengths.


63-88: LGTM: Good test for null handling

This test effectively verifies that null values in cells are handled gracefully. The expected output correctly shows an empty cell for the null value.

To make this test even more robust, consider adding an assertion to explicitly check for the absence of the string "null" in the output:

Assert.DoesNotContain("null", result, StringComparison.OrdinalIgnoreCase);

This additional check would ensure that null values are truly represented as empty cells and not as the string "null".


90-115: Consider adding a test with mixed empty and non-empty cells

This test effectively verifies the handling of a single empty string in a cell. To further enhance the test suite, consider adding a case with a mix of empty and non-empty cells in a single row. This would ensure that the table formatting remains correct when dealing with varied cell contents.

Example:

var rows = new List<List<object>>
{
    new() { "Header1", "Header2", "Header3" },
    new() { "", "Non-empty", "" }
};

This addition would help verify that the method correctly handles more complex scenarios with mixed cell contents.


117-142: LGTM: Good test for numeric right alignment

This test effectively verifies that numeric values are right-aligned within cells. The expected output correctly demonstrates the desired alignment.

To make this test more comprehensive, consider adding a case with a mix of numeric and non-numeric values:

var rows = new List<List<object>>
{
    new() { "Header1", "Header2" },
    new() { 12345, "Text" }
};

This would ensure that the right alignment is applied only to numeric values while other types of content remain left-aligned.


145-172: Enhance test for non-string object handling

This test effectively verifies that non-string objects are converted to strings and wrapped correctly. To further improve this test:

  1. Add an explicit check for the conversion, as suggested in the previous review:
Assert.Contains(1234567890.ToString(), result, StringComparison.Ordinal);
  1. Consider adding a test case with a custom object that overrides ToString():
public class CustomObject
{
    public override string ToString() => "Custom string representation";
}

// In the test method
var rows = new List<List<object>>
{
    new() { "Header1" },
    new() { new CustomObject() }
};

This would ensure that the ToAsciiTable method correctly handles various types of non-string objects.


1-172: Overall, excellent test coverage with room for minor enhancements

The AsciiTableFormatterTests class provides a comprehensive suite of tests for the ToAsciiTable method. Each test is well-structured and focuses on a specific functionality or edge case. The suggestions provided in the individual test reviews will further enhance the robustness of this test suite.

To complete this test suite, consider adding the following:

  1. A test for tables with multiple columns of varying widths.
  2. A test with Unicode characters to ensure proper handling of non-ASCII text.
  3. A test with a very large dataset to verify performance and memory usage.

These additions would provide even more thorough coverage of the ToAsciiTable method's capabilities and edge cases.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7a50fbb and 85b174b.

📒 Files selected for processing (1)
  • tests/Digdir.Tool.Dialogporten.SlackNotifier.Tests/AsciiTableFormatterTests.cs (1 hunks)
🧰 Additional context used

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.

Actionable comments posted: 5

🧹 Outside diff range and nitpick comments (4)
tests/Digdir.Tool.Dialogporten.SlackNotifier.Tests/AsciiTableFormatterTests.cs (4)

36-61: LGTM: Effective test for handling long words

This test successfully verifies that long words are not broken when they exceed the maximum column width. It's an important edge case to cover.

As suggested in a previous review, consider adding an assertion to check the actual width of the resulting table:

Assert.True(result.Split('\n')[1].Length > maxColumnWidth, "Table width should exceed maxColumnWidth for long words");

This additional check would further validate the behavior and ensure that the table expands to accommodate long words.


90-115: LGTM: Good test for empty string handling

This test effectively verifies that the ToAsciiTable method handles empty strings correctly by representing them as empty cells.

As suggested in a previous review, consider adding an explicit assertion to check that the cell maintains its structure:

Assert.Contains("|         |", result, StringComparison.Ordinal);

This additional check would ensure that the empty cell is correctly formatted within the table structure.


145-171: LGTM: Good test for non-string object handling, but could be more explicit

This test effectively verifies that non-string objects are converted to strings and wrapped correctly within the table. It's an important test for ensuring the ToAsciiTable method can handle various data types.

As suggested in a previous review, consider adding an explicit check for the conversion:

var nonStringObject = 1234567890;
Assert.Contains(nonStringObject.ToString(), result, StringComparison.Ordinal);

This additional assertion would explicitly verify that the non-string object was converted to a string during the table formation.


1-202: Overall, excellent test coverage with room for minor enhancements

The AsciiTableFormatterTests class provides a comprehensive suite of tests for the ToAsciiTable method. The tests cover various aspects including text wrapping, handling of long words, null values, empty strings, numeric right alignment, non-string object conversion, and jagged table handling. Each test is well-structured and focuses on a specific functionality or edge case.

To further enhance the test suite, consider adding the following tests as suggested in a previous review:

  1. A test for multiple columns to ensure proper alignment and separation.
  2. A test with a very large dataset to verify performance and memory usage.
  3. A test for special characters (e.g., Unicode) to ensure proper handling and alignment.
  4. A test for extremely small maxColumnWidth values (e.g., 1 or 2) to verify graceful handling of edge cases.

These additional tests would provide even more robust coverage of the ToAsciiTable method's capabilities and edge cases.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 85b174b and ae9b384.

📒 Files selected for processing (2)
  • src/Digdir.Tool.Dialogporten.SlackNotifier/Common/AsciiTableFormatter.cs (2 hunks)
  • tests/Digdir.Tool.Dialogporten.SlackNotifier.Tests/AsciiTableFormatterTests.cs (1 hunks)
🧰 Additional context used
📓 Learnings (1)
src/Digdir.Tool.Dialogporten.SlackNotifier/Common/AsciiTableFormatter.cs (2)
Learnt from: elsand
PR: digdir/dialogporten#1232
File: src/Digdir.Tool.Dialogporten.SlackNotifier/Common/AsciiTableFormatter.cs:0-0
Timestamp: 2024-10-07T07:45:33.970Z
Learning: The `ToAsciiTable` method creates a copy of the input `rows` and operates on it, so the original `rows` passed to the method remains unchanged.
Learnt from: elsand
PR: digdir/dialogporten#1232
File: src/Digdir.Tool.Dialogporten.SlackNotifier/Common/AsciiTableFormatter.cs:12-12
Timestamp: 2024-10-07T07:31:46.700Z
Learning: In C# 12, square brackets `[]` can be used for array initialization, e.g., `string[] array = [ "value" ];`.
🔇 Additional comments (3)
tests/Digdir.Tool.Dialogporten.SlackNotifier.Tests/AsciiTableFormatterTests.cs (3)

7-34: LGTM: Well-structured test for text wrapping

This test effectively verifies that the ToAsciiTable method correctly wraps text when it exceeds the specified maximum column width. The test case is well-structured with clear Arrange, Act, and Assert sections, and the expected output accurately represents the desired behavior.


63-88: LGTM: Proper null value handling test

This test effectively verifies that the ToAsciiTable method handles null values gracefully by representing them as empty cells. The expected output correctly demonstrates this behavior, ensuring that the method doesn't throw exceptions when encountering null values.


173-202: LGTM: Excellent test for jagged table handling

This test effectively verifies that the ToAsciiTable method correctly handles jagged tables (rows with different numbers of columns) by padding them with empty cells. The expected output accurately represents the desired behavior, ensuring that the table structure is maintained even with inconsistent row lengths.

Copy link

sonarqubecloud bot commented Oct 7, 2024

@elsand elsand merged commit 142e596 into main Oct 7, 2024
22 checks passed
@elsand elsand deleted the chore/improve-slack-table-formatting branch October 7, 2024 13:34
@coderabbitai coderabbitai bot mentioned this pull request Nov 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants