Skip to content

Closing brace is missed when writing PowerShell cmdlets and calling WriteError #1183

@fgimian

Description

@fgimian

Hey there, firstly thank you so much for this incredible tool! 😄

When writing PowerShell cmdlets in C#, it is common to run the inherited WriteError to write non-terminating errors. Sadly it seems that Coverlet does not detect the closing brace in this scenario.

Here's a simply demo example:

using System;
using System.Management.Automation;

namespace Lunette.Cmdlets.Utilities
{
    [Cmdlet(VerbsCommon.Get, "SpecialFolderPath")]
    [OutputType(typeof(string))]
    public class GetSpecialFolderPathCommand : Cmdlet
    {
        [Parameter(Position = 0, Mandatory = true)]
        public string Name { get; set; }

        protected override void ProcessRecord()
        {
            if (Name == "BAD")
            {
                WriteError(new ErrorRecord(
                    new ArgumentException("oh no"),
                    "ItemNotFoundException",
                    ErrorCategory.InvalidArgument,
                    "Hello"));
            }
            else
            {
                WriteObject("hello");
            }
        }
    }
}

And here are the tests:

using System;
using System.Linq;
using Lunette.Cmdlets.Utilities;
using Xunit;

namespace Lunette.Tests.Cmdlets.Utilities
{
    public class GetSpecialFolderPathCommandTests
    {
        [Fact]
        public void Invoke_ValidSpecialFolder_ShouldReturnPath()
        {
            // Arrange
            var cmdlet = new GetSpecialFolderPathCommand()
            {
                Name = "GOOD"
            };

            // Act
            var results = cmdlet.Invoke().OfType<string>().ToList();

            // Assert
            Assert.Equal("hello", results[0]);
        }

        [Fact]
        public void Invoke_InvalidSpecialFolder_ShouldError()
        {
            // Arrange
            var cmdlet = new GetSpecialFolderPathCommand()
            {
                Name = "BAD"
            };

            // Act & Assert
            var exception = Assert.Throws<ArgumentException>(
                () => cmdlet.Invoke().GetEnumerator().MoveNext());
            Assert.Equal("oh no", exception.Message);
        }
    }
}

And as per the coverage report, the closing brace on line 22 is not covered:

image

Any ideas if there's a way to work through this?

Huge thanks!
Fotis

Metadata

Metadata

Assignees

No one assigned

    Labels

    staletenet-coverageIssue related to possible incorrect coverage

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions