public static void DependencyPropertyRegisterAttachedReadOnly() { var code = @" namespace N { using System.Windows; public static class Foo { private static readonly DependencyPropertyKey BarPropertyKey = DependencyProperty.RegisterAttachedReadOnly( ""Bar"", typeof(int), typeof(Foo), new PropertyMetadata(default(int))); public static readonly DependencyProperty BarProperty = BarPropertyKey.DependencyProperty; /// <summary>Helper for setting <see cref=""BarPropertyKey""/> on <paramref name=""element""/>.</summary> /// <param name=""element""><see cref=""FrameworkElement""/> to set <see cref=""BarPropertyKey""/> on.</param> /// <param name=""value"">Bar property value.</param> public static void SetBar(this FrameworkElement element, int value) { element.SetValue(BarPropertyKey, value); } /// <summary>Helper for getting <see cref=""BarProperty""/> from <paramref name=""element""/>.</summary> /// <param name=""element""><see cref=""FrameworkElement""/> to read <see cref=""BarProperty""/> from.</param> /// <returns>Bar property value.</returns> [AttachedPropertyBrowsableForType(typeof(FrameworkElement))] public static int GetBar(this FrameworkElement element) { return (int) element.GetValue(BarProperty); } } }"; RoslynAssert.Valid(Analyzer, code); }
public static void OnPropertyChangedCallerMemberNameCopyLocalNullCheckInvoke() { var code = @" namespace N { using System.ComponentModel; using System.Runtime.CompilerServices; public class C : INotifyPropertyChanged { private int p; public event PropertyChangedEventHandler PropertyChanged; public int P { get { return this.p; } set { if (value == this.p) return; this.p = value; this.OnPropertyChanged(); } } protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { var handler = this.PropertyChanged; if (handler != null) { handler.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } }"; RoslynAssert.Valid(Analyzer, code); }
public static void DependencyPropertyRegisterWithMetadata(string metadata) { var code = @" namespace N { using System.Windows; using System.Windows.Controls; public class FooControl : Control { public static readonly DependencyProperty BarProperty = DependencyProperty.Register( nameof(Bar), typeof(int), typeof(FooControl), new PropertyMetadata(default(int), OnBarChanged)); public int Bar { get { return (int)this.GetValue(BarProperty); } set { this.SetValue(BarProperty, value); } } private static void OnBarChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var control = (FooControl)d; var oldValue = (int)e.OldValue; var newValue = (int)e.NewValue; } private static object CoerceBar(DependencyObject d, object baseValue) { return baseValue; } } }".AssertReplace("new PropertyMetadata(default(int), OnBarChanged)", metadata); RoslynAssert.Valid(Analyzer, code); }
public static void WhenOverriddenIsNotVirtualDispose() { var baseClass = @" namespace N { using System; using System.IO; abstract class BaseClass : IDisposable { public void Dispose() { this.M(); } protected abstract void M(); } }"; var code = @" namespace N { using System; using System.IO; class C : BaseClass { private readonly Stream stream = File.OpenRead(string.Empty); protected override void M() { this.stream.Dispose(); } } }"; RoslynAssert.Valid(Analyzer, baseClass, code); }
public static void DependencyPropertyPartial(string setValueCall) { var part1 = @" namespace N { using System.Windows; using System.Windows.Controls; public partial class FooControl : Control { public static readonly DependencyProperty BarProperty = DependencyProperty.Register( ""Bar"", typeof(int), typeof(FooControl), new PropertyMetadata(default(int))); public int Bar { get { return (int)GetValue(BarProperty); } set { SetValue(BarProperty, value); } } } }"; var part2 = @" namespace N { public partial class FooControl { public void Meh() { this.SetValue(BarProperty, 1); } } }".AssertReplace("this.SetValue(BarProperty, 1);", setValueCall); RoslynAssert.Valid(Analyzer, part1, part2); }
public static void WhenExplicitAndExplicit(string call) { var interfaceCode = @" namespace RoslynSandbox { using System; public interface IC { event EventHandler Bar; } }"; var code = @" namespace RoslynSandbox { using System; using System.Reflection; public sealed class C : IC { public C() { var member = typeof(C).GetEvent(nameof(this.Bar), BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); } internal event EventHandler Bar; event EventHandler IC.Bar { add => this.Bar += value; remove => this.Bar -= value; } } }".AssertReplace("typeof(C).GetEvent(nameof(this.Bar), BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)", call); RoslynAssert.Valid(Analyzer, Descriptor, interfaceCode, code); }
public static void GetNestedType(string call) { var code = @" namespace RoslynSandbox { using System.Reflection; class C { public C() { var methodInfo = typeof(C).GetNestedType(nameof(Public), BindingFlags.Public); } public static class PublicStatic { } public class Generic<T> { } public class Public { } private static class PrivateStatic { } private class Private { } } }".AssertReplace("GetNestedType(nameof(Public), BindingFlags.Public)", call); RoslynAssert.Valid(Analyzer, Descriptor, code); }
public static void ChainedCtors() { var code = @" namespace N { using System; public sealed class C : IDisposable { private readonly int n; public C() : this(new Disposable()) { } private C(IDisposable disposable) : this(disposable, 1) { } private C(IDisposable disposable, int n) { this.n = n; this.Disposable = disposable; } public IDisposable Disposable { get; } public void Dispose() { this.Disposable.Dispose(); } } }"; RoslynAssert.Valid(Analyzer, DisposableCode, code); }
public void DependencyPropertyPartial() { var part1 = @" namespace RoslynSandbox { using System.Windows; using System.Windows.Controls; public partial class FooControl : Control { private static readonly DependencyPropertyKey BarPropertyKey = DependencyProperty.RegisterReadOnly( ""Bar"", typeof(int), typeof(FooControl), new PropertyMetadata(default(int))); } }"; var part2 = @" namespace RoslynSandbox { using System.Windows; using System.Windows.Controls; public partial class FooControl { public static readonly DependencyProperty BarProperty = BarPropertyKey.DependencyProperty; public int Bar { get { return (int)GetValue(BarProperty); } set { SetValue(BarPropertyKey, value); } } } }"; RoslynAssert.Valid(Analyzer, part1, part2); }
public static void WhenOneValid() { var code = @" namespace N { using Gu.Roslyn.Asserts; using NUnit.Framework; public static class Valid { private static readonly PlaceholderAnalyzer Analyzer = new PlaceholderAnalyzer(); [Test] public static void M() { var c = ""class C { }""; RoslynAssert.Valid(Analyzer, c); } } }"; RoslynAssert.Valid(Analyzer, Code.PlaceholderAnalyzer, code); }
public static void DontUseUsingWhenAssigningAFieldTernary() { var code = @" namespace N { using System.IO; public class C { private readonly Stream stream; public C(bool flag) { var temp = File.OpenRead(string.Empty); this.stream = flag ? null : temp; } } }"; RoslynAssert.Valid(Analyzer, code); }
public void DependencyPropertyRegisterBackingField() { var testCode = @" namespace RoslynSandbox { using System.Windows; using System.Windows.Controls; public class FooControl : Control { /// <summary>Identifies the <see cref=""Bar""/> dependency property.</summary> public static readonly DependencyProperty BarProperty = DependencyProperty.Register(nameof(Bar), typeof(int), typeof(FooControl), new PropertyMetadata(default(int))); public int Bar { get { return (int)GetValue(BarProperty); } set { SetValue(BarProperty, value); } } } }"; RoslynAssert.Valid(Analyzer, testCode); }
public static void IgnoresTypeName() { var code = @" namespace N { using System; public class C { public void M1() { this.M2(""Exception""); } public void M2(string value) { throw new ArgumentException(nameof(value), value); } } }"; RoslynAssert.Valid(Analyzer, code); }
public void IgnoreOverrideMetadataWhenContainingTypeIsNotSubclassOfOwningType() { var testCode = @" namespace RoslynSandbox { using System.Globalization; using System.Windows; using System.Windows.Markup; public partial class App : Application { static App() { // Ensure that we are using the right culture FrameworkElement.LanguageProperty.OverrideMetadata( typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag))); } } }"; RoslynAssert.Valid(Analyzer, testCode); }
public void IgnoredWhenCreatedInScopeWithIf(string setCall) { var testCode = @" namespace RoslynSandbox { using System.Windows; using System.Windows.Controls; public static class Foo { public static void MethodName() { var textBox = new TextBox(); if (true) { textBox.Visibility = Visibility.Hidden; } } } }".AssertReplace("textBox.Visibility = Visibility.Hidden;", setCall); RoslynAssert.Valid(Analyzer, testCode); }
public void NoDiagnosticWhenCustomComparerProvided() { var testCode = TestUtility.WrapClassInNamespaceAndAddUsing(@" class A { } class B { } class ABComparer : IComparer { public int Compare(object x, object y) => 0; } public class Tests { [Test] public void TestMethod() { var actual = new A(); var expected = new B(); Assert.That(actual, Is.GreaterThan(expected).Using(new ABComparer())); } }", "using System.Collections;"); RoslynAssert.Valid(analyzer, testCode); }
public void DependencyPropertyRegisterAttached() { var testCode = @" namespace RoslynSandbox { using System.Windows; public static class Foo { public static readonly DependencyProperty BarProperty = DependencyProperty.RegisterAttached( ""Bar"", typeof(int), typeof(Foo), new PropertyMetadata(default(int))); public static void SetBar(this FrameworkElement element, int value) => element.SetValue(BarProperty, value); public static int GetBar(this FrameworkElement element) => (int)element.GetValue(BarProperty); } }"; RoslynAssert.Valid(Analyzer, testCode); }
public static void ReassignAfterDispose() { var code = @" namespace N { using System.IO; public sealed class C { public void M() { var stream = File.OpenRead(string.Empty); var b = stream.ReadByte(); stream.Dispose(); stream = File.OpenRead(string.Empty); b = stream.ReadByte(); stream.Dispose(); } } }"; RoslynAssert.Valid(Analyzer, Descriptor, code); }
public static void DiagnosticsOneParamWithPositionAssertReplace() { var code = @" namespace N { using Gu.Roslyn.Asserts; using NUnit.Framework; public static class C { private static readonly PlaceholderAnalyzer Analyzer = new PlaceholderAnalyzer(); [TestCase(""C { }"")] public static void M(string declaration) { var code = ""↓class C { }"".AssertReplace(""C { }"", declaration); RoslynAssert.Diagnostics(Analyzer, code); } } }"; RoslynAssert.Valid(Analyzer, Descriptor, Code.PlaceholderAnalyzer, code); }
public void NoDiagnosticWhenExpectedHasIEquatableOfActual() { var testCode = TestUtility.WrapClassInNamespaceAndAddUsing(@" class A { } class B : IEquatable<A> { public bool Equals(A? other) => true; } public class Tests { [Test] public void TestMethod() { var actual = new A(); var expected = new B(); Assert.That(actual, Is.EqualTo(expected)); } }"); RoslynAssert.Valid(analyzer, testCode); }
public static void ILoggerFactoryAddApplicationInsights() { var code = @" namespace N { using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Logging; public class Foo { public void Configure( IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Warning); } } }"; RoslynAssert.Valid(Analyzer, code); }
public static void DoNotWarnOnConfigureAwait() { var code = @" namespace N { using System.Threading.Tasks; public class C { public void M() { Task<int> a = null; Task b = null; a.ConfigureAwait(false); a.ConfigureAwait(true); b.ConfigureAwait(false); b.ConfigureAwait(true); } } }"; RoslynAssert.Valid(Analyzer, code); }
public static void IgnoresVariableDeclaredAfter() { var code = @" namespace N { using System; public class C { public void M1() { var text = this.M2(""text""); } public string M2(string value) { throw new ArgumentException(nameof(value), value); } } }"; RoslynAssert.Valid(Analyzer, code); }
// Not-nested name public void Valid_Code_01() { var before = @" namespace ExtendedAnalyzers { using System.IO; using System.Threading.Tasks; public class C { public async Task MyMethod() { using (var fileStream = File.OpenRead(""filename"")) { var reader = new StreamReader(fileStream); var text = await reader.ReadToEndAsync(); } } } }"; RoslynAssert.Valid(Analyzer, before); }
public void AnalyzeWhenAllInformationIsProvidedByAttribute() { var testCode = TestUtility.WrapClassInNamespaceAndAddUsing(@" public class AnalyzeWhenAllInformationIsProvidedByAttribute { [Test] public void ShortName([ValueSource(typeof(AnotherClass), ""TestStrings"")] string name) { Assert.That(name.Length, Is.LessThan(15)); } } class AnotherClass { static IEnumerable<string> TestStrings() { yield return ""SomeName""; yield return ""YetAnotherName""; } }", additionalUsings: "using System.Collections.Generic;"); RoslynAssert.Valid(analyzer, testCode); }
public void WhenNoAttribute() { var testCode = @" namespace RoslynSandbox { using System; using System.Windows.Markup; [MarkupExtensionReturnType(typeof(string))] public class FooExtension : MarkupExtension { public string Text { get; set; } /// <inheritdoc /> public override object ProvideValue(IServiceProvider serviceProvider) { return Text; } } }"; RoslynAssert.Valid(Analyzer, testCode); }
public static void WhenNoAsserts() { var code = @" namespace N { using System; using NUnit.Framework; public static class C { private static readonly PlaceholderAnalyzer Analyzer = new PlaceholderAnalyzer(); [Test] public static void M() { var c = ""class C { }""; Console.WriteLine(c); } } }"; RoslynAssert.Valid(Analyzer, Code.PlaceholderAnalyzer, code); }
public static void FactoryMethodCallingPrivateCtorWithCachedDisposable() { var code = @" namespace N { using System; public sealed class C { private static readonly IDisposable Cached = new Disposable(); private readonly IDisposable value; private C(IDisposable value) { this.value = value; } public static C Create() => new C(Cached); } }"; RoslynAssert.Valid(Analyzer, DisposableCode, code); }
public static void DependencyPropertyRegisterBackingProperty(string nameof) { var code = @" namespace N { using System.Windows; using System.Windows.Controls; public class FooControl : Control { /// <summary>Identifies the <see cref=""Bar""/> dependency property.</summary> public static DependencyProperty BarProperty { get; } = DependencyProperty.Register(nameof(Bar), typeof(int), typeof(FooControl), new PropertyMetadata(default(int))); public int Bar { get { return (int)GetValue(BarProperty); } set { SetValue(BarProperty, value); } } } }".AssertReplace("nameof(Bar)", nameof); RoslynAssert.Valid(Analyzer, code); }
public void NoDiagnosticWhenExpectedHasIComparableOfActual() { var testCode = TestUtility.WrapClassInNamespaceAndAddUsing(@" class A { } class B : IComparable<A> { public int CompareTo(A other) => 0; } class Tests { [Test] public void TestMethod() { var actual = new A(); var expected = new B(); Assert.That(actual, Is.LessThanOrEqualTo(expected)); } }"); RoslynAssert.Valid(analyzer, testCode); }