Ejemplo n.º 1
0
        void AssetRewrite(string from, string to)
        {
            var context = new Mock<HttpContextBase>();
            var request = new Mock<HttpRequestBase>();
            var cache = new Mock<HttpCachePolicyBase>();
            var cassetteSettings = new CassetteSettings();
            var requestHeaders = new NameValueCollection();
            context.SetupGet(c => c.Request).Returns(request.Object);
            context.Setup(c => c.Response.Cache).Returns(cache.Object);
            var auth = new Mock<IFileAccessAuthorization>();
            auth.Setup(a => a.CanAccess(It.IsAny<string>())).Returns(true);
            var hasher = new Mock<IFileContentHasher>();
            hasher.Setup(h => h.Hash(It.IsAny<string>())).Returns(new byte[] { 1 });
            request
                .SetupGet(r => r.AppRelativeCurrentExecutionFilePath)
                .Returns("~/cassette.axd");
            request
                .SetupGet(r => r.PathInfo)
                .Returns(from);
            request
                .SetupGet(r => r.Headers)
                .Returns(requestHeaders);

            var rewriter = new RawFileRequestRewriter(context.Object, auth.Object, hasher.Object, cassetteSettings, usingIntegratedPipeline: true);
            rewriter.Rewrite();

            context.Verify(c => c.RewritePath(to));
        }
Ejemplo n.º 2
0
		private static IList<IAttribute> CreateMockAttributes(IEnumerable<Expression<Func<System.Attribute>>> attributes) {
			var result = new List<IAttribute>();
			if (attributes != null) {
				foreach (var attrExpression in attributes) {
					var attr = new Mock<IAttribute>(MockBehavior.Strict);
					var body = (NewExpression)attrExpression.Body;
					attr.SetupGet(_ => _.AttributeType).Returns(CreateMockTypeDefinition(body.Type.FullName, null));
					var posArgs = new List<ResolveResult>();
					foreach (var argExpression in body.Arguments) {
						var argType = new Mock<IType>(MockBehavior.Strict);
						argType.SetupGet(_ => _.FullName).Returns(argExpression.Type.FullName);
						var arg = new ConstantResolveResult(argType.Object, ((ConstantExpression)argExpression).Value);
						posArgs.Add(arg);
					}
					attr.SetupGet(_ => _.PositionalArguments).Returns(posArgs);

					if (body.Members != null && body.Members.Count > 0)
						throw new InvalidOperationException("Named attribute args are not supported");

					attr.SetupGet(_ => _.NamedArguments).Returns(new KeyValuePair<IMember, ResolveResult>[0]);

					result.Add(attr.Object);
				}
			}
			return result;
		}
        public void Handle_SameLegalName_NoAliasAdded()
        {
            AgencyName agencyName = new AgencyName("TestAgencyName", "DisplayName", "BusinessName");

            AgencyProfile agencyProfile = new AgencyProfile (
                new Mock<AgencyType> ().Object,
                agencyName,
                new DateRange ( DateTime.Now.AddDays ( -1 ), DateTime.Now ),
                "url",
                new Mock<GeographicalRegion> ().Object,
                "note" );

            var aliasAdded = false;

            var agencyMock = new Mock<Agency>();
            agencyMock.SetupGet(p => p.AgencyProfile).Returns(agencyProfile);
            agencyMock.Setup(a => a.AddAgencyAlias(It.IsAny<AgencyAlias>())).Callback(() => aliasAdded = true);

            var agencyProfileChangedEvent = new Mock<AgencyProfileChangedEvent>();
            agencyProfileChangedEvent.SetupGet(p => p.Agency).Returns(agencyMock.Object);
            agencyProfileChangedEvent.SetupGet(p => p.OldAgencyProfile).Returns(agencyProfile);

            new AgencyProfileChangedEventHandler().Handle(agencyProfileChangedEvent.Object);

            Assert.IsFalse(aliasAdded);
        }
        public void SourceFileWithLayoutPageTest()
        {
            // Arrange
            var pagePath = "~/MyApp/index.cshtml";
            var layoutPath = "~/MyFiles/Layout.cshtml";
            var layoutPage = "~/MyFiles/Layout.cshtml";
            var content = "hello world";
            var title = "MyPage";
            var page = CreatePageWithLayout(
                p =>
                {
                    p.PageData["Title"] = title;
                    p.WriteLiteral(content);
                },
                p =>
                {
                    p.WriteLiteral(p.PageData["Title"]);
                    p.Write(p.RenderBody());
                }, pagePath, layoutPath, layoutPage);
            var request = new Mock<HttpRequestBase>();
            request.SetupGet(c => c.Path).Returns("/myapp/index.cshtml");
            request.SetupGet(c => c.RawUrl).Returns("http://localhost:8080/index.cshtml");
            request.SetupGet(c => c.IsLocal).Returns(true);
            request.Setup(c => c.MapPath(It.IsAny<string>())).Returns<string>(c => c);
            request.Setup(c => c.Browser.IsMobileDevice).Returns(false);
            request.Setup(c => c.Cookies).Returns(new HttpCookieCollection());

            var result = Utils.RenderWebPage(page, request: request.Object);
            Assert.Equal(2, page.PageContext.SourceFiles.Count);
            Assert.True(page.PageContext.SourceFiles.Contains("~/MyApp/index.cshtml"));
            Assert.True(page.PageContext.SourceFiles.Contains("~/MyFiles/Layout.cshtml"));
        }
Ejemplo n.º 5
0
            public GetAssemblyNamesMethod()
            {
                _workingDirectory = "c:\\test";

                _filesystem = new Mock<IFileSystem>();
                _filesystem.SetupGet(i => i.CurrentDirectory).Returns("c:\\test");
                _filesystem.Setup(i => i.DirectoryExists(It.IsAny<string>())).Returns(true);
                _filesystem.Setup(i => i.FileExists(It.IsAny<string>())).Returns(true);

                _logger = new Mock<ILog>();

                _package = new Mock<IPackageObject>();
                _package.Setup(i => i.GetCompatibleDlls(It.IsAny<FrameworkName>()))
                        .Returns(new List<string> { "test.dll", "test2.dll" });
                _package.SetupGet(i => i.Id).Returns("id");
                _package.SetupGet(i => i.Version).Returns(new Version("3.0"));
                _package.SetupGet(i => i.TextVersion).Returns("3.0");
                _package.SetupGet(i => i.FullName).Returns(_package.Object.Id + "." + _package.Object.Version);

                _packageIds = new List<IPackageReference>
                    {
                        new PackageReference("testId", VersionUtility.ParseFrameworkName("net40"), new Version("3.0"))
                    };

                _packageContainer = new Mock<IPackageContainer>();
                _packageContainer.Setup(i => i.FindReferences(It.IsAny<string>())).Returns(_packageIds);
                _packageContainer.Setup(i => i.FindPackage(It.IsAny<string>(), It.IsAny<IPackageReference>())).Returns(_package.Object);
            }
Ejemplo n.º 6
0
        public StylesheetPipeline_Process_TestBase()
        {
            settings = new CassetteSettings();
            bundle = new StylesheetBundle("~");
            asset1 = new Mock<IAsset>();
            asset2 = new Mock<IAsset>();
            bundle.Assets.Add(asset1.Object);
            bundle.Assets.Add(asset2.Object);

            asset1.SetupGet(a => a.Path)
                  .Returns("~/asset1.css");
            asset1.Setup(a => a.OpenStream())
                  .Returns(() => "/* @reference \"asset2.css\"; */".AsStream());
            asset2.SetupGet(a => a.Path)
                  .Returns("~/asset2.css");
            asset2.Setup(a => a.OpenStream())
                  .Returns(() => "p { color: White; }".AsStream());
            asset1.SetupGet(a => a.References)
                  .Returns(new[] { new AssetReference(asset1.Object.Path, "~/asset2.css", -1, AssetReferenceType.SameBundle) });

            minifier = new MicrosoftStylesheetMinifier();
            urlGenerator = new Mock<IUrlGenerator>();
            container = new TinyIoCContainer();
            container.Register(minifier);
            container.Register(urlGenerator.Object);
            container.Register(settings);
        }
		Selection GetSelectionWithCaretPos (int row, int column)
		{
			var documentMock = new Mock<ICaret>();
			documentMock.SetupGet(o => o.Row).Returns(row);
			documentMock.SetupGet(o => o.Column).Returns(column);
			return new Selection(documentMock.Object);
		}
Ejemplo n.º 8
0
        public void ProcessRequest_Should_Save_File()
        {
            var reference = Guid.NewGuid().ToString();
            var pluploadContextMock = new Mock<IPluploadContext>();
            var httpPostedFileMock = new Mock<HttpPostedFileBase>();
            var httpFileCollectionMock = new Mock<HttpFileCollectionBase>();
            httpFileCollectionMock.SetupGet(c => c.AllKeys).Returns(new string[] { "FileName.Extension" });
            httpFileCollectionMock.Setup(c => c.Get("FileName.Extension")).Returns(httpPostedFileMock.Object);
            httpFileCollectionMock.Setup(c => c.Get(0)).Returns(httpPostedFileMock.Object);
            httpFileCollectionMock.SetupGet(c => c[0]).Returns(httpPostedFileMock.Object);
            var httpRequestMock = new Mock<HttpRequestBase>();
            httpRequestMock.SetupGet(r => r.Files).Returns(httpFileCollectionMock.Object);
            httpRequestMock.SetupGet(r => r.Params).Returns(new NameValueCollection() { { "reference", reference.ToString() } });
            var httpResponseMock = new Mock<HttpResponseBase>();
            var httpContextMock = new Mock<HttpContextBase>();
            httpContextMock.SetupGet(c => c.Request).Returns(httpRequestMock.Object);
            httpContextMock.SetupGet(c => c.Response).Returns(httpResponseMock.Object);
            httpContextMock.SetupGet(c => c.Items).Returns(new ListDictionary());
            httpContextMock.Object.SetPluploadContext(pluploadContextMock.Object);

            var handler = new PluploadHandler();
            handler.ProcessRequest(httpContextMock.Object);

            pluploadContextMock.Verify(c => c.SaveFile(httpPostedFileMock.Object, reference), Times.Once);
            httpResponseMock.Verify(r => r.Write("OK"), Times.Once);
        }
Ejemplo n.º 9
0
        public void TestAddingRecordingDeviceToSelected()
        {
            var configurationMoq = new Mock<ISoundSwitchConfiguration> {Name = "Configuration mock"};
            var audioMoqI = new Mock<IAudioDevice> {Name = "first audio dev"};
            audioMoqI.SetupGet(a => a.FriendlyName).Returns("Speakers (Test device)");
            audioMoqI.SetupGet(a => a.Type).Returns(AudioDeviceType.Recording);

            //Setup
            configurationMoq.Setup(c => c.SelectedRecordingDeviceList).Returns(new HashSet<string>());
            TestHelpers.SetConfigurationMoq(configurationMoq);

            //Action
            var eventCalled = false;
            AppModel.Instance.SelectedDeviceChanged += (sender, changed) => eventCalled = true;
            Assert.True(AppModel.Instance.SelectDevice(audioMoqI.Object));

            //Asserts
            configurationMoq.VerifyGet(c => c.SelectedRecordingDeviceList);
            configurationMoq.Verify(c => c.Save());
            audioMoqI.VerifyGet(a => a.FriendlyName);
            audioMoqI.VerifyGet(a => a.Type);
            Assert.That(configurationMoq.Object.SelectedRecordingDeviceList.Count == 1);
            Assert.That(configurationMoq.Object.SelectedRecordingDeviceList.Contains("Speakers (Test device)"));
            Assert.That(eventCalled, "SelectedDeviceChanged not called");
        }
        public void ItReturnsTheGrandChildrenChildrenAfterTheChild()
        {
            var treeItem1 = Mock.Of<ITreeItem>();
            var treeItem2 = new Mock<ITreeItem>();
            var treeItem3 = Mock.Of<ITreeItem>();
            var child1 = Mock.Of<ITreeItem>();
            var child2 = new Mock<ITreeItem>();
            var child3 = Mock.Of<ITreeItem>();
            var grandChild1 = Mock.Of<ITreeItem>();
            var grandChild2 = Mock.Of<ITreeItem>();

            treeItem2.SetupGet(i => i.IsExpanded).Returns(true);
            treeItem2.SetupGet(i => i.Children).Returns(A.Array(child1, child2.Object, child3));
            child2.SetupGet(i => i.IsExpanded).Returns(true);
            child2.SetupGet(i => i.Children).Returns(A.Array(grandChild1, grandChild2));

            var collection = new TreeItemHierarchyFlattener2();
            var flattenedHierarchy = collection.Flatten(A.Array(treeItem1, treeItem2.Object, treeItem3));
            flattenedHierarchy.AssertContains(
                treeItem1
                , treeItem2.Object
                , child1
                , child2.Object
                , grandChild1
                , grandChild2
                , child3
                , treeItem3);
        }
        public void TestQueryAsync_ServerReturnsQuery_ReturnsListWithFieldworkOffices()
        {
            const HttpStatusCode httpStatusCode = HttpStatusCode.NotFound;
            var expectedFieldworkOffices = new FieldworkOffice[]
            { new FieldworkOffice{OfficeId = "TestOfficeId"},
              new FieldworkOffice{OfficeId = "AnotherTestOfficeId"}
            };
            var mockedNfieldConnection = new Mock<INfieldConnectionClient>();
            var mockedHttpClient = new Mock<INfieldHttpClient>();
            mockedHttpClient
                .Setup(client => client.GetAsync(ServiceAddress + "offices/"))
                .Returns(
                    Task.Factory.StartNew(
                        () =>
                            new HttpResponseMessage(httpStatusCode)
                            {
                                Content = new StringContent(JsonConvert.SerializeObject(expectedFieldworkOffices))
                            }));
            mockedNfieldConnection
                .SetupGet(connection => connection.Client)
                .Returns(mockedHttpClient.Object);
            mockedNfieldConnection
                .SetupGet(connection => connection.NfieldServerUri)
                .Returns(new Uri(ServiceAddress));

            var target = new NfieldFieldworkOfficesService();
            target.InitializeNfieldConnection(mockedNfieldConnection.Object);

            var actualFieldworkOffices = target.QueryAsync().Result;
            Assert.Equal(expectedFieldworkOffices[0].OfficeId, actualFieldworkOffices.ToArray()[0].OfficeId);
            Assert.Equal(expectedFieldworkOffices[1].OfficeId, actualFieldworkOffices.ToArray()[1].OfficeId);
            Assert.Equal(2, actualFieldworkOffices.Count());
        }
Ejemplo n.º 12
0
 public static ITransferContentData TransferData(RawContent masterContentData, params RawContent[] languageContent)
 {
     var transferData = new Mock<ITransferContentData>();
     transferData.SetupGet(x => x.RawContentData).Returns(masterContentData);
     transferData.SetupGet(x => x.RawLanguageData).Returns(new List<RawContent>(languageContent));
     return transferData.Object;
 }
Ejemplo n.º 13
0
        protected CommandMarginControllerTest()
        {
            _factory = new MockRepository(MockBehavior.Strict);
            _marginControl = new CommandMarginControl();
            _marginControl.CommandLineTextBox.Text = String.Empty;

            _search = _factory.Create<IIncrementalSearch>();
            _search.SetupGet(x => x.InSearch).Returns(false);
            _search.SetupGet(x => x.InPasteWait).Returns(false);
            _vimBuffer = new MockVimBuffer();
            _vimBuffer.IncrementalSearchImpl = _search.Object;
            _vimBuffer.VimImpl = MockObjectFactory.CreateVim(factory: _factory).Object;
            _vimBuffer.CommandModeImpl = _factory.Create<ICommandMode>(MockBehavior.Loose).Object;
            var textBuffer = CreateTextBuffer(new []{""});
            _vimBuffer.TextViewImpl = TextEditorFactoryService.CreateTextView(textBuffer);

            Mock<IVimGlobalSettings> globalSettings = new Mock<IVimGlobalSettings>();
            _vimBuffer.GlobalSettingsImpl = globalSettings.Object;

            var editorFormatMap = _factory.Create<IEditorFormatMap>(MockBehavior.Loose);
            editorFormatMap.Setup(x => x.GetProperties(It.IsAny<string>())).Returns(new ResourceDictionary());

            var parentVisualElement = _factory.Create<FrameworkElement>();

            _controller = new CommandMarginController(
                _vimBuffer,
                parentVisualElement.Object,
                _marginControl,
                VimEditorHost.EditorFormatMapService.GetEditorFormatMap(_vimBuffer.TextView),
                VimEditorHost.ClassificationFormatMapService.GetClassificationFormatMap(_vimBuffer.TextView));
        }
Ejemplo n.º 14
0
        public void Setup()
        {
            _principal = new Mock<IPrincipal>();
            _httpContext = new Mock<HttpContextBase>();
            _httpContext.Setup(x => x.User).Returns(_principal.Object);

            _volunteerService = new Mock<IVolunteerService>();
            _cluster = new Mock<ICluster>();
            _webSecurity = new Mock<IWebSecurityWrapper>();
            _webSecurity.SetupGet(x => x.CurrentUserId).Returns(42);
            _messageService = new Mock<IMessageService>();

            var request = new Mock<HttpRequestBase>();
            request.SetupGet(x => x.Url).Returns(new Uri("http://localhost/"));
            _httpContext.Setup(ctx => ctx.Request).Returns(request.Object);
            _httpContext.SetupGet(x => x.Request).Returns(request.Object);

            var response = new Mock<HttpResponseBase>();
            response.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(x => x);
            _httpContext.Setup(ctx => ctx.Response).Returns(response.Object);
            _httpContext.SetupGet(x => x.Response).Returns(response.Object);

            var reqContext = new RequestContext(_httpContext.Object, new RouteData());

            _controllerUnderTest = new AccountController(_volunteerService.Object, _cluster.Object, _webSecurity.Object, _messageService.Object);
            _controllerUnderTest.ControllerContext = new ControllerContext(reqContext, _controllerUnderTest);

            _routeCollection = new RouteCollection();
            RouteConfig.RegisterRoutes(_routeCollection);
            _controllerUnderTest.Url = new UrlHelper(reqContext, _routeCollection);
        }
        public void AnErrorIsIssuedIfTheMainMethodIsNotImplementedAsANormalMethod()
        {
            var type = CreateMockTypeDefinition("MyClass");
            var main = new Mock<IMethod>(MockBehavior.Strict);
            main.SetupGet(_ => _.DeclaringTypeDefinition).Returns(type);
            main.SetupGet(_ => _.Name).Returns("Main");
            main.SetupGet(_ => _.FullName).Returns("MyClass.Main");
            main.SetupGet(_ => _.Parameters).Returns(EmptyList<IParameter>.Instance);
            main.SetupGet(_ => _.Region).Returns(DomRegion.Empty);

            var er = new MockErrorReporter();

            Process(
                new[] {
                    new JsClass(type, JsClass.ClassTypeEnum.Class, null, null, null) {
                        StaticMethods = { new JsMethod(main.Object, "$Main", new string[0], JsExpression.FunctionDefinition(new string[0], new JsExpressionStatement(JsExpression.Identifier("X")))) }
                    }
                },
                new MockScriptSharpMetadataImporter() { GetMethodSemantics = m => ReferenceEquals(m, main.Object) ? MethodScriptSemantics.InlineCode("X") : MethodScriptSemantics.NormalMethod("$" + m.Name) },
                er,
                main.Object
            );

            Assert.That(er.AllMessages, Has.Count.EqualTo(1));
            Assert.That(er.AllMessages.Any(m => m.Code == 7801 && (string)m.Args[0] == "MyClass.Main"));
        }
Ejemplo n.º 16
0
        public void Start_WhenInputFormatIsValidAddToShoppingCartCommand_ShouldAddProductToTheShoppingCart()
        {
            //Arrange
            var productName = "Fa Shampoo";

            var mockedFactory = new Mock<ICosmeticsFactory>();
            var mockedShoppingCart = new Mock<IShoppingCart>();
            var mockedCommandParser = new Mock<ICommandParser>();

            var mockedCommand = new Mock<ICommand>();
            var mockedProduct = new Mock<IProduct>();

            mockedCommand.SetupGet(x => x.Name).Returns("AddToShoppingCart");
            mockedCommand.SetupGet(x => x.Parameters).Returns(new List<string>() { productName });

            mockedCommandParser.Setup(p => p.ReadCommands()).Returns(() => new List<ICommand>() { mockedCommand.Object });

            var engine = new MockedCosmeticsEngine(mockedFactory.Object, mockedShoppingCart.Object, mockedCommandParser.Object);

            engine.Products.Add(productName, mockedProduct.Object);

            //Act
            engine.Start();

            //Assert
            mockedShoppingCart.Verify(x => x.AddProduct(mockedProduct.Object), Times.Once);
        }
Ejemplo n.º 17
0
        public void CancelledTaskHandledinServerSentEvents()
        {
            var tcs = new TaskCompletionSource<IResponse>();
            tcs.TrySetCanceled();

            var httpClient = new Mock<IHttpClient>();
            var connection = new Mock<IConnection>();

            httpClient.Setup(c => c.Get(It.IsAny<string>(), It.IsAny<Action<IRequest>>(), It.IsAny<bool>()))
                .Returns<string, Action<IRequest>, bool>((url, prepareRequest, isLongRunning) =>
                {
                    prepareRequest(Mock.Of<IRequest>());
                    return tcs.Task;
                });

            connection.SetupGet(c => c.ConnectionToken).Returns("foo");
            connection.SetupGet(c => c.TotalTransportConnectTimeout).Returns(TimeSpan.FromSeconds(15));

            var sse = new ServerSentEventsTransport(httpClient.Object);

            var exception = Assert.Throws<AggregateException>(
                () => sse.Start(connection.Object, string.Empty, CancellationToken.None).Wait(TimeSpan.FromSeconds(5)));

            Assert.IsType(typeof(OperationCanceledException), exception.InnerException);
        }
Ejemplo n.º 18
0
        private void MockSecurityDataContext()
        {
            _MockSecurityDataContext = new Mock<ISecurityDataContext>();

            _MockSecurityDataContext.SetupGet(c => c.Computers).Returns(CreateComputers());
            _MockSecurityDataContext.SetupGet(c => c.Rooms).Returns(CreateRooms());
        }
 private IAppConfiguration GetConfiguration()
 {
     var mockConfiguration = new Mock<IAppConfiguration>();
     mockConfiguration.SetupGet(c => c.ServiceDiscoveryUri).Returns(new Uri("https://api.nuget.org/v3/index.json"));
     mockConfiguration.SetupGet(c => c.AutocompleteServiceResourceType).Returns("SearchAutocompleteService/3.0.0-rc");
     return mockConfiguration.Object;
 }
        public async Task When_registering_session_with_no_projectApiKey_set()
        {
            //Arrange
            var configurationMock = new Mock<IConfiguration>(MockBehavior.Strict);
            configurationMock.SetupGet(x => x.ProjectApiKey).Returns((string)null);
            configurationMock.SetupGet(x => x.Session.Environment).Returns("Test");
            configurationMock.SetupGet(x => x.Target.Location).Returns("http://localhost");
            configurationMock.SetupGet(x => x.AllowMultipleInstances).Returns(true);

            var webApiClientMock = new Mock<IWebApiClient>(MockBehavior.Strict);
            webApiClientMock.Setup(x => x.CreateAsync<SessionRequest, SessionResponse>(It.IsAny<string>(), It.IsAny<SessionRequest>())).Returns(Task.FromResult(default(SessionResponse)));

            var session = Register_session_setup.GivenThereIsASession(webApiClientMock, configurationMock, null, null);

            ExpectedIssues.ProjectApiKeyNotSetException exception = null;
            SessionResult result = null;

            //Act
            try
            {
                result = await session.RegisterAsync();
            }
            catch (ExpectedIssues.ProjectApiKeyNotSetException exp)
            {
                exception = exp;
            }

            //Assert
            Assert.That(exception, Is.Not.Null);
            Assert.That(result, Is.Null);
            webApiClientMock.Verify(x => x.CreateAsync<SessionRequest, SessionResponse>(It.IsAny<string>(), It.IsAny<SessionRequest>()), Times.Never);
        }
        public void Initialize()
        {
            _dataCollector = new Mock<IDataCollector>();
            _setter = new ContextVariablesSetter(_dataCollector.Object, true);
            _containerProvider = new Mock<IDIContainerProvider>();

            _environment = new Mock<IEnvironment>();
            _languageManagerProvider = new Mock<ILanguageManagerProvider>();
            _languageManager = new Mock<ILanguageManager>();
            _contextProvider = new Mock<IAcspNetContextProvider>();
            _context = new Mock<IAcspNetContext>();
            _stringTable = new Mock<IStringTable>();
            _stopwatchProvider = new Mock<IStopwatchProvider>();

            _dataCollector.SetupGet(x => x.TitleVariableName).Returns("Title");

            _environment.SetupGet(x => x.TemplatesPath).Returns("Templates");
            _environment.SetupGet(x => x.SiteStyle).Returns("Main");

            _languageManager.SetupGet(x => x.Language).Returns("ru");
            _languageManagerProvider.Setup(x => x.Get()).Returns(_languageManager.Object);

            _context.SetupGet(x => x.SiteUrl).Returns("http://localhost/mysite/");
            _context.SetupGet(x => x.VirtualPath).Returns("/mysite");
            _contextProvider.Setup(x => x.Get()).Returns(_context.Object);
            _context.SetupGet(x => x.Request.PathBase).Returns(new PathString("/mysite"));

            _stopwatchProvider.Setup(x => x.StopAndGetMeasurement()).Returns(new TimeSpan(0, 0, 1, 15, 342));

            _containerProvider.Setup(x => x.Resolve(It.Is<Type>(d => d == typeof(IEnvironment)))).Returns(_environment.Object);
            _containerProvider.Setup(x => x.Resolve(It.Is<Type>(d => d == typeof(ILanguageManagerProvider)))).Returns(_languageManagerProvider.Object);
            _containerProvider.Setup(x => x.Resolve(It.Is<Type>(d => d == typeof(IAcspNetContextProvider)))).Returns(_contextProvider.Object);
            _containerProvider.Setup(x => x.Resolve(It.Is<Type>(d => d == typeof(IStringTable)))).Returns(_stringTable.Object);
            _containerProvider.Setup(x => x.Resolve(It.Is<Type>(d => d == typeof(IStopwatchProvider)))).Returns(_stopwatchProvider.Object);
        }
        public void RequireHttpsAttributeDoesNotThrowForInsecureConnectionIfNotAuthenticatedOrForcingSSLAndOnlyWhenAuthenticatedSet()
        {
            // Arrange
            var mockAuthContext = new Mock<AuthorizationContext>(MockBehavior.Strict);
            var mockConfig = new Mock<IAppConfiguration>();
            var mockFormsAuth = new Mock<IFormsAuthenticationService>();
            mockConfig.Setup(cfg => cfg.RequireSSL).Returns(true);
            mockAuthContext.SetupGet(c => c.HttpContext.Request.IsSecureConnection).Returns(false);
            mockAuthContext.SetupGet(c => c.HttpContext.Request.IsAuthenticated).Returns(false);
            var context = mockAuthContext.Object;
            mockFormsAuth.Setup(fas => fas.ShouldForceSSL(context.HttpContext)).Returns(false);
            var attribute = new RequireRemoteHttpsAttribute()
            {
                Configuration = mockConfig.Object,
                OnlyWhenAuthenticated = true,
                FormsAuthentication = mockFormsAuth.Object
            };
            var result = new ViewResult();
            context.Result = result;

            // Act
            attribute.OnAuthorization(context);

            // Assert
            Assert.Same(result, context.Result);
        }
Ejemplo n.º 23
0
        public void HandleTest()
        {
            string pageName = "search";
            byte[] content = Encoding.UTF8.GetBytes("<html><body>Search me</body></html>");

            MockResourceRepository resourceRepository = new MockResourceRepository();
            resourceRepository.LoadResource(pageName, content);

            HtmlPage target = new HtmlPage();

            var request = new Mock<IServiceRequest>();
            request.SetupGet(x => x.ResourceName).Returns(pageName);
            request.SetupGet(x => x.Extension).Returns("");
            request.SetupGet(x => x.Query).Returns("");

            var response = new Mock<IServiceResponse>();
            response.SetupProperty(x => x.ContentType);
            response.SetupProperty(x => x.StatusCode);

            MemoryStream contentStream = new MemoryStream();
            response.SetupGet(x => x.ContentStream).Returns(contentStream);

            target.Handle(request.Object, response.Object, resourceRepository);

            Assert.AreEqual("text/html", response.Object.ContentType);
            Assert.AreEqual(200, response.Object.StatusCode);

            byte[] actualContent = contentStream.ToArray();
            Assert.AreEqual(content.Length, actualContent.Length);
            for (int i = 0; i < content.Length; i++)
            {
                Assert.AreEqual(content[i], actualContent[i]);
            }
        }
        public void should_return_base_eneryg_plus_any_equiped_items_that_affect_energy()
        {
            Guid userId = Guid.NewGuid();

            //given user that exists
            _userRetriever.Setup(s => s.UserExists(userId)).Returns(true);

            //and a base energy of 100
            _userRetriever.Setup(s => s.GetCurrentBaseEnergy(userId)).Returns(100);

            //and the following equipment, one of which is one time, one of which is not
            List<IItem> items = new List<IItem>();

            Mock<IItem> item = new Mock<IItem>();
            item.SetupGet(s => s.Energy).Returns(20);
            item.SetupGet(s => s.IsOneTimeUse).Returns(true);
            items.Add(item.Object);

            item = new Mock<IItem>();
            item.SetupGet(s => s.Energy).Returns(10);
            items.Add(item.Object);
            _userItemRetriever.Setup(s => s.GetUserItems(userId)).Returns(items);

            //should return 110 for base energy which excludes one time use
            int energy = _userEnergyProvider.GetUserMaxEnergy(userId);
            Assert.AreEqual(110, energy);
        }
Ejemplo n.º 25
0
        public void CheckUnlockStatus_EveryIAchievementConditionIsUnlocked_ShouldFireAchievementCompletedEvent()
        {
            // Arrange
            Mock<IAchievementCondition> achievementConditionMock1 = new Mock<IAchievementCondition>();
            achievementConditionMock1.SetupGet(x => x.Unlocked).Returns(true);
            achievementConditionMock1.SetupGet(x => x.UniqueId).Returns("ac1");

            Mock<IAchievementCondition> achievementConditionMock2 = new Mock<IAchievementCondition>();
            achievementConditionMock2.SetupGet(x => x.Unlocked).Returns(true);
            achievementConditionMock2.SetupGet(x => x.UniqueId).Returns("ac2");

            Mock<IAchievementCondition> achievementConditionMock3 = new Mock<IAchievementCondition>();
            achievementConditionMock3.SetupGet(x => x.Unlocked).Returns(true);
            achievementConditionMock3.SetupGet(x => x.UniqueId).Returns("ac3");

            List<IAchievementCondition> achievementConditions = new List<IAchievementCondition>
            {
                achievementConditionMock1.Object,
                achievementConditionMock2.Object,
                achievementConditionMock3.Object
            };
            Achievement achievement = new Achievement("uniqueId", "titel", "description", achievementConditions);

            Achievement reportedAchievement = null;
            achievement.AchievementCompleted += delegate(Achievement a) { reportedAchievement = a; };

            // Act
            achievement.CheckUnlockStatus();

            // Assert
            Assert.AreEqual(achievement, reportedAchievement);
            Assert.IsTrue(achievement.Unlocked);
        }
Ejemplo n.º 26
0
        [InlineData(44300, "{0}:44300")]    // Non-standard Port, Authenticated, always force SSL for this action
        public void RequireHttpsAttributeRedirectsGetRequest(int port, string hostFormatter)
        {
            // Arrange
            var mockAuthContext = new Mock<AuthorizationContext>(MockBehavior.Strict);
            var mockConfig = new Mock<IAppConfiguration>();
            var mockFormsAuth = new Mock<IFormsAuthenticationService>();

            mockAuthContext.SetupGet(c => c.HttpContext.Request.HttpMethod).Returns("get");
            mockAuthContext.SetupGet(c => c.HttpContext.Request.Url).Returns(new Uri("http://test.nuget.org/login"));
            mockAuthContext.SetupGet(c => c.HttpContext.Request.RawUrl).Returns("/login");
            mockAuthContext.SetupGet(c => c.HttpContext.Request.IsSecureConnection).Returns(false);

            mockConfig.Setup(cfg => cfg.RequireSSL).Returns(true);
            mockConfig.Setup(cfg => cfg.SSLPort).Returns(port);
            
            var attribute = new RequireSslAttribute()
            {
                Configuration = mockConfig.Object
            };

            var result = new ViewResult();
            var context = mockAuthContext.Object;
            
            // Act
            attribute.OnAuthorization(context);

            // Assert
            Assert.IsType<RedirectResult>(context.Result);
            Assert.Equal("https://" + String.Format(hostFormatter, "test.nuget.org") + "/login", ((RedirectResult)context.Result).Url);
        }
        public AccountControllerTests()
        {
            WebSecurity = new Mock<IWebSecurity>(MockBehavior.Strict);
            OAuthWebSecurity = new Mock<IOAuthWebSecurity>(MockBehavior.Strict);

            Identity = new Mock<IIdentity>(MockBehavior.Strict);
            User = new Mock<IPrincipal>(MockBehavior.Strict);
            User.SetupGet(u => u.Identity).Returns(Identity.Object);
            WebSecurity.SetupGet(w => w.CurrentUser).Returns(User.Object);

            Routes = new RouteCollection();
            RouteConfig.RegisterRoutes(Routes);

            Request = new Mock<HttpRequestBase>(MockBehavior.Strict);
            Request.SetupGet(x => x.ApplicationPath).Returns("/");
            Request.SetupGet(x => x.Url).Returns(new Uri("http://localhost/a", UriKind.Absolute));
            Request.SetupGet(x => x.ServerVariables).Returns(new System.Collections.Specialized.NameValueCollection());

            Response = new Mock<HttpResponseBase>(MockBehavior.Strict);

            Context = new Mock<HttpContextBase>(MockBehavior.Strict);
            Context.SetupGet(x => x.Request).Returns(Request.Object);
            Context.SetupGet(x => x.Response).Returns(Response.Object);

            Controller = new AccountController(WebSecurity.Object, OAuthWebSecurity.Object);
            Controller.ControllerContext = new ControllerContext(Context.Object, new RouteData(), Controller);
            Controller.Url = new UrlHelper(new RequestContext(Context.Object, new RouteData()), Routes);
        }
Ejemplo n.º 28
0
        public void MiniDumpDeleteOnCloseTests()
        {
            // Arrange
            var path = @"x:\temp\minidump.dmp";
            var fileSystem = new Mock<IFileSystem>();
            var file = new Mock<FileBase>();
            var fileInfoFactory = new Mock<IFileInfoFactory>();
            var fileInfo = new Mock<FileInfoBase>();

            // Setup
            fileSystem.SetupGet(fs => fs.File)
                      .Returns(file.Object);
            fileSystem.SetupGet(fs => fs.FileInfo)
                      .Returns(fileInfoFactory.Object);
            file.Setup(f => f.Exists(path))
                      .Returns(true);
            file.Setup(f => f.OpenRead(path))
                      .Returns(() => new MemoryStream());
            fileInfoFactory.Setup(f => f.FromFileName(path))
                           .Returns(() => fileInfo.Object);
            fileInfo.Setup(f => f.Exists)
                    .Returns(true);
            FileSystemHelpers.Instance = fileSystem.Object;

            // Test
            var stream = ProcessController.FileStreamWrapper.OpenRead(path);
            stream.Close();

            // Assert
            fileInfo.Verify(f => f.Delete(), Times.Once());
        }
Ejemplo n.º 29
0
        public void BindTest1()
        {
            var bindingToSyntax = new Mock<IBindingToSyntax<object>>(MockBehavior.Loose);
            var bindingNamed = new Mock<IBindingWhenInNamedWithOrOnSyntax<object>>(MockBehavior.Loose);
            var bInfo = new Mock<IBindInfo>(MockBehavior.Loose);
            var scopeBinder = new Mock<IScopeBinder>(MockBehavior.Loose);
            var scoped = new Mock<IBindingNamedWithOrOnSyntax<object>>(MockBehavior.Loose);
            var typesFrom = new List<Type>();
            var typeTo = typeof (string);
            var bindingScope = new BindingScope("sdrjklgnlsdjkg");

            bindingToSyntax.Name = "bindingToSyntax";
            bindingNamed.Name = "bindingNamed";
            bInfo.Name = "bInfo";
            scopeBinder.Name = "scopeBinder";
            scoped.Name = "scoped";

            bInfo.SetupGet(x => x.From).Returns(typesFrom).Verifiable();
            bInfo.SetupGet(x => x.To).Returns(typeTo).Verifiable();
            bInfo.SetupGet(x => x.Scope).Returns(bindingScope).Verifiable();
            bInfo.SetupGet(x => x.Name).Returns((string)null).Verifiable();
            bindingNamed.Setup(x => x.GetHashCode()).Returns(100.GetHashCode()).Verifiable();
            bindingNamed.Setup(x => x.ToString()).Returns("100").Verifiable();

            scopeBinder.Setup(x => x.InScope(bindingNamed.Object, bindingScope)).Returns(scoped.Object).Verifiable();
            bindingToSyntax.Setup(x => x.To(typeTo)).Returns(bindingNamed.Object).Verifiable();


            new NinjectBinder(types => bindingToSyntax.Object, scopeBinder.Object).Bind(new[] {bInfo.Object});

        }
Ejemplo n.º 30
0
        private ControllerContext GetControllerContext(Controller target, bool isAjax)
        {
            Mock <HttpRequestBase> mockHttpRequest = new Mock <HttpRequestBase>();

            if (isAjax)
            {
                mockHttpRequest.SetupGet(x => x.Headers).Returns(new WebHeaderCollection()
                {
                    "X-Requested-With:XMLHttpRequest"
                });
            }
            else
            {
                mockHttpRequest.SetupGet(x => x.Headers).Returns(new WebHeaderCollection()
                {
                    "X-Requested-With:"
                });
            }
            Mock <HttpContextBase> mockHttpContext = new Mock <HttpContextBase>();

            mockHttpContext.SetupGet(x => x.Request).Returns(mockHttpRequest.Object);
            return(new ControllerContext(mockHttpContext.Object, new RouteData(), target));
        }
Ejemplo n.º 31
0
        public void NotifySpamStory_Should_Send_Spamed_Story_Details()
        {
            const string mailTemplate = "Title: <%=title%>" +
                                        "Site Url: <%=siteUrl%>" +
                                        "Original Url: <%=originalUrl%>" +
                                        "User: <%=userName%>";

            var user = new Mock <IUser>();

            user.SetupGet(u => u.UserName).Returns("Dummy user");

            var story = new Mock <IStory>();

            story.SetupGet(s => s.Title).Returns("A dummy story");
            story.SetupGet(s => s.Url).Returns("http://www.dummystory.com");
            story.SetupGet(s => s.PostedBy).Returns(user.Object);

            _file.Setup(f => f.ReadAllText(It.IsAny <string>())).Returns(mailTemplate).Verifiable();

            _emailSender.NotifySpamStory("http://dotnetshoutout.com/The-Dummy_Story", story.Object, "foo");

            Sleep();
        }
Ejemplo n.º 32
0
        public void FindTest()
        {
            Mock <IProjectConfigurationManagement> _projectConfigurationMock = new Mock <IProjectConfigurationManagement>();
            Mock <OPCFModelDesign> _OPCFModelDesignMock = new Mock <OPCFModelDesign>();

            _projectConfigurationMock.SetupGet <OPCFModelDesign>(x => x.ModelDesign).Returns(_OPCFModelDesignMock.Object);
            _projectConfigurationMock.SetupGet <string>(x => x.Name).Returns("EFFF0C05 - 8406 - 4AD9 - 8725 - F00FC8295327");
            Mock <BaseTreeNode> _parentMock = new Mock <BaseTreeNode>("ParentBaseNode");

            _parentMock.SetupGet <string[]>(x => x.AvailiableNamespaces).Returns(new List <string>()
            {
                "ns1", "ns2"
            }.ToArray());
            ProjectTreeNode _newItem = new ProjectTreeNode(_projectConfigurationMock.Object)
            {
                Parent = _parentMock.Object
            };

            XmlQualifiedName _toFind     = new XmlQualifiedName("Name", "Namespace");
            ITypeDesign      _findReturn = _newItem.Find(_toFind);

            Assert.IsNull(_findReturn);
        }
        public async void BulkInsert_Errors()
        {
            VehCapabilityControllerMockFacade mock = new VehCapabilityControllerMockFacade();

            var mockResponse = new Mock <CreateResponse <ApiVehCapabilityServerResponseModel> >(null as ApiVehCapabilityServerResponseModel);

            mockResponse.SetupGet(x => x.Success).Returns(false);

            mock.ServiceMock.Setup(x => x.Create(It.IsAny <ApiVehCapabilityServerRequestModel>())).Returns(Task.FromResult <CreateResponse <ApiVehCapabilityServerResponseModel> >(mockResponse.Object));
            VehCapabilityController controller = new VehCapabilityController(mock.ApiSettingsMoc.Object, mock.LoggerMock.Object, mock.TransactionCoordinatorMock.Object, mock.ServiceMock.Object, mock.ModelMapperMock.Object);

            controller.ControllerContext             = new ControllerContext();
            controller.ControllerContext.HttpContext = new DefaultHttpContext();

            var records = new List <ApiVehCapabilityServerRequestModel>();

            records.Add(new ApiVehCapabilityServerRequestModel());
            IActionResult response = await controller.BulkInsert(records);

            response.Should().BeOfType <ObjectResult>();
            (response as ObjectResult).StatusCode.Should().Be((int)HttpStatusCode.UnprocessableEntity);
            mock.ServiceMock.Verify(x => x.Create(It.IsAny <ApiVehCapabilityServerRequestModel>()));
        }
Ejemplo n.º 34
0
        private ServiceModelServiceMethodProvider <TService> CreateSut <TService>()
            where TService : class
        {
            var rootConfiguration = new Mock <IOptions <ServiceModelGrpcServiceOptions> >(MockBehavior.Strict);

            rootConfiguration
            .SetupGet(c => c.Value)
            .Returns(new ServiceModelGrpcServiceOptions());

            var serviceConfiguration = new Mock <IOptions <ServiceModelGrpcServiceOptions <TService> > >(MockBehavior.Strict);

            serviceConfiguration
            .SetupGet(c => c.Value)
            .Returns(new ServiceModelGrpcServiceOptions <TService>());

            var logger = new Mock <ILogger <ServiceModelServiceMethodProvider <TService> > >(MockBehavior.Strict);

            return(new ServiceModelServiceMethodProvider <TService>(
                       rootConfiguration.Object,
                       serviceConfiguration.Object,
                       logger.Object,
                       _serviceProvider.Object));
        }
            public void DoesNotIncludeIgnoredColumns()
            {
                Mock <IPropertyMap> property1 = new Mock <IPropertyMap>();

                property1.SetupGet(p => p.SelectIgnored).Returns(true).Verifiable();
                Mock <IPropertyMap> property2 = new Mock <IPropertyMap>();
                var properties = new List <IPropertyMap>
                {
                    property1.Object,
                    property2.Object
                };

                Generator.Setup(g => g.GetColumnName(ClassMap.Object, property2.Object, true)).Returns("Column2").Verifiable();
                ClassMap.SetupGet(c => c.Properties).Returns(properties).Verifiable();

                var result = Generator.Object.BuildSelectColumns(ClassMap.Object);

                Assert.AreEqual("Column2", result);
                ClassMap.Verify();
                Generator.Verify();
                Generator.Verify(g => g.GetColumnName(ClassMap.Object, property1.Object, true), Times.Never());
                property1.Verify();
            }
        public static void GetPackageReferencesMarkedForReinstallationReturnsEmptyListWhenNuGetIsNotInUseInAProject()
        {
            // Arrange
            Mock<Project> mockProject = new Mock<Project>();
            mockProject.SetupGet(p => p.FullName).Returns(@"c:\a\b\c.csproj");

            // Setup project kind to a supported value. This makes sure that the check for existence of packages.config happens
            mockProject.Setup(p => p.Kind).Returns(CsharpProjectTypeGuid);

            var mockServices = new Dictionary<Type, object>();
            Mock<IVsSolution> mockSolution = new Mock<IVsSolution>();
            mockServices.Add(typeof(IVsSolution), mockSolution.Object);
            Mock<IVsHierarchy> mockHier = new Mock<IVsHierarchy>();
            IVsHierarchy hier = mockHier.Object;
            mockSolution.Setup(m => m.GetProjectOfUniqueName(It.IsAny<string>(), out hier)).Returns(0);
            ServiceLocator.TestServiceCache = mockServices;

            // Act
            var packagesToBeReinstalled = ProjectRetargetingUtility.GetPackageReferencesMarkedForReinstallation(mockProject.Object);

            // Assert
            Assert.True(packagesToBeReinstalled.IsEmpty());
        }
Ejemplo n.º 37
0
    public void AddFileVersionToPath_DoesNotLockFileAfterReading()
    {
        // Arrange
        var stream   = new TestableMemoryStream(Encoding.UTF8.GetBytes("Hello World!"));
        var mockFile = new Mock <IFileInfo>();

        mockFile.SetupGet(f => f.Exists).Returns(true);
        mockFile
        .Setup(m => m.CreateReadStream())
        .Returns(stream);

        var fileProvider = new TestFileProvider();

        fileProvider.AddFile("/hello/world", mockFile.Object);
        var requestPath         = GetRequestPathBase();
        var fileVersionProvider = GetFileVersionProvider(fileProvider);

        // Act
        var result = fileVersionProvider.AddFileVersionToPath(requestPath, "/hello/world");

        // Assert
        Assert.True(stream.Disposed);
    }
Ejemplo n.º 38
0
        public async Task ExtendedMediasAreIncludedInInlineMedias()
        {
            // Arrange
            var json   = File.ReadAllText("Data/tweet_extmedia.json");
            var data   = JsonMapper.ToObject(json);
            var status = new Status(data);

            var context      = new Mock <IContextEntry>();
            var config       = new Mock <IConfig>();
            var visualConfig = new VisualConfig {
                InlineMedia = true
            };

            config.SetupGet(c => c.Visual).Returns(visualConfig);
            var vm = new StatusViewModel(status, context.Object, config.Object, null);
            await vm.LoadDataAsync();

            // Act
            var medias = vm.InlineMedias.ToArray();

            // Assert
            Assert.AreEqual(3, medias.Length);
        }
        public async Task ReturnErrorObject_GivenNoRunningGameIsFound()
        {
            var mockPhases  = new List <Phase>().AsQueryable().BuildMockDbSet();
            var dataContext = new Mock <DataContext>();

            dataContext.SetupGet(x => x.Phases).Returns(mockPhases.Object);
            var requestContext       = new RequestContext();
            var gameApiServiceLogger = GetMockLogger <GameApiService>().Object;
            var gameApiService       = new Mock <GameApiService>(dataContext.Object, gameApiServiceLogger, requestContext)
            {
                CallBase = true
            }.Object;
            var requestLoggingService = new RequestLoggingService(requestContext, dataContext.Object);
            var logger        = GetMockLogger <GameStatusController>().Object;
            var modController = new GameStatusController(requestContext, gameApiService, requestLoggingService, logger);
            var response      = await modController.Get();

            response.StatusCode.Should().Be(200);
            var result = (GameStatusResponse)response.Value;

            result.Err.Should().NotBeNull();
            result.Err.Description.Should().Be("Game is not running");
        }
Ejemplo n.º 40
0
        RandomlyPlaceShip_WHEN_Invoked_THEN_ReturnRandomlyPlacedShip(int length)
        {
            var mapRepoMock  = new Mock <IRepository <Map> >();
            var mapWithShips = new Map(10, 10);

            mapWithShips.Fields[0][1].Ship = new Ship(4);
            mapWithShips.Fields[0][2].Ship = new Ship(4);
            mapWithShips.Fields[0][3].Ship = new Ship(4);
            mapWithShips.Fields[0][4].Ship = new Ship(4);

            mapWithShips.Fields[0][0].Ship = new Ship(4);
            mapWithShips.Fields[1][0].Ship = new Ship(4);
            mapWithShips.Fields[2][0].Ship = new Ship(4);
            mapWithShips.Fields[3][0].Ship = new Ship(4);

            mapRepoMock.SetupGet(c => c.Entity).Returns(new Map(10, 10));
            var shipService = new ShipService(mapRepoMock.Object);
            var result      = shipService.RandomlyPlaceShip(length);

            result.Success.Should().BeTrue();
            result.Ship.Should().NotBeNull();
            result.Ship.Coordinates.Count.Should().Be(length);
        }
Ejemplo n.º 41
0
        public void SearchParameterLocator_LocateHelper_Succeeds()
        {
            Mock<ICode> code = new Mock<ICode>();
            byte[] codeBytes = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 };
            code.SetupGet(x => x.CodeBytes).Returns(codeBytes);

            DefaultParameterLocator locator = new DefaultParameterLocator(code.Object);
            PrivateObject privateObjectHelper = new PrivateObject(locator);

            const int PARAMETER_OFFSET = 2;
            int outIndex = 1;

            List<Type> parameterTypes = new List<Type>() { typeof(ParameterType), typeof(byte[]), typeof(int), typeof(ParameterOffsetDirection), typeof(int).MakeByRefType() };
            List<Object> parameterValuesBefore = new List<Object>() { ParameterType.Undefined, new byte[] { 0x04, 0x05 }, PARAMETER_OFFSET, ParameterOffsetDirection.Before, outIndex };
            List<Object> parameterValuesAfter = new List<Object>() { ParameterType.Undefined, new byte[] { 0x04, 0x05 }, PARAMETER_OFFSET, ParameterOffsetDirection.After, outIndex };
            List<Type> typeArguments = new List<Type>() { typeof(UInt16) };

            UInt16 resultBefore = (UInt16)privateObjectHelper.Invoke("LocateHelper", parameterTypes.ToArray(), parameterValuesBefore.ToArray(), typeArguments.ToArray());
            Assert.AreEqual(0x0203, resultBefore);

            UInt16 resultAfter = (UInt16)privateObjectHelper.Invoke("LocateHelper", parameterTypes.ToArray(), parameterValuesAfter.ToArray(), typeArguments.ToArray());
            Assert.AreEqual(0x0708, resultAfter);
        }
Ejemplo n.º 42
0
    public void GetUrlHelper_CreatesNewInstance_IfExpectedTypeIsNotPresent()
    {
        // Arrange
        var httpContext = new Mock <HttpContext>();

        httpContext.SetupGet(h => h.Features).Returns(new FeatureCollection());
        var mockItems = new Dictionary <object, object>
        {
            { typeof(IUrlHelper), null }
        };

        httpContext.Setup(h => h.Items).Returns(mockItems);

        var actionContext    = CreateActionContext(httpContext.Object);
        var urlHelperFactory = new UrlHelperFactory();

        // Act
        var urlHelper = urlHelperFactory.GetUrlHelper(actionContext);

        // Assert
        Assert.NotNull(urlHelper);
        Assert.Same(urlHelper, actionContext.HttpContext.Items[typeof(IUrlHelper)] as IUrlHelper);
    }
Ejemplo n.º 43
0
        public void AddMvcCore_GetsPartsForApplication()
        {
            // Arrange
            var services        = new ServiceCollection();
            var environment     = new Mock <IWebHostEnvironment>();
            var assemblyName    = typeof(MvcCoreServiceCollectionExtensionsTest).Assembly.GetName();
            var applicationName = assemblyName.FullName;

            environment.SetupGet(e => e.ApplicationName).Returns(applicationName).Verifiable();
            services.AddSingleton <IWebHostEnvironment>(environment.Object);

            // Act
            var builder = services.AddMvcCore();

            // Assert
            Assert.NotNull(builder.PartManager);
            Assert.Contains(
                builder.PartManager.ApplicationParts,
                part => string.Equals(assemblyName.Name, part.Name, StringComparison.Ordinal));
            Assert.Contains(builder.PartManager.FeatureProviders, provider => provider is ControllerFeatureProvider);

            environment.VerifyAll();
        }
        protected override void Arrange()
        {
            _documentData = new DocumentData();

            _graphicsMock = new Mock <IGraphics>(MockBehavior.Strict);

            _renderDataMock = new Mock <IRenderData>(MockBehavior.Strict);
            _referencePoint = new ReferencePoint();

            _renderDataMock = new Mock <IRenderData>(MockBehavior.Strict);
            _renderDataMock.Setup(x => x.ParentBounds).Returns(It.IsAny <XRect>());
            _renderDataMock.Setup(x => x.Graphics).Returns(_graphicsMock.Object);
            _renderDataMock.Setup(x => x.Section).Returns(new Section());
            _renderDataMock.Setup(x => x.DocumentData).Returns(_documentData);
            _renderDataMock.Setup(x => x.PageNumberInfo).Returns(new PageNumberInfo(1, 1));
            _renderDataMock.Setup(x => x.DebugData).Returns((IDebugData)null);
            _renderDataMock.Setup(x => x.IncludeBackground).Returns(false);
            _renderDataMock.Setup(x => x.ElementBounds).Returns(It.IsAny <XRect>());
            _renderDataMock.SetupSet(x => x.ElementBounds = It.IsAny <XRect>());
            _renderDataMock.SetupGet(x => x.DocumentProperties).Returns(Mock.Of <DocumentProperties>());

            _referencePoint.PreRender(_renderDataMock.Object);
        }
Ejemplo n.º 45
0
        public void RequireHttpsAttributeDoesNotThrowForSecureConnection()
        {
            // Arrange
            var mockAuthContext = new Mock <AuthorizationContext>(MockBehavior.Strict);
            var mockConfig      = new Mock <IAppConfiguration>();

            mockConfig.Setup(cfg => cfg.RequireSSL).Returns(true);
            mockAuthContext.SetupGet(c => c.HttpContext.Request.IsSecureConnection).Returns(true);
            var context   = mockAuthContext.Object;
            var attribute = new RequireSslAttribute()
            {
                Configuration = mockConfig.Object
            };
            var result = new ViewResult();

            context.Result = result;

            // Act
            attribute.OnAuthorization(context);

            // Assert
            Assert.Same(result, context.Result);
        }
            private static IProperty CreateProperty(string name, object value, List <object> setValues = null)
            {
                var property = new Mock <IProperty>(MockBehavior.Strict);

                property.SetupGet(o => o.Name)
                .Returns(name);

                property.Setup(o => o.GetValueAsync())
                .ReturnsAsync(value);

                property.As <IEvaluatedProperty>().Setup(p => p.GetEvaluatedValueAtEndAsync()).ReturnsAsync(value.ToString());
                property.As <IEvaluatedProperty>().Setup(p => p.GetEvaluatedValueAsync()).ReturnsAsync(value.ToString());

                if (setValues != null)
                {
                    property
                    .Setup(p => p.SetValueAsync(It.IsAny <object>()))
                    .Callback <object>(obj => setValues.Add(obj))
                    .Returns(() => Task.CompletedTask);
                }

                return(property.Object);
            }
Ejemplo n.º 47
0
    public void GetUrlHelper_ReturnsSameInstance_IfAlreadyPresent()
    {
        // Arrange
        var expectedUrlHelper = CreateUrlHelper();
        var httpContext       = new Mock <HttpContext>();

        httpContext.SetupGet(h => h.Features).Returns(new FeatureCollection());
        var mockItems = new Dictionary <object, object>
        {
            { typeof(IUrlHelper), expectedUrlHelper }
        };

        httpContext.Setup(h => h.Items).Returns(mockItems);

        var actionContext    = CreateActionContext(httpContext.Object);
        var urlHelperFactory = new UrlHelperFactory();

        // Act
        var urlHelper = urlHelperFactory.GetUrlHelper(actionContext);

        // Assert
        Assert.Same(expectedUrlHelper, urlHelper);
    }
        public async Task DownloadsInBlocksWhenOverTheLimit()
        {
            MemoryStream          stream      = new MemoryStream();
            MockDataSource        dataSource  = new MockDataSource(100);
            Mock <BlobBaseClient> blockClient = new Mock <BlobBaseClient>(MockBehavior.Strict, new Uri("http://mock"), new BlobClientOptions());

            blockClient.SetupGet(c => c.ClientConfiguration).CallBase();
            SetupDownload(blockClient, dataSource);

            PartitionedDownloader downloader = new PartitionedDownloader(
                blockClient.Object,
                new StorageTransferOptions()
            {
                MaximumTransferLength = 10,
                InitialTransferLength = 20
            });

            Response result = await InvokeDownloadToAsync(downloader, stream);

            Assert.AreEqual(dataSource.Requests.Count, 9);
            AssertContent(100, stream);
            Assert.NotNull(result);
        }
Ejemplo n.º 49
0
        public void RendererIsDisposed()
        {
            using (Start())
            {
                var renderer = new Mock <IRenderer>();
                renderer.Setup(x => x.Dispose());
                var impl = new Mock <IWindowImpl>();
                impl.SetupGet(x => x.RenderScaling).Returns(1);
                impl.SetupProperty(x => x.Closed);
                impl.Setup(x => x.CreateRenderer(It.IsAny <IRenderRoot>())).Returns(renderer.Object);
                impl.Setup(x => x.Dispose()).Callback(() => impl.Object.Closed());

                AvaloniaLocator.CurrentMutable.Bind <IWindowingPlatform>()
                .ToConstant(new MockWindowingPlatform(() => impl.Object));
                var window = new Window()
                {
                    Content = new Button()
                };
                window.Show();
                window.Close();
                renderer.Verify(r => r.Dispose());
            }
        }
        public void ModuleSettingsPresenter_SaveSettings_Saves_ModuleSettings()
        {
            // Arrange
            var view = new Mock<ISettingsView<SettingsModel>>();
            view.SetupGet(v => v.Model).Returns(new SettingsModel());

            var controller = new Mock<IModuleController>();

            var presenter = new TestSettingsPresenter(view.Object) { ModuleContext = this.CreateModuleContext() };
            presenter.IsPostBack = true;
            view.Raise(v => v.Load += null, EventArgs.Empty);

            // Act
            view.Raise(v => v.OnSaveSettings += null, EventArgs.Empty);

            // Assert
            foreach (var setting in view.Object.Model.ModuleSettings)
            {
                var key = setting.Key;
                var value = setting.Value;
                controller.Verify(c => c.UpdateModuleSetting(It.IsAny<int>(), key, value), Times.Once());
            }
        }
Ejemplo n.º 51
0
        private static HttpContext GetHttpContext(string appRoot,
                                                  string contentPath,
                                                  string expectedPath,
                                                  HttpResponse response)
        {
            var httpContext         = new Mock <HttpContext>();
            var actionContext       = GetActionContext(httpContext.Object);
            var mockContentAccessor = new Mock <IContextAccessor <ActionContext> >();

            mockContentAccessor.SetupGet(o => o.Value).Returns(actionContext);
            var mockActionSelector = new Mock <IActionSelector>();
            var urlHelper          = new UrlHelper(mockContentAccessor.Object, mockActionSelector.Object);
            var serviceProvider    = GetServiceProvider(urlHelper);

            httpContext.Setup(o => o.Response)
            .Returns(response);
            httpContext.SetupGet(o => o.RequestServices)
            .Returns(serviceProvider);
            httpContext.Setup(o => o.Request.PathBase)
            .Returns(new PathString(appRoot));

            return(httpContext.Object);
        }
Ejemplo n.º 52
0
        public void TestValidateItemAsList()
        {
            var element       = new BaseElement();
            var parentElement = new BaseElement();

            var listMock = new Mock <IElementList <BaseElement, BaseElement> >(MockBehavior.Strict);

            listMock.SetupGet(l => l.Parent).Returns(parentElement);

            var pageBase = new Mock <IPageElementHandler <BaseElement> >(MockBehavior.Strict);

            pageBase.Setup(p => p.GetElementText(parentElement)).Returns("My Data");

            var propertyData = CreatePropertyData(pageBase, element, (p, f) => f(listMock.Object));

            string actualValue;
            var    result = propertyData.ValidateItem(ItemValidationHelper.Create("MyProperty", "My Data"), out actualValue);

            Assert.IsTrue(result);

            pageBase.VerifyAll();
            listMock.VerifyAll();
        }
        public async Task TestCreateTokenClient()
        {
            var mockApp = new Mock <IAssemblyInformationProvider>();

            mockApp.SetupGet(x => x.ProductInfoHeaderValue).Returns(new ProductInfoHeaderValue("TGSTests", "1.2.3")).Verifiable();

            var mockOptions = new Mock <IOptions <GeneralConfiguration> >();

            mockOptions.SetupGet(x => x.Value).Returns(new GeneralConfiguration());
            var factory = new GitHubClientFactory(mockApp.Object, mockOptions.Object);

            Assert.ThrowsException <ArgumentNullException>(() => factory.CreateClient(null));

            var client = factory.CreateClient("asdf");

            Assert.IsNotNull(client);

            var credentials = await client.Connection.CredentialStore.GetCredentials().ConfigureAwait(false);

            Assert.AreEqual(AuthenticationType.Oauth, credentials.AuthenticationType);

            mockApp.VerifyAll();
        }
        public GetAzureRmMetricDefinitionTests()
        {
            insightsMetricDefinitionOperationsMock = new Mock <IMetricDefinitionOperations>();
            insightsClientMock = new Mock <InsightsClient>();
            commandRuntimeMock = new Mock <ICommandRuntime>();
            cmdlet             = new GetAzureRmMetricDefinitionCommand()
            {
                CommandRuntime = commandRuntimeMock.Object,
                InsightsClient = insightsClientMock.Object
            };

            response = Utilities.InitializeMetricDefinitionResponse();

            insightsMetricDefinitionOperationsMock.Setup(f => f.GetMetricDefinitionsAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <MetricDefinitionListResponse>(response))
            .Callback((string f, string s, CancellationToken t) =>
            {
                resourceId = f;
                filter     = s;
            });

            insightsClientMock.SetupGet(f => f.MetricDefinitionOperations).Returns(this.insightsMetricDefinitionOperationsMock.Object);
        }
        public void CityHash_Implementation_Constructor_Config_HashSizeInBits_IsInvalid_Throws()
        {
            var invalidLengths = new[] { 0, 1, 8, 16, 31, 33, 63, 65, 127, 129, 256 };

            foreach (var length in invalidLengths)
            {
                var cityHashConfigMock = new Mock <ICityHashConfig>();
                {
                    cityHashConfigMock.SetupGet(chc => chc.HashSizeInBits)
                    .Returns(length);

                    cityHashConfigMock.Setup(chc => chc.Clone())
                    .Returns(() => cityHashConfigMock.Object);
                }


                Assert.Equal(
                    "config.HashSizeInBits",
                    Assert.Throws <ArgumentOutOfRangeException>(
                        () => new CityHash_Implementation(cityHashConfigMock.Object))
                    .ParamName);
            }
        }
        public void TestCanWriteValidRequest()
        {
            var uri         = new Uri($"https://www.xfinity.com{ ModuleInfo.RoutePrefix }buy/home/page1/en.json");
            var requestMock = new Mock <HttpRequestBase>();

            requestMock.Setup(r => r.Url).Returns(uri);
            var contextMock = new Mock <HttpContextBase>();
            var items       = new Dictionary <string, object>();

            contextMock.SetupGet(c => c.Items).Returns(items);
            contextMock.Setup(c => c.Request).Returns(requestMock.Object);
            contextMock.Setup(c => c.RewritePath(It.Is <string>(s =>
                                                                MatchesExpected(s, ModuleInfo.RoutePrefix.TrimEnd('/'), "buy", "/home/page1", "en")
                                                                ))).Verifiable("The RewritePath method was never called with the expected URL.");

            var context   = contextMock.Object;
            var processor = new HeadlessRequestUrlRewriteProcessor();

            processor.ExecuteRewrite(context, ModuleInfo.RoutePrefix.TrimEnd('/'));

            contextMock.Verify();
            Assert.IsTrue(context.IsHeadless());
        }
Ejemplo n.º 57
0
        public void SetUp()
        {
            unRegisterDirectoryOnDispose = false;

            directoryCache = new Mock <IDirectoryCache>();
            directory      = new Mock <IDirectory>();
            directory.SetupGet(x => x.BlockId).Returns(123);
            directory.Setup(x => x.GetDirectoryEntries()).Returns(new[]
            {
                Mock.Of <IDirectoryEntryInfo>(y => y.IsDirectory && y.BlockId == 1 && y.Name == "Dir 1"),
                Mock.Of <IDirectoryEntryInfo>(y => y.IsDirectory && y.BlockId == 2 && y.Name == "Dir 2"),
                Mock.Of <IDirectoryEntryInfo>(y => y.IsDirectory == false && y.BlockId == 3 && y.Name == "File 1"),
            });

            newDirectory     = new Mock <IDirectoryEntry>();
            directoryFactory = new Mock <IFactory <IDirectoryEntry, IDirectoryCache, IDirectory, bool> >();
            directoryFactory.Setup(x => x.Create(It.IsAny <IDirectoryCache>(), It.IsAny <IDirectory>(), It.IsAny <bool>()))
            .Returns(newDirectory.Object);

            newFile     = new Mock <IFileEntry>();
            fileFactory = new Mock <IFactory <IFileEntry, IDirectoryCache, IFile> >();
            fileFactory.Setup(x => x.Create(It.IsAny <IDirectoryCache>(), It.IsAny <IFile>())).Returns(newFile.Object);
        }
Ejemplo n.º 58
0
        public void Create_DuplicateCreditCard_ThrowsException()
        {
            //setup
            Mock <CreditCard> creditCard = new Mock <CreditCard>()
            {
                CallBase = true
            };

            creditCard.SetupGet(x => x.CardNumber).Returns("293923910200292");
            creditCard.SetupGet(x => x.Expiry).Returns(DateTime.Today.AddDays(1));

            Mock <Customer> customer = new Mock <Customer>();

            customer.SetupGet(x => x.CreditCards)
            .Returns(new ReadOnlyCollection <CreditCard>(new List <CreditCard>()
            {
                creditCard.Object
            }));

            //cal
            CreditCard actual = CreditCard.Create(customer.Object, "MR J SMITH",
                                                  "293923910200292", DateTime.Today.AddDays(1));
        }
Ejemplo n.º 59
0
        public void Refill_should_give_a_card_to_each_player()
        {
            _deckFactoryMock.Setup(x => x.CreateDeck()).Returns(_deckMock.Object);
            _deckMock.Setup(d => d.Pop()).Returns(new Card("foo", 1));
            _deckMock.SetupGet(d => d.Count).Returns(40);

            var strategyMock = new Mock <IStrategy>();

            _playerFactoryMock.Setup(f => f.CreatePlayer(_players[0], strategyMock.Object))
            .Returns(new Player(_strategyMock.Object, _players[0]));
            _playerFactoryMock.Setup(f => f.CreatePlayer(_players[1], strategyMock.Object))
            .Returns(new Player(_strategyMock.Object, _players[1]));
            _sut.Join(_players[0], strategyMock.Object);
            _sut.Join(_players[1], strategyMock.Object);
            _sut.Start();

            _sut.Refill();


            _sut.State.Players.All(p => p.HandCards.Count() == 4).Should().Be.True();
            _sut.State.Turn.Should().Be.EqualTo(0);
            _sut.State.Dish.Should().Be.Empty();
        }
        public void Should_send_multiple_points_when_not_using_fieldname()
        {
            //Arrange
            string databaseName = "AA";
            var performanceCounterGroupMock = new Mock<IPerformanceCounterGroup>(MockBehavior.Strict);
            performanceCounterGroupMock.SetupGet(x => x.SecondsInterval).Returns(1);
            performanceCounterGroupMock.SetupGet(x => x.RefreshInstanceInterval).Returns(1);
            performanceCounterGroupMock.SetupGet(x => x.Name).Returns("cpu");
            performanceCounterGroupMock.Setup(x => x.GetFreshCounters()).Returns(new List<IPerformanceCounterInfo>
            {
                new PerformanceCounterInfo(string.Empty, new PerformanceCounter("Processor", "% Processor Time", "_Total")),
                new PerformanceCounterInfo(string.Empty, new PerformanceCounter("Processor", "% Idle Time", "_Total"))
            });
            performanceCounterGroupMock.SetupGet(x => x.Tags).Returns(new ITag[] { });
            var sendBusinessMock = new Mock<ISendBusiness>(MockBehavior.Strict);
            sendBusinessMock.Setup(x => x.Enqueue(It.IsAny<Point[]>()));
            var tagLaoderMock = new Mock<ITagLoader>(MockBehavior.Strict);
            tagLaoderMock.Setup(x => x.GetGlobalTags()).Returns(new[] { Mock.Of<ITag>(x => x.Name == "B") });
            var collectorEngine = new ExactCollectorEngine(performanceCounterGroupMock.Object, sendBusinessMock.Object, tagLaoderMock.Object, false);

            //Act
            var response = collectorEngine.CollectRegisterCounterValuesAsync().Result;

            //Assert
            tagLaoderMock.Verify(x => x.GetGlobalTags(), Times.Once);
            sendBusinessMock.Verify(x => x.Enqueue(It.IsAny<Point[]>()), Times.Once);
            Assert.That(response, Is.EqualTo(2));
        }