public void Bounds_Should_Be_Set_After_Layout_Pass() { using (Locator.CurrentMutable.WithResolver()) { this.RegisterServices(); Locator.CurrentMutable.RegisterConstant(new LayoutManager(), typeof(ILayoutManager)); var impl = new Mock<ITopLevelImpl>(); impl.SetupProperty(x => x.ClientSize); impl.SetupProperty(x => x.Resized); var target = new TestTopLevel(impl.Object) { Template = new ControlTemplate<TestTopLevel>(x => new ContentPresenter { [~ContentPresenter.ContentProperty] = x[~TestTopLevel.ContentProperty], }), Content = new TextBlock { Width = 321, Height = 432, } }; target.LayoutManager.ExecuteLayoutPass(); Assert.Equal(new Rect(0, 0, 321, 432), target.Bounds); } }
public void ItShouldBeAbleToSetQueryParameter() { // Arrange var dataProviderMock = new Mock<IDataObjectsFactory>(); var dataCommandMock = new Mock<IDbCommand>(); var dataParameterMock = new Mock<IDbDataParameter>(); var databaseContext = Database.ForProvider(dataProviderMock.Object); dataProviderMock.Setup(c => c.CreateCommand()) .Returns(dataCommandMock.Object); dataProviderMock.Setup(c => c.CreateParameter()) .Returns(dataParameterMock.Object); dataParameterMock.SetupProperty(c => c.Value); dataParameterMock.SetupProperty(c => c.ParameterName); // Act var databaseCommand = databaseContext.Execute("SELECT * FROM Table") .Where("Id", p => p.Is(1)); // Assert Assert.That(dataParameterMock.Object.ParameterName, Is.EqualTo("@Id")); Assert.That(dataParameterMock.Object.Value, Is.EqualTo(1)); }
public static RequestContext GetMockRequestContext(this HttpContextBase httpContextBase) { var requestContext = new Mock<RequestContext>(); requestContext.SetupProperty(r => r.HttpContext, httpContextBase); requestContext.SetupProperty(r => r.RouteData, new RouteData()); return requestContext.Object; }
public void Example() { var mock = new Mock<IFoo>(); mock.Setup(foo => foo.Name).Returns("bar"); // auto-mocking hierarchies (a.k.a. recursive mocks) mock.Setup(foo => foo.Bar.Baz.Name).Returns("baz"); // expects an invocation to set the value to "foo" mock.SetupSet(foo => foo.Name = "foo"); // or verify the setter directly mock.VerifySet(foo => foo.Name = "foo"); //Setup a property so that it will automatically start tracking its value (also known as Stub): // start "tracking" sets/gets to this property mock.SetupProperty(f => f.Name); // alternatively, provide a default value for the stubbed property mock.SetupProperty(f => f.Name, "foo"); // Now you can do: IFoo ifoo = mock.Object; // Initial value was stored Assert.AreEqual("foo", ifoo.Name); // New value set which changes the initial value ifoo.Name = "bar"; Assert.AreEqual("bar", ifoo.Name); }
public void ShouldFillComboInfoWhenLoading() { //Arrange Mock<IPermittingView> view = new Mock<IPermittingView>(); EquipmentComboVO equipment = new EquipmentComboVO() { EquipmentId = 1, IsPrimary = true, DivisionNumber = "084", UnitNumber = "01", Descriptor = "Dozer" }; view.SetupProperty(v => v.EquipmentInfoItem, equipment); view.SetupProperty(v => v.IsPrimaryObjectSelected, false); view.SetupProperty(v => v.DivisionSelected, string.Empty); view.SetupProperty(v => v.UnitNumberSelected, string.Empty); view.SetupProperty(v => v.DescriptorSelected, string.Empty); //Act PermittingPresenter presenter = new PermittingPresenter(view.Object); presenter.LoadShoppingCartRow(); //Assert Assert.IsTrue(view.Object.IsPrimaryObjectSelected); Assert.AreEqual<string>(view.Object.DivisionSelected, "084"); Assert.AreEqual<string>(view.Object.UnitNumberSelected, "01"); Assert.AreEqual<string>(view.Object.DescriptorSelected, "Dozer"); }
public void ShouldFillDataSourceComboInShoppingCart() { //Arrange Mock<IPermittingView> view = new Mock<IPermittingView>(); view.SetupProperty(v => v.EquipmentComboId, 1); view.SetupProperty(v => v.ComboName, string.Empty); view.SetupProperty(v => v.ComboType, string.Empty); view.SetupProperty(v => v.EquipmentInfoShoppingCartDataSource, null); Mock<EquipmentModel> model = new Mock<EquipmentModel>(); model.Setup(m => m.GetCombo(1)).Returns(new CS_EquipmentCombo() { Name = "comboName", ComboType = "comboType" }); model.Setup(m => m.ListEquipmentsOfACombo(1)).Returns( new List<EquipmentComboVO>() { new EquipmentComboVO() { Descriptor = null, DivisionNumber = "Division", EquipmentId = 1, IsPrimary = true, UnitNumber = "1" }, new EquipmentComboVO() { Descriptor = null, DivisionNumber = "Division", EquipmentId = 2, IsPrimary = false, UnitNumber = "2" } }); PermittingPresenter presenter = new PermittingPresenter(view.Object, model.Object); //Act presenter.LoadCombo(); //Assert Assert.AreEqual("comboName", view.Object.ComboName, "Failed in ComboName Property"); Assert.AreEqual("comboType", view.Object.ComboType, "Failed in ComboType Property"); Assert.IsNotNull(view.Object.EquipmentInfoShoppingCartDataSource, "Failed in DataSource Property (NULL)"); Assert.AreEqual(2, view.Object.EquipmentInfoShoppingCartDataSource.Count, "Failed in DataSource Property (COUNT)"); }
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 PassesWhen_StartTimeIsBeforeEndTime() { //arrange var startTimeProperty = new Mock<IPropertyInfo>(); startTimeProperty.Setup(s => s.Name).Returns("StartTime"); startTimeProperty.Setup(s => s.Type).Returns(typeof(DateTime)); var endTimeProperty = new Mock<IPropertyInfo>(); endTimeProperty.Setup(s => s.Name).Returns("EndTime"); endTimeProperty.Setup(s => s.Type).Returns(typeof(DateTime)); var wsMock = new Mock<IWorkSchedule>(); wsMock.SetupProperty<DateTime>(ws => ws.StartTime, new DateTime(2014,4,1,10,0,0)); wsMock.SetupProperty<DateTime>(ws => ws.EndTime, new DateTime(2014, 4, 1, 11, 0, 0)); var innerRule1 = new TopOfTheHourRule(startTimeProperty.Object); var innerRule2 = new TopOfTheHourRule(endTimeProperty.Object); var newRule = new TimeRangeRule(startTimeProperty.Object, endTimeProperty.Object, innerRule1, innerRule2); var ruleContext = new RuleContext(null, newRule, wsMock.Object, new Dictionary<IPropertyInfo, object>() { { startTimeProperty.Object, wsMock.Object.StartTime }, {endTimeProperty.Object, wsMock.Object.EndTime} }); var ruleInterface = (IBusinessRule)newRule; //act ruleInterface.Execute(ruleContext); //assert Assert.IsNull(ruleContext.Results.SingleOrDefault(_ => _.Description == ValidationMessages.InvalidTimeRange)); }
public void Bounds_Should_Be_Set_After_Layout_Pass() { using (PerspexLocator.EnterScope()) { RegisterServices(); PerspexLocator.CurrentMutable.Bind<ILayoutManager>().ToConstant(new LayoutManager()); var impl = new Mock<ITopLevelImpl>(); impl.SetupProperty(x => x.ClientSize); impl.SetupProperty(x => x.Resized); var target = new TestTopLevel(impl.Object) { Template = CreateTemplate(), Content = new TextBlock { Width = 321, Height = 432, } }; target.LayoutManager.ExecuteLayoutPass(); Assert.Equal(new Rect(0, 0, 321, 432), target.Bounds); } }
public void Call_with_HttpMethod_Post_must_write_content_on_request_body() { var content = "{" + "\"id\": \"1\"," + "\"name\": \"Department\"" + "}"; string writedString = string.Empty; var mockMS = new Mock<MemoryStream>(); mockMS.Setup(m => m.CanWrite).Returns(true); mockMS.Setup(m => m.Write(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>())).Callback( (byte[] b, int i1, int i2) => { writedString = new System.Text.ASCIIEncoding().GetString(b, i1, i2); }); var mock = new Mock<HttpHelper>("https://www.mystore.com/api/v1"); mock.SetupProperty(m => m.HttpWebRequest.Method); mock.SetupProperty(m => m.HttpWebRequest.ContentType); mock.SetupProperty(m => m.HttpWebRequest.Headers, new WebHeaderCollection()); mock.Setup(m => m.HttpWebRequest.GetRequestStream()).Returns(mockMS.Object); mock.Setup(m => m.HttpWebRequest.GetResponse().GetResponseStream()).Returns(new MemoryStream()); APIClient target = new APIClient(new AuthState { AccessToken = "token", ApiUrl = "https://www.mystore.com/api/v1" }); target.Call(HttpMethods.POST, "departments", content, mock.Object); mock.VerifySet(h => h.HttpWebRequest.Method = "POST"); Assert.AreEqual(content, writedString); }
public void FilteredEquipmentsRowDataBound() { //Arrange IList<CS_FirstAlertVehicle> firstAlertVehicleList = new List<CS_FirstAlertVehicle>(); firstAlertVehicleList.Add(new CS_FirstAlertVehicle() { Active = true, EquipmentID = 1, Damage = "TL", EstimatedCost = 100, }); Mock<IFirstAlertView> mock = new Mock<IFirstAlertView>(); mock.SetupProperty(c => c.FirstAlertVehicleList, firstAlertVehicleList); mock.SetupProperty(c => c.FilteredEquipmentsEquipmentID, 1); mock.SetupProperty(c => c.FilteredEquipmentsDamage, ""); mock.SetupProperty(c => c.FilteredEquipmentsEstCost, ""); mock.SetupProperty(c => c.FilteredEquipmentsSelect, false); //Act FirstAlertViewModel viewModel = new FirstAlertViewModel(mock.Object); viewModel.FilteredEquipmentsRowDataBound(); // Assert Assert.AreEqual("TL", mock.Object.FilteredEquipmentsDamage, "Failed in FilteredEquipmentsDamage"); Assert.AreEqual(string.Format("{0:0.00}", 100), mock.Object.FilteredEquipmentsEstCost, "Failed in FilteredEquipmentsEstCost"); Assert.AreEqual(true, mock.Object.FilteredEquipmentsSelect, "Failed in FilteredEquipmentsSelect"); }
public void MinHourDifferenceIsAtLeastAnHour() { var startTimeProperty = new Mock<IPropertyInfo>(); startTimeProperty.Setup(s => s.Name).Returns("StartTime"); startTimeProperty.Setup(s => s.Type).Returns(typeof(DateTime)); var endTimeProperty = new Mock<IPropertyInfo>(); endTimeProperty.Setup(s => s.Name).Returns("endTime"); endTimeProperty.Setup(s => s.Type).Returns(typeof(DateTime)); var wsMock = new Mock<IWorkSchedule>(); wsMock.SetupProperty<DateTime>(ws => ws.StartTime, new DateTime(2014, 4, 1, 10, 0, 0)); wsMock.SetupProperty<DateTime>(ws => ws.EndTime, new DateTime(2014, 4, 1, 10, 30, 0)); var newRule = new MinHourDifferenceRule(startTimeProperty.Object, endTimeProperty.Object); var ruleContext = new RuleContext(null, newRule, wsMock.Object, new Dictionary<IPropertyInfo, object>() { { startTimeProperty.Object, wsMock.Object.StartTime }, { endTimeProperty.Object, wsMock.Object.EndTime } }); var ruleInterface = (IBusinessRule)newRule; ruleInterface.Execute(ruleContext); Assert.IsTrue(ruleContext.Results.Count > 0); wsMock.SetupProperty<DateTime>(ws => ws.StartTime, new DateTime(2014, 4, 1, 8, 0, 0)); wsMock.SetupProperty<DateTime>(ws => ws.EndTime, new DateTime(2014, 4, 1, 9, 30, 0)); ruleContext = new RuleContext(null, newRule, wsMock.Object, new Dictionary<IPropertyInfo, object>() { { startTimeProperty.Object, wsMock.Object.StartTime }, { endTimeProperty.Object, wsMock.Object.EndTime } }); ruleInterface = (IBusinessRule)newRule; ruleInterface.Execute(ruleContext); Assert.IsTrue(ruleContext.Results.Count == 0); }
Role SetupMock() { Mock<Role> moq = new Mock<Role>(); moq.SetupProperty(_ => _.Id, id); moq.SetupProperty(_ => _.Name, NAME); moq.SetupProperty(_ => _.Description, DESCRIPTION); return moq.Object; }
public void SetUp() { _navigationServiceBuilder = new NavigationServiceBuilder(false); _navigationServiceMock = new Mock<INavigationService>(); _navigationServiceMock.SetupProperty(service => service.PrimaryNavigatorManager); _navigationServiceMock.SetupProperty(service => service.SupportedNavigatorManagers); _service = _navigationServiceMock.Object; }
Permission SetupMock() { Mock<Permission> moq = new Mock<Permission>(); moq.SetupProperty(_ => _.Id, id); moq.SetupProperty(_ => _.Name, NAME); moq.SetupProperty(_ => _.NameTranslation, TRANSLATE_NAME); return moq.Object; }
PlateManufacturer SetupMock() { Mock<PlateManufacturer> moq = new Mock<PlateManufacturer>(); moq.SetupProperty(_ => _.Id, id); moq.SetupProperty(_ => _.Name, NAME); moq.SetupProperty(_ => _.IsActive, true); return moq.Object; }
public static IDbDataParameter Create() { var mockParam = new Mock<IDbDataParameter>(); mockParam.SetupProperty(param => param.ParameterName, null); mockParam.SetupProperty(param => param.Value, null); return mockParam.Object; }
PurchaseOrder SetupMock() { Mock<PurchaseOrder> poMoq = new Mock<PurchaseOrder>(); poMoq.SetupProperty(_ => _.Id, id); poMoq.SetupProperty(_ => _.Number, NUMBER); poMoq.SetupProperty(_ => _.Date, DATE); poMoq.SetupProperty(_ => _.IsActive, true); return poMoq.Object; }
public static void ReturnsJson(this Mock<Facebook.FacebookClient> facebookClient, string json, out Mock<HttpWebRequestWrapper> mockRequest, out Mock<HttpWebResponseWrapper> mockResponse) { mockRequest = new Mock<HttpWebRequestWrapper>(); mockResponse = new Mock<HttpWebResponseWrapper>(); var mockAsyncResult = new Mock<IAsyncResult>(); var request = mockRequest.Object; var response = mockResponse.Object; var asyncResult = mockAsyncResult.Object; mockRequest.SetupProperty(r => r.Method); mockRequest.SetupProperty(r => r.ContentType); mockRequest.SetupProperty(r => r.ContentLength); mockAsyncResult .Setup(ar => ar.AsyncWaitHandle) .Returns((ManualResetEvent)null); var responseStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)); mockRequest .Setup(r => r.GetResponse()) .Returns(response); AsyncCallback callback = null; mockRequest .Setup(r => r.BeginGetResponse(It.IsAny<AsyncCallback>(), It.IsAny<object>())) .Callback<AsyncCallback, object>((c, s) => { callback = c; }) .Returns(() => { callback(asyncResult); return asyncResult; }); mockRequest .Setup(r => r.EndGetResponse(It.IsAny<IAsyncResult>())) .Returns(response); mockResponse .Setup(r => r.GetResponseStream()) .Returns(responseStream); mockResponse .Setup(r => r.ContentLength) .Returns(responseStream.Length); var mockRequestCopy = mockRequest; facebookClient.Protected() .Setup<HttpWebRequestWrapper>("CreateHttpWebRequest", ItExpr.IsAny<Uri>()) .Callback<Uri>(uri => mockRequestCopy.Setup(r => r.RequestUri).Returns(uri)) .Returns(request); }
public Mock<IDonationCaseContract> MockDonationCase() { var caseName = Faker.Name.FullName(); var mock = new Mock<IDonationCaseContract>(); mock.SetupProperty(x => x.Name, caseName); mock.SetupProperty(x => x.StartDate, DateTime.Now.AddDays(-20)); mock.SetupProperty(x => x.DonationCaseStatus, DonationCaseStatus.Active); mock.SetupProperty(x => x.EndDate, DateTime.Now.AddDays(+20)); return mock; }
Heat SetupMock() { Mock<Heat> moq = new Mock<Heat>(); moq.SetupProperty(_ => _.Id, id); moq.SetupProperty(_ => _.IsActive, true); moq.SetupProperty(_ => _.Number, NUMBER); moq.SetupProperty(_ => _.SteelGrade, STEEL_GRADE); return moq.Object; }
/// <summary> /// Creates a mock <see cref="Window"/> that is particularly useful for passing into <see cref="MockWindowsCollection"/>'s ctor. /// </summary> /// <returns> /// A <see cref="Mock{Window}"/>that has all the properties needed for <see cref="DockableToolwindowPresenter"/> pre-setup. /// </returns> internal static Mock<Window> CreateWindowMock() { var window = new Mock<Window>(); window.SetupProperty(w => w.Visible, false); window.SetupGet(w => w.LinkedWindows).Returns((LinkedWindows) null); window.SetupProperty(w => w.Height); window.SetupProperty(w => w.Width); return window; }
public Mock<ICommitmentContract> MockCommitment(Guid donorId, Guid donationCaseId) { var mock = new Mock<ICommitmentContract>(); mock.SetupProperty(x => x.DonorId, donorId); mock.SetupProperty(x => x.StartDate, DateTime.Now.AddDays(-20)); mock.SetupProperty(x => x.DonationCaseId, donationCaseId); mock.SetupProperty(x => x.EndDate, DateTime.Now.AddDays(+20)); mock.SetupProperty(x => x.Amount, Faker.RandomNumber.Next(200,1000)); return mock; }
ReleaseNote SetupMock() { Mock<ReleaseNote> moq = new Mock<ReleaseNote>(); moq.SetupProperty(_ => _.Id, id); moq.SetupProperty(_ => _.Number, NUMBER); moq.SetupProperty(_ => _.IsActive, true); moq.SetupProperty(_ => _.Date, Date); moq.SetupProperty(_ => _.Shipped, true); return moq.Object; }
Plate SetupMock() { Mock<Plate> plate = new Mock<Plate>(); plate.SetupProperty(_ => _.Id, id); plate.SetupProperty(_ => _.IsActive, true); plate.SetupProperty(_ => _.Number, NUMBER); plate.SetupProperty(_ => _.Thickness, THICKNESS); plate.SetupProperty(_ => _.Heat, new Heat()); return plate.Object; }
protected override void EstablishContext() { base.EstablishContext(); CommonCategory = new Mock<AlarmCategoryAbstract>(); CommonCategory.Setup(c => c.Id).Returns(0); AlarmService.Add(CommonCategory.Object); Category = new Mock<AlarmCategoryAbstract>(); Category.SetupProperty(c => c.HasActive); Category.SetupProperty(c => c.HasUnacknowledged); Category.Setup(c => c.Id).Returns(1); AlarmService.Add(Category.Object); }
public void Initialize() { _output = new StringBuilder(); _outputStream = new MemoryStream(); Mock<HttpResponseBase> mockResponse = new Mock<HttpResponseBase>(); mockResponse.SetupProperty(response => response.StatusCode); mockResponse.SetupProperty(response => response.ContentType); mockResponse.Setup(response => response.Redirect(It.IsAny<string>())).Callback((string url) => _redirectUrl = url); mockResponse.Setup(response => response.Write(It.IsAny<string>())).Callback((string str) => _output.Append(str)); mockResponse.Setup(response => response.OutputStream).Returns(_outputStream); mockResponse.Setup(response => response.OutputStream).Returns(_outputStream); mockResponse.Setup(response => response.Output).Returns(new StringWriter(_output)); _response = mockResponse.Object; }
public void TestIfPrimaryCallTypesFieldsAreBeingFilled() { // Arrange EntityCollection<CS_PrimaryCallType_CallType> primaryCallTypeReference = new EntityCollection<CS_PrimaryCallType_CallType>(); primaryCallTypeReference.Add( new CS_PrimaryCallType_CallType() { ID = 1, PrimaryCallTypeID = 1, CallTypeID = 1, CS_CallType = new CS_CallType() { ID = 1, Description = "Call Type 1", Active = true } }); primaryCallTypeReference.Add( new CS_PrimaryCallType_CallType() { ID = 2, PrimaryCallTypeID = 1, CallTypeID = 2, CS_CallType = new CS_CallType() { ID = 2, Description = "Call Type 2", Active = true } }); CS_PrimaryCallType primaryCallTypeRepeaterDataItem = new CS_PrimaryCallType() { ID = 1, Type = "Primary Call Type", Active = true, CS_PrimaryCallType_CallType = primaryCallTypeReference }; Mock<ICallCriteriaInfoView> view = new Mock<ICallCriteriaInfoView>(); view.SetupProperty(m => m.PrimaryCallTypeRepeaterDataItem, primaryCallTypeRepeaterDataItem); view.SetupProperty(m => m.PrimaryCallTypeRepeaterRowDescription, string.Empty); view.SetupProperty(m => m.PrimaryCallTypeRepeaterRowCallTypeList, new List<CS_PrimaryCallType_CallType>()); // Act CallCriteriaInfoPresenter presenter = new CallCriteriaInfoPresenter(view.Object); presenter.FillPrimaryCallTypeRow(); // Assert Assert.AreEqual("Primary Call Type", view.Object.PrimaryCallTypeRepeaterRowDescription); Assert.AreEqual(2, view.Object.PrimaryCallTypeRepeaterRowCallTypeList.Count); }
public void Update_Resource_Fails_If_Readonly() { // Arrange var resource = new Mock<Resource>(); resource.SetupProperty(r => r.IsReadOnly, true); resource.SetupProperty(r => r.Name, "test"); var resourceRepository = new Mock<IResourceRepository>(); var resourceService = CreateResourceService(resourceRepository.Object); // Act resourceService.UpdateResource(resource.Object); // Asserted by exception attribute }
public void MustFillFirstAlertHeaderWithEntityObject() { //Arrange Mock<IFirstAlertView> mockView = new Mock<IFirstAlertView>(); Mock<FirstAlertModel> mockModel = new Mock<FirstAlertModel>(); System.Data.Objects.DataClasses.EntityCollection<CS_FirstAlertDivision> divisions = new System.Data.Objects.DataClasses.EntityCollection<CS_FirstAlertDivision>(); divisions.Add(new CS_FirstAlertDivision() { CS_Division = new CS_Division() {ID=1, Name="001"}}); divisions.Add(new CS_FirstAlertDivision() { CS_Division = new CS_Division() {ID=1, Name="002"}}); CS_FirstAlert firstAlertStub = new CS_FirstAlert() { ID=1, CS_Job = new CS_Job() { ID=1, Number = "1234"}, CS_Customer = new CS_Customer() {ID=2, Name = "Customer 1" }, CS_Employee_InCharge = new CS_Contact() { ID = 2, Name = "Peter", LastName = "Parker", Active = true}, CS_FirstAlertDivision = divisions, Date = new DateTime(2011, 7, 12, 5, 0, 0), CS_Country = new CS_Country() { ID = 1, Name = "USA" }, CS_State = new CS_State() { ID = 1, Name = "Florida" }, CS_City = new CS_City() { ID = 1, Name = "Miami" }, ReportedBy = "danilo", CS_Employee_CompletedBy = new CS_Employee() { ID = 1, FirstName = "Danilo", Name = "Ruziska" }, Details = "details", HasPoliceReport = true, PoliceAgency = "agency", PoliceReportNumber = "1234" } ; mockView.SetupProperty(e => e.FirstAlertID, 1); mockView.SetupProperty(e => e.FirstAlertEntity, null); mockModel.Setup(e => e.GetFirstAlertById(1)).Returns(firstAlertStub); FirstAlertPresenter presenter = new FirstAlertPresenter(mockView.Object, mockModel.Object); //Act presenter.FillFirstAlertHeaderFields(); //Assert Assert.AreEqual(firstAlertStub.CS_Job.Number, mockView.Object.FirstAlertEntity.CS_Job.Number); Assert.AreEqual(firstAlertStub.CS_Customer.ID, mockView.Object.FirstAlertEntity.CS_Customer.ID); Assert.AreEqual(firstAlertStub.CS_Employee_InCharge.ID, mockView.Object.FirstAlertEntity.CS_Employee_InCharge.ID); Assert.AreEqual(firstAlertStub.CS_FirstAlertDivision.Count, mockView.Object.FirstAlertEntity.CS_FirstAlertDivision.Count); Assert.AreEqual(firstAlertStub.Date, mockView.Object.FirstAlertEntity.Date); Assert.AreEqual(firstAlertStub.CS_Country.ID, mockView.Object.FirstAlertEntity.CS_Country.ID); Assert.AreEqual(firstAlertStub.CS_City.ID, mockView.Object.FirstAlertEntity.CS_City.ID); Assert.AreEqual(firstAlertStub.CS_State.ID, mockView.Object.FirstAlertEntity.CS_State.ID); Assert.AreEqual(firstAlertStub.ReportedBy, mockView.Object.FirstAlertEntity.ReportedBy); Assert.AreEqual(firstAlertStub.CS_Employee_CompletedBy.ID, mockView.Object.FirstAlertEntity.CS_Employee_CompletedBy.ID); Assert.AreEqual(firstAlertStub.ReportedBy, mockView.Object.FirstAlertEntity.ReportedBy); Assert.AreEqual(firstAlertStub.Details, mockView.Object.FirstAlertEntity.Details); Assert.AreEqual(firstAlertStub.HasPoliceReport, mockView.Object.FirstAlertEntity.HasPoliceReport); Assert.AreEqual(firstAlertStub.PoliceAgency, mockView.Object.FirstAlertEntity.PoliceAgency); Assert.AreEqual(firstAlertStub.PoliceReportNumber, mockView.Object.FirstAlertEntity.PoliceReportNumber); }
public Mock <HttpContextBase> CreateMockHttpContext() { var context = new Mock <HttpContextBase>(); var cookies = new HttpCookieCollection(); var identity = new System.Security.Principal.GenericIdentity("identity"); var principal = new System.Security.Principal.GenericPrincipal(identity, null); // Response var response = new Mock <HttpResponseBase>(); var cachePolicy = new Mock <HttpCachePolicyBase>(); response.SetupProperty(r => r.StatusCode, 200); response.Setup(r => r.Cache).Returns(cachePolicy.Object); response.Setup(r => r.ApplyAppPathModifier(It.IsAny <string>())).Returns <string>(r => r); response.Setup(r => r.Cookies).Returns(cookies); context.Setup(ctx => ctx.Response).Returns(response.Object); // Request var request = new Mock <HttpRequestBase>(); var visitorId = Guid.NewGuid().ToString(); request.Setup(r => r.Cookies).Returns(cookies); request.Setup(r => r.Url).Returns(new Uri("http://www.test.com")); request.Setup(r => r.Headers).Returns(new System.Collections.Specialized.NameValueCollection()); request.Setup(r => r.RequestContext).Returns(new System.Web.Routing.RequestContext(context.Object, new System.Web.Routing.RouteData())); request.SetupGet(x => x.PhysicalApplicationPath).Returns("/"); request.Setup(r => r.UserHostAddress).Returns("127.0.0.1"); request.Setup(r => r.UserAgent).Returns("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0"); request.SetupGet(r => r.QueryString).Returns(new System.Collections.Specialized.NameValueCollection()); request.SetupGet(r => r.Form).Returns(new System.Collections.Specialized.NameValueCollection()); request.SetupGet(r => r.PathInfo).Returns(string.Empty); request.SetupGet(r => r.AppRelativeCurrentExecutionFilePath).Returns("~/"); context.Setup(ctx => ctx.Request).Returns(request.Object); // Sessions var session = new Mock <HttpSessionStateBase>(); context.Setup(ctx => ctx.Session).Returns(session.Object); // Server var server = new Mock <HttpServerUtilityBase>(); server.Setup(s => s.MapPath(It.IsAny <string>())).Returns <string>(r => { if (r.Equals("/bin", StringComparison.InvariantCultureIgnoreCase)) { r = string.Empty; } var path = this.GetType().Assembly.Location; var fileName = System.IO.Path.GetFileName(path); path = path.Replace(fileName, string.Empty); r = r.Trim('/').Trim('\\'); path = System.IO.Path.Combine(path, r); return(path); }); context.Setup(ctx => ctx.Server).Returns(server.Object); // Principal context.Setup(ctx => ctx.User).Returns(principal); // Items context.Setup(ctx => ctx.Items).Returns(new Dictionary <string, object>()); return(context); }
private void SetupValidVbProject() { var project = new Mock <IVBProject>().SetupProperty(p => p.HelpFile, DummyRepoId); _vbe.SetupProperty(vbe => vbe.ActiveVBProject, project.Object); }
public void MergeViewSourceBranchesAreSetBeforeShowing() { //arrange _mergeView.SetupProperty(m => m.SourceSelectorData); _view.SetupProperty(v => v.Local, new List <string>() { "master", "dev" }); //act _view.Raise(v => v.Merge += null, new EventArgs()); //assert CollectionAssert.AreEqual(_view.Object.Local.ToList(), _mergeView.Object.SourceSelectorData.ToList()); }
public void CreateBranch_AndBranchExists() { //arrange var branchName = "master"; var branches = new List <string>() { branchName }; _view.SetupProperty(v => v.Local, branches); _createView.SetupProperty(c => c.UserInputText, branchName); _createView.SetupProperty(c => c.IsValidBranchName); //act _createView.Raise(c => c.UserInputTextChanged += null, new EventArgs()); //Assert Assert.IsFalse(_createView.Object.IsValidBranchName); }
protected override void GivenDestinationSpaceWithoutCommandFactory() { _mockSpace.SetupProperty(s => s.CommandFactory, null); }
public void AutoNextSong_SongIsCaching_SwapSongs() { var eventWait = new ManualResetEvent(false); // We need this, because Library.PlaySong() pops up a new thread interally and then returns var jumpAudioPlayer = new JumpAudioPlayer(); var jumpSong = new Mock <Song>("JumpSong", AudioType.Mp3, TimeSpan.Zero); jumpSong.Setup(p => p.CreateAudioPlayer()).Returns(jumpAudioPlayer); jumpSong.SetupGet(p => p.HasToCache).Returns(false); var foreverAudioPlayer = new Mock <AudioPlayer>(); foreverAudioPlayer.SetupProperty(p => p.Volume); foreverAudioPlayer.Setup(p => p.Play()).Callback(() => { }); // Never raises SongFinished var cachingSong = new Mock <Song>("CachingSong", AudioType.Mp3, TimeSpan.Zero); cachingSong.SetupGet(p => p.HasToCache).Returns(true); cachingSong.Setup(p => p.CreateAudioPlayer()).Returns(foreverAudioPlayer.Object); var cachingSong2 = new Mock <Song>("CachingSong2", AudioType.Mp3, TimeSpan.Zero); cachingSong2.SetupGet(p => p.HasToCache).Returns(true); var nextSong = new Mock <Song>("NextSong", AudioType.Mp3, TimeSpan.Zero); nextSong.Setup(p => p.CreateAudioPlayer()).Returns(jumpAudioPlayer); nextSong.SetupGet(p => p.HasToCache).Returns(false); using (var library = new Library.Library()) { int finished = 0; // We need to wait till the second played song has finished and then release our lock, // otherwise it would directly call the assertion, without anything changed library.SongFinished += (sender, e) => { finished++; if (finished == 2) { eventWait.Set(); } }; IEnumerable <Song> songs = new[] { jumpSong.Object, cachingSong.Object, cachingSong2.Object, nextSong.Object }; library.AddSongsToPlaylist(songs); library.PlaySong(0); eventWait.WaitOne(); IEnumerable <Song> expectedSongs = new[] { jumpSong.Object, nextSong.Object, cachingSong.Object, cachingSong2.Object }; Assert.IsTrue(expectedSongs.SequenceEqual(library.Playlist)); } }
public void DueSpawnStepLoopABCD() { // order of rooms /* A=>B * v v * C=>D */ Mock <IViewPlaceableRoomTestContext> mockMap = new Mock <IViewPlaceableRoomTestContext>(MockBehavior.Strict); Mock <FloorPlan> mockFloor = new Mock <FloorPlan>(MockBehavior.Strict); mockFloor.SetupGet(p => p.RoomCount).Returns(4); Mock <TestFloorPlanGen> startRoom = new Mock <TestFloorPlanGen>(MockBehavior.Strict); startRoom.SetupProperty(p => p.Draw); startRoom.SetupGet(p => p.Draw).Returns(new Rect(2, 2, 4, 4)); startRoom.Object.Identifier = 'A'; mockFloor.Setup(p => p.GetRoom(0)).Returns(startRoom.Object); mockFloor.Setup(p => p.GetRoom(1)).Returns(new TestFloorPlanGen('B')); mockFloor.Setup(p => p.GetRoom(2)).Returns(new TestFloorPlanGen('C')); mockFloor.Setup(p => p.GetRoom(3)).Returns(new TestFloorPlanGen('D')); mockMap.SetupGet(p => p.RoomPlan).Returns(mockFloor.Object); List <int> adjacents = new List <int> { 1, 2 }; mockFloor.Setup(p => p.GetAdjacentRooms(0)).Returns(adjacents); adjacents = new List <int> { 0, 3 }; mockFloor.Setup(p => p.GetAdjacentRooms(1)).Returns(adjacents); adjacents = new List <int> { 0, 3 }; mockFloor.Setup(p => p.GetAdjacentRooms(2)).Returns(adjacents); adjacents = new List <int> { 2, 1 }; mockFloor.Setup(p => p.GetAdjacentRooms(3)).Returns(adjacents); mockMap.SetupGet(p => p.RoomPlan).Returns(mockFloor.Object); mockMap.Setup(p => p.GetLoc(0)).Returns(new Loc(3, 3)); Mock <List <SpawnableChar> > mockSpawns = new Mock <List <SpawnableChar> >(MockBehavior.Strict); var roomSpawner = new Mock <DueSpawnStep <IViewPlaceableRoomTestContext, SpawnableChar, TestEntryPoint> >(null, 100) { CallBase = true }; const int maxVal = 3; const int rooms = 4; var compare = new SpawnList <RoomHallIndex> { { new RoomHallIndex(0, false), int.MaxValue / maxVal / rooms * 1 }, { new RoomHallIndex(1, false), int.MaxValue / maxVal / rooms * 2 }, { new RoomHallIndex(2, false), int.MaxValue / maxVal / rooms * 2 }, { new RoomHallIndex(3, false), int.MaxValue / maxVal / rooms * 3 }, }; roomSpawner.Setup(p => p.SpawnRandInCandRooms(mockMap.Object, It.IsAny <SpawnList <RoomHallIndex> >(), mockSpawns.Object, 100)); roomSpawner.Object.DistributeSpawns(mockMap.Object, mockSpawns.Object); roomSpawner.Verify(p => p.SpawnRandInCandRooms(mockMap.Object, It.Is <SpawnList <RoomHallIndex> >(s => s.Equals(compare)), mockSpawns.Object, 100), Times.Exactly(1)); }
private static Mock <IContext> CreateContext(string url, int currentUserClientId) { var uri = new Uri(url); var mock = new Mock <IContext>(); mock.Setup(x => x.Url).Returns(uri); mock.Setup(x => x.VirtualToAbsolute(It.IsAny <string>())).Returns <string>(x => { return(x.Replace("~", uri.AbsolutePath)); }); mock.Setup(x => x.VirtualToUri(It.IsAny <string>())).Returns <string>(x => { var baseUri = new Uri(mock.Object.Url.GetLeftPart(UriPartial.Authority)); var result = new Uri(baseUri, mock.Object.VirtualToAbsolute(x)); return(result); }); IPrincipal user = null; IProvider provider = Container.GetInstance <IProvider>(); ISession session = provider.DataAccess.Session; if (currentUserClientId > 0) { var client = session.Single <Client>(currentUserClientId); if (client != null) { var ident = new GenericIdentity(client.UserName); user = new GenericPrincipal(ident, client.Roles()); } } mock.SetupProperty(x => x.User, user); mock.Setup(x => x.CurrentUser).Returns(() => { var username = mock.Object.User.Identity.Name; var c = session.Query <ClientInfo>().First(x => x.UserName == username); return(new Models.Client() { ClientID = c.ClientID, LName = c.LName, FName = c.FName, Email = c.Email, Phone = c.Phone }); }); mock.Setup(x => x.GetSessionValue(It.IsAny <string>())).Returns <string>(x => { return(_session.ContainsKey(x) ? _session[x] : null); }); mock.Setup(x => x.SetSessionValue(It.IsAny <string>(), It.IsAny <object>())).Callback <string, object>((k, v) => { if (_session.ContainsKey(k)) { _session[k] = v; } else { _session.Add(k, v); } }); mock.Setup(x => x.RemoveSessionValue(It.IsAny <string>())).Callback <string>(k => { if (_session.ContainsKey(k)) { _session.Remove(k); } }); var baseDir = AppDomain.CurrentDomain.BaseDirectory; mock.Setup(x => x.MapPath(It.IsAny <string>())).Returns <string>(x => { return(Path.Combine(baseDir, x.Replace(".", string.Empty))); }); return(mock); }
private void InitResult(bool success) { _result.SetupProperty(p => p.ApplicationId, 1); _result.SetupProperty(p => p.Success, success); }
public async Task SetUpAsync() { Container = new ServiceCollection(); var testMap = await SquareMapFactory.CreateAsync(10).ConfigureAwait(false); var sectorMock = new Mock <ISector>(); sectorMock.SetupGet(x => x.Map).Returns(testMap); var sector = sectorMock.Object; var sectorNodeMock = new Mock <ISectorNode>(); sectorNodeMock.SetupGet(x => x.Sector).Returns(sector); var sectorNode = sectorNodeMock.Object; var playerMock = new Mock <IPlayer>(); playerMock.SetupGet(x => x.SectorNode).Returns(sectorNode); var player = playerMock.Object; Container.AddSingleton(player); var simpleAct = CreateSimpleAct(); var cooldownAct = CreateActWithCooldown(); var cooldownResolvedAct = CreateActWithResolvedCooldown(); var combatActModuleMock = new Mock <ICombatActModule>(); combatActModuleMock.Setup(x => x.CalcCombatActs()) .Returns(new[] { simpleAct, cooldownAct, cooldownResolvedAct }); var combatActModule = combatActModuleMock.Object; var equipmentCarrierMock = new Mock <IEquipmentModule>(); equipmentCarrierMock.SetupGet(x => x.Slots).Returns(new[] { new PersonSlotSubScheme { Types = EquipmentSlotTypes.Hand } }); var equipmentCarrier = equipmentCarrierMock.Object; var personMock = new Mock <IPerson>(); personMock.Setup(x => x.GetModule <ICombatActModule>(It.IsAny <string>())).Returns(combatActModule); personMock.Setup(x => x.GetModule <IEquipmentModule>(It.IsAny <string>())).Returns(equipmentCarrier); personMock.SetupGet(x => x.PhysicalSize).Returns(PhysicalSizePattern.Size1); var person = personMock.Object; var actorMock = new Mock <IActor>(); var actorNode = testMap.Nodes.SelectByHexCoords(0, 0); actorMock.SetupGet(x => x.Node).Returns(actorNode); actorMock.SetupGet(x => x.Person).Returns(person); var actor = actorMock.Object; var actorVmMock = new Mock <IActorViewModel>(); actorVmMock.SetupProperty(x => x.Actor, actor); var actorVm = actorVmMock.Object; var humanTaskSourceMock = new Mock <IHumanActorTaskSource <ISectorTaskSourceContext> >(); var humanTaskSource = humanTaskSourceMock.Object; var playerStateMock = new Mock <ISectorUiState>(); playerStateMock.SetupProperty(x => x.ActiveActor, actorVm); playerStateMock.SetupGet(x => x.TaskSource).Returns(humanTaskSource); playerStateMock.SetupProperty(x => x.TacticalAct, simpleAct); var playerState = playerStateMock.Object; sectorMock.SetupGet(x => x.ActorManager) .Returns(() => ServiceProvider.GetRequiredService <IActorManager>()); var usageServiceMock = new Mock <ITacticalActUsageService>(); var usageService = usageServiceMock.Object; Container.AddSingleton(factory => humanTaskSourceMock); Container.AddSingleton(factory => playerState); Container.AddSingleton(factory => usageService); RegisterSpecificServices(testMap, playerStateMock); ServiceProvider = Container.BuildServiceProvider(); }
public void CanRead() { // Array generated by DFU File Manager v3.0.6 var sample = new byte[] { 0x44, 0x66, 0x75, 0x53, 0x65, 0x01, 0x29, 0x01, 0x00, 0x00, 0x01, 0x54, 0x61, 0x72, 0x67, 0x65, 0x74, 0x02, 0x01, 0x00, 0x00, 0x00, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x51, 0x0C, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x04, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x78, 0x56, 0x34, 0x12, 0x83, 0x04, 0x1A, 0x01, 0x55, 0x46, 0x44, 0x10, 0xB7, 0x02, 0xE0, 0x8D }; var dfuSuffixMock = new Mock <IDfuSuffix>(); dfuSuffixMock.SetupProperty(x => x.Device); dfuSuffixMock.SetupProperty(x => x.Product); dfuSuffixMock.SetupProperty(x => x.Vendor); dfuSuffixMock.SetupProperty(x => x.Dfu); dfuSuffixMock.SetupProperty(x => x.Length); dfuSuffixMock.SetupProperty(x => x.DfuSignature); var tempStream = new MemoryStream(sample, false); tempStream.Seek(sample.Length - 16, SeekOrigin.Begin); var sut = new DfuSuffixDeserializer( (m, p) => new DeserializerException(m, p), () => dfuSuffixMock.Object); var dfuSuffix = sut.Read(tempStream); Assert.That(dfuSuffix.Device, Is.EqualTo(0x5678)); Assert.That(dfuSuffix.Product, Is.EqualTo(0x1234)); Assert.That(dfuSuffix.Vendor, Is.EqualTo(0x0483)); Assert.That(dfuSuffix.Dfu, Is.EqualTo(0x011a)); Assert.That(dfuSuffix.DfuSignature, Is.EqualTo("UFD")); Assert.That(dfuSuffix.Length, Is.EqualTo(16)); }
private AuthorizationContext GetAuthorizationContext(Action <ServiceCollection> registerServices, bool anonymous = false) { var basicPrincipal = new ClaimsPrincipal( new ClaimsIdentity( new Claim[] { new Claim("Permission", "CanViewPage"), new Claim(ClaimTypes.Role, "Administrator"), new Claim(ClaimTypes.Role, "User"), new Claim(ClaimTypes.NameIdentifier, "John") }, "Basic")); var validUser = basicPrincipal; var bearerIdentity = new ClaimsIdentity( new Claim[] { new Claim("Permission", "CupBearer"), new Claim(ClaimTypes.Role, "Token"), new Claim(ClaimTypes.NameIdentifier, "John Bear") }, "Bearer"); var bearerPrincipal = new ClaimsPrincipal(bearerIdentity); validUser.AddIdentity(bearerIdentity); // ServiceProvider var serviceCollection = new ServiceCollection(); if (registerServices != null) { registerServices(serviceCollection); } var serviceProvider = serviceCollection.BuildServiceProvider(); // HttpContext var httpContext = new Mock <HttpContext>(); var auth = new Mock <AuthenticationManager>(); httpContext.Setup(o => o.Authentication).Returns(auth.Object); httpContext.SetupProperty(c => c.User); if (!anonymous) { httpContext.Object.User = validUser; } httpContext.SetupGet(c => c.RequestServices).Returns(serviceProvider); auth.Setup(c => c.AuthenticateAsync("Bearer")).ReturnsAsync(bearerPrincipal); auth.Setup(c => c.AuthenticateAsync("Basic")).ReturnsAsync(basicPrincipal); auth.Setup(c => c.AuthenticateAsync("Fails")).ReturnsAsync(null); // AuthorizationContext var actionContext = new ActionContext( httpContext: httpContext.Object, routeData: new RouteData(), actionDescriptor: null ); var authorizationContext = new AuthorizationContext( actionContext, Enumerable.Empty <IFilterMetadata>().ToList() ); return(authorizationContext); }
public void ConnectControlViewModel_UpdateRepositoryOnServerSaved() { var serverGuid = Guid.NewGuid(); var uri = new Uri("http://bravo.com/"); var serverDisplayName = "johnnyBravoServer"; var mockShellViewModel = new Mock <IShellViewModel>(); var mockExplorerRepository = new Mock <IExplorerRepository>(); var mockEnvironmentConnection = new Mock <IEnvironmentConnection>(); mockEnvironmentConnection.Setup(a => a.AppServerUri).Returns(uri); mockEnvironmentConnection.Setup(a => a.UserName).Returns("johnny"); mockEnvironmentConnection.Setup(a => a.Password).Returns("bravo"); mockEnvironmentConnection.Setup(a => a.WebServerUri).Returns(uri); mockEnvironmentConnection.Setup(a => a.ID).Returns(serverGuid); mockEnvironmentConnection.Setup(a => a.IsConnected).Returns(false); mockEnvironmentConnection.SetupProperty(a => a.DisplayName); mockEnvironmentConnection.Object.DisplayName = serverDisplayName; mockExplorerRepository.Setup( repository => repository.CreateFolder(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Guid>())); mockExplorerRepository.Setup( repository => repository.Rename(It.IsAny <IExplorerItemViewModel>(), It.IsAny <string>())).Returns(true); var server = new ServerForTesting(mockExplorerRepository); server.EnvironmentID = serverGuid; server.ResourceName = "mr_J_bravo"; server.Connection = mockEnvironmentConnection.Object; mockShellViewModel.Setup(a => a.ActiveServer).Returns(server); mockShellViewModel.Setup(model => model.LocalhostServer).Returns(server); CustomContainer.Register <IServer>(server); CustomContainer.Register(mockShellViewModel.Object); var environmentModel = new Mock <IServer>(); environmentModel.SetupGet(a => a.Connection).Returns(mockEnvironmentConnection.Object); environmentModel.SetupGet(a => a.IsConnected).Returns(true); var e1 = new Server(serverGuid, mockEnvironmentConnection.Object); var repo = new TestServerRespository(environmentModel.Object, e1) { ActiveServer = e1 }; var environmentRepository = new ServerRepository(repo); Assert.IsNotNull(environmentRepository); var passed = false; mockShellViewModel.Setup(a => a.OpenResource(It.IsAny <Guid>(), It.IsAny <Guid>(), It.IsAny <IServer>())) .Callback((Guid id1, Guid id2, IServer a) => { passed = a.EnvironmentID == serverGuid; }); //------------Setup for test-------------------------- var connectControlViewModel = new ConnectControlViewModel(server, new EventAggregator()); var privateObject = new Testing.PrivateObject(connectControlViewModel); privateObject.SetProperty("IsConnecting", false); privateObject.Invoke("UpdateRepositoryOnServerSaved", serverGuid, false); //------------Execute Test--------------------------- //------------Assert Results------------------------- Assert.AreEqual("johnnyBravoServer", mockEnvironmentConnection.Object.DisplayName); }
public void InitRepository_WhenUserConfirms_RepoIsAddedToConfig() { //arrange _configService.Setup(c => c.LoadConfiguration()) .Returns(GetDummyConfig()); _folderBrowser.Setup(b => b.ShowDialog()).Returns(DialogResult.OK); _folderBrowser.SetupProperty(b => b.SelectedPath, @"C:\path\to\repo\"); SetupVM(); //act _vm.InitRepoCommand.Execute(null); //assert _configService.Verify(c => c.SaveConfiguration(It.IsAny <SourceControlConfiguration>()), Times.Once); }
public async Task TestOpenCoverNullFlatDevice() { _mockFlatDeviceChooserVM.SetupProperty(m => m.SelectedDevice, null); _sut.FlatDeviceChooserVM = _mockFlatDeviceChooserVM.Object; Assert.That(await _sut.OpenCover(), Is.False); }
private void SetupValidVbProject() { var project = new Mock <VBProject>().SetupProperty(p => p.Name, DummyRepoName); _vbe.SetupProperty(vbe => vbe.ActiveVBProject, project.Object); }
private AuthorizationFilterContext GetAuthorizationContext( bool anonymous = false, Action <IServiceCollection> registerServices = null) { var basicPrincipal = new ClaimsPrincipal( new ClaimsIdentity( new Claim[] { new Claim("Permission", "CanViewPage"), new Claim(ClaimTypes.Role, "Administrator"), new Claim(ClaimTypes.Role, "User"), new Claim(ClaimTypes.NameIdentifier, "John") }, "Basic")); var validUser = basicPrincipal; var bearerIdentity = new ClaimsIdentity( new Claim[] { new Claim("Permission", "CupBearer"), new Claim(ClaimTypes.Role, "Token"), new Claim(ClaimTypes.NameIdentifier, "John Bear") }, "Bearer"); var bearerPrincipal = new ClaimsPrincipal(bearerIdentity); validUser.AddIdentity(bearerIdentity); // ServiceProvider var serviceCollection = new ServiceCollection(); var auth = new Mock <IAuthenticationService>(); serviceCollection.AddOptions(); serviceCollection.AddLogging(); serviceCollection.AddSingleton(auth.Object); serviceCollection.AddAuthorization(); serviceCollection.AddAuthorizationPolicyEvaluator(); registerServices?.Invoke(serviceCollection); var serviceProvider = serviceCollection.BuildServiceProvider(); // HttpContext var httpContext = new Mock <HttpContext>(); auth.Setup(c => c.AuthenticateAsync(httpContext.Object, "Bearer")).ReturnsAsync(AuthenticateResult.Success(new AuthenticationTicket(bearerPrincipal, "Bearer"))); auth.Setup(c => c.AuthenticateAsync(httpContext.Object, "Basic")).ReturnsAsync(AuthenticateResult.Success(new AuthenticationTicket(basicPrincipal, "Basic"))); auth.Setup(c => c.AuthenticateAsync(httpContext.Object, "Fails")).ReturnsAsync(AuthenticateResult.Fail("Fails")); httpContext.SetupProperty(c => c.User); if (!anonymous) { httpContext.Object.User = validUser; } httpContext.SetupGet(c => c.RequestServices).Returns(serviceProvider); var contextItems = new Dictionary <object, object>(); httpContext.SetupGet(c => c.Items).Returns(contextItems); httpContext.SetupGet(c => c.Features).Returns(Mock.Of <IFeatureCollection>()); // AuthorizationFilterContext var actionContext = new ActionContext( httpContext: httpContext.Object, routeData: new RouteData(), actionDescriptor: new ActionDescriptor()); var authorizationContext = new AuthorizationFilterContext( actionContext, Enumerable.Empty <IFilterMetadata>().ToList() ); return(authorizationContext); }
public void Wamp_CanCallCommand() { // Local variable where the registered procedures are stored var procedures = new Dictionary <string, IWampRpcOperation>(); var rpcOperationClientCallback = new MockRawRpcOperationClientCallback(); var rpcOperationRouterCallbackMock = new MockRpcOperationRouterCallback(rpcOperationClientCallback); // Setup empty IAsyncDisposable var emptyAsyncDisposableMock = new Mock <IAsyncDisposable>(); emptyAsyncDisposableMock.Setup(it => it.DisposeAsync()).Returns(() => Task.CompletedTask); var emptyAsyncDisposable = emptyAsyncDisposableMock.Object; // Setup operation catalog var operationCatalogMock = new Mock <IWampRpcOperationCatalogProxy>(); operationCatalogMock .Setup(it => it.Register(It.IsAny <IWampRpcOperation>(), It.IsAny <RegisterOptions>())) .Callback <IWampRpcOperation, RegisterOptions>((oper, option) => procedures.Add(oper.Procedure, oper)) .Returns(() => Task.FromResult(emptyAsyncDisposable)); operationCatalogMock .Setup(it => it.Invoke(It.IsAny <IWampRawRpcOperationClientCallback>(), It.IsAny <CallOptions>(), It.IsAny <string>(), It.IsAny <object[]>())) .Callback <IWampRawRpcOperationClientCallback, CallOptions, string, object[]>((caller, options, procedure, arguments) => { var rpcOperation = procedures[procedure]; rpcOperation.Invoke(rpcOperationRouterCallbackMock, new WampSharp.Newtonsoft.JsonFormatter(), null, arguments.Cast <JToken>().ToArray()); }) .Returns(() => (IWampCancellableInvocationProxy)null); var operationCatalog = operationCatalogMock.Object; // Mock the Realm proxy var realmProxyMock = new Mock <IWampRealmProxy>(); realmProxyMock.Setup(it => it.RpcCatalog).Returns(operationCatalog); var realmProxy = realmProxyMock.Object; // Mock an IWampChannel var channelMock = new Mock <IWampChannel>(); channelMock.Setup(it => it.RealmProxy).Returns(realmProxy); var channel = channelMock.Object; var channelObservable = Observable.Never <IWampChannel>().StartWith(channel); // Create the metadata collection var metadataCollection = new MetadataCollection(new[] { typeof(ITestService) }, "bla", 1, 5); // Create a service instance var service = new TestService(); // Mock the logger var logger = new MockLogger <WampService>(); // Mock the ServiceContextAccessor var serviceContextAccessorMock = new Mock <IServiceContextAccessor>(); serviceContextAccessorMock.SetupProperty(it => it.ServiceContext); var serviceContextAccessor = serviceContextAccessorMock.Object; // Create a mock Dependency Injector var serviceProviderMock = new Mock <IServiceProvider>(); serviceProviderMock.Setup(it => it.GetService(It.Is <Type>(tp => tp == typeof(IServiceContextAccessor)))).Returns(serviceContextAccessor); serviceProviderMock.Setup(it => it.GetService(It.Is <Type>(tp => tp == typeof(ITestService)))).Returns(service); var serviceProvider = serviceProviderMock.Object; // Mock the Service scope var serviceScopeMock = new Mock <IServiceScope>(); serviceScopeMock.SetupGet(it => it.ServiceProvider).Returns(serviceProvider); var serviceScope = serviceScopeMock.Object; // Mock the Service scope factory var serviceScopeFactoryMock = new Mock <IServiceScopeFactory>(); serviceScopeFactoryMock.Setup(it => it.CreateScope()).Returns(() => serviceScope); var serviceScopeFactory = serviceScopeFactoryMock.Object; // Register Service scope factory at the Dependency Injector serviceProviderMock.Setup(it => it.GetService(It.Is <Type>(tp => tp == typeof(IWampOperation)))).Returns(() => new WampOperation(new MockLogger <WampOperation>(), serviceContextAccessor, serviceScopeFactory) ); // Create an instance of WampService -> internal but visible to us using the InternalsVisibleTo-attribute in AssemblyInfo.cs. var wampService = new WampService(metadataCollection, logger, channelObservable); // Configure the WampService wampService.Configure(serviceProvider); wampService.Run(); // Add three persons operationCatalog.Invoke(rpcOperationClientCallback, new CallOptions(), "bla.v1.testservice.addperson", new object[] { JToken.Parse("{ Name: 'Piet', Gender: 0, Age: 33 }") }); operationCatalog.Invoke(rpcOperationClientCallback, new CallOptions(), "bla.v1.testservice.addperson", new object[] { JToken.Parse("{ Name: 'Jannie', Gender: 1, Age: 13 }") }); operationCatalog.Invoke(rpcOperationClientCallback, new CallOptions(), "bla.v1.testservice.addperson", new object[] { JToken.Parse("{ Name: 'Jan', Gender: 0, Age: 35 }") }); // Find all persons that start with "ja" operationCatalog.Invoke(rpcOperationClientCallback, new CallOptions(), "bla.v1.testservice.findpersons", new object[] { (JValue)"ja" }); var values = rpcOperationClientCallback.Message as JArray; // Should have a result Assert.NotNull(values); // Should be an array having two records Assert.Equal(2, values.Count); // Of which each records' "Name" starts with "ja" Assert.All(values, v => Assert.StartsWith("ja", v["name"].Value <string>(), StringComparison.InvariantCultureIgnoreCase)); //wampService.Dispose(); }
public void SearchFollowersNoUserFoundTest() { var appSettingsClass = new AppSettings() { Secret = "1xNQ0brDZ6TwznGi9p58WRI2gfLJXcvq" }; IOptions <AppSettings> appSettings = Options.Create(appSettingsClass); var data = new List <UserModel> { new UserModel() { Id = 1, Token = "aa", Username = "******", Password = "******", Email = "@gmail" }.HashPassword(), new UserModel() { Id = 2, Token = "aaa", Username = "******", Password = "******", Email = "[email protected]" }.HashPassword() }.AsQueryable(); var mockSet = new Mock <DbSet <UserModel> >(); mockSet.As <IQueryable <UserModel> >().Setup(m => m.Provider).Returns(data.Provider); mockSet.As <IQueryable <UserModel> >().Setup(m => m.Expression).Returns(data.Expression); mockSet.As <IQueryable <UserModel> >().Setup(m => m.ElementType).Returns(data.ElementType); mockSet.As <IQueryable <UserModel> >().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); var followerData = new List <FollowerModel> { new FollowerModel() { FollowedId = 2, FollowerId = 1, Id = 1 } }.AsQueryable(); var followerMockSet = new Mock <DbSet <FollowerModel> >(); followerMockSet.As <IQueryable <FollowerModel> >().Setup(m => m.Provider).Returns(followerData.Provider); followerMockSet.As <IQueryable <FollowerModel> >().Setup(m => m.Expression).Returns(followerData.Expression); followerMockSet.As <IQueryable <FollowerModel> >().Setup(m => m.ElementType).Returns(followerData.ElementType); followerMockSet.As <IQueryable <FollowerModel> >().Setup(m => m.GetEnumerator()).Returns(followerData.GetEnumerator()); var options = new DbContextOptionsBuilder <MyDbContext>() .Options; var mockContext = new Mock <MyDbContext>(options); mockContext.Setup(x => x.Users).Returns(mockSet.Object); mockContext.Setup(x => x.Followers).Returns(followerMockSet.Object); mockContext.SetupProperty(x => x.Trips); mockContext.SetupProperty(x => x.PinPoints); var userService = new UserService(appSettings, mockContext.Object); var service = new AccountController(mockContext.Object, userService); var result = service.SearchFollowers("BB"); Assert.AreEqual(result.Result.Value, null); }
public void LoadOperationArgumentsTest() { var program = new Program(); program._dieException = (Program caller, Exception e, string path, int line, string name) => Assert.False(true, $"Error: {e.ToString()}"); program._dieMessage = (Program caller, string m, string path, int line, string name) => Assert.False(true, $"Error: {m}"); program._exit = (Program caller, int e, string m, string path, int line, string name) => Assert.False(true, $"Error: {e} {m}"); var configs = new Dictionary <Git.ConfigurationLevel, Dictionary <string, string> > { { Git.ConfigurationLevel.Local, new Dictionary <string, string>(StringComparer.Ordinal) { { "credential.validate", "true" }, { "credential.useHttpPath", "true" }, { "credential.not-match.com.useHttpPath", "false" }, } }, { Git.ConfigurationLevel.Global, new Dictionary <string, string>(StringComparer.Ordinal) { { "credential.validate", "false" }, } }, { Git.ConfigurationLevel.Xdg, new Dictionary <string, string>(StringComparer.Ordinal) { } }, { Git.ConfigurationLevel.System, new Dictionary <string, string>(StringComparer.Ordinal) { } }, { Git.ConfigurationLevel.Portable, new Dictionary <string, string>(StringComparer.Ordinal) { } }, }; var envvars = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase) { { "HOME", Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) }, }; var gitconfig = new Git.Configuration.Impl(configs); var targetUri = new Authentication.TargetUri("https://example.visualstudio.com/"); var opargsMock = new Mock <OperationArguments>(MockBehavior.Strict); opargsMock.Setup(r => r.EnvironmentVariables) .Returns(envvars); opargsMock.Setup(r => r.GitConfiguration) .Returns(gitconfig); opargsMock.Setup(r => r.LoadConfiguration()); opargsMock.Setup(r => r.TargetUri) .Returns(targetUri); opargsMock.Setup(r => r.QueryUri) .Returns(targetUri); opargsMock.SetupProperty(r => r.UseHttpPath); opargsMock.SetupProperty(r => r.ValidateCredentials); var opargs = opargsMock.Object; program.LoadOperationArguments(opargs); Assert.NotNull(opargs); Assert.True(opargs.ValidateCredentials, "credential.validate"); Assert.True(opargs.UseHttpPath, "credential.useHttpPath"); }
public void SelectedBranchShouldBeCurrentBranchAfterRefresh() { //arrange _view.SetupProperty(v => v.Current); //act _presenter.RefreshView(); //assert Assert.AreEqual(_provider.Object.CurrentBranch.Name, _view.Object.Current); }
public void Linq3_MoCK_Given10000_DeepEqualTrue() { // Arrange Mock <IDataSource> mockData = new Mock <IDataSource>(); mockData.SetupProperty(x => x.Customers, new List <Customer>() { new Customer() { CustomerID = "ALFKI", CompanyName = "Alfreds Futterkiste", Address = "Obere Str. 57", City = "Berlin", Region = null, PostalCode = "12209", Country = "Germany", Phone = "030-0074321", Fax = "030-0076545", Orders = new Order[] { new Order() { OrderID = 10643, OrderDate = new DateTime(1997, 08, 25, 00, 00, 00), Total = 8800 }, new Order() { OrderID = 10643, OrderDate = new DateTime(1997, 08, 25, 00, 00, 00), Total = 800 } } }, new Customer() { CustomerID = "hhhhh", CompanyName = "Alfreds Futterkiste", Address = "Obere Str. 57", City = "Berlin", Region = null, PostalCode = "12209", Country = "Germany", Phone = "030-0074321", Fax = "030-0076545", Orders = new Order[] { new Order() { OrderID = 10643, OrderDate = new DateTime(1997, 08, 25, 00, 00, 00), Total = 100 }, new Order() { OrderID = 10643, OrderDate = new DateTime(1997, 08, 25, 00, 00, 00), Total = 200 } } } }); var linqSamples = new LinqSamples(mockData.Object, null); int count = 8700; IEnumerable <Customer> expected = new List <Customer>() { new Customer() { CustomerID = "ALFKI", CompanyName = "Alfreds Futterkiste", Address = "Obere Str. 57", City = "Berlin", Region = null, PostalCode = "12209", Country = "Germany", Phone = "030-0074321", Fax = "030-0076545", Orders = new Order[] { new Order() { OrderID = 10643, OrderDate = new DateTime(1997, 08, 25, 00, 00, 00), Total = 8800 }, new Order() { OrderID = 10643, OrderDate = new DateTime(1997, 08, 25, 00, 00, 00), Total = 800 } } } }; // Act var actual = linqSamples.Linq3(count); // Assert Assert.IsTrue(actual.IsDeepEqual(expected)); }
public Mock <T> SetupProperty <TProperty>(Expression <Func <T, TProperty> > property, TProperty initialValue) => _mock.SetupProperty(property, initialValue);
public static void FiddlerNoInternetConnection(this Mock <Facebook.FacebookClient> facebookClient, out Mock <HttpWebRequestWrapper> mockRequest, out Mock <HttpWebResponseWrapper> mockResponse, out Mock <WebExceptionWrapper> mockWebException) { mockRequest = new Mock <HttpWebRequestWrapper>(); mockResponse = new Mock <HttpWebResponseWrapper>(); mockWebException = new Mock <WebExceptionWrapper>(); var mockAsyncResult = new Mock <IAsyncResult>(); var request = mockRequest.Object; var response = mockResponse.Object; var webException = mockWebException.Object; var asyncResult = mockAsyncResult.Object; mockRequest.SetupProperty(r => r.Method); mockRequest.SetupProperty(r => r.ContentType); mockRequest.SetupProperty(r => r.ContentLength); mockAsyncResult .Setup(ar => ar.AsyncWaitHandle) .Returns((ManualResetEvent)null); var responseStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("Fiddler: DNS Lookup for graph.facebook.com failed. ")); mockResponse .Setup(r => r.GetResponseStream()) .Returns(responseStream); mockWebException .Setup(e => e.Message) .Returns("The remote server returned an error: (502) Bad Gateway."); mockWebException .Setup(e => e.GetResponse()) .Returns(response); mockRequest .Setup(r => r.GetResponse()) .Throws(webException); mockRequest .Setup(r => r.EndGetResponse(It.IsAny <IAsyncResult>())) .Throws(webException); AsyncCallback callback = null; mockRequest .Setup(r => r.BeginGetResponse(It.IsAny <AsyncCallback>(), It.IsAny <object>())) .Callback <AsyncCallback, object>((c, s) => { callback = c; }) .Returns(() => { callback(asyncResult); return(asyncResult); }); var mockRequestCopy = mockRequest; facebookClient.Protected() .Setup <HttpWebRequestWrapper>("CreateHttpWebRequest", ItExpr.IsAny <Uri>()) .Callback <Uri>(uri => mockRequestCopy.Setup(r => r.RequestUri).Returns(uri)) .Returns(request); }
public void VerifyOverriddenProperties() { var configuration = new TelemetryConfiguration(); var sentItems = new List <ITelemetry>(); var mockTelemetryChannel = new Mock <ITelemetryChannel>(); mockTelemetryChannel.Setup(c => c.Send(It.IsAny <ITelemetry>())) .Callback <ITelemetry>((telemetry) => sentItems.Add(telemetry)) .Verifiable(); configuration.TelemetryChannel = mockTelemetryChannel.Object; configuration.InstrumentationKey = Guid.NewGuid().ToString(); // Mock http context var httpContext = new Mock <HttpContext>(); IDictionary <object, object> items = new Dictionary <object, object>(); httpContext.SetupProperty(c => c.Items, items); var httpContextAccessor = new Mock <IHttpContextAccessor>(); httpContextAccessor.SetupProperty(c => c.HttpContext, httpContext.Object); // Simulate what Middleware does to read body var fromID = "FROMID"; var channelID = "CHANNELID"; var conversationID = "CONVERSATIONID"; var activityID = "ACTIVITYID"; var activity = Activity.CreateMessageActivity(); activity.From = new ChannelAccount(fromID); activity.ChannelId = channelID; activity.Conversation = new ConversationAccount(false, "CONVOTYPE", conversationID); activity.Id = activityID; var activityBody = JObject.FromObject(activity); items.Add(TelemetryBotIdInitializer.BotActivityKey, activityBody); configuration.TelemetryInitializers.Add(new TelemetryBotIdInitializer(httpContextAccessor.Object)); var telemetryClient = new TelemetryClient(configuration); var activityIdValue = "Oh yeah I did it"; var channelIdValue = "Hello"; var activityTypeValue = "Breaking all the rules"; // Should not throw. This implicitly calls the initializer. // Note: We are setting properties that should be populated by the TelemetryInitailizer. // We honor overrides. var metrics = new Dictionary <string, double>() { { "metric", 0.6 }, }; telemetryClient.TrackEvent("test", new Dictionary <string, string>() { { "activityId", activityIdValue }, // The activityId can be overridden. { "channelId", channelIdValue }, { "activityType", activityTypeValue }, }, #pragma warning disable SA1117 // Parameters should be on same line or separate lines metrics); #pragma warning restore SA1117 // Parameters should be on same line or separate lines Assert.IsTrue(sentItems.Count == 1); var telem = sentItems[0] as EventTelemetry; Assert.IsTrue(telem != null); Assert.IsTrue(telem.Context.Session.Id == conversationID); Assert.IsTrue(telem.Context.User.Id == channelID + fromID); // The TelemetryInitializer honors being overridden // What we get out should be what we originally put in, and not what the Initializer // normally does. Assert.IsFalse(telem.Properties["activityId"] == activityID); Assert.IsTrue(telem.Properties["activityId"] == activityIdValue); Assert.IsTrue(telem.Properties["channelId"] == channelIdValue); Assert.IsFalse(telem.Properties["channelId"] == "CHANNELID"); Assert.IsTrue(telem.Properties["activityType"] == activityTypeValue); Assert.IsFalse(telem.Properties["activityType"] == "message"); Assert.IsTrue(telem.Metrics["metric"] == 0.6); }
public void Init() { sysAdmin = new User { Email = "*****@*****.**", ID = 1, IsActive = true, IsSysAdmin = true, OrganizationID = 2 }; otherOrganization = new Organization { ID = 3, Name = "OrgName3", IsActive = true }; user = new User { Email = "*****@*****.**", ID = 2, IsSysAdmin = false, OrganizationID = 2 }; otherUser = new User { Email = "*****@*****.**", ID = 3, IsSysAdmin = false, OrganizationID = otherOrganization.ID }; organization = new Organization { ID = 2, Name = "OrgName2", IsActive = true }; activeService = new Application { OrganizationID = organization.ID, IsActive = true, Name = "activeService", PublicID = new Guid("421befd1-ef28-4c25-bcf6-5ead09dabb71"), ID = 1, IsIntroducedAsIndustryGood = true, IsProvider = true }; consumerApplication = new Application { OrganizationID = 2, IsActive = true, Name = "active applications", PublicID = new Guid("421befd1-ef28-4c25-bcf6-5ead09dabb71"), ID = 4, IsProvider = false }; notActiveService = new Application { OrganizationID = 2, IsActive = false, Name = "notActiveService", PublicID = new Guid("421befd1-ef28-4c25-bcf6-5ead09dabb71"), ID = 2, IsProvider = false }; otherService = new Application { OrganizationID = 3, IsActive = true, Name = "otherService", PublicID = new Guid("421befd1-ef28-4c25-bcf6-5ead09dabb71"), ID = 3, IsProvider = false }; dataSchema = new DataSchema { ID = 1, Name = "Schema1" }; providerEndpoint = new ProviderEndpoint { ApplicationId = activeService.ID, ID = 1, DataSchemaID = dataSchema.ID, IsIndustryGood = true, Description = "Description" }; licenseTemplate = new LicenseTemplate { ID = 1, LicenseID = 1, Status = (int)TemplateStatus.Active }; _organizationLicense = new OrganizationLicense { ID = 1, Status = (int)PublishStatus.Published, ProviderEndpointID = providerEndpoint.ID, DataSchemaID = providerEndpoint.DataSchemaID, LicenseTemplateID = licenseTemplate.ID }; applicationToken = new ApplicationToken { ID = 1, ApplicationID = activeService.ID, Token = "token" }; appService = new Mock <IApplicationsService>(); _userService = new Mock <IUserService>(); orgService = new Mock <IOrganizationService>(); schemaService = new Mock <IDataSchemaService>(); endpointService = new Mock <IProviderEndpointService>(); licenseTemplateService = new Mock <ILicenseTemplatesService>(); sectionService = new Mock <ILicenseSectionService>(); clauseService = new Mock <ILicenseClauseService>(); clauseTemplateService = new Mock <ILicenseClauseTemplateService>(); endpointLicClauseService = new Mock <IOrganizationLicenseClauseService>(); licenseService = new Mock <IOrganizationLicenseService>(); notificationService = new Mock <INotificationService>(); applicationTokenService = new Mock <IService <ApplicationToken> >(); applicationAuthenticationService = new Mock <IService <ApplicationAuthentication> >(); configService = new Mock <IConfigurationService>(); licenseContentBuilder = new Mock <ILicenseContentBuilder>(); adminNotificationService = new Mock <IAdminNotificationService>(); // Notification service notificationService.Setup(i => i.Admin).Returns(adminNotificationService.Object); configService.SetupProperty(p => p.ManageApplicationsPageSize, 5); var mockUrl = new Mock <UrlHelper>(); // Setup application token service applicationTokenService.Setup(i => i.Get(applicationToken.ID)).Returns(applicationToken); applicationTokenService.Setup(i => i.Add(It.IsAny <ApplicationToken>())).Returns(true); applicationTokenService.Setup(i => i.Update(It.IsAny <ApplicationToken>())).Returns(true); // Schema service schemaService.Setup(p => p.Get(dataSchema.ID)).Returns(dataSchema); schemaService.Setup(p => p.Get(10)).Returns(new DataSchema { ID = 10, IsIndustryGood = false }); schemaService.Setup(p => p.GetPublishedSchemas()).Returns(new List <DataSchema> { dataSchema, new DataSchema { ID = 10, IsIndustryGood = false } }); // Endpoint service endpointService.Setup(p => p.Get(It.IsAny <Expression <Func <ProviderEndpoint, bool> > >())) .Returns(new List <ProviderEndpoint> { providerEndpoint }); endpointService.Setup(p => p.Get(providerEndpoint.ID)).Returns(providerEndpoint); licenseService.Setup(p => p.Get(It.IsAny <Expression <Func <OrganizationLicense, bool> > >())) .Returns(new List <OrganizationLicense> { _organizationLicense }); // License template service licenseTemplateService.Setup(p => p.GetAll(false)).Returns(new List <LicenseTemplate> { licenseTemplate }); licenseTemplateService.Setup(p => p.GetPublishedGlobalLicense()).Returns(licenseTemplate); // Application service appService.Setup(p => p.GetApplicationsFor((int)user.OrganizationID)) .Returns(new List <Application> { activeService, notActiveService }); appService.Setup(p => p.GetAllApplications()) .Returns(new List <Application> { activeService, otherService, notActiveService }); appService.Setup(p => p.Get(activeService.ID)).Returns(activeService); appService.Setup(p => p.Get(notActiveService.ID)).Returns(notActiveService); appService.Setup(p => p.Get(otherService.ID)).Returns(otherService); appService.Setup(p => p.Get(consumerApplication.ID)).Returns(consumerApplication); appService.Setup(p => p.GetAuthenticationFor(activeService.ID)).Returns(new ApplicationAuthentication()); // Organization service orgService.Setup(p => p.Get(organization.ID)).Returns(organization); orgService.Setup(p => p.Get(otherOrganization.ID)).Returns(otherOrganization); var context = new Mock <ControllerContext>(); context.Setup(m => m.HttpContext.Request.Form).Returns(new FormCollection()); context.Setup(m => m.HttpContext.Request.Url).Returns(new Uri("http://test.com")); context.Setup(m => m.HttpContext.Request.Browser).Returns(new Mock <HttpBrowserCapabilitiesBase>().Object); controller = new ApplicationsController(appService.Object, applicationTokenService.Object, applicationAuthenticationService.Object, _userService.Object, orgService.Object, schemaService.Object, endpointService.Object, licenseService.Object, configService.Object, notificationService.Object); controller.ControllerContext = context.Object; controller.Url = mockUrl.Object; }
public void ConsensusService_Primary_Sends_PrepareRequest_After_OnStart() { TestProbe subscriber = CreateTestProbe(); var mockConsensusContext = new Mock <IConsensusContext>(); var mockStore = new Mock <Store>(); // context.Reset(): do nothing //mockConsensusContext.Setup(mr => mr.Reset()).Verifiable(); // void mockConsensusContext.SetupGet(mr => mr.MyIndex).Returns(2); // MyIndex == 2 mockConsensusContext.SetupGet(mr => mr.BlockIndex).Returns(2); mockConsensusContext.SetupGet(mr => mr.PrimaryIndex).Returns(2); mockConsensusContext.SetupGet(mr => mr.ViewNumber).Returns(0); mockConsensusContext.SetupProperty(mr => mr.Nonce); mockConsensusContext.SetupProperty(mr => mr.NextConsensus); mockConsensusContext.Object.NextConsensus = UInt160.Zero; mockConsensusContext.SetupGet(mr => mr.PreparationPayloads).Returns(new ConsensusPayload[7]); mockConsensusContext.SetupGet(mr => mr.CommitPayloads).Returns(new ConsensusPayload[7]); int timeIndex = 0; var timeValues = new[] { //new DateTime(1968, 06, 01, 0, 0, 15, DateTimeKind.Utc), // For tests here new DateTime(1968, 06, 01, 0, 0, 1, DateTimeKind.Utc), // For receiving block new DateTime(1968, 06, 01, 0, 0, (int)Blockchain.SecondsPerBlock, DateTimeKind.Utc), // For Initialize new DateTime(1968, 06, 01, 0, 0, 15, DateTimeKind.Utc), // unused new DateTime(1968, 06, 01, 0, 0, 15, DateTimeKind.Utc) // unused }; //TimeProvider.Current.UtcNow.ToTimestamp().Should().Be(4244941711); //1968-06-01 00:00:15 Console.WriteLine($"time 0: {timeValues[0].ToString()} 1: {timeValues[1].ToString()} 2: {timeValues[2].ToString()} 3: {timeValues[3].ToString()}"); //mockConsensusContext.Object.block_received_time = new DateTime(1968, 06, 01, 0, 0, 1, DateTimeKind.Utc); //mockConsensusContext.Setup(mr => mr.GetUtcNow()).Returns(new DateTime(1968, 06, 01, 0, 0, 15, DateTimeKind.Utc)); var timeMock = new Mock <TimeProvider>(); timeMock.SetupGet(tp => tp.UtcNow).Returns(() => timeValues[timeIndex]) .Callback(() => timeIndex++); //new DateTime(1968, 06, 01, 0, 0, 15, DateTimeKind.Utc)); TimeProvider.Current = timeMock.Object; //public void Log(string message, LogLevel level) // TODO: create ILogPlugin for Tests /* * mockConsensusContext.Setup(mr => mr.Log(It.IsAny<string>(), It.IsAny<LogLevel>())) * .Callback((string message, LogLevel level) => { * Console.WriteLine($"CONSENSUS LOG: {message}"); * } * ); */ // Creating proposed block Header header = new Header(); TestUtils.SetupHeaderWithValues(header, UInt256.Zero, out UInt256 merkRootVal, out UInt160 val160, out uint timestampVal, out uint indexVal, out ulong consensusDataVal, out Witness scriptVal); header.Size.Should().Be(109); Console.WriteLine($"header {header} hash {header.Hash} timstamp {timestampVal}"); timestampVal.Should().Be(4244941696); //1968-06-01 00:00:00 // check basic ConsensusContext mockConsensusContext.Object.MyIndex.Should().Be(2); //mockConsensusContext.Object.block_received_time.ToTimestamp().Should().Be(4244941697); //1968-06-01 00:00:01 MinerTransaction minerTx = new MinerTransaction { Attributes = new TransactionAttribute[0], Inputs = new CoinReference[0], Outputs = new TransactionOutput[0], Witnesses = new Witness[0], Nonce = 42 }; PrepareRequest prep = new PrepareRequest { Nonce = mockConsensusContext.Object.Nonce, NextConsensus = mockConsensusContext.Object.NextConsensus, TransactionHashes = new UInt256[0], MinerTransaction = minerTx //(MinerTransaction)Transactions[TransactionHashes[0]], }; ConsensusPayload prepPayload = new ConsensusPayload { Version = 0, PrevHash = mockConsensusContext.Object.PrevHash, BlockIndex = mockConsensusContext.Object.BlockIndex, ValidatorIndex = (ushort)mockConsensusContext.Object.MyIndex, ConsensusMessage = prep }; mockConsensusContext.Setup(mr => mr.MakePrepareRequest()).Returns(prepPayload); // ============================================================================ // creating ConsensusService actor // ============================================================================ TestActorRef <ConsensusService> actorConsensus = ActorOfAsTestActorRef <ConsensusService>( Akka.Actor.Props.Create(() => new ConsensusService(subscriber, subscriber, mockConsensusContext.Object)) ); Console.WriteLine("will trigger OnPersistCompleted!"); actorConsensus.Tell(new Blockchain.PersistCompleted { Block = new Block { Version = header.Version, PrevHash = header.PrevHash, MerkleRoot = header.MerkleRoot, Timestamp = header.Timestamp, Index = header.Index, ConsensusData = header.ConsensusData, NextConsensus = header.NextConsensus } }); // OnPersist will not launch timer, we need OnStart Console.WriteLine("will start consensus!"); actorConsensus.Tell(new ConsensusService.Start()); Console.WriteLine("OnTimer should expire!"); Console.WriteLine("Waiting for subscriber message!"); // Timer should expire in one second (block_received_time at :01, initialized at :02) var answer = subscriber.ExpectMsg <LocalNode.SendDirectly>(); Console.WriteLine($"MESSAGE 1: {answer}"); //var answer2 = subscriber.ExpectMsg<LocalNode.SendDirectly>(); // expects to fail! // ============================================================================ // finalize ConsensusService actor // ============================================================================ //Thread.Sleep(4000); Sys.Stop(actorConsensus); TimeProvider.ResetToDefault(); Assert.AreEqual(1, 1); }
public void Run() { var mockOut = new Mock <TextWriter>(); var mockGraphics = new Mock <IGraphics>(); var myBot = new Mock <IBaseAdvancedRobot>(MockBehavior.Strict); IContext context = new Context(myBot.Object); BaseBehavior.Context = context; BaseStrategy.Context = context; var behaviours = new BaseBehavior[] { // new RunAwayAndHideBehaviour(), new SearchBehavior(), new MeleeBehavior(), new OneVsOneBehavior(), new VictoryBehavior() }; IBrain brain = new Brain( myBot.Object, behaviours, context); myBot.Setup(bot => bot.Out).Returns(mockOut.Object); myBot.Setup(bot => bot.SetColors(It.IsAny <Color>(), It.IsAny <Color>(), It.IsAny <Color>())); myBot.SetupProperty(bot => bot.IsAdjustGunForRobotTurn); myBot.SetupProperty(bot => bot.IsAdjustRadarForGunTurn); myBot.SetupProperty(bot => bot.IsAdjustRadarForRobotTurn); myBot.Setup(bot => bot.BattleFieldWidth).Returns(800d); myBot.Setup(bot => bot.BattleFieldHeight).Returns(600d); var startAt = RandomHelper.RandomLocation(); myBot.Setup(bot => bot.X).Returns(startAt.X); myBot.Setup(bot => bot.Y).Returns(startAt.Y); brain.RunInit(); myBot.Setup(bot => bot.GunHeading).Returns(0d); myBot.Setup(bot => bot.GunTurnRemaining).Returns(0d); myBot.Setup(bot => bot.GunHeat).Returns(0d); myBot.Setup(bot => bot.Others).Returns(10); myBot.Setup(bot => bot.SetTurnRadarRight(It.IsAny <double>())); myBot.Setup(bot => bot.SetTurnGunRight(It.IsAny <double>())); myBot.Setup(bot => bot.SetTurnRight(It.IsAny <double>())); myBot.Setup(bot => bot.SetAhead(It.IsAny <double>())); myBot.Setup(bot => bot.SetFireBullet(It.IsAny <double>())) .Returns(RandomHelper.RandomBullet()); myBot.Setup(bot => bot.Heading).Returns(RandomHelper.RandomHeading()); myBot.Setup(bot => bot.Execute()); myBot.Setup(bot => bot.GunCoolingRate).Returns(5); myBot.Setup(bot => bot.Energy).Returns(RandomHelper.RandomEnergy()); for (int turn = 0; turn < 200; turn++) { brain.Render(mockGraphics.Object); myBot.Setup(bot => bot.Time).Returns(turn); if (turn % 7 == 0) { for (int i = 0; i < 2; i++) { brain.OnScannedRobot(new ScannedRobotEvent( RandomHelper.RandomRobotName(), RandomHelper.RandomEnergy(), RandomHelper.RandomBearing(), RandomHelper.RandomDistance(), RandomHelper.RandomHeading(), RandomHelper.RandomVelocity() )); } } brain.Run(); } }
public void SetUp() { _container = new ServiceContainer(); var testMap = new TestGridGenMap(3); var sectorMock = new Mock <ISector>(); sectorMock.SetupGet(x => x.Map).Returns(testMap); var sector = sectorMock.Object; var sectorManagerMock = new Mock <ISectorManager>(); sectorManagerMock.SetupProperty(x => x.CurrentSector, sector); var sectorManager = sectorManagerMock.Object; var actMock = new Mock <ITacticalAct>(); actMock.SetupGet(x => x.Stats).Returns(new TacticalActStatsSubScheme { Range = new Range <int>(1, 2) }); var act = actMock.Object; var actCarrierMock = new Mock <ITacticalActCarrier>(); actCarrierMock.SetupGet(x => x.Acts) .Returns(new[] { act }); var actCarrier = actCarrierMock.Object; var equipmentCarrierMock = new Mock <IEquipmentCarrier>(); equipmentCarrierMock.SetupGet(x => x.Slots).Returns(new[] { new PersonSlotSubScheme { Types = EquipmentSlotTypes.Hand } }); var equipmentCarrier = equipmentCarrierMock.Object; var personMock = new Mock <IPerson>(); personMock.SetupGet(x => x.TacticalActCarrier).Returns(actCarrier); personMock.SetupGet(x => x.EquipmentCarrier).Returns(equipmentCarrier); var person = personMock.Object; var actorMock = new Mock <IActor>(); var actorNode = testMap.Nodes.OfType <HexNode>().SelectBy(0, 0); actorMock.SetupGet(x => x.Node).Returns(actorNode); actorMock.SetupGet(x => x.Person).Returns(person); var actor = actorMock.Object; var actorVmMock = new Mock <IActorViewModel>(); actorVmMock.SetupProperty(x => x.Actor, actor); var actorVm = actorVmMock.Object; var humanTaskSourceMock = new Mock <IHumanActorTaskSource>(); var humanTaskSource = humanTaskSourceMock.Object; var playerStateMock = new Mock <IPlayerState>(); playerStateMock.SetupProperty(x => x.ActiveActor, actorVm); playerStateMock.SetupProperty(x => x.TaskSource, humanTaskSource); var playerState = playerStateMock.Object; var gameLoopMock = new Mock <IGameLoop>(); var gameLoop = gameLoopMock.Object; var usageServiceMock = new Mock <ITacticalActUsageService>(); var usageService = usageServiceMock.Object; _container.Register(factory => sectorManager, new PerContainerLifetime()); _container.Register(factory => humanTaskSourceMock, new PerContainerLifetime()); _container.Register(factory => playerState, new PerContainerLifetime()); _container.Register(factory => gameLoop, new PerContainerLifetime()); _container.Register(factory => usageService, new PerContainerLifetime()); RegisterSpecificServices(testMap, playerStateMock); }
public async Task LoadOperationArgumentsTest() { var program = new Program(RuntimeContext.Default) { _dieException = (Program caller, Exception e, string path, int line, string name) => Assert.False(true, $"Error: {e.ToString()}"), _dieMessage = (Program caller, string m, string path, int line, string name) => Assert.False(true, $"Error: {m}"), _exit = (Program caller, int e, string m, string path, int line, string name) => Assert.False(true, $"Error: {e} {m}") }; var configs = new Dictionary <Git.ConfigurationLevel, Dictionary <string, string> > { { Git.ConfigurationLevel.Local, new Dictionary <string, string>(Program.ConfigKeyComparer) { { "credential.validate", "true" }, { "credential.useHttpPath", "true" }, { "credential.not-match.com.useHttpPath", "false" }, } }, { Git.ConfigurationLevel.Global, new Dictionary <string, string>(Program.ConfigKeyComparer) { { "credential.validate", "false" }, { "credential.vstsScope", "vso.build,vso.code_write" }, } }, { Git.ConfigurationLevel.Xdg, new Dictionary <string, string>(Program.ConfigKeyComparer) { } }, { Git.ConfigurationLevel.System, new Dictionary <string, string>(Program.ConfigKeyComparer) { } }, { Git.ConfigurationLevel.Portable, new Dictionary <string, string>(Program.ConfigKeyComparer) { } }, }; var envvars = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase) { { "HOME", Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) }, }; var gitconfig = new Git.Configuration(RuntimeContext.Default, configs); var targetUri = new TargetUri("https://example.visualstudio.com/"); var opargsMock = new Mock <OperationArguments>(); opargsMock.Setup(o => o.EnvironmentVariables) .Returns(envvars); opargsMock.Setup(o => o.GitConfiguration) .Returns(gitconfig); opargsMock.Setup(o => o.TargetUri) .Returns(targetUri); opargsMock.Setup(o => o.QueryUri) .Returns(targetUri); opargsMock.SetupProperty(o => o.UseHttpPath); opargsMock.SetupProperty(o => o.ValidateCredentials); opargsMock.SetupProperty(o => o.DevOpsTokenScope); var opargs = opargsMock.Object; await program.LoadOperationArguments(opargs); Assert.NotNull(opargs); Assert.True(opargs.ValidateCredentials, "credential.validate"); Assert.True(opargs.UseHttpPath, "credential.useHttpPath"); Assert.NotNull(opargs.DevOpsTokenScope); var expectedScope = AzureDev.TokenScope.BuildAccess | AzureDev.TokenScope.CodeWrite; Assert.Equal(expectedScope, opargs.DevOpsTokenScope); }