public void TestRegisterServiceNoGeneric()
 {
     ServiceMock s = new ServiceMock();
     _container.RegisterService(typeof(IContract), s);
     IContract c;
     c = _container.GetService<IContract>();
     Assert.IsNotNull(c);
     Assert.AreEqual("dave", c.Echo("dave"));
 }
        public async void Get_WhenPremiumMessage_ShouldThrowValidException()
        {
            ServiceMock.ForceResponse("PREMIUM");

            Func <Task <Result <TimeSeriesEntry> > > get = () => AlphaVantage.Stocks.Daily("MSFT").GetAsync();

            var exception = await get.ShouldThrowAsync <AlphaVantageException>();

            exception.Message.ShouldBe("Thank you for using Alpha Vantage! Please visit https://www.alphavantage.co/premium/ if you would like to have a higher API call volume.");
        }
        public void RegisterNamedInstanceReturnsSameInstance()
        {
            var instance  = new ServiceMock();
            var container = new ContainerExtension();

            container.RegisterInstance <object>(instance, "Test");
            var resolved = container.Resolve <object>("Test");

            Assert.Same(instance, resolved);
        }
        public async void Get_WhenError_ShouldThrowValidException()
        {
            ServiceMock.ForceResponse("ERROR");

            Func <Task <Result <TimeSeriesEntry> > > get = () => AlphaVantage.Stocks.Daily("MSFT").GetAsync();

            var exception = await get.ShouldThrowAsync <AlphaVantageException>();

            exception.Message.ShouldBe("Invalid API call. Please retry or visit the documentation (https://www.alphavantage.co/documentation/) for CMO.");
        }
        public async void Get_WhenApiLimitMessage_ShouldThrowValidException()
        {
            ServiceMock.ForceResponse("APILIMIT");

            Func <Task <Result <TimeSeriesEntry> > > get = () => AlphaVantage.Stocks.Daily("MSFT").GetAsync();

            var exception = await get.ShouldThrowAsync <AlphaVantageApiLimitException>();

            exception.Message.ShouldBe("Thank you for using Alpha Vantage! Our standard API call frequency is 5 calls per minute and 500 calls per day. Please visit https://www.alphavantage.co/premium/ if you would like to target a higher API call frequency.");
        }
Exemple #6
0
        private void SendOfflineBroadcastResponseMessage(string channelId, object broadcastMessage,
                                                         int numberOfClients, int numberOfMessages,
                                                         int openConnectionTimeout,
                                                         int allMessagesReceivedTimeout)
        {
            ThreadPool.SetMinThreads(50, 2);

            ClientMockFarm aClientFarm = new ClientMockFarm(MessagingSystem, channelId, numberOfClients);
            ServiceMock    aService    = new ServiceMock(MessagingSystem, channelId);

            try
            {
                aService.InputChannel.StartListening();

                // Send broadcasts.
                for (int i = 0; i < numberOfMessages; ++i)
                {
                    aService.InputChannel.SendResponseMessage("*", broadcastMessage);
                }

                Thread.Sleep(500);

                aClientFarm.OpenConnectionsAsync();

                aClientFarm.WaitUntilAllConnectionsAreOpen(openConnectionTimeout);
                aService.WaitUntilResponseReceiversConnectNotified(numberOfClients, openConnectionTimeout);
                Assert.AreEqual(aClientFarm.Clients.Count(), aService.ConnectedResponseReceivers.Count());
                foreach (ClientMock aClient in aClientFarm.Clients)
                {
                    Assert.IsTrue(aService.ConnectedResponseReceivers.Any(x => x.ResponseReceiverId == aClient.OutputChannel.ResponseReceiverId));
                }

                PerformanceTimer aStopWatch = new PerformanceTimer();
                aStopWatch.Start();

                aClientFarm.WaitUntilAllResponsesAreReceived(numberOfMessages, allMessagesReceivedTimeout);

                aStopWatch.Stop();

                foreach (DuplexChannelMessageEventArgs aResponseMessage in aClientFarm.ReceivedResponses)
                {
                    Assert.AreEqual(broadcastMessage, aResponseMessage.Message);
                }
            }
            finally
            {
                EneterTrace.Debug("CLEANING AFTER TEST");

                aClientFarm.CloseAllConnections();
                aService.InputChannel.StopListening();

                //EneterTrace.StopProfiler();
                Thread.Sleep(500);
            }
        }
Exemple #7
0
        public void TestRegisterServiceNoGeneric()
        {
            ServiceMock s = new ServiceMock();

            _container.RegisterService(typeof(IContract), s);
            IContract c;

            c = _container.GetService <IContract>();
            Assert.IsNotNull(c);
            Assert.AreEqual("dave", c.Echo("dave"));
        }
        public void PutTest()
        {
            var category = new Category {
                Name = "test"
            };

            Controller.PutAsync(category).Wait();

            MapperMock.Verify(m => m.Map <DAL.Entities.Category>(category), Times.Once());
            ServiceMock.Verify(s => s.UpdateCategoryAsync(It.IsAny <DAL.Entities.Category>()), Times.Once());
        }
        public void PutTest()
        {
            var model = new DTOs.AddOrUpdateModels.UpdateExpenseModel {
                Id = 1, Amount = 1000, CategoryId = 1, ReportId = 1, UserId = 1
            };

            Controller.PutAsync(model).Wait();

            MapperMock.Verify(m => m.Map <DAL.Entities.Expense>(model), Times.Once());
            ServiceMock.Verify(s => s.UpdateExpenseAsync(It.IsAny <DAL.Entities.Expense>()), Times.Once());
        }
Exemple #10
0
        public void EditStore_Post_saves_settings_into_company()
        {
            // Arrange

            var model = new StoreSettingsViewModel
            {
                Keywords = "app taxi cab",
                UniqueDeviceIdentificationNumber = new List <string> {
                    "1234567890abcdef"
                },
                AppStoreCredentials = new AppleStoreCredentials
                {
                    Username = "******",
                    Password = "******",
                    Team     = "team"
                },
                GooglePlayCredentials = new AndroidStoreCredentials
                {
                    Username = "******",
                    Password = "******"
                }
            };

            // Act
            Sut.EditStore(model);

            // Assert
            ServiceMock.Verify(x => x.UpdateStoreSettings(It.Is <StoreSettings>(s => s
                                                                                .Keywords == "app taxi cab"
                                                                                &&
                                                                                s.UniqueDeviceIdentificationNumber[0
                                                                                ] == "1234567890abcdef")));

            ServiceMock.Verify(x => x.UpdateAppleAppStoreCredentials(It.Is <AppleStoreCredentials>(s =>
                                                                                                   s.Username ==
                                                                                                   "user@appstore"
                                                                                                   &&
                                                                                                   s.Password ==
                                                                                                   "password"
                                                                                                   &&
                                                                                                   s.Team ==
                                                                                                   "team")));

            ServiceMock.Verify(x => x.UpdateGooglePlayCredentials(It.Is <AndroidStoreCredentials>(s =>
                                                                                                  s.Username ==
                                                                                                  "user@googleplay"
                                                                                                  &&
                                                                                                  s.Password ==
                                                                                                  "password")));
        }
        public void TestRemoveGceManagedInstanceGroupByRegion()
        {
            string instanceGroupName = "instance-group";
            Mock <RegionInstanceGroupManagersResource> instances =
                ServiceMock.Resource(s => s.RegionInstanceGroupManagers);

            instances.SetupRequest(
                item => item.Delete(FakeProjectId, FakeRegionName, instanceGroupName), DoneOperation);

            Pipeline.Commands.AddScript(
                $"Remove-GceManagedInstanceGroup -Name {instanceGroupName} -Region {FakeRegionName}");
            Pipeline.Invoke();

            instances.VerifyAll();
        }
Exemple #12
0
        public void TestVss()
        {
            Mock <DisksResource.CreateSnapshotRequest> requestMock = ServiceMock.Resource(s => s.Disks).SetupRequest(
                d => d.CreateSnapshot(It.IsAny <Snapshot>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()),
                DoneOperation);
            var snapshotResult = new Snapshot();

            ServiceMock.Resource(s => s.Snapshots).SetupRequest(
                s => s.Get(It.IsAny <string>(), It.IsAny <string>()), snapshotResult);

            Pipeline.Commands.AddScript("Add-GceSnapShot -DiskName diskname -VSS");
            Collection <PSObject> results = Pipeline.Invoke();

            CollectionAssert.AreEqual(results, new[] { snapshotResult });
            requestMock.VerifySet(r => r.GuestFlush = true, Times.Once);
        }
Exemple #13
0
        public void TestLabels()
        {
            Mock <DisksResource.CreateSnapshotRequest> requestMock = ServiceMock.Resource(s => s.Disks).SetupRequest(
                d => d.CreateSnapshot(It.Is <Snapshot>(snapshot => snapshot.Labels["key"] == "value"),
                                      It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()),
                DoneOperation);
            var snapshotResult = new Snapshot();

            ServiceMock.Resource(s => s.Snapshots).SetupRequest(
                s => s.Get(It.IsAny <string>(), It.IsAny <string>()), snapshotResult);

            Pipeline.Commands.AddScript("Add-GceSnapShot -DiskName diskname -Label @{'key' = 'value'}");
            Collection <PSObject> results = Pipeline.Invoke();

            CollectionAssert.AreEqual(results, new[] { snapshotResult });
        }
Exemple #14
0
        public async Task UpdateContactAsync_WhereInputIsValid_ReturnsSuccessContactStatus()
        {
            //Arrange
            _contactServiceMock.Setup(x => x.UpdateContactAsync(It.IsAny <int>(), It.IsAny <ContactInfo>()))
            .Returns(Task.FromResult(new ResultHandler(ServiceMock.GetContact())));
            var controller = new ContactsController(_contactServiceMock.Object, _mapper)
            {
                ControllerContext = new ControllerContext {
                    HttpContext = new DefaultHttpContext()
                }
            };
            //Act
            var result = (OkObjectResult)await controller.PutAsync(ServiceMock.GetExistingContactRequest(), ServiceMock.GetAddContactRequest());

            //Assert
            Assert.Equal(StatusCodes.Status200OK, result.StatusCode);
        }
Exemple #15
0
        public async Task DeleteUsersAsync_WhereUserDoesNotExist_ReturnsSuccessCode()
        {
            //Arrange
            _contactServiceMock.Setup(x => x.DeleteContactAsync(It.IsAny <int>()))
            .Returns(Task.FromResult(new ResultHandler(String.Empty)));
            var controller = new ContactsController(_contactServiceMock.Object, _mapper)
            {
                ControllerContext = new ControllerContext {
                    HttpContext = new DefaultHttpContext()
                }
            };
            //Act
            var result = (BadRequestObjectResult)await _controller.DeleteAsync(ServiceMock.GetNonExistingContactRequest());

            //Assert
            Assert.Equal(StatusCodes.Status400BadRequest, result.StatusCode);
        }
Exemple #16
0
        public async Task AddContactAsync_WhereInputIsInvalid_ReturnsFailureContactStatus()
        {
            //Arrange
            _contactServiceMock.Setup(x => x.AddContactAsync(It.IsAny <ContactInfo>()))
            .Returns(Task.FromResult(new ResultHandler(String.Empty)));
            var controller = new ContactsController(_contactServiceMock.Object, _mapper)
            {
                ControllerContext = new ControllerContext {
                    HttpContext = new DefaultHttpContext()
                }
            };
            //Act
            var result = (BadRequestObjectResult)await controller.PostAsync(ServiceMock.GetInvalidAddContactRequest());

            //Assert
            Assert.Equal(StatusCodes.Status400BadRequest, result.StatusCode);
        }
        public void Init()
        {
            dataChar = new CharacteristicMock();
            dataChar.ID = new Guid(0xaa01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);

            switchChar = new CharacteristicMock();
            switchChar.ID = new Guid(0xaa02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);

            periodChar = new CharacteristicMock();
            periodChar.ID = new Guid(0xaa03, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);

            service = new ServiceMock();
            service.Characteristics = new List<ICharacteristic>()
            {
                dataChar, switchChar, periodChar
            };
        }
Exemple #18
0
        public void GetBookings_IdIsValid_ExpectedResult()
        {
            IList <BookingDto> list = new List <BookingDto> {
                new BookingDto()
            };

            ServiceMock.Setup(m => m.GetBookings(It.IsAny <int>())).Returns(Task.FromResult(list))
            .Verifiable();

            var response = sut.GetBookings(1).GetAwaiter().GetResult();

            ServiceMock.Verify();

            Assert.IsNotNull(response);
            Assert.IsInstanceOfType(response, typeof(Microsoft.AspNetCore.Mvc.OkObjectResult));
            Assert.AreEqual((int)HttpStatusCode.OK, (response as Microsoft.AspNetCore.Mvc.OkObjectResult).StatusCode);
        }
Exemple #19
0
        public void GetLocation_CoordinatesValid_ExpectedResult()
        {
            IList <HotelDto> list = new List <HotelDto> {
                new HotelDto()
            };

            ServiceMock.Setup(m => m.GetByLocation(It.IsAny <string>())).Returns(Task.FromResult(list))
            .Verifiable();

            var response = sut.GetLocation("19.22,189.33").GetAwaiter().GetResult();

            ServiceMock.Verify();

            Assert.IsNotNull(response);
            Assert.IsInstanceOfType(response, typeof(Microsoft.AspNetCore.Mvc.OkObjectResult));
            Assert.AreEqual((int)HttpStatusCode.OK, (response as Microsoft.AspNetCore.Mvc.OkObjectResult).StatusCode);
        }
Exemple #20
0
        public void A13_TimeoutedResponseReceiver()
        {
            ClientMock  aClient  = new ClientMock(MessagingSystem, ChannelId);
            ServiceMock aService = new ServiceMock(MessagingSystem, ChannelId);

            try
            {
                aService.InputChannel.StartListening();

                // Open the connection.
                aClient.OutputChannel.OpenConnection();
                Assert.IsTrue(aClient.OutputChannel.IsConnected);

                // handling open connection on the client side.
                EneterTrace.Info("1");
                aClient.WaitUntilConnectionOpenIsNotified(2000);
                Assert.AreEqual(aClient.OutputChannel.ChannelId, aClient.NotifiedOpenConnection.ChannelId);
                Assert.AreEqual(aClient.OutputChannel.ResponseReceiverId, aClient.NotifiedOpenConnection.ResponseReceiverId);

                // handling open connection on the service side.
                EneterTrace.Info("2");
                aService.WaitUntilResponseReceiversConnectNotified(1, 1000);
                Assert.AreEqual(1, aService.ConnectedResponseReceivers.Count());
                Assert.AreEqual(aClient.OutputChannel.ResponseReceiverId, aService.ConnectedResponseReceivers[0].ResponseReceiverId);

                aClient.OutputChannel.CloseConnection();
                Assert.IsFalse(aClient.OutputChannel.IsConnected);

                // Service will disconnect the response receiver when the offline timout is exceeded.
                EneterTrace.Info("3");
                aService.WaitUntilAllResponseReceiversDisconnectNotified(2000);
                Assert.AreEqual(1, aService.DisconnectedResponseReceivers.Count());
                Assert.AreEqual(aClient.OutputChannel.ResponseReceiverId, aService.DisconnectedResponseReceivers.First().ResponseReceiverId);
            }
            finally
            {
                EneterTrace.Debug("CLEANING AFTER TEST");

                aClient.OutputChannel.CloseConnection();
                aService.InputChannel.StopListening();

                // Wait for traces.
                Thread.Sleep(100);
            }
        }
        public void TestGetGceManagedInstanceGroupByNameAndRegion()
        {
            string instanceGroupName = FirstTestGroup.Name;
            Mock <RegionInstanceGroupManagersResource> instances =
                ServiceMock.Resource(s => s.RegionInstanceGroupManagers);

            instances.SetupRequest(
                item => item.Get(FakeProjectId, FakeRegionName, instanceGroupName), FirstTestGroup);

            Pipeline.Commands.AddScript(
                $"Get-GceManagedInstanceGroup -Name {instanceGroupName} -Region {FakeRegionName}");
            Collection <PSObject> results = Pipeline.Invoke();

            Assert.AreEqual(results.Count, 1);
            InstanceGroupManager retrievedInstance = results[0].BaseObject as InstanceGroupManager;

            Assert.AreEqual(retrievedInstance?.Name, instanceGroupName);
        }
Exemple #22
0
        public void PopulateRelationshipActionNoManyToManyRelationships()
        {
            string entityLogicalName = "contact";
            var    entityMetadata    = new EntityMetadata();

            var migratorServiceParameters = GenerateMigratorParameters();

            MetadataServiceMock.Setup(x => x.RetrieveEntities(It.IsAny <string>(), It.IsAny <IOrganizationService>(), It.IsAny <IExceptionService>()))
            .Returns(entityMetadata)
            .Verifiable();

            var actual = systemUnderTest.PopulateRelationshipAction(entityLogicalName, inputEntityRelationships, migratorServiceParameters);

            actual.Count.Should().Be(0);

            ServiceMock.VerifyAll();
            MetadataServiceMock.VerifyAll();
        }
        public void TestGetGcsObjectMissingError()
        {
            const string           bucketName = "mock-bucket";
            const string           objectName = "mock-object";
            Mock <ObjectsResource> objects    = ServiceMock.Resource(s => s.Objects);

            objects.SetupRequestError <ObjectsResource, ObjectsResource.GetRequest, Object>(
                o => o.Get(bucketName, objectName),
                new GoogleApiException("service-name", "error-message")
            {
                HttpStatusCode = HttpStatusCode.NotFound
            });

            Pipeline.Commands.AddScript($"Get-GcsObject -Bucket {bucketName} -ObjectName {objectName}");
            Pipeline.Invoke();

            TestErrorRecord(ErrorCategory.ResourceUnavailable);
        }
Exemple #24
0
        public async Task GetAllUsersAsync_WhereContactsExist_ReturnsSuccessCode()
        {
            //Arrange
            _contactServiceMock.Setup(x => x.GetContactsAsync())
            .Returns(Task.FromResult(ServiceMock.GetAllContacts()));
            var controller = new ContactsController(_contactServiceMock.Object, _mapper)
            {
                ControllerContext = new ControllerContext {
                    HttpContext = new DefaultHttpContext()
                }
            };
            //Act
            var expected = typeof(List <ContactInfo>);
            var result   = await _controller.GetAllContactsAsync();

            //Assert
            Assert.IsType <List <ContactInfo> >(result);
            Assert.IsType(expected, result);
        }
Exemple #25
0
        public void CreateBookings_CoordinatesValid_ExpectedResult()
        {
            IList <HotelDto> list = new List <HotelDto> {
                new HotelDto()
            };

            ServiceMock.Setup(m => m.CreateBookings(It.IsAny <BookingDto>())).Returns(Task.FromResult("test"))
            .Verifiable();

            var response = sut.CreateBookings(new BookingDto {
                From = DateTime.Now, To = DateTime.Now.AddDays(1), HotelId = 1
            })
                           .GetAwaiter().GetResult();

            ServiceMock.Verify();

            Assert.IsNotNull(response);
            Assert.IsInstanceOfType(response, typeof(Microsoft.AspNetCore.Mvc.OkObjectResult));
            Assert.AreEqual((int)HttpStatusCode.OK, (response as Microsoft.AspNetCore.Mvc.OkObjectResult).StatusCode);
        }
        public void TestGetGcsObjectNamed()
        {
            const string bucketName = "mock-bucket";
            const string objectName = "mock-object";
            var          response   = new Object {
                Bucket = bucketName, Name = objectName
            };
            Mock <ObjectsResource> objects = ServiceMock.Resource(s => s.Objects);

            objects.SetupRequest(o => o.Get(bucketName, objectName), response);

            Pipeline.Commands.AddScript($"Get-GcsObject -Bucket {bucketName} -ObjectName {objectName}");
            Collection <PSObject> results = Pipeline.Invoke();

            var result = results.Single().BaseObject as Object;

            Assert.IsNotNull(result);
            Assert.AreEqual(bucketName, result.Bucket);
            Assert.AreEqual(objectName, result.Name);
        }
        public void TestHandle()
        {
            var accountGuid        = Guid.NewGuid();
            var accountName        = "testName";
            var createAccountEvent = new CreateAccountEvent {
                EventGuid   = Guid.NewGuid(),
                ItemGuid    = accountGuid,
                AccountName = accountName
            };
            var accountServiceMock = new ServiceMock();
            var eventHandler       = new CreateAccountEventHandler(accountServiceMock);

            eventHandler.Handle(createAccountEvent);

            Assert.Single(ServiceMock.Saved);
            var accountModel = ServiceMock.Saved.First();

            Assert.True(accountModel.Guid.Equals(accountGuid));
            Assert.True(accountModel.Name.Equals(accountName));
        }
Exemple #28
0
        public void PopulateRelationshipAction()
        {
            string entityLogicalName = "account_contact";
            var    items             = new List <System.Windows.Forms.ListViewItem>
            {
                new System.Windows.Forms.ListViewItem("Item1"),
                new System.Windows.Forms.ListViewItem("Item2")
            };

            var entityMetadata = new EntityMetadata();

            var relationship = new ManyToManyRelationshipMetadata
            {
                Entity1LogicalName        = "account",
                Entity1IntersectAttribute = "accountid",
                IntersectEntityName       = "account_contact",
                Entity2LogicalName        = "contact",
                Entity2IntersectAttribute = "contactid"
            };

            InsertManyToManyRelationshipMetadata(entityMetadata, relationship);

            var migratorServiceParameters = GenerateMigratorParameters();

            MetadataServiceMock.Setup(x => x.RetrieveEntities(It.IsAny <string>(), It.IsAny <IOrganizationService>(), It.IsAny <IExceptionService>()))
            .Returns(entityMetadata)
            .Verifiable();

            using (var listView = new System.Windows.Forms.ListView())
            {
                var controller = new EntityController();
                controller.PopulateEntitiesListView(items, null, null, listView, NotificationServiceMock.Object);

                var actual = systemUnderTest.PopulateRelationshipAction(entityLogicalName, inputEntityRelationships, migratorServiceParameters);

                actual.Count.Should().BeGreaterThan(0);
            }

            ServiceMock.VerifyAll();
            MetadataServiceMock.VerifyAll();
        }
Exemple #29
0
        public void GetEpisodesForSeries()
        {
            var series = (PartialViewResult)_controller.GetEpisodes(1, "stringTitle");
            var model  = (SonarrEpisodeViewModel)series.Model;

            Assert.That(model.EpisodeViewModels.Count, Is.GreaterThan(0));
            Assert.That(model.SeasonTitle, Is.EqualTo("stringTitle"));
            Assert.That(model.EpisodeViewModels[SonarrEpisode[0].seasonNumber][0].Monitored, Is.EqualTo(SonarrEpisode[0].monitored));
            Assert.That(model.EpisodeViewModels[SonarrEpisode[0].seasonNumber][0].Overview, Is.EqualTo(SonarrEpisode[0].overview));
            Assert.That(model.EpisodeViewModels[SonarrEpisode[0].seasonNumber][0].Title, Is.EqualTo(SonarrEpisode[0].title));
            Assert.That(model.EpisodeViewModels[SonarrEpisode[0].seasonNumber][0].AbsoluteEpisodeNumber, Is.EqualTo(SonarrEpisode[0].absoluteEpisodeNumber));
            Assert.That(model.EpisodeViewModels[SonarrEpisode[0].seasonNumber][0].Downloading, Is.EqualTo(SonarrEpisode[0].downloading));
            Assert.That(model.EpisodeViewModels[SonarrEpisode[0].seasonNumber][0].EpisodeFileId, Is.EqualTo(SonarrEpisode[0].episodeFileId));
            Assert.That(model.EpisodeViewModels[SonarrEpisode[0].seasonNumber][0].HasFile, Is.EqualTo(SonarrEpisode[0].hasFile));
            Assert.That(model.EpisodeViewModels[SonarrEpisode[0].seasonNumber][0].ID, Is.EqualTo(SonarrEpisode[0].id));
            Assert.That(model.EpisodeViewModels[SonarrEpisode[0].seasonNumber][0].SeasonNumber, Is.EqualTo(SonarrEpisode[0].seasonNumber));


            ServiceMock.Verify(x => x.GetSonarrEpisodes(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>()), Times.Once);
            SettingsMock.Verify(x => x.GetSettings(), Times.Once);
        }
Exemple #30
0
        public void TestDiskNameParameterSet()
        {
            const string         diskName         = "diskname";
            Mock <DisksResource> diskResourceMock = ServiceMock.Resource(s => s.Disks);
            Mock <DisksResource.CreateSnapshotRequest> requestMock = diskResourceMock.SetupRequest(
                d => d.CreateSnapshot(
                    It.Is <Snapshot>(s => s.Name.StartsWith(diskName, StringComparison.Ordinal)), FakeProjectId, FakeZoneName,
                    diskName),
                DoneOperation);
            var snapshotResult = new Snapshot();

            ServiceMock.Resource(s => s.Snapshots).SetupRequest(
                s => s.Get(It.IsAny <string>(), It.IsAny <string>()), snapshotResult);

            Pipeline.Commands.AddScript($"Add-GceSnapShot -DiskName {diskName}");
            Collection <PSObject> results = Pipeline.Invoke();

            CollectionAssert.AreEqual(results, new[] { snapshotResult });
            diskResourceMock.VerifyAll();
            requestMock.VerifySet(r => r.GuestFlush = It.IsAny <bool>(), Times.Never);
        }
Exemple #31
0
        private void DynamicRequestLargePayload(int sizeKB, string requestQueue = "Resources", TimeSpan?timeout = null, bool checkHashInPayload = false)
        {
            //generate large payload
            var rand   = new Random(System.DateTimeOffset.Now.Millisecond);
            var ms     = new MemoryStream();
            var buffer = new byte[1024];

            for (var written = 0L; written < sizeKB; written++)
            {
                rand.NextBytes(buffer);
                ms.Write(buffer);
            }
            var base64String = Convert.ToBase64String(ms.ToArray());

            var msg = new
            {
                name     = $"rand{sizeKB}KB.bin",
                mimeType = "application/octet-stream",
                body     = base64String
            };

            var response = Fixture.AmqpService.RequestReply(msg, "PutResource", requestQueue, timeout);

            Assert.NotNull(response);
            var amqpApiResponse = AmqpApiUtils.ParseApiResult(response);

            Assert.NotNull(amqpApiResponse);
            Assert.NotNull(amqpApiResponse.ResponseObject);
            Assert.NotNull(amqpApiResponse.ResponseObject["uuid"]);
            var guid = Guid.Parse(amqpApiResponse.ResponseObject["uuid"].ToObject <string>());

            if (checkHashInPayload)
            {
                Assert.NotNull(amqpApiResponse.ResponseObject["hash"]);
                var hash          = amqpApiResponse.ResponseObject["hash"];
                var referenceHash = ServiceMock.Hash64Str(base64String);
                Assert.Equal(referenceHash, hash);
            }
        }