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

Assert fails on integer field with padded zeros #181

Open
Tandis5 opened this issue Apr 24, 2023 · 0 comments
Open

Assert fails on integer field with padded zeros #181

Tandis5 opened this issue Apr 24, 2023 · 0 comments

Comments

@Tandis5
Copy link

Tandis5 commented Apr 24, 2023

In our tests, we are doing validation of large XML objects. If I try to perform an assert against a particular field in that XML that is an integer but written with zeros padded on the beginning, the assert fails if I try to do it as an integer.

Here is a simple example:

[Fact]
public void SimpleTest()
{
    string xml = "<RootNode><MyElement>00000123</MyElement></RootNode>";
    XElement actual = XElement.Parse(xml);

    Snapshot.Match(actual, options => options.Assert(a => a.Field<int>("RootNode.MyElement").Should().Be(123)));
}

if I run this test, I get:
Snapshooter.Exceptions.SnapshotCompareException : The compare action has been failed. Error: Expected a.Field<int>("RootNode.MyElement") to be 123, but found 83 (difference of -40).

The problem appears to be this code:

public static T ConvertToType<T>(this JToken field)
{
    if (typeof(T) == typeof(int))
    {
        // This is a workaround, because the json method ToObject<> rounds
        // decimal values to integer values, which is wrong.
        return JsonConvert.DeserializeObject<T>(field.Value<string>());
    }

    return field.ToObject<T>();
}

The deserialize of "00000123" to an integer returns 83 (for reasons unbeknownst to me). Since you already know this is an integer, should it not just return Convert.ToInt32(field.Value<string>())? Or, similar to the rounding of the decimal, should the test prevent this and throw a more logical error, indicating that 00000123 does not equal 123 or something like that? I personally feel that allowing the int comparison in this situation is fine, but it's not my code so I'll leave it to you.

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

No branches or pull requests

1 participant