ExpressionObserverTests_AvaloniaProperty.cs 2.5 KB

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