Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -92,12 +92,7 @@ protected override void EndProcessing()
// The first input string does not represent a complete Json Syntax.
// Hence consider the the entire input as a single Json content.
}
#if CORECLR
catch (Newtonsoft.Json.JsonSerializationException)
{
// we use another serializer for CORECLR implementation
}
#endif

if (successfullyConverted)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Why we don't want to mask this exception?

@2xmax Max Maximov (2xmax) Dec 13, 2016 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Since it is already handled here. I decided to fix the behavior of JsonObject making them invariant of a platform rather than handling serialization exceptions for every platform. You can also take a look at the C# unit tests I mentioned above.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I like this change, so when using JsonObject.ConvertFromJson in C#, you don't need to catch different exceptions between FullCLR and CoreCLR.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks. Clear.

{
for (int index = 1; index < _inputObjectBuffer.Count; index++)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,20 +44,32 @@ public static object ConvertFromJson(string input, out ErrorRecord error)
}
error = null;
#if CORECLR
object obj = JsonConvert.DeserializeObject(input, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.None, MaxDepth = 1024 });

// JObject is a IDictionary
if (obj is JObject)
object obj = null;
try
{
obj = JsonConvert.DeserializeObject(input, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.None, MaxDepth = 1024 });

// JObject is a IDictionary
var dictionary = obj as JObject;
obj = PopulateFromJDictionary(dictionary, out error);
if (dictionary != null)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I hope Declaration Expressions can be brought back in C# 7. It will make code like this much more concise.

{
obj = PopulateFromJDictionary(dictionary, out error);
}
else
{
// JArray is a collection
var list = obj as JArray;
if (list != null)
{
obj = PopulateFromJArray(list, out error);
}
}
}

// JArray is a collection
else if (obj is JArray)
catch (JsonException je)
{
var list = obj as JArray;
obj = PopulateFromJArray(list, out error);
var msg = string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.JsonDeserializationFailed, je.Message);
// the same as JavaScriptSerializer does
throw new ArgumentException(msg, je);
}
#else
//In ConvertTo-Json, to serialize an object with a given depth, we set the RecursionLimit to depth + 2, see JavaScriptSerializer constructor in ConvertToJsonCommand.cs.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -207,4 +207,7 @@
<data name="ReachedMaximumDepthAllowed" xml:space="preserve">
<value>The maximum depth allowed for serialization is {0}.</value>
</data>
<data name="JsonDeserializationFailed" xml:space="preserve">
<value>Conversion from JSON failed with error: {0}</value>
</data>
</root>

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Please add newline.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

this file is autogenerated

Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
Describe 'Unit tests for JsonObject' -tags "CI" {

function ShouldThrow

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Please use the template with FullyQualifiedErrorId to check for proper errors

it "Get-Item on a nonexisting file should have error PathNotFound" {
    try
    {
        get-item "ThisFileCannotPossiblyExist" -ErrorAction Stop
        throw "No Exception!"
    }
    catch
    {
        $_.FullyQualifiedErrorId | should be "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand"
    }
}

And see my comment about testcase.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This man tells that I've got to verify FullyQualifiedErrorId, going to fix this, thx. However, it does not explicitly state that all the expected exception checks should
follow this template. Nevertheless, If I had adhered to the whole template, imho, the test would have been less clear and concise, so I'd prefer to keep the ShouldThrow checker. Moreover, the copypaste is prone to mistakes, just take a look at my quick findings:

grep -Hn -B 4 -ir "FullyQualifiedErrorId.*should" --include *Test*.ps1 --group-separator=$'\n\n---------------------------------\n\n'

Here developers simply forgot to throw before catch:

engine/ParameterBinding/ParameterBinding.Tests.ps1-16-            test-PositionalBinding1 1
engine/ParameterBinding/ParameterBinding.Tests.ps1-17-        }
engine/ParameterBinding/ParameterBinding.Tests.ps1-18-        catch
engine/ParameterBinding/ParameterBinding.Tests.ps1-19-        {
engine/ParameterBinding/ParameterBinding.Tests.ps1:20:            $_.FullyQualifiedErrorId | should be "AmbiguousPositionalParameterNoName,test-PositionalBinding1"
--- 
Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1-920-        try {
Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1-921-            Set-ExecutionPolicy -Scope $policyScope -ExecutionPolicy Restricted
Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1-922-        }
Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1-923-        catch {
Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1:924:            $_.FullyQualifiedErrorId | Should Be "CantSetGroupPolicy,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand"
--
Modules/Microsoft.PowerShell.Security/SecureString.Tests.ps1-15-        try {
Modules/Microsoft.PowerShell.Security/SecureString.Tests.ps1-16-            ConvertFrom-SecureString -secureString $null -key $null
Modules/Microsoft.PowerShell.Security/SecureString.Tests.ps1-17-        }
Modules/Microsoft.PowerShell.Security/SecureString.Tests.ps1-18-        catch {
Modules/Microsoft.PowerShell.Security/SecureString.Tests.ps1:19:            $_.FullyQualifiedErrorId | should be "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertFromSecureStringCommand"
--
Modules/Microsoft.PowerShell.Utility/Export-Alias.Tests.ps1-104-                try{
Modules/Microsoft.PowerShell.Utility/Export-Alias.Tests.ps1-105-                        Export-Alias $fulltestpath abcd02
Modules/Microsoft.PowerShell.Utility/Export-Alias.Tests.ps1-106-                }
Modules/Microsoft.PowerShell.Utility/Export-Alias.Tests.ps1-107-                catch{
Modules/Microsoft.PowerShell.Utility/Export-Alias.Tests.ps1:108:                        $_.FullyQualifiedErrorId | Should be "FileOpenFailure,Microsoft.PowerShell.Commands.ExportAliasCommand"

Here instead of err checking we will get a nullref:

Modules/Microsoft.PowerShell.Management/TimeZone.Tests.ps1-76-    It "Call Get-TimeZone using ID param and multiple items, where first and third are invalid ids - expect error" {
Modules/Microsoft.PowerShell.Management/TimeZone.Tests.ps1-77-        $null = Get-TimeZone -Id @("Cape Verde Standard","Morocco Standard Time","Azores Standard") `
Modules/Microsoft.PowerShell.Management/TimeZone.Tests.ps1-78-                             -ErrorVariable errVar -ErrorAction SilentlyContinue
Modules/Microsoft.PowerShell.Management/TimeZone.Tests.ps1-79-        $errVar.Count -eq 2 | Should Be $true
Modules/Microsoft.PowerShell.Management/TimeZone.Tests.ps1:80:        $errVar[0].FullyQualifiedErrorID | Should Be "TimeZoneNotFound,Microsoft.PowerShell.Commands.GetTimeZoneCommand"

Perhaps this is the reason why in places like here or here were desided to implement the custom assertions. Of course, all the mistakes I encountered are related to lack of calibration, but I merely revealed you a couple of drawbacks.

All in all, you can still insist on it, persuade me by proposing other arguments and other ideas to refactor it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

the comment about testcase is valid, thx

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It's totally fine to have custom assertions in your test. I think Ilya (@iSazonov) meant that the try/catch section in ShouldThrow should be better use the template, so it would be like

function ShouldThrow
{
   ....
   try {
       & $InputObject
       throw "Should throw ArgumentException"
    } catch {
       $_.FullyQualifiedErrorId | should be "ArgumentException"
    }
}

For those tests you found out, they were written before we came up with the guidelines, but we do want future test to follow the guidelines as much as possible 😄

{
param (
[Parameter(ValueFromPipeline = $true)]
$InputObject,
[Parameter(Position = 0)]
$ExpectedException
)

try
{
& $InputObject
throw "Should throw exception"
}
catch
{
$_.FullyQualifiedErrorId | should be $ExpectedException
}
}

$validStrings = @(
@{ name = "empty"; str = "" }
@{ name = "spaces"; str = " " }
@{ name = "object"; str = "{a:1}" }
)

It 'no error for valid string - <name>' -TestCase $validStrings {
param ($str)
$errRecord = $null
[Microsoft.PowerShell.Commands.JsonObject]::ConvertFromJson($str, [ref]$errRecord)
$errRecord | Should BeNullOrEmpty
}

$invalidStrings = @(
@{ name = "plain text"; str = "plaintext" }
@{ name = "part"; str = '{"a" :' }
)

It 'throw ArgumentException for invalid string - <name>' -TestCase $invalidStrings {
param ($str)
$errRecord = $null
{ [Microsoft.PowerShell.Commands.JsonObject]::ConvertFromJson($str, [ref]$errRecord) } | ShouldThrow 'ArgumentException'
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -635,4 +635,11 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" {
$result = ExecuteWebCommand -command $command
$result.Error | Should BeNullOrEmpty
}

It "Invoke-RestMethod supports request that returns plain text response." {

$command = "Invoke-RestMethod -Uri 'http://httpbin.org/encoding/utf8'"
$result = ExecuteWebCommand -command $command
$result.Error | Should BeNullOrEmpty
}
}