Skip to content

Commit

Permalink
feat(QueryAttribute): log error on non-VisualElement fields
Browse files Browse the repository at this point in the history
  • Loading branch information
jonisavo committed Jun 12, 2022
1 parent d3bb5c1 commit 0855628
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
30 changes: 30 additions & 0 deletions Assets/UIComponents.Tests/QueryAttributeTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
using System.Collections.Generic;
using System.Text.RegularExpressions;
using NUnit.Framework;
using UIComponents.Experimental;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.UIElements;

namespace UIComponents.Tests
Expand Down Expand Up @@ -76,5 +79,32 @@ public void Should_Populate_Inherited_Fields()
Assert.That(component.FoldoutContent, Is.InstanceOf<Label>());
Assert.That(component.FoldoutContent.text, Is.EqualTo("Foldout content"));
}

[Layout("UIComponentTests/LayoutAttributeTests")]
private class ComponentWithInvalidQueryAttribute : UIComponent
{
[Query]
public object InvalidField;

[Query]
public object[] InvalidArray;

[Query]
public List<List<VisualElement>> InvalidList;
}

[Test]
public void Should_Log_Error_On_Invalid_Fields()
{
var component = new ComponentWithInvalidQueryAttribute();

Assert.That(component.InvalidField, Is.Null);
Assert.That(component.InvalidArray, Is.Null);
Assert.That(component.InvalidList, Is.Null);

LogAssert.Expect(LogType.Error, "QueryAttribute must be used on a VisualElement field. InvalidField is System.Object");
LogAssert.Expect(LogType.Error, "QueryAttribute must be used on a VisualElement field. InvalidArray is System.Object");
LogAssert.Expect(LogType.Error, new Regex(Regex.Escape("QueryAttribute must be used on a VisualElement field. InvalidList is System.Collections.Generic.List`1[[UnityEngine.UIElements.VisualElement")));
}
}
}
8 changes: 8 additions & 0 deletions Assets/UIComponents/Core/UIComponent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,8 @@ private void LoadStyles()
if (loadedStyleSheets[i] != null)
styleSheets.Add(loadedStyleSheets[i]);
}

private static readonly Type VisualElementType = typeof(VisualElement);

private void PopulateQueryFields()
{
Expand All @@ -219,6 +221,12 @@ private void PopulateQueryFields()
var fieldType = fieldInfo.FieldType;
var concreteType = TypeUtils.GetConcreteType(fieldType);

if (!VisualElementType.IsAssignableFrom(concreteType))
{
Debug.LogError($"QueryAttribute must be used on a VisualElement field. {fieldInfo.Name} is {concreteType.FullName}");
continue;
}

var results = new List<VisualElement>();

for (var i = 0; i < queryAttributes.Length; i++)
Expand Down

0 comments on commit 0855628

Please sign in to comment.