示例#1
0
        public async Task EmptyResult()
        {
            // Arrange
            var level = Fixture.Create <int>() % MaxLevel;
            var x     = Fixture.Create <int>();
            var y     = Fixture.Create <int>();

            using var container = AutoSubstitute.Configure()
                                  .Provide(Options)
                                  .InitializeProviderTests()
                                  .ConfigureParameterQ(GetParameterQ(level, x, y))
                                  .Build();

            var empty = Task.FromResult <Stream>(new MemoryStream());

            GetStreamFromPlateTilePyramidAsync(container.Resolve <IPlateTilePyramid>(), level, x, y).Returns(empty, default);

            // Act
            await container.RunProviderTestAsync <T>();

            // Assert
            await GetStreamFromPlateTilePyramidAsync(container.Resolve <IPlateTilePyramid>().Received(1), level, x, y);

            Assert.Empty(container.GetOutputData());
        }
示例#2
0
        private IContainer CreateMock(string name, bool exists)
        {
            var options = _fixture.Create <AzureTourOptions>();

            return(AutoSubstitute.Configure()
                   .InjectProperties()
                   .MakeUnregisteredTypesPerLifetime()
                   .Provide(options)
                   .SubstituteFor <DownloadResult>()
                   .SubstituteFor <BlobClient>()
                   .ConfigureSubstitute((client, ctx) =>
            {
                if (exists)
                {
                    var s = ctx.Resolve <DownloadResult>();
                    client.Configure().OpenReadAsync(Arg.Any <BlobOpenReadOptions>()).Returns(s);
                }
                else
                {
                    Task <Stream> Throws(CallInfo _) => throw new RequestFailedException(string.Empty);

                    client.Configure().OpenReadAsync(Arg.Any <BlobOpenReadOptions>()).Returns(Throws);
                }
            })
                   .SubstituteFor <BlobContainerClient>()
                   .ResolveReturnValue(container => container.GetBlobClient(name))
                   .SubstituteFor <BlobServiceClient>()
                   .ResolveReturnValue(service => service.GetBlobContainerClient(options.ContainerName))
                   .Build().Container);
        }
示例#3
0
        public async Task NullResult()
        {
            // Arrange
            var level = Fixture.Create <int>() % MaxLevel;
            var x     = Fixture.Create <int>();
            var y     = Fixture.Create <int>();

            using var container = AutoSubstitute.Configure()
                                  .Provide(Options)
                                  .InitializeProviderTests()
                                  .ConfigureParameterQ(GetParameterQ(level, x, y))
                                  .Build();

            GetStreamFromPlateTilePyramidAsync(container.Resolve <IPlateTilePyramid>(), level, x, y).Returns((Stream)null);

            if (NullStreamResponseHandler is null)
            {
                await Assert.ThrowsAsync <NullReferenceException>(() => container.RunProviderTestAsync <T>());
            }
            else
            {
                // Act
                await container.RunProviderTestAsync <T>();

                // Assert
                await GetStreamFromPlateTilePyramidAsync(container.Resolve <IPlateTilePyramid>().Received(1), level, x, y);

                NullStreamResponseHandler(container.Resolve <IResponse>());
            }
        }
示例#4
0
        public void LowLevels(int level)
        {
            // Arrange
            var x       = _fixture.Create <int>();
            var y       = _fixture.Create <int>();
            var options = _fixture.Create <DSSOptions>();

            using var container = AutoSubstitute.Configure()
                                  .InitializeHttpWrappers()
                                  .Provide(options)
                                  .ConfigureParameters(a => a.Add("Q", $"{level},{x},{y}"))
                                  .Build();

            var data         = _fixture.CreateMany <byte>(10);
            var result       = new MemoryStream(data.ToArray());
            var outputStream = new MemoryStream();

            container.Resolve <HttpResponseBase>().Configure().OutputStream.Returns(outputStream);
            container.Resolve <IPlateTilePyramid>().GetStream(options.WwtTilesDir, "dssterrapixel.plate", level, x, y).Returns(result);

            // Act
            container.Resolve <DSSProvider>().Run(container.Resolve <IWwtContext>());

            // Assert
            Assert.Equal("image/png", container.Resolve <HttpResponseBase>().ContentType);
            Assert.Equal(data, outputStream.ToArray());
        }
示例#5
0
        public void HighLevels(int level, int x, int y, int fileX, int fileY, int level2, int x2, int y2)
        {
            // Arrange
            var options = _fixture.Create <DSSOptions>();

            using var container = AutoSubstitute.Configure()
                                  .InitializeHttpWrappers()
                                  .Provide(options)
                                  .ConfigureParameters(a => a.Add("Q", $"{level},{x},{y}"))
                                  .Build();

            var data         = _fixture.CreateMany <byte>(10);
            var result       = new MemoryStream(data.ToArray());
            var outputStream = new MemoryStream();
            var filename     = $"DSSpngL5to12_x{fileX}_y{fileY}.plate";

            container.Resolve <HttpResponseBase>().Configure().OutputStream.Returns(outputStream);
            container.Resolve <IPlateTilePyramid>().GetStream(options.DssTerapixelDir, filename, level2, x2, y2).Returns(result);

            // Act
            container.Resolve <DSSProvider>().Run(container.Resolve <IWwtContext>());

            // Assert
            //Assert.Equal("image/png", container.Resolve<HttpResponseBase>().ContentType);
            Assert.Equal(data, outputStream.ToArray());
        }
示例#6
0
        public async Task AboveMaxLevel()
        {
            if (MaxLevel < 0)
            {
                return;
            }

            foreach (var level in GetLevelsAboveMax())
            {
                // Arrange
                var x = Fixture.Create <int>();
                var y = Fixture.Create <int>();

                using var container = AutoSubstitute.Configure()
                                      .Provide(Options)
                                      .InitializeProviderTests()
                                      .ConfigureParameterQ(GetParameterQ(level, x, y))
                                      .Build();

                // Act
                await container.RunProviderTestAsync <T>();

                // Assert
                ExpectedResponseAboveMaxLevel(container.Resolve <IResponse>());
            }

            IEnumerable <int> GetLevelsAboveMax()
            {
                for (int i = 0; i < 10; i++)
                {
                    yield return(MaxLevel + Fixture.Create <int>());
                }
            }
        }
        private static AutoSubstituteBuilder ConfigureServiceClient(string plateFile, int level, int x, int y, string expectedContainerName = null, string blobFormat = null)
        {
            // For all the non dss plate files
            var blobName      = $"{plateFile.Replace(".plate", string.Empty)}/L{level}X{x}Y{y}.png";
            var containerName = AzurePlateTilePyramidOptions.DefaultContainer;

            if (plateFile == "dssterrapixel.plate")
            {
                blobName      = $"DSSTerraPixelL{level}X{x}Y{y}.png";
                containerName = "dss";
            }

            return(AutoSubstitute.Configure()
                   .InjectProperties()
                   .MakeUnregisteredTypesPerLifetime()
                   .SubstituteFor <Response <BlobDownloadInfo> >()
                   .SubstituteFor <DownloadResult>()
                   .Provide(ctx => BlobsModelFactory.BlobDownloadInfo(content: ctx.Resolve <DownloadResult>()))
                   .SubstituteFor <BlobClient>()
                   .ResolveReturnValue(c => c.Download())
                   .SubstituteFor <BlobContainerClient>()
                   .ResolveReturnValue(t => t.GetBlobClient(blobName))
                   .ConfigureSubstitute(c =>
            {
                c.Configure()
                .CreateIfNotExists().Returns(Substitute.For <Response <BlobContainerInfo> >());
            })
                   .SubstituteFor <BlobServiceClient>()
                   .ResolveReturnValue(service => service.GetBlobContainerClient(containerName)));
        }
示例#8
0
        public async Task ExpectedTests()
        {
            for (int level = 0; level < MaxLevel; level++)
            {
                // Arrange
                var data = Fixture.CreateMany <byte>().ToArray();
                var x    = Fixture.Create <int>();
                var y    = Fixture.Create <int>();

                using var container = AutoSubstitute.Configure()
                                      .InitializeProviderTests()
                                      .Provide(Options)
                                      .ConfigureParameterQ(GetParameterQ(level, x, y))
                                      .Build();

                GetStreamFromPlateTilePyramidAsync(container.Resolve <IPlateTilePyramid>(), level, x, y).Returns(new MemoryStream(data));

                // Act
                await container.RunProviderTestAsync <T>();

                // Assert
                await GetStreamFromPlateTilePyramidAsync(container.Resolve <IPlateTilePyramid>().Received(1), level, x, y);

                Assert.Equal(data, container.GetOutputData());
            }
        }
        private static AutoSubstituteBuilder ConfigureServiceClient(string plateFile, int level, int x, int y, string expectedContainerName = null, string blobFormat = null)
        {
            blobFormat ??= "L{0}X{1}Y{2}.png";
            var blobName      = string.Format(blobFormat, level, x, y);
            var containerName = expectedContainerName ?? plateFile.Replace(".plate", string.Empty);

            return(AutoSubstitute.Configure()
                   .SubstituteFor2 <DownloadResult>().Provide(out var result).Configured()
                   .SubstituteFor2 <BlobClient>().Provide(out var blob).Configure(b =>
            {
                var response = Substitute.ForPartsOf <Response <BlobDownloadInfo> >();
                response.Value.Returns(BlobsModelFactory.BlobDownloadInfo(content: result.Value));

                b.Configure()
                .Download().Returns(response);

                b.WhenForAnyArgs(b => b.Upload(Arg.Any <Stream>(), Arg.Any <bool>(), Arg.Any <CancellationToken>()))
                .DoNotCallBase();
            })
                   .SubstituteFor2 <BlobContainerClient>().Provide(out var container).Configure(c =>
            {
                c.Configure()
                .GetBlobClient(blobName).Returns(blob.Value);

                c.Configure()
                .CreateIfNotExists().Returns(Substitute.For <Response <BlobContainerInfo> >());
            })
                   .SubstituteFor2 <BlobServiceClient>().Provide(out var service).Configure(service =>
            {
                service.Configure()
                .GetBlobContainerClient(containerName).Returns(container.Value);
            }));
        }
示例#10
0
        public void BuildsMap()
        {
            // Arrange
            var knownPlates = _fixture.CreateMany <string>(10).ToList();
            var file        = CreateFile(knownPlates);
            var options     = _fixture.Create <AzurePlateTilePyramidOptions>();

            using var mock = AutoSubstitute.Configure()
                             .MakeUnregisteredTypesPerLifetime()
                             .Provide(options)
                             .SubstituteFor <BlobServiceClient>()
                             .ResolveReturnValue(s => s.GetBlobContainerClient(options.Container))
                             .SubstituteFor <BlobContainerClient>()
                             .ResolveReturnValue(c => c.GetBlobClient(options.KnownPlateFile))
                             .SubstituteFor <BlobClient>()
                             .ConfigureSubstitute(b => b.OpenRead().Returns(file))
                             .Build();

            var known = mock.Resolve <AzureKnownPlateFile>();

            var expected = knownPlates[3];
            var upper    = expected.ToUpperInvariant();

            // Act/Assert
            Assert.True(known.TryNormalizePlateName(expected, out var test1));
            Assert.Equal(expected, test1);

            Assert.True(known.TryNormalizePlateName(upper, out var test2));
            Assert.NotEqual(upper, test2);
            Assert.Equal(expected, test2);

            Assert.False(known.TryNormalizePlateName(_fixture.Create <string>(), out _));
        }
示例#11
0
        public void FailsIfSubstituteTypeIsChanged()
        {
            var builder = AutoSubstitute.Configure()
                          .SubstituteFor <Test1>();

            Assert.Throws <InvalidOperationException>(() => builder.SubstituteForPartsOf <Test1>());
        }
示例#12
0
        public void RedisUsedWithConnectionString()
        {
            // Arrange
            var original = Substitute.For <ITestService>();
            var mock     = AutoSubstitute.Configure()
                           .InjectProperties()
                           .MakeUnregisteredTypesPerLifetime()
                           .ConfigureOptions(options =>
            {
                options.MockHandlers.Add(SkipTypeMockHandler.Create(typeof(IValidateOptions <>)));
            })
                           .ConfigureServices(services =>
            {
                services.AddSingleton(original);
                services
                .AddCaching(options =>
                {
                    options.UseCaching = true;
                    options.RedisCacheConnectionString = _fixture.Create <string>();
                })
                .CacheType <ITestService>(_ => { });
            })
                           .SubstituteFor <IConnectionMultiplexer>()
                           .Build();

            // Act
            var resolved = mock.Resolve <IDistributedCache>();

            // Assert
            var inMemory = Assert.IsType <AppInsightsDistributedCache>(resolved);
        }
        public void InternalConstructorFails()
        {
            using var mock = AutoSubstitute.Configure()
                             .Build()
                             .Container;

            Assert.Throws <DependencyResolutionException>(() => mock.Resolve <ClassWithInternalConstructor>());
        }
        public void ProvideImplementation()
        {
            using var mock = AutoSubstitute.Configure()
                             .Provide <IServiceA, ServiceA>(out var serviceA)
                             .Build();

            Assert.IsNotNull(serviceA.Value);
            Assert.IsFalse(serviceA.Value is ICallRouter);
        }
        public void BaseCallDisabled()
        {
            using var mock = AutoSubstitute.Configure()
                             .SubstituteForPartsOf <ClassWithBase>().DoNotCallBase()
                             .Build()
                             .Container;

            Assert.Null(mock.Resolve <ClassWithBase>().Throws());
        }
        public void BaseCalledByDefault()
        {
            using var mock = AutoSubstitute.Configure()
                             .SubstituteForPartsOf <ClassWithBase>()
                             .Build()
                             .Container;

            Assert.Throws <InvalidOperationException>(() => mock.Resolve <ClassWithBase>().Throws());
        }
        public void InternalConstructorSucceeds()
        {
            using var mock = AutoSubstitute.Configure()
                             .UnregisteredTypesUseInternalConstructor()
                             .Build()
                             .Container;

            Assert.NotNull(mock.Resolve <ClassWithInternalConstructor>());
        }
示例#18
0
        public void PropertiesNotSetByDefault()
        {
            using var mock = AutoSubstitute.Configure()
                             .Provide <IProperty, CustomProperty>(out _)
                             .SubstituteFor <TestWithProperty>()
                             .Build();

            Assert.IsNull(mock.Resolve <TestWithProperty>().PropertySetter);
            Assert.That(mock.Resolve <TestWithProperty>().VirtualProperty, Is.NSubstituteMock);
        }
        public void NoInjectPropertiesClass()
        {
            using var mock = AutoSubstitute.Configure()
                             .Build()
                             .Container;

            var obj = mock.Resolve <WithProperties>();

            Assert.IsNull(obj.Service);
        }
示例#20
0
        public void BaseNotCalledOnSubstituteFor()
        {
            using var mock = AutoSubstitute.Configure()
                             .SubstituteFor <Test1>()
                             .Build();

            var test1 = mock.Resolve <Test1>();

            Assert.That(test1, Is.NSubstituteMock);
            Assert.Null(test1.Throws());
        }
示例#21
0
        public void BaseCalledOnSubstituteForPartsOf()
        {
            using var mock = AutoSubstitute.Configure()
                             .SubstituteForPartsOf <Test1>()
                             .Build();

            var test1 = mock.Resolve <Test1>();

            Assert.That(test1, Is.NSubstituteMock);
            Assert.Throws <InvalidOperationException>(() => test1.Throws());
        }
示例#22
0
        public void PropertiesSetIfGloballyRequested()
        {
            using var mock = AutoSubstitute.Configure()
                             .InjectProperties()
                             .Provide <IProperty, CustomProperty>(out var property)
                             .SubstituteFor <TestWithProperty>()
                             .Build();

            Assert.AreEqual(property.Value, mock.Resolve <TestWithProperty>().PropertySetter);
            Assert.AreEqual(property.Value, mock.Resolve <TestWithProperty>().VirtualProperty);
        }
        public void NoInjectPropertiesInterface()
        {
            using var mock = AutoSubstitute.Configure()
                             .Build()
                             .Container;

            var testInterface1 = mock.Resolve <ITestInterface1>();
            var class1         = mock.Resolve <Class1>();

            Assert.AreNotSame(class1, testInterface1.Instance);
        }
        public void InjectPropertiesInterface()
        {
            using var mock = AutoSubstitute.Configure()
                             .InjectProperties()
                             .Build()
                             .Container;

            var testInterface1 = mock.Resolve <ITestInterface1>();

            Assert.That(testInterface1.Instance, Is.TypeOf <Class1>());
        }
        public void ManuallyAddTypeToSkip()
        {
            var mock = AutoSubstitute.Configure()
                       .ConfigureOptions(options =>
            {
                options.TypesToSkipForMocking.Add(typeof(IDependency));
            })
                       .Build();

            Assert.Throws <ComponentNotRegisteredException>(() => mock.Resolve <IDependency>());
        }
        public void InjectPropertiesInterfaceRecursive()
        {
            using var mock = AutoSubstitute.Configure()
                             .InjectProperties()
                             .MakeUnregisteredTypesPerLifetime()
                             .Build()
                             .Container;

            var obj = mock.Resolve <ITestInterfaceRecursive>();

            Assert.AreSame(obj, obj.Instance.Recursive);
        }
        public void Example_provide_service_with_out_param()
        {
            const int val1 = 2;

            using var mock = AutoSubstitute.Configure()
                             .Provide <ConcreteClassWithDependency>(out var c, new TypedParameter(typeof(int), val1))
                             .Build();

            var result = mock.Resolve <ConcreteClassWithDependency>();

            Assert.AreSame(result, c.Value);
        }
        public void InjectPropertiesInterfaceWithUnregisteredPerLifetime()
        {
            using var mock = AutoSubstitute.Configure()
                             .InjectProperties()
                             .MakeUnregisteredTypesPerLifetime()
                             .Build()
                             .Container;

            var class1         = mock.Resolve <Class1>();
            var testInterface1 = mock.Resolve <ITestInterface1>();

            Assert.AreSame(class1, testInterface1.Instance);
        }
        public void TestIListCorrectlyResolves()
        {
            using var autosub = AutoSubstitute.Configure()
                                .Provide <IServiceItem, ServiceItemA>(out var mockA)
                                .Provide <IServiceItem, ServiceItemB>(out var mockB)
                                .Build();

            var component = autosub.Resolve <TestIListComponent>();

            Assert.That(component.ServiceItems, Is.Not.Empty);
            Assert.That(component.ServiceItems.Contains(mockA.Value), Is.True);
            Assert.That(component.ServiceItems.Contains(mockB.Value), Is.True);
        }
        public void WithoutOption()
        {
            var mock = AutoSubstitute.Configure()
                       .Provide <IDependency, Impl1>(out var impl1)
                       .Provide <IDependency, Impl2>(out var impl2)
                       .Build();

            var items = mock.Resolve <IDependency[]>();

            Assert.AreEqual(impl1.Value, items[0]);
            Assert.AreEqual(impl2.Value, items[1]);
            Assert.That(items[2], Is.NSubstituteMock);
        }