Пример #1
0
    public async Task DiagnosticsAreReturned_ForNotFoundNullActionResults()
    {
        // Arrange
        var source           = @"
using Microsoft.AspNetCore.Mvc;

namespace Test
{
    [ApiController]
    [Route(""[controller]"")]
    public class TestController : ControllerBase
    {
        [HttpGet]
        public ActionResult<string> Test()
        {
            return NotFound(null);
        }
    }
}";
        var testSource       = TestSource.Read(source);
        var expectedLocation = testSource.DefaultMarkerLocation;

        // Act
        var result = await Executor.GetDiagnosticsAsync(testSource.Source);

        // Assert
        Assert.Contains(result, d => d.Id == ApiDiagnosticDescriptors.API1000_ActionReturnsUndocumentedStatusCode.Id);
    }
Пример #2
0
        public async Task Local_declared_as_var___no_warning_or_error()
        {
            string library = @"
namespace MyLib.Services
{
    public class Bar
    {
        public void Do() { }
    }
}";

            TestSource code = TestSource.Read(@"
using MyLib.Services;

namespace MyProgram
{
    internal class Worker
    {
        public void Do()
        {
            var bar = new Bar();
        }
    }
}");

            Diagnostic[] diagnostics = await this.GetDiagnosticsWithProjectReference(code.Source, library);

            Assert.AreEqual(0, diagnostics.Length);
        }
Пример #3
0
 private static void Then_source_and_result_should_be_equal(TestSource source, TestTarget result)
 {
     Assert.Equal(source.BoolProp, result.BoolProp);
     Assert.Equal(source.EnumProp, result.EnumProp);
     Assert.Equal(source.IntProp, result.IntProp);
     Assert.Equal(source.StringProp, result.StringProp);
 }
Пример #4
0
    public async Task DiagnosticsAreReturned_ForIncompleteActionResults()
    {
        // Arrange
        var source           = @"
using Microsoft.AspNetCore.Mvc;

namespace Test
{
    [ApiController]
    [Route(""[controller]/[action]"")
    public class TestController : ControllerBase
    {
        public IActionResult Get(int id)
        {
            if (id == 0)
            {
                return /*MM*/NotFound();
            }

            return;
        }
    }
}";
        var testSource       = TestSource.Read(source);
        var expectedLocation = testSource.DefaultMarkerLocation;

        // Act
        var result = await Executor.GetDiagnosticsAsync(testSource.Source);

        // Assert
        var diagnostic = Assert.Single(result, d => d.Id == ApiDiagnosticDescriptors.API1000_ActionReturnsUndocumentedStatusCode.Id);

        AnalyzerAssert.DiagnosticLocation(expectedLocation, diagnostic.Location);
    }
        public void TestInterception()
        {
            List <ExceptionNotification> Received = new List <ExceptionNotification>();
            var src = new TestSource
            {
                ExceptionHandler = (o, a) => Received.Add(a)
            };

            src.Test("Unintercepted");
            Assert.AreEqual(1, Received.Count());
            Assert.IsTrue(Received.All(r => r.Message == "Unintercepted"));

            string intercepted = null;

            using (src.Catch((_, args) => intercepted = args.Message))
            {
                src.Test("Intercepted-true");
            }

            Assert.AreEqual("Intercepted-true", intercepted);
            Assert.AreEqual(1, Received.Count());   // since we've intercepted
            Assert.IsFalse(Received.Any(r => r.Message == "Intercepted-true"));

            src.Test("Unintercepted2");

            Assert.AreEqual("Intercepted-true", intercepted); // should not have intercepted anymore
            Assert.AreEqual(2, Received.Count());             // original sink remains active
            Assert.AreEqual("Unintercepted2", Received.Last().Message);
        }
Пример #6
0
    static void Main(string[] args)
    {
        var x = new TestSource();
        var y = new TestDestination();

        x.Bind <string, string>(Name => y.Id);
    }
Пример #7
0
        public async Task Pubternal_type_in_nested_namespace_field___warning_GF0001()
        {
            string library = @"
namespace MyLib.Internal.Services
{
    public class Bar
    {
        public void Do() { }
    }
}";

            TestSource code = TestSource.Read(@"
using MyLib.Internal.Services;

namespace MyProgram
{
    internal class Worker
    {
        private /*MM*/Bar _bar = new Bar();
    }
}");

            Diagnostic[] diagnostics = await this.GetDiagnosticsWithProjectReference(code.Source, library);

            Assert.AreEqual(0, diagnostics.Length);
        }
Пример #8
0
        public async Task Local___warning_GF0001()
        {
            string library = @"
namespace MyLib.Internal
{
    public class Bar
    {
        public void Do() { }
    }
}";

            TestSource code = TestSource.Read(@"
using MyLib.Internal;

namespace MyProgram
{
    internal class Worker
    {
        public void Do()
        {
            /*MM*/Bar bar = new Bar();
        }
    }
}");

            Diagnostic[] diagnostics = await this.GetDiagnosticsWithProjectReference(code.Source, library);

            Assert.AreEqual(0, diagnostics.Length);
        }
Пример #9
0
        public void GroupBy_must_fail_when_exceeding_maxSubstreams()
        {
            this.AssertAllStagesStopped(() =>
            {
                var f = Flow.Create <int>().GroupBy(1, x => x % 2).PrefixAndTail(0).MergeSubstreams();
                var t = ((Flow <int, Tuple <IImmutableList <int>, Source <int, NotUsed> >, NotUsed>)f)
                        .RunWith(TestSource.SourceProbe <int>(this), TestSink.SinkProbe <Tuple <IImmutableList <int>, Source <int, NotUsed> > >(this), Materializer);
                var up   = t.Item1;
                var down = t.Item2;

                down.Request(2);

                up.SendNext(1);
                var first = down.ExpectNext();
                var s1    = new StreamPuppet(first.Item2.RunWith(Sink.AsPublisher <int>(false), Materializer), this);

                s1.Request(1);
                s1.ExpectNext(1);

                up.SendNext(2);
                var ex = down.ExpectError();
                ex.Message.Should().Contain("too many substreams");
                s1.ExpectError(ex);
            }, Materializer);
        }
Пример #10
0
        public async Task Pubternal_type_in_nested_namespace_field___warning_GF0001()
        {
            string library = @"
namespace gfoidl.Internal.Services
{
    public class Bar
    {
        public void Do() { }
    }
}";

            TestSource code = TestSource.Read(@"
using gfoidl.Internal.Services;

namespace MyProgram
{
    internal class Worker
    {
        private /*MM*/Bar _bar = new Bar();
    }
}");
            Diagnostic[] diagnostics    = await this.GetDiagnosticsWithProjectReference(code.Source, library);
            DiagnosticLocation expected = code.DefaultMarkerLocation;

            Assert.Multiple(() =>
            {
                Assert.AreEqual(1, diagnostics.Length);

                Diagnostic diagnostic = diagnostics[0];
                Assert.AreEqual("GF0001", diagnostic.Id);
                Assert.IsTrue(diagnostic.Location.IsInSource);
                Assert.That(diagnostic.Location, Is.EqualTo(expected));
            });
        }
Пример #11
0
        public async Task StartupAnalyzer_WorksWithOtherMethodsInProgram()
        {
            // Arrange
            var source = TestSource.Read(@"using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
        builder.Services.AddMvc();
        var app = builder.Build();
        app.UseStaticFiles();
        app.UseMiddleware<AuthorizationMiddleware>();
        /*MM*/app.UseMvc();
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
        });
        app.Run();
    }

    private static void MethodA()
    {
    }

    private static void MethodB()
    {
    }
}");

            // Act
            var diagnostics = await Runner.GetDiagnosticsAsync(source.Source);

            // Assert
            var optionsAnalysis = Assert.Single(Analyses.OfType <OptionsAnalysis>());

            Assert.False(OptionsFacts.IsEndpointRoutingExplicitlyDisabled(optionsAnalysis));

            var middlewareAnalysis = Assert.Single(Analyses.OfType <MiddlewareAnalysis>());

            Assert.Collection(
                middlewareAnalysis.Middleware,
                item => Assert.Equal("UseStaticFiles", item.UseMethod.Name),
                item => Assert.Equal("UseMiddleware", item.UseMethod.Name),
                item => Assert.Equal("UseMvc", item.UseMethod.Name),
                item => Assert.Equal("UseRouting", item.UseMethod.Name),
                item => Assert.Equal("UseEndpoints", item.UseMethod.Name));

            Assert.Collection(
                diagnostics,
                diagnostic =>
            {
                Assert.Same(StartupAnalyzer.Diagnostics.UnsupportedUseMvcWithEndpointRouting, diagnostic.Descriptor);
                AnalyzerAssert.DiagnosticLocation(source.DefaultMarkerLocation, diagnostic.Location);
                Assert.Contains("inside 'Main", diagnostic.GetMessage());
            });
        }
Пример #12
0
    public static TestSource Read(string rawSource)
    {
        var testInput = new TestSource();
        var lines     = rawSource.Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);

        for (var i = 0; i < lines.Length; i++)
        {
            var line = lines[i];

            while (true)
            {
                var markerStartIndex = line.IndexOf(MarkerStart, StringComparison.Ordinal);
                if (markerStartIndex == -1)
                {
                    break;
                }

                var markerEndIndex = line.IndexOf(MarkerEnd, markerStartIndex, StringComparison.Ordinal);
                var markerName     = line.Substring(markerStartIndex + 2, markerEndIndex - markerStartIndex - 2);
                var markerLocation = new DiagnosticLocation(i + 1, markerStartIndex + 1);
                if (testInput.DefaultMarkerLocation == null)
                {
                    testInput.DefaultMarkerLocation = markerLocation;
                }

                testInput.MarkerLocations.Add(markerName, markerLocation);
                line = line.Substring(0, markerStartIndex) + line.Substring(markerEndIndex + MarkerEnd.Length);
            }

            lines[i] = line;
        }

        testInput.Source = string.Join(Environment.NewLine, lines);
        return(testInput);
    }
        private async Task VerifyNoDiagnosticsAreReturned(TestSource source)
        {
            // Act
            var result = await Executor.GetDiagnosticsAsync(source.Source);

            // Assert
            Assert.Empty(result);
        }
Пример #14
0
        public async Task ObservingThoughApiWorks()
        {
            await Prepared.ConfigureAwait(false);

            var builder = new HubConnectionBuilder()
                          .WithUrl($"http://test{LiveHub.Route}",
                                   cfg => cfg.HttpMessageHandlerFactory = _ => Server.CreateHandler())
            ;
            var hubConnection = builder.Build();
            await hubConnection.StartAsync();

            var       obs       = hubConnection.Observe <ChangeData>(nameof(LiveHub.Observe));
            const int takeCount = 10;
            var       sem       = new SemaphoreSlim(2); // Coordinate progress between produced data and listener

            var obsTask = obs
                          .TraceTest(Output)
                          .Take(takeCount)
                          .Select((v, idx) => new { v, idx })
                          // Start a new producer whenever we have received 5 items
                          .Do(x =>
            {
                if (x.idx % 5 == 0)
                {
                    sem.Release();
                }
            })
                          .TraceTest(Output)
                          .Select(x => x.v)
                          .ToListAsync(CancellationToken);

            var pushTask = TestSource.ProduceData(
                // Wait for sem for each batch of data
                sem.ObserveRelease().Take(2).Select(_ => DateTime.UtcNow)
                .TraceTest(Output)
                )
                           .TraceTest(Output)
                           .SelectMany(x => x)
                           .TraceTest(Output)
                           .ToListAsync(CancellationToken);

            // All ready, start pusing
            sem.Release();

            var observedChanges = await obsTask.ConfigureAwait(false);

            var observed = observedChanges.Select(c => c.Entity).ToList();
            var pushed   = await pushTask.ConfigureAwait(false);

            var expect = pushed.Take(takeCount);

            observed.Should().BeEquivalentTo(expect,
                                             cfg => cfg.Excluding(x => x.Installation).Excluding(x => x.Signal));
            // Reception should contained interleaved data
            observed.Select(x => x.InstallationId)
            .Should().NotBeAscendingInOrder()
            .And.NotBeDescendingInOrder();
        }
Пример #15
0
        public void Add_Positive_Test()
        {
            var source = new TestSource();

            Assert.Equal(3, source.Add(1, 2));
            Assert.Equal(5, source.Add(3, 2));
            Assert.NotEqual(8, source.Add(3, 4));
            Assert.NotEqual(10, source.Add(5, 4));
        }
Пример #16
0
        public void GetPage_Should_Stop_Loading_Pages_When_LoadPage_Throws()
        {
            var target = new TestSource(2);

            Assert.That(target.PagesLoaded, Is.Empty);

            Assert.ThrowsAsync <AggregateException>(() => target.GetPage(3));
            Assert.That(target.PagesLoaded, Is.EqualTo(new[] { 0, 1 }));
        }
Пример #17
0
        public void Add_Positive_Negative_Test()
        {
            var source = new TestSource();

            Assert.Equal(1, source.Add(-1, 2));
            Assert.Equal(1, source.Add(3, -2));
            Assert.NotEqual(5, source.Add(3, -4));
            Assert.NotEqual(-1, source.Add(5, -4));
        }
Пример #18
0
        public void Add_Negative_Test()
        {
            var source = new TestSource();

            Assert.Equal(-3, source.Add(-1, -2));
            Assert.Equal(-5, source.Add(-3, -2));
            Assert.NotEqual(-8, source.Add(-3, -4));
            Assert.NotEqual(-10, source.Add(-5, -4));
        }
Пример #19
0
        public void IsLoading_Should_Be_Set_To_False_When_LoadPage_Throws()
        {
            var target = new TestSource(2);

            Assert.That(target.PagesLoaded, Is.Empty);

            Assert.ThrowsAsync <AggregateException>(() => target.GetPage(3));
            Assert.That(target.IsLoading, Is.False);
        }
Пример #20
0
        public async Task GetPage_Should_Load_Pages()
        {
            var target = new TestSource();

            Assert.That(target.PagesLoaded, Is.Empty);

            var count = await target.GetPage(3);

            Assert.That(target.PagesLoaded, Is.EqualTo(new[] { 0, 1, 2, 3 }));
        }
Пример #21
0
 public void DefaultMappingAction_PropertyIsNull_InvalidCastExceptionIsThrown()
 {
     Assert.Throws(
         typeof(InvalidCastException),
         new TestDelegate(() =>
     {
         var mapFromTestSourceToDestination = new Map(typeof(TestSource), typeof(Destination));
         var sourceObject = new TestSource();
         mapFromTestSourceToDestination.DefaultMappingAction(sourceObject);
     }));
 }
Пример #22
0
        public void GetFileByName_FileInFinalSubFolder_IsFoundByNameWithSubDirsImplicit()
        {
            // Arrange
            string fileName = "Sub2FolderBinFile.rar";
            // Act
            ITestSourceItem testSourcesItem = TestSource.GetFileByName(fileName, true);

            // Assert
            testSourcesItem.Should().NotBeNull();
            testSourcesItem.Name.Should().Be(fileName);
        }
Пример #23
0
        public void GetByName_FileInRoot_IsNotFoundByNameInLowerCase()
        {
            // Arrange
            string fileName = "binfile01.rar";

            // Act
            ITestSourceItem testSourcesItem = TestSource.GetByName(fileName, false);

            // Assert
            testSourcesItem.Should().BeNull();
        }
Пример #24
0
        public async Task GetCount_Should_Load_First_Page()
        {
            var target = new TestSource();

            Assert.That(target.PagesLoaded, Is.Empty);

            var count = await target.GetCount();

            Assert.That(count, Is.EqualTo(100));
            Assert.That(target.PagesLoaded, Is.EqualTo(new[] { 0 }));
        }
Пример #25
0
        public void GetByName_UnexistingFileInRoot_IsNotFoundByNameWithoutSubdirs()
        {
            // Arrange
            string fileName = "IDoNotExist.ext";

            // Act
            ITestSourceItem testSourcesItem = TestSource.GetByName(fileName, false);

            // Assert
            testSourcesItem.Should().BeNull();
        }
Пример #26
0
        public IDictionary <string, string> ImmutableDictionaryAdd(TestSource test)
        {
            var dictionary = ImmutableDictionary <string, string> .Empty;

            foreach (var s in test.Data)
            {
                dictionary = dictionary.Add(s, s);
            }

            return(dictionary);
        }
Пример #27
0
        public void ShouldWork()
        {
            var source = new TestSource();
            var target = new TestTarget();

            this.utilitiesService.UpdatePropertiesReflection(source, target);

            source.Date.Should().Be(target.Date);
            source.Name.Should().Be(target.Name);
            source.Id.Should().Be(target.Id);
        }
Пример #28
0
        public void GetFolderByName_FolderInFinalSubFolder_IsFoundByNameWithSubDirsExplicit()
        {
            // Arrange
            string folderName = "sub02";

            // Act
            ITestSourceItem testSourcesItem = TestSource.GetFolderByName(folderName, true);

            // Assert
            testSourcesItem.Should().NotBeNull();
            testSourcesItem.Name.Should().Be(folderName);
        }
Пример #29
0
        public void GetFolderByName_FolderInRoot_IsFoundByNameWithoutSubDirs()
        {
            // Arrange
            string folderName = "FileContentTests";

            // Act
            ITestSourceItem testSourcesItem = TestSource.GetFolderByName(folderName, false);

            // Assert
            testSourcesItem.Should().NotBeNull();
            testSourcesItem.Name.Should().Be(folderName);
        }
        public void CanRemoveEventHandler()
        {
            var source    = new TestSource();
            int beforeRun = source.Count;

            source.Fire();

            Assert.IsTrue(source.Count == 1);
            source.Clean();
            source.Fire();
            Assert.IsTrue(source.Count == 1);
        }
        public void PropertySource_is_stored_and_retrieved()
        {
            var target = new Tracker();
            var source = new TestSource();
            var metadata = new HarshObjectMetadata(typeof(Tracker));

            var accessor = metadata.ReadableWritableInstanceProperties.Single();

            accessor.SetValue(target, "42", source);

            Assert.Equal("42", target.Property);
            Assert.Same(source, accessor.GetValueSource(target));
        }
        public void IsolateSecureSettingSource()
        {
            var testSource = new TestSource {Name = Value };
            _fakeSetting = new TestSetting(testSource);
            _fakeSetting.Key = _fakeSetting.SecureMarker + Value;
            _fakeSetting.Value = _fakeSetting.SecureMarker + Value;
            Isolate.WhenCalled(() => _fakeSetting.Key = null).CallOriginal();

            _secretKeyManager = new SecretKeyManager();
            Isolate.WhenCalled(() => _secretKeyManager.GetKey()).WillReturn(Secret);

            _crypt = Isolate.Fake.Instance<CryptoGraphy>();
            Isolate.WhenCalled(() => _crypt.SetKey(Secret)).IgnoreCall();

            _secureSetting = new SecureSetting(_fakeSetting, _secretKeyManager, _crypt);

            Isolate.WhenCalled(() => _crypt.Encrypt(Value)).WillReturn(Value);
            var secureValue = _secureSetting.SecureMarker + Value;
            Isolate.WhenCalled(() => _crypt.Decrypt(secureValue)).WillReturn(Value);
        }
Пример #33
0
		public MainWindow()
		{
			InitializeComponent();

			// immediate flush
			_logManager.FlushInterval = TimeSpan.FromMilliseconds(1);

			// set test log source
			_logManager.Sources.Add(_testSource = new TestSource());

			// set .NET Trace system based source
			_logManager.Sources.Add(new StockSharp.Logging.TraceSource());

			// write logs into MainWindow
			_logManager.Listeners.Add(new GuiLogListener(Monitor));

			// and file logs.txt
			_logManager.Listeners.Add(new FileLogListener
			{
				FileName = "logs",
			});
		}