Skip to content

Commit

Permalink
make sure _jsonElement is filled with a default value so that Old and…
Browse files Browse the repository at this point in the history
… New do not throw
  • Loading branch information
Barsonax committed Aug 24, 2024
1 parent 6881467 commit d61aa71
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
14 changes: 14 additions & 0 deletions src/HassModel/NetDaemon.HassModel.Tests/Entities/EntityTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,18 @@ public void ShouldWrapAreaFromContext()
// Assert
Assert.Equal("Area Name", target.Area);
}

[Fact]
public void StateChange_WithTestConstructor_PropertiesShouldNotThrow()
{
// Arrange
var haContextMock = new Mock<IHaContext>();
var target = new TestEntity(haContextMock.Object, "domain.testEntity");
var stateChange = new StateChange(target, null, null);

// Act & Assert
Assert.NotNull(stateChange.Entity);
Assert.Null(stateChange.Old);
Assert.Null(stateChange.New);
}
}
8 changes: 5 additions & 3 deletions src/HassModel/NetDeamon.HassModel/Entities/StateChange.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,15 @@ internal StateChange(JsonElement jsonElement, IHaContext haContext)
public StateChange(Entity entity, EntityState? old, EntityState? @new)
{
_entity = entity;
_new = @new;
_old = old;
_new = @new;
_old = old;
_haContext = null!; // haContext is not used when _entity is already initialized
_jsonElement = JsonSerializer.SerializeToDocument(new HassStateChangedEventData()).RootElement; // Use a default value so _jsonElement.GetProperty is not going to throw.
}

/// <summary>The Entity that changed</summary>
public virtual Entity Entity => _entity ??= new Entity(_haContext, _jsonElement.GetProperty("entity_id").GetString() ?? throw new InvalidOperationException("No Entity_id in state_change event"));
public virtual Entity Entity =>
_entity ??= new Entity(_haContext, _jsonElement.GetProperty("entity_id").GetString() ?? throw new InvalidOperationException("No Entity_id in state_change event"));

/// <summary>The old state of the entity</summary>
public virtual EntityState? Old => _old ??= _jsonElement.GetProperty("old_state").Deserialize<EntityState>();
Expand Down

0 comments on commit d61aa71

Please sign in to comment.