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

Attribute validation error message now provides valid FHIR definitional paths. #3025

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
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
14 changes: 13 additions & 1 deletion src/Hl7.Fhir.Base/Introspection/FhirElementAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ POSSIBILITY OF SUCH DAMAGE.
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;

#nullable enable

Expand Down Expand Up @@ -125,7 +126,18 @@ public FhirElementAttribute(string name, ChoiceType choice, XmlRepresentation re

private void validateElement(object value, ValidationContext validationContext, List<ValidationResult> result)
{
DotNetAttributeValidation.TryValidate(value, validationContext.IntoPath(value, validationContext.MemberName ?? Name), result);
var useName = validationContext.MemberName;
if (!string.IsNullOrEmpty(useName))
{
var pm = ReflectionHelper.FindProperty(validationContext.ObjectType, validationContext.MemberName);
if (pm != null)
{
var at = pm.GetCustomAttribute<FhirElementAttribute>();
if (at != null)
useName = at.Name;
}
}
DotNetAttributeValidation.TryValidate(value, validationContext.IntoPath(value, useName ?? Name), result);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
#pragma warning disable CS1580 // Invalid type for parameter in XML comment cref attribute
#pragma warning disable CS1584 // XML comment has syntactically incorrect cref attribute

Expand Down Expand Up @@ -88,7 +89,13 @@ public void ValidateInstance(object? instance, in InstanceDeserializationContext
{
// Add the name of the property to the path, so we can display the correct name of the element,
// even if it does not really contain any values.
var nestedContext = validationContext.IntoEmptyProperty(propMapping.Name);
var useName = propMapping.Name;
// Use the fhir property name, not the .NET property name.
var at = propMapping.NativeProperty.GetCustomAttribute<FhirElementAttribute>();
if (at != null)
useName = at.Name;

var nestedContext = validationContext.IntoEmptyProperty(useName);

errors = add(errors, runAttributeValidation(propValue, new[] { cardinality }, nestedContext));
}
Expand Down
16 changes: 13 additions & 3 deletions src/Hl7.Fhir.Base/Utility/ExtendedCodedException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,20 @@ public ExtendedCodedException(

private static string formatLocationMessage(string baseMessage, string? instancePath, long? lineNumber, long? position)
{
string location = $"At line {lineNumber}, position {position}";
// If there is no location data, just return the base message
if (string.IsNullOrEmpty(instancePath) && !lineNumber.HasValue && !position.HasValue)
return baseMessage;

string? location = null;
if (!string.IsNullOrEmpty(instancePath))
location = $"At {instancePath}, line {lineNumber}, position {position}";
var messageWithLocation = $"{baseMessage} {location}";
location += instancePath;
if (lineNumber.HasValue && position.HasValue)
{
if (!string.IsNullOrEmpty(location))
location += ", ";
location += $"line {lineNumber}, position {position}";
}
var messageWithLocation = $"{baseMessage} At {location}";
return messageWithLocation;
}

Expand Down
18 changes: 17 additions & 1 deletion src/Hl7.Fhir.Base/Validation/CodedValidationException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@
* available at https://raw.githubusercontent.com/FirelyTeam/firely-net-sdk/master/LICENSE
*/

using Hl7.Fhir.Introspection;
using Hl7.Fhir.Model;
using Hl7.Fhir.Utility;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using COVE = Hl7.Fhir.Validation.CodedValidationException;
using OO_Sev = Hl7.Fhir.Model.OperationOutcome.IssueSeverity;
using OO_Typ = Hl7.Fhir.Model.OperationOutcome.IssueType;
Expand Down Expand Up @@ -93,7 +95,21 @@ internal static CodedValidationException Initialize(ValidationContext context, s
// will return the parent, so we need to add the MemberName.
if (context.MemberName is not null)
{
path = $"{path}.{context.MemberName}";
var useName = context.MemberName;
var pm = ReflectionHelper.FindProperty(context.ObjectType, context.MemberName);
if (pm != null)
{
var at = pm.GetCustomAttribute<FhirElementAttribute>();
if (at != null)
{
useName = at.Name;
if (at.IsPrimitiveValue)
useName = null;
}
}

if (!string.IsNullOrEmpty(useName))
path = $"{path}.{useName}";
}
}

Expand Down
4 changes: 4 additions & 0 deletions src/Hl7.Fhir.Shared.Tests/Validation/ValidatePatient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@
using Hl7.Fhir.Serialization;
using Hl7.Fhir.Validation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Xml;

namespace Hl7.Fhir.Tests.Validation
Expand All @@ -33,6 +35,7 @@ public void ValidateDemoPatient()

Assert.IsFalse(DotNetAttributeValidation.TryValidate(patient, results, true));
Assert.IsTrue(results.Count > 0);
Console.WriteLine(string.Join("\n", results.Select(r => r.ErrorMessage)));

results.Clear();
foreach (DomainResource contained in patient.Contained) contained.Text = null;
Expand All @@ -46,6 +49,7 @@ public void ValidateDemoPatient()

Assert.IsFalse(DotNetAttributeValidation.TryValidate(patient, results, true));
Assert.IsTrue(results.Count > 0);
Console.WriteLine(string.Join("\n", results.Select(r => r.ErrorMessage)));
}
}
}
11 changes: 7 additions & 4 deletions src/Hl7.Fhir.Shared.Tests/Validation/ValidationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public void TestIdValidation()
validateErrorOrFail(id);

id = new Id("123456789012345678901234567890123456745290123456745290123456745290123456745290");
validateErrorOrFail(id);
validateErrorOrFail(id, errorMessage: "'123456789012345678901234567890123456745290123456745290123456745290123456745290' is not a correct literal for an id. At Id");
}

[TestMethod]
Expand All @@ -63,7 +63,7 @@ public void ValidatesResourceTag()
Assert.IsFalse(DotNetAttributeValidation.TryValidate(p, recurse: true));
}

private static void validateErrorOrFail(Base instance, bool recurse = false, string membername = null)
private static void validateErrorOrFail(Base instance, bool recurse = false, string membername = null, string errorMessage = null)
{
try
{
Expand All @@ -73,8 +73,11 @@ private static void validateErrorOrFail(Base instance, bool recurse = false, str
}
catch (ValidationException ve)
{
Console.WriteLine($"Error: {ve.ValidationResult?.ErrorMessage}");
if (membername != null)
Assert.IsTrue(ve.ValidationResult.MemberNames.Contains(membername));
if (errorMessage != null)
Assert.AreEqual(errorMessage, ve.ValidationResult.ErrorMessage);
}
}

Expand Down Expand Up @@ -213,7 +216,7 @@ public void ValidateResourceWithIncorrectChildElement()
DotNetAttributeValidation.Validate(obs);

// When we recurse, this should fail
validateErrorOrFail(obs, true, membername: "Value");
validateErrorOrFail(obs, true, membername: "Value", errorMessage: "'Ewout Kramer' is not a correct literal for a dateTime. At Observation.effective.start");
}

#if !NETSTANDARD1_6
Expand All @@ -230,7 +233,7 @@ public void TestXhtmlValidation()
validateErrorOrFail(p, true);

p.Text.Div = "<div xmlns='http://www.w3.org/1999/xhtml'><img onmouseover='bigImg(this)' src='smiley.gif' alt='Smiley' /></div>";
validateErrorOrFail(p, true);
validateErrorOrFail(p, true, null, "Value is not well-formed Xml adhering to the FHIR schema for Narrative: The 'onmouseover' attribute is not declared. At Patient.text.div");
}
#endif

Expand Down
Loading