Exemplo n.º 1
0
 public void ReturnsCollection()
 {
     if (_generalSetup != null)
     {
         _generalSetup.Returns(Enumerable.Repeat(new T(), 2));
     }
     else if (_collectionTaskSetup != null)
     {
         Task = Task.Factory.StartNew(() =>
         {
             return(Enumerable.Repeat(new T(), 2));
         });
         _collectionTaskSetup.Returns((Task <IEnumerable <T> >)Task);
     }
 }
Exemplo n.º 2
0
        public static int SetUpDefaultRemoteAppVNetByName(Mock <IRemoteAppManagementClient> clientMock, string vNetName, bool IncludeSharedKey)
        {
            VNetResult response = new VNetResult();

            response.VNet = new VNet()
            {
                Name      = vNetName,
                Region    = "West US",
                SharedKey = "22222",
                State     = VNetState.Ready
            };

            mockVNetList = new List <VNet>()
            {
                new VNet()
                {
                    Name      = response.VNet.Name,
                    Region    = response.VNet.Region,
                    SharedKey = response.VNet.SharedKey,
                    State     = response.VNet.State
                }
            };

            ISetup <IRemoteAppManagementClient, Task <VNetResult> > setup = clientMock.Setup(c => c.VNet.GetAsync(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <CancellationToken>()));

            setup.Returns(Task.Factory.StartNew(() => response));

            return(mockVNetList.Count);
        }
Exemplo n.º 3
0
        protected T SetUpTestCommon <T>() where T : RdsCmdlet, new()
        {
            T RemoteAppCmdlet = null;
            ISetup <Microsoft.WindowsAzure.Management.ManagementClient, Task <AzureOperationResponse> > setup = null;

            AzureOperationResponse response = new AzureOperationResponse()
            {
                RequestId  = "1",
                StatusCode = System.Net.HttpStatusCode.OK
            };

            mgmtClient = new Mock <WindowsAzure.Management.ManagementClient>();
            setup      = mgmtClient.Setup(c => c.Subscriptions.RegisterResourceAsync("remoteapp", It.IsAny <CancellationToken>()));
            setup.Returns(Task.Factory.StartNew(() => response));

            RemoteAppCmdlet = new T()
            {
                CommandRuntime        = mockCommandRuntime,
                Client                = remoteAppManagementClientMock.Object,
                ActiveDirectoryHelper = new MockAdHelper(),
                MgmtClient            = mgmtClient.Object
            };

            return(RemoteAppCmdlet);
        }
        /// <summary>Returnses the in order.</summary>
        /// <typeparam name="T">Type T</typeparam>
        /// <typeparam name="TResult">The type of the result.</typeparam>
        /// <param name="setup">The setup.</param>
        /// <param name="results">The results.</param>
        public static void ReturnsInOrder <T, TResult>(this ISetup <T, TResult> setup, params object[] results) where T : class
        {
            var queue = new Queue(results);

            setup.Returns(
                () =>
            {
                try
                {
                    var result = queue.Dequeue();
                    if (result is Exception)
                    {
                        throw result as Exception;
                    }

                    queue.Enqueue(result);
                    return((TResult)result);
                }
                catch (Exception ex)
                {
                    Logger.Error(m => m("Error occurred dequeuing object."), ex);
                    throw;
                }
            });
        }
Exemplo n.º 5
0
        public static void SetUpDefaultEditWorkspace(Mock <IRemoteAppManagementClient> clientMock, string endUserFeedName)
        {
            ISetup <IRemoteAppManagementClient, Task <OperationResultWithTrackingId> > Setup = null;
            AccountDetailsParameter details = new AccountDetailsParameter()
            {
                AccountInfo = new AccountDetails()
                {
                    EndUserFeedName = endUserFeedName
                }
            };

            OperationResultWithTrackingId response = new OperationResultWithTrackingId()
            {
                StatusCode = System.Net.HttpStatusCode.Accepted,
                TrackingId = "34167",
                RequestId  = "111-2222-4444"
            };

            mockTrackingId = new List <TrackingResult>()
            {
                new TrackingResult(response)
            };

            Setup = clientMock.Setup(c => c.Account.SetAsync(It.IsAny <AccountDetailsParameter>(), It.IsAny <CancellationToken>()));
            Setup.Returns(Task.Factory.StartNew(() => response));
        }
Exemplo n.º 6
0
        public static IReturnsResult <TMock> Returns <TMock, TResult>(this ISetup <TMock, TResult> setup, IEnumerable <TResult> values)
            where TMock : class
        {
            var queue = new Queue <TResult>(values);

            return(setup.Returns(() => queue.Count > 0 ? queue.Dequeue() : default(TResult)));
        }
        public static int SetUpDefaultRemoteAppCollectionByName(Mock <IRemoteAppManagementClient> clientMock, string collectionName)
        {
            CollectionResult response = new CollectionResult();

            response.Collection = new Collection()
            {
                Name   = collectionName,
                Region = "West US",
                Status = "Active"
            };

            mockCollectionList = new List <Collection>()
            {
                new Collection()
                {
                    Name   = response.Collection.Name,
                    Region = response.Collection.Region,
                    Status = response.Collection.Status
                }
            };

            ISetup <IRemoteAppManagementClient, Task <CollectionResult> > setup = clientMock.Setup(c => c.Collections.GetAsync(collectionName, It.IsAny <CancellationToken>()));

            setup.Returns(Task.Factory.StartNew(() => response));

            return(mockCollectionList.Count);
        }
Exemplo n.º 8
0
 public static void ReturnsInOrder <T, TResult>(
     this ISetup <T, TResult> setup,
     params TResult[] results)
     where T : class
 {
     setup.Returns(new Func <TResult>(new Queue <TResult>((IEnumerable <TResult>)results).Dequeue));
 }
        public static void SetUpDefaultRemoteAppRegionList(Mock <IRemoteAppManagementClient> clientMock)
        {
            ISetup <IRemoteAppManagementClient, Task <RegionListResult> > setup = null;
            RegionListResult response = new RegionListResult()
            {
                RequestId  = "23113-442",
                StatusCode = HttpStatusCode.OK,
                Regions    = new List <Region>()
                {
                    new Region()
                    {
                        Name = "West US"
                    },
                    new Region()
                    {
                        Name = "East-US"
                    },
                    new Region()
                    {
                        Name = "North Europe"
                    }
                }
            };

            mockRegionList = new List <Region>(response.Regions);

            setup = clientMock.Setup(c => c.Collections.RegionListAsync(It.IsAny <CancellationToken>()));
            setup.Returns(Task.Factory.StartNew(() => response));
        }
Exemplo n.º 10
0
        public static void SetUpDefaultRemoteAppRenameTemplate(Mock <IRemoteAppManagementClient> clientMock, string newName, string id)
        {
            TemplateImageResult response = new TemplateImageResult()
            {
                StatusCode    = System.Net.HttpStatusCode.Accepted,
                RequestId     = "12345",
                TemplateImage = new TemplateImage()
                {
                    Id         = id,
                    Name       = newName,
                    RegionList = new List <string>()
                    {
                        "West US"
                    }
                }
            };

            mockTemplates = new List <TemplateImage>()
            {
                new TemplateImage()
                {
                    Id         = response.TemplateImage.Id,
                    Name       = response.TemplateImage.Name,
                    RegionList = response.TemplateImage.RegionList
                }
            };

            ISetup <IRemoteAppManagementClient, Task <TemplateImageResult> > setup = clientMock.Setup(c => c.TemplateImages.SetAsync(It.IsAny <TemplateImageDetails>(), It.IsAny <CancellationToken>()));

            setup.Returns(Task.Factory.StartNew(() => response));

            return;
        }
Exemplo n.º 11
0
 public void ReturnOrThrow(ISetup<IWebClient, byte[]> setup)
 {
     if (_exception != null)
         setup.Throws(_exception);
     else
         setup.Returns(_response);
 }
Exemplo n.º 12
0
 public static IReturnsResult <IHttpClient> ReturnsOkResult(this ISetup <IHttpClient, string> httpClientMockSetupFlow)
 {
     return(httpClientMockSetupFlow.Returns(
                new JObject(
                    new JProperty("Result", "OK"))
                .ToString()));
 }
Exemplo n.º 13
0
        public static IReturnsResult <TMock> Returns <TMock, TResult>(this ISetup <TMock, TResult> setup, params Func <TResult>[] funcs)
            where TMock : class
        {
            var sequence = new Queue <Func <TResult> >(funcs);

            return(setup.Returns(() => sequence.Dequeue()()));
        }
        public static int SetUpDefaultRemoteAppOperationResult(Mock <IRemoteAppManagementClient> clientMock, string trackingId)
        {
            ISetup <IRemoteAppManagementClient, Task <RemoteAppOperationStatusResult> > setup = null;

            RemoteAppOperationStatusResult response = new RemoteAppOperationStatusResult()
            {
                RequestId  = "77394",
                StatusCode = HttpStatusCode.OK,
                RemoteAppOperationResult = new OperationResult()
                {
                    Description  = "The Operation has completed successfully",
                    ErrorDetails = null,
                    Status       = RemoteAppOperationStatus.Success
                }
            };

            mockOperationResult = new List <OperationResult>()
            {
                new OperationResult()
                {
                    Description  = response.RemoteAppOperationResult.Description,
                    ErrorDetails = response.RemoteAppOperationResult.ErrorDetails,
                    Status       = response.RemoteAppOperationResult.Status
                }
            };

            setup = clientMock.Setup(c => c.OperationResults.GetAsync(trackingId, It.IsAny <CancellationToken>()));
            setup.Returns(Task.Factory.StartNew(() => response));

            return(mockOperationResult.Count);
        }
Exemplo n.º 15
0
        private static IClientService GetMockedClientService <TRequest, TResponse>(IEnumerable <TResponse> responses)
            where TRequest : ClientServiceRequest <TResponse>
        {
            var clientServiceMock = new Mock <IClientService>();
            var handlerMock       = new Mock <HttpMessageHandler>(MockBehavior.Strict);
            // Use MockBehavior.Strict to ensure we make no acutal http requests.
            var configurableHandlerMock =
                new Mock <ConfigurableMessageHandler>(MockBehavior.Strict, handlerMock.Object);
            var clientMock = new Mock <ConfigurableHttpClient>(MockBehavior.Strict, configurableHandlerMock.Object);

            clientMock.Setup(c => c.SendAsync(It.IsAny <HttpRequestMessage>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(new HttpResponseMessage()));

            clientServiceMock.Setup(c => c.BaseUri).Returns("https://mock.uri");
            clientServiceMock.Setup(c => c.HttpClient).Returns(clientMock.Object);
            clientServiceMock.Setup(c => c.Serializer.Format).Returns("json");
            clientServiceMock.Setup(c => c.SerializeObject(It.IsAny <object>())).Returns("{}");

            ISetup <IClientService, Task <TResponse> > deserializeSetup =
                clientServiceMock.Setup(c => c.DeserializeResponse <TResponse>(It.IsAny <HttpResponseMessage>()));
            var responseQueue =
                new Queue <Task <TResponse> >(
                    responses?.Select(Task.FromResult) ?? Enumerable.Empty <Task <TResponse> >());

            if (responseQueue.Count == 0)
            {
                deserializeSetup.Throws(new GoogleApiException(typeof(TRequest).FullName, MockExceptionMessage));
            }
            else
            {
                deserializeSetup.Returns(responseQueue.Dequeue);
            }
            return(clientServiceMock.Object);
        }
Exemplo n.º 16
0
 public static IReturnsResult <T> ThrowsTask <T>(this ISetup <T, Task> setup, Func <Exception> excepection) where T : class
 {
     return(setup.Returns(() => Task.Run(() =>
     {
         throw excepection();
     })));
 }
Exemplo n.º 17
0
        public static ISetup <T, TResult> AndResolveWith <T, TResult>(this ISetup <T, TResult> setup, Moqer magic)
            where T : class
        {
            setup.Returns(magic.Resolve <TResult>());

            return(setup);
        }
        private void PerfomrCollectionTestHelper(
            RdsCmdlet mockCmdlet,
            string collectionName,
            Collection expectedCollection,
            String trackingId,
            CollectionUpdateDetails reqestData,
            bool forceRedeploy)
        {
            ISetup <IRemoteAppManagementClient, Task <CollectionResult> > setupGet = null;
            ISetup <IRemoteAppManagementClient, Task <OperationResultWithTrackingId> > setupSetApi = null;
            MockCommandRuntime           cmdRuntime  = null;
            IEnumerable <TrackingResult> trackingIds = null;

            // Setup the environment for testing this cmdlet
            setupGet = remoteAppManagementClientMock.Setup(c => c.Collections.GetAsync(collectionName, It.IsAny <CancellationToken>()));

            setupGet.Returns(Task.Factory.StartNew(
                                 () =>
                                 new CollectionResult()
            {
                Collection = expectedCollection,
                StatusCode = System.Net.HttpStatusCode.OK
            }));

            setupSetApi = remoteAppManagementClientMock.Setup(
                c => c.Collections.SetAsync(
                    collectionName,
                    forceRedeploy,
                    false,
                    It.Is <CollectionUpdateDetails>(col =>
                                                    col.CustomRdpProperty == reqestData.CustomRdpProperty &&
                                                    col.Description == reqestData.Description &&
                                                    col.PlanName == reqestData.PlanName &&
                                                    col.TemplateImageName == reqestData.TemplateImageName &&
                                                    col.AdInfo == null),
                    It.IsAny <CancellationToken>()));
            setupSetApi.Returns(Task.Factory.StartNew(() => new OperationResultWithTrackingId()
            {
                TrackingId = trackingId
            }));

            mockCmdlet.ResetPipelines();

            mockCmdlet.ExecuteCmdlet();

            cmdRuntime = mockCmdlet.runTime();
            if (cmdRuntime.ErrorStream.Count > 0)
            {
                Assert.True(cmdRuntime.ErrorStream.Count == 0,
                            String.Format("Set-AzureRemoteAppCollection returned the following error {0}",
                                          mockCmdlet.runTime().ErrorStream[0].Exception.Message));
            }

            trackingIds = LanguagePrimitives.GetEnumerable(mockCmdlet.runTime().OutputPipeline).Cast <TrackingResult>();
            Assert.NotNull(trackingIds);

            Assert.Equal(1, trackingIds.Count());

            Assert.True(trackingIds.Any(t => t.TrackingId == trackingId), "The actual result does not match the expected.");
        }
Exemplo n.º 19
0
    public static IReturnsResult <TMock> ReturnsInOrder <TMock, TResult, T1>(this ISetup <TMock, TResult> setup, params Func <T1, TResult>[] valueFunctions)
        where TMock : class
    {
        var queue = new Queue <Func <T1, TResult> >(valueFunctions);

        return(setup.Returns <T1>(arg => queue.Dequeue()(arg)));
    }
Exemplo n.º 20
0
        public static int SetUpDefaultRemoteAppTemplateCreate(Mock <IRemoteAppManagementClient> clientMock, string imageName, string id, string region, string vhdPath)
        {
            const int numberOfTemplatesCreated = 1;

            TemplateImageResult response = new TemplateImageResult()
            {
                RequestId     = "1111-33444",
                StatusCode    = System.Net.HttpStatusCode.Accepted,
                TemplateImage = new TemplateImage()
                {
                    Name       = imageName,
                    Status     = TemplateImageStatus.UploadPending,
                    Type       = TemplateImageType.PlatformImage,
                    RegionList = new List <string>()
                    {
                        region
                    }
                }
            };

            mockTemplates = new List <TemplateImage>()
            {
                new TemplateImage()
                {
                    Name   = response.TemplateImage.Name,
                    Status = response.TemplateImage.Status,
                    Id     = response.TemplateImage.Id,
                    NumberOfLinkedCollections = response.TemplateImage.NumberOfLinkedCollections,
                    Type       = response.TemplateImage.Type,
                    RegionList = response.TemplateImage.RegionList
                }
            };

            OperationResultWithTrackingId responseWithTrackingId = new OperationResultWithTrackingId()
            {
                RequestId  = "2222-1111-33424",
                StatusCode = System.Net.HttpStatusCode.OK
            };

            UploadScriptResult responseUpload = new UploadScriptResult()
            {
                RequestId  = "1111-33333-5",
                StatusCode = System.Net.HttpStatusCode.OK,
                Script     = "$i = 1; foreach ($arg in $Args) { echo \"The $i parameter is $arg\"; $i++ }; return $true", // mock script just prints out arguments
            };

            ISetup <IRemoteAppManagementClient, Task <OperationResultWithTrackingId> > SetupStorageTemplate = clientMock.Setup(c => c.TemplateImages.EnsureStorageInRegionAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()));

            SetupStorageTemplate.Returns(Task.Factory.StartNew(() => responseWithTrackingId));

            ISetup <IRemoteAppManagementClient, Task <TemplateImageResult> > SetupSetTemplate = clientMock.Setup(c => c.TemplateImages.SetAsync(It.IsAny <TemplateImageDetails>(), It.IsAny <CancellationToken>()));

            SetupSetTemplate.Returns(Task.Factory.StartNew(() => response));

            ISetup <IRemoteAppManagementClient, Task <UploadScriptResult> > SetupUploadTemplate = clientMock.Setup(c => c.TemplateImages.GetUploadScriptAsync(It.IsAny <CancellationToken>()));

            SetupUploadTemplate.Returns(Task.Factory.StartNew(() => responseUpload));

            return(numberOfTemplatesCreated);
        }
Exemplo n.º 21
0
        public static int SetUpDefaultVpnDevice(Mock <IRemoteAppManagementClient> clientMock, string name)
        {
            ISetup <IRemoteAppManagementClient, Task <VNetVpnDeviceResult> > setup = null;

            VNetVpnDeviceResult response = new VNetVpnDeviceResult()
            {
                RequestId  = "23411-345",
                StatusCode = System.Net.HttpStatusCode.OK,
                Vendors    = new Vendor[]
                {
                    new Vendor()
                    {
                        Name      = "Acme",
                        Platforms = new List <Platform>()
                        {
                            new Platform()
                            {
                                Name       = "BasicVPN",
                                OsFamilies = new List <OsFamily>()
                            }
                        }
                    }
                }
            };

            mockVpnList = new List <Vendor>(response.Vendors);

            setup = clientMock.Setup(c => c.VNet.GetVpnDevicesAsync(name, It.IsAny <CancellationToken>()));
            setup.Returns(Task.Factory.StartNew(() => response));

            return(mockVpnList.Count);
        }
Exemplo n.º 22
0
        public static IReturnsResult <TMock> ReturnsAsyncEntitySet <TMock, TResult>(this ISetup <TMock, IEntitySet <TResult> > setup, IList <TResult> items)
            where TMock : class
            where TResult : class
        {
            var fakeDbSet = new FakeAsyncDbSet <TResult>(items);

            return(setup.Returns(new FakeAsyncEntitySet <TResult>(fakeDbSet)));
        }
Exemplo n.º 23
0
        public static void ReturnsCount <T1, T2>(this ISetup <T1, T2> setup, Func <int, T2> action)
            where T1 : class
        {
            var i = 1;

            setup.Returns(() => action(i))
            .Callback(() => i++);
        }
Exemplo n.º 24
0
 public static IReturnsResult <TMock> ExecutesAsyncPredicateOn <TMock, TResult>(this ISetup <TMock, Task <IList <TResult> > > mock, IList <TResult> data) where TMock : class
 {
     return(mock.Returns((Expression <Func <TResult, Boolean> > predicate) =>
     {
         var compiledPredicate = predicate.Compile();
         return Task.FromResult((IList <TResult>)data.Where(compiledPredicate).ToList());
     }));
 }
        public static IReturnsResult <T> ReturnsDbQuery <T, TEntity>(this ISetup <T, DbQuery <TEntity> > setupResult, IEnumerable <TEntity> entities, Mock <DbQuery <TEntity> > dbQueryMock = null) where T : DbContext where TEntity : class
        {
            dbQueryMock = dbQueryMock ?? new Mock <DbQuery <TEntity> >();

            ConfigureMock(dbQueryMock, entities);

            return(setupResult.Returns(dbQueryMock.Object));
        }
Exemplo n.º 26
0
        public static Mock <IMongoCollection <T> > CreateMockCollection <T>(ISetup <IMongoDbContext, IMongoCollection <T> > setup)
        {
            var mockCollection = new Mock <IMongoCollection <T> > {
                DefaultValue = DefaultValue.Mock
            };

            setup.Returns(mockCollection.Object);
            return(mockCollection);
        }
        public static IReturnsResult <Stream> ReturnsUncompleted(this ISetup <Stream, IAsyncResult> setup)
        {
            if (setup == null)
            {
                throw new ArgumentNullException("setup");
            }

            return(setup.Returns <byte[], int, int, AsyncCallback, object>((i1, i2, i3, i4, state) =>
                                                                           new UncompletedAsyncResult(state)));
        }
        public static IReturnsResult <Stream> ReturnsUncompleted(
            this ISetup <Stream, IAsyncResult> setup)
        {
            if (setup == null)
            {
                throw new ArgumentNullException(nameof(setup));
            }

            return(setup.Returns <byte[], int, int, AsyncCallback, object>((a1, a2, a3, a4, state) => new UncompletedCancellableAsyncResult(state)));
        }
Exemplo n.º 29
0
        public static IReturnsResult <CloudBlobStream> ReturnsUncompleted(
            this ISetup <CloudBlobStream, ICancellableAsyncResult> setup)
        {
            if (setup == null)
            {
                throw new ArgumentNullException("setup");
            }

            return(setup.Returns <AsyncCallback, object>((i4, state) => new UncompletedCancellableAsyncResult(state)));
        }
 public static IReturnsResult <T> ReturnsGivenResult <T, TResult>(this ISetup <T, IResult <TResult> > setup,
                                                                  TResult resultObject = default(TResult)
                                                                  ) where T : class
 {
     return(setup
            .Returns(new Result <TResult> {
         Errors = new List <IError>(),
         ResultObject = resultObject
     }));
 }
Exemplo n.º 31
0
        public static Mock <DbSet <TItem> > ReturnsAsEmptyDbSet <T, TItem>(this ISetup <T, DbSet <TItem> > setup)
            where T : class
            where TItem : class
        {
            var mock       = new Mock <DbSet <TItem> >();
            var collection = new List <TItem>().AsQueryable();

            mock.SetupAsQueryable(collection);
            setup.Returns(mock.Object);
            return(mock);
        }