ExpressionObserverTests_AvaloniaProperty.cs 2.7 KB

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