ExpressionObserverTests_AvaloniaProperty.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright (c) The Avalonia Project. All rights reserved.
  2. // Licensed under the MIT license. See licence.md file in the project root for full license information.
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Reactive.Linq;
  6. using System.Threading.Tasks;
  7. using Avalonia.Diagnostics;
  8. using Avalonia.Data.Core;
  9. using Xunit;
  10. namespace Avalonia.Base.UnitTests.Data.Core
  11. {
  12. public class ExpressionObserverTests_AvaloniaProperty
  13. {
  14. public ExpressionObserverTests_AvaloniaProperty()
  15. {
  16. var foo = Class1.FooProperty;
  17. }
  18. [Fact]
  19. public async Task Should_Get_Simple_Property_Value()
  20. {
  21. var data = new Class1();
  22. var target = new ExpressionObserver(data, "Foo");
  23. var result = await target.Take(1);
  24. Assert.Equal("foo", result);
  25. Assert.Null(((IAvaloniaObjectDebug)data).GetPropertyChangedSubscribers());
  26. }
  27. [Fact]
  28. public async Task Should_Get_Simple_ClrProperty_Value()
  29. {
  30. var data = new Class1();
  31. var target = new ExpressionObserver(data, "ClrProperty");
  32. var result = await target.Take(1);
  33. Assert.Equal("clr-property", result);
  34. }
  35. [Fact]
  36. public void Should_Track_Simple_Property_Value()
  37. {
  38. var data = new Class1();
  39. var target = new ExpressionObserver(data, "Foo");
  40. var result = new List<object>();
  41. var sub = target.Subscribe(x => result.Add(x));
  42. data.SetValue(Class1.FooProperty, "bar");
  43. Assert.Equal(new[] { "foo", "bar" }, result);
  44. sub.Dispose();
  45. Assert.Null(((IAvaloniaObjectDebug)data).GetPropertyChangedSubscribers());
  46. }
  47. [Fact]
  48. public void Should_Not_Keep_Source_Alive()
  49. {
  50. Func<Tuple<ExpressionObserver, WeakReference>> run = () =>
  51. {
  52. var source = new Class1();
  53. var target = new ExpressionObserver(source, "Foo");
  54. return Tuple.Create(target, new WeakReference(source));
  55. };
  56. var result = run();
  57. result.Item1.Subscribe(x => { });
  58. GC.Collect();
  59. Assert.Null(result.Item2.Target);
  60. }
  61. private class Class1 : AvaloniaObject
  62. {
  63. public static readonly StyledProperty<string> FooProperty =
  64. AvaloniaProperty.Register<Class1, string>("Foo", defaultValue: "foo");
  65. public string ClrProperty { get; } = "clr-property";
  66. }
  67. }
  68. }