public void Equals_OtherHasSameFileAndId_ReturnsTrue() { const string fileName1 = @"c:\xyz\abc"; const string fileName2 = @"c:\xyz\abc"; const int id1 = 24680; const int id2 = 24680; using (ShimsContext.Create()) { ShimFile.ExistsString = (f) => { return((f == fileName1 || f == fileName2) ? true : ShimsContext.ExecuteWithoutShims(() => File.Exists(f))); }; A11yElement element1 = new ShimA11yElement { UniqueIdGet = () => id1, }; A11yElement element2 = new ShimA11yElement { UniqueIdGet = () => id2, }; ILocation location1 = new OutputFileLocation(fileName1, element1); ILocation location2 = new OutputFileLocation(fileName2, element2); Assert.IsTrue(location1.Equals(location2)); Assert.IsTrue(location2.Equals(location1)); } }
public void Open_FileDoesNotExist_ReturnsFalse() { const string fileName = @"c:\xyz\abc"; const int id = 24680; bool fileExists = true; using (ShimsContext.Create()) { ShimFile.ExistsString = (f) => { return((f == fileName) ? fileExists : ShimsContext.ExecuteWithoutShims(() => File.Exists(f))); }; A11yElement element = new ShimA11yElement { UniqueIdGet = () => id, }; ILocation location = new OutputFileLocation(fileName, element); fileExists = false; Assert.IsFalse(location.Open()); } }
private DataSet BouceEngineLoadXMLFile(string filePath) { var result = new DataSet(); ShimsContext.ExecuteWithoutShims(() => { var xml = string.Empty; if (filePath == BounceConfigFileName) { xml = GetBoundConfigXml(); } else if (filePath == PagerConfigFileName) { xml = GetPagerConfigXml(); } else if (filePath == BounceSignaturesFileName) { xml = File.ReadAllText(BounceSignaturesFileName); } using (var stringReader = new StringReader(xml)) { result.ReadXml(stringReader); } }); return(result); }
public void Open_ProcessStartReturnsNonNull_ReturnsTrue() { const string fileName = @"c:\xyz\abc"; const int id = 24680; using (ShimsContext.Create()) { ShimFile.ExistsString = (f) => { return((f == fileName) ? true : ShimsContext.ExecuteWithoutShims(() => File.Exists(f))); }; A11yElement element = new ShimA11yElement { UniqueIdGet = () => id, }; ProcessStartInfo actualStartInfo = null; ILocation location = new OutputFileLocation(fileName, element, (startInfo) => { actualStartInfo = startInfo; return(new Process()); }); Assert.IsNull(actualStartInfo); Assert.IsTrue(location.Open()); Assert.IsNotNull(actualStartInfo); Assert.AreEqual(fileName, actualStartInfo.FileName); Assert.AreEqual("open", actualStartInfo.Verb); } }
public void RegisterCommentCreationActivity_WhenThreadNotNull_RegistersActivity() { // Arrange const bool registerExpected = true; var registerActual = false; var data = CreateDataObject(); data.Add(CommentIdString, 1); data.Add(CommentString, CommentString); data.Add(CommentersColumn, Commenters); data.Add(ThreadValue, new Thread() { Id = guid }); var threadTable = CreateThreadTable(); ShimSqlCommand.AllInstances.ExecuteNonQuery = sqlCommand => { if (sqlCommand.CommandText.StartsWith("INSERT INTO SS_Activities")) { registerActual = true; } return(1); }; ShimSqlCommand.AllInstances.ExecuteReader = sqlCommand => { var reader = new ShimSqlDataReader() { Close = () => { } }; return(reader); }; ShimDataRowCollection.AllInstances.CountGet = _ => 1; ShimDataRowCollection.AllInstances.ItemGetInt32 = (_, _1) => { DataRow result = null; ShimsContext.ExecuteWithoutShims(() => { result = threadTable.Rows[0]; }); return(result); }; var args = new ProcessActivityEventArgs(ObjectKind.List, ActivityKind.CommentAdded, data, spWeb, streamManager, threadManager, activityManager); // Act privateObj.Invoke( RegisterCommentCreationActivityMethod, BindingFlags.Instance | BindingFlags.NonPublic, new object[] { args }); // Assert registerActual.ShouldBe(registerExpected); }
private void ShimAppSettings() { ShimConfigurationManager.AppSettingsGet = () => { var originalAppSettings = ShimsContext.ExecuteWithoutShims(() => ConfigurationManager.AppSettings); var result = new NameValueCollection(originalAppSettings); result.Add(AppSettings); return(result); }; }
public void CreateChildControls_OnValidCall_UpdateFields() { // Arrange SetupShimsForHttpRequest(); SetupShimsForSqlClient(); SetupShimsForSharePoint(); _queryString.Add("duser", DummyString); ShimCoreFunctions.getConfigSettingSPWebString = (_, name) => { if (name.Equals("EPMLiveDaySettings")) { return(string.Join("|", Enumerable.Repeat(bool.TrueString, 30))); } if (name.Equals("EPMLiveResourceURL")) { return(DummyUrl); } return(DummyString); }; ShimAct.AllInstances.CheckOnlineFeatureLicenseActFeatureStringSPSite = (_, _2, _3, _4) => 0; ShimStringDictionary.AllInstances.ContainsKeyString = (sd, key) => { if (key.Equals("EPMLiveResourceURL")) { return(true); } return(ShimsContext.ExecuteWithoutShims(() => sd.ContainsKey(key))); }; ShimStringDictionary.AllInstances.ItemGetString = (sd, key) => { if (key.Equals("EPMLiveResourceURL")) { return(DummyString); } return(ShimsContext.ExecuteWithoutShims(() => sd[key])); }; ShimTemplateControl.AllInstances.LoadControlString = (_, name) => new ToolBarFake(); ShimPeopleEditor.Constructor = _ => { }; // Act PrivateObject.Invoke("CreateChildControls"); var arrPeriods = Get <SortedList>("arrPeriods"); // Assert this.ShouldSatisfyAllConditions( () => Get <string>("username").ShouldContain(DummyString), () => Get <string>("impersonatedUser").ShouldContain(DummyString), () => Get <bool>("impersonate").ShouldBeTrue(), () => arrPeriods.Count.ShouldBe(1), () => arrPeriods.ContainsKey(DummyInt).ShouldBeTrue()); }
public async Task GetJsonAsyncNoGzipTestAsync() { using (ShimsContext.Create()) { var person = new Person { DateOfBirth = DateTime.Now.Subtract(new TimeSpan(800, 1, 1, 1)), Firstname = "First", Lastname = "Person", PhoneNumber = "0123456789", SomeString = "This is just a string" }; ShimHttpWebRequest.AllInstances.BeginGetResponseAsyncCallbackObject = (request, callback, arg3) => { return(ShimsContext.ExecuteWithoutShims(() => request.BeginGetResponse(callback, arg3))); }; ShimHttpWebResponse.AllInstances.StatusCodeGet = response => { return(ShimsContext.ExecuteWithoutShims(() => response.StatusCode)); }; ShimHttpWebResponse.AllInstances.GetResponseStream = response => { var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(person)); var stream = new MemoryStream(bytes); return(stream); }; ShimHttpWebResponse.AllInstances.HeadersGet = response => { var headers = new WebHeaderCollection(); headers.Add(HttpRequestHeader.ContentType, "text/html; charset=utf-8"); //base = {Content-Encoding: gzip Content-Type: text/html; charset=utf-8 Content-Length: 155} return(headers); }; using (var client = new UncommonHttpClient()) { var result = await client.GetJsonAsync <Person>("http://www.xciles.com/"); Assert.AreEqual(person.Firstname, result.Firstname); Assert.AreEqual(person.Lastname, result.Lastname); Assert.AreEqual(person.PhoneNumber, result.PhoneNumber); } } }
private bool FileExists(string filePath) { var result = false; if (_testContext.FileExistsPathToReturnTrue != null) { result = filePath.Contains(_testContext.FileExistsPathToReturnTrue); } if (!result) { return(ShimsContext.ExecuteWithoutShims(() => File.Exists(filePath))); } return(result); }
public void TestMethod3() { using (ShimsContext.Create()) { ConsoleApp.Fakes.ShimProgram.Hello = () => { return(ShimsContext.ExecuteWithoutShims(() => { Console.WriteLine("Overwride by shim"); return Program.Hello(); })); }; string actual = Program.Hello(); Assert.AreEqual(Program.res1, actual); } }
public void Dispose_WhenCalled_DisposesSubControls() { // Arrange var disposeCountOfWebControls = 0; var disposeCountOfHtmlSelect = 0; var disposeCountOfHtmlGenericControl = 0; ShimControl.AllInstances.Dispose = instance => { try { // Table, TableRow, TableCell, ImageButton, DropDownList if (instance is WebControl) { disposeCountOfWebControls++; } else if (instance is HtmlSelect) { disposeCountOfHtmlSelect++; } else if (instance is HtmlGenericControl) { disposeCountOfHtmlGenericControl++; } } finally { ShimsContext.ExecuteWithoutShims(() => instance.Dispose()); } }; // Act using (_testEntity = new GenericQueryControl()) { _testEntityPrivate = new PrivateObject(_testEntity); _testEntityPrivate.SetField("propertyBag", new ShimGenericEntityPickerPropertyBag().Instance); _testEntityPrivate.Invoke(MethodCreateChildControls); } // Assert _testEntity.ShouldSatisfyAllConditions( () => disposeCountOfWebControls.ShouldBe(10), () => disposeCountOfHtmlSelect.ShouldBe(1), () => disposeCountOfHtmlGenericControl.ShouldBe(1)); }
public void DemoSpyTest() { using (ShimsContext.Create()) { int cont = 0; const string filename = @"D:\Cursos\dotnet\MSTEST20200518\Demos.Tests\AreaTest.csv"; System.IO.Fakes.ShimFile.ReadAllLinesString = s => { Assert.AreEqual(filename, s); cont++; string[] rslt = null; ShimsContext.ExecuteWithoutShims(() => { rslt = File.ReadAllLines(s); }); return(rslt); }; var arrage = new LoadTextFile(filename); Assert.AreEqual(1, cont); AreEqual(4, arrage.Size); } }
public void Dispose_Invoke_DisposesAllObjects() { // Arrange var disposedControls = false; ShimControl.AllInstances.Dispose = control => { disposedControls = true; ShimsContext.ExecuteWithoutShims(() => control.Dispose()); }; // Act _testObject.Dispose(); // Assert disposedControls.ShouldBeTrue(); }
public void Dispose_WhenCalled_DisposesSubControls() { // Arrange var disposeCountOfLiteralControls = 0; var disposeCountOfPanel = 0; ShimControl.AllInstances.Dispose = instance => { try { if (instance is LiteralControl) { disposeCountOfLiteralControls++; } else if (instance is Panel) { disposeCountOfPanel++; } } finally { ShimsContext.ExecuteWithoutShims(() => instance.Dispose()); } }; var subControlsCountOfMainPanel = 0; // Act using (_testEntity = new WorkspaceListWPCanvas()) { _testEntityPrivate = new PrivateObject(_testEntity); var mainPanel = new Panel(); _testEntityPrivate.SetField(FieldMainPanel, mainPanel); _testEntityPrivate.Invoke(MethodPageLoad, this, EventArgs.Empty); subControlsCountOfMainPanel = mainPanel.Controls.Count; } // Assert _testEntity.ShouldSatisfyAllConditions( () => disposeCountOfLiteralControls.ShouldBe(subControlsCountOfMainPanel), () => disposeCountOfPanel.ShouldBe(1)); }
public void WhenGetAssetsIsCalledWithAPredicateThenAssetsCollectionIsFiltered() { var client = new AzureMediaServicesClient("myAccountName", "myAccountKey"); using (ShimsContext.Create()) { var asset1 = new StubIAsset { NameGet = () => "EZ" }; var asset2 = new StubIAsset { NameGet = () => "VOD" }; var sampleAssets = new List <IAsset> { asset1, asset2 }; var collection = new StubAssetBaseCollection { QueryableGet = sampleAssets.AsQueryable }; Expression <Func <IAsset, bool> > filter = asset => asset.Name == "EZ"; Expression <Func <IAsset, bool> > providedPredicate = null; ShimCloudMediaContext.ConstructorStringString = (context, accountName, accountKey) => { }; ShimCloudMediaContext.AllInstances.AssetsGet = context => collection; ShimQueryable.WhereOf1IQueryableOfM0ExpressionOfFuncOfM0Boolean <IAsset>((assets, predicate) => { Assert.AreEqual(2, assets.Count()); providedPredicate = predicate; return(ShimsContext.ExecuteWithoutShims(() => assets.Where(predicate))); }); var returnedAssets = client.GetAssets(filter); Assert.AreSame(filter, providedPredicate); Assert.AreEqual(1, returnedAssets.Count()); Assert.AreEqual(asset1.NameGet(), returnedAssets.First().Name); } }
private async Task ProcessGetRequestHttpRequestExceptionTestAsync() { var exceptionObject = new ExceptionObject() { Description = "This is a test Exception Description", Message = "This is a test Exception Message", Type = EType.WrongHeaders }; using (ShimsContext.Create()) { ShimHttpClient.AllInstances.SendAsyncHttpRequestMessageCancellationToken = (client, message, arg3) => { //var webEx = new WebException("", WebExceptionStatus.UnknownError, ) throw new HttpRequestException(); }; ShimHttpWebResponse.AllInstances.ResponseStreamGet = (response) => { return(ShimsContext.ExecuteWithoutShims(() => response.GetResponseStream())); }; try { var result = await UncommonRequestHelper.ProcessGetRequestAsync <Person>("http://www.xciles.com/"); Assert.Fail("Should not be able to be here..."); } catch (UncommonRequestException ex) { Assert.IsTrue(ex.RequestExceptionStatus == EUncommonRequestExceptionStatus.ServiceError); Assert.IsTrue(ex.StatusCode == HttpStatusCode.BadRequest); //var responseResult = ex.ConvertExceptionResponseToObject<ExceptionObject>(); //Assert.IsTrue(responseResult != null); //Assert.IsTrue(responseResult.Description == exceptionObject.Description); //Assert.IsTrue(responseResult.Message == exceptionObject.Message); //Assert.IsTrue(responseResult.Type == exceptionObject.Type); } } }
public void Equals_OtherIsDifferentClass_ReturnsFalse() { const string fileName = @"c:\xyz\abc"; using (ShimsContext.Create()) { ShimFile.ExistsString = (f) => { return(f == fileName ? true : ShimsContext.ExecuteWithoutShims(() => File.Exists(f))); }; A11yElement element = new ShimA11yElement { UniqueIdGet = () => 24680, }; ILocation location = new OutputFileLocation(fileName, element); Assert.IsFalse(location.Equals(new StubILocation())); } }
public void Ctor_SimpleCase_PropertiesAreSetCorrectly() { const string fileName = @"c:\xyz\abc"; using (ShimsContext.Create()) { ShimFile.ExistsString = (f) => { return(f == fileName ? true : ShimsContext.ExecuteWithoutShims(() => File.Exists(f))); }; A11yElement element = new ShimA11yElement { UniqueIdGet = () => 24680, }; ILocation location = new OutputFileLocation(fileName, element); Assert.AreEqual(fileName, location.Source); Assert.AreEqual("24680", location.Id); } }
public void Ctor_FileDoesNotExist_ThrowsArgumentException() { const string invalidFile = @"c:\myfile.xyz"; using (ShimsContext.Create()) { ShimFile.ExistsString = (f) => { return(f == invalidFile ? false : ShimsContext.ExecuteWithoutShims(() => File.Exists(f))); }; try { new OutputFileLocation(invalidFile, new A11yElement()); } catch (ArgumentException e) { Assert.AreEqual("file", e.ParamName); Assert.IsNull(e.InnerException); throw; } } }
public void Open_ProcessStartThrowsNonEnumeratedException_RethrowsException() { const string fileName = @"c:\xyz\abc"; const int id = 24680; using (ShimsContext.Create()) { ShimFile.ExistsString = (f) => { return((f == fileName) ? true : ShimsContext.ExecuteWithoutShims(() => File.Exists(f))); }; A11yElement element = new ShimA11yElement { UniqueIdGet = () => id, }; ILocation location = new OutputFileLocation(fileName, element, (startInfo) => { throw new OutOfMemoryException(); }); location.Open(); } }
public void UserDisplayInfo_SimpleCase_OutputIsContainsLocationProperties() { const string fileName = "c:\\abc\\xyz"; using (ShimsContext.Create()) { ShimFile.ExistsString = (f) => { return(f == fileName ? true : ShimsContext.ExecuteWithoutShims(() => File.Exists(f))); }; A11yElement element = new ShimA11yElement { UniqueIdGet = () => 13579, }; ILocation location = new OutputFileLocation(fileName, element); string displayInfo = location.UserDisplayInfo; Assert.IsTrue(displayInfo.Contains(location.Source)); Assert.IsTrue(displayInfo.Contains(location.Id)); } }
public void RegisterGridIdAndCss_WhenCalled_Registers() { // Arrange const string dataXmlString = @" <xmlcfg> <Id>111</Id> </xmlcfg>"; var actual = default(XElement); var dataXml = XDocument.Parse(dataXmlString); var resultRootElement = new XElement("resultRootElement"); ShimXContainer.AllInstances.AddObject = (instance, input) => { if (instance.NodeType == XmlNodeType.Element) { if (resultRootElement.Name.LocalName.Equals(((XElement)instance).Name.LocalName)) { actual = (XElement)input; } } ShimsContext.ExecuteWithoutShims(() => { instance.Add(input); }); }; // Act privateObject.Invoke( RegisterGridIdAndCssMethodName, BindingFlags.Static | BindingFlags.NonPublic, new object[] { resultRootElement, dataXml }); // Assert actual.ShouldSatisfyAllConditions( () => actual.Name.LocalName.ShouldBe("Cfg"), () => actual.Attribute("id").Value.ShouldBe("111")); }
public void Open_ProcessStartThrowsEnumeratedException_ReturnsFalse() { const string fileName = @"c:\xyz\abc"; const int id = 24680; using (ShimsContext.Create()) { ShimFile.ExistsString = (f) => { return((f == fileName) ? true : ShimsContext.ExecuteWithoutShims(() => File.Exists(f))); }; A11yElement element = new ShimA11yElement { UniqueIdGet = () => id, }; List <Exception> enumeratedExceptions = new List <Exception> { new InvalidOperationException(), new ArgumentException(), new ObjectDisposedException("blah", new Exception()), new FileNotFoundException(), new Win32Exception(), }; int exceptionsTested = 0; foreach (Exception e in enumeratedExceptions) { ILocation location = new OutputFileLocation(fileName, element, (startInfo) => { throw e; }); Assert.IsFalse(location.Open(), "Simulated Exception: " + e.ToString()); exceptionsTested++; } Assert.AreEqual(enumeratedExceptions.Count, exceptionsTested); } }
private void SetupShims() { shimsContext = ShimsContext.Create(); SetupVariables(); ShimAPIEmail.QueueItemMessageInt32BooleanHashtableStringArrayStringArrayBooleanBooleanSPWebSPUserBoolean = (_, _1, _2, _3, _4, _5, _6, _7, _8, _9) => { }; ShimAPITeam.GetResourcePoolStringSPWeb = (_, __) => dTableTeam; ShimCoreFunctions.enqueueGuidInt32 = (_, __) => { }; ShimCoreFunctions.getLockConfigSettingSPWebStringBoolean = (_, key, _2) => { var result = key; switch (key) { case "EPMLivePublisherProjectCenter": result = ProjectList; break; case "EPMLivePlannermsprojectTaskCenterFields": result = "field11,field12|field21,field22"; break; } return(result); }; ShimCoreFunctions.getLockedWebSPWeb = _ => guid; ShimCoreFunctions.getConnectionStringGuid = _ => ConnectionString; ShimCoreFunctions.getConfigSettingSPWebString = (_, key) => { var result = key; switch (key) { case "EPMLivePlannerPlannerPJLockItems": result = LockedItems; break; case "EPMLivePlannerPlannerTSFlag": case "EPMLivePlannerPlannerTSHours": result = string.Empty; break; case "updateperflimit": result = "5"; break; } return(result); }; ShimCoreFunctions.getListSettingStringSPList = (key, _1) => string.Empty; ShimCoreFunctions.GetPlannerListSPWebSPListItem = (_, __) => defs; ShimExtensionMethods.ContainsFieldWithInternalNameSPFieldCollectionString = (_, _1) => true; ShimHttpUtility.UrlDecodeString = url => url; ShimList <SPFieldUserValue> .AllInstances.GetEnumerator = _ => { var result = default(List <SPFieldUserValue> .Enumerator); ShimsContext.ExecuteWithoutShims(() => { result = userList.GetEnumerator(); }); return(result); }; ShimPath.GetFileNameWithoutExtensionString = fileName => fileName; ShimPlannerCore.getWorkPlannerStatusFieldsSPWebString = (_, __) => new SortedList(); ShimSPFieldLookupValue.AllInstances.LookupIdGet = _ => 1; ShimSPFieldUserValue.ConstructorSPWebString = (_, _1, _2) => new ShimSPFieldUserValue(); ShimSPFieldUserValue.AllInstances.LookupValueGet = _ => Title; ShimSPFieldUserValueCollection.ConstructorSPWebString = (_, _1, _2) => new SPFieldUserValueCollection(); ShimSPPersistedObject.AllInstances.IdGet = _ => guid; ShimSPSecurity.RunWithElevatedPrivilegesSPSecurityCodeToRunElevated = codeToRun => { codeToRun(); }; ShimSPSite.ConstructorGuid = (_, _1) => new ShimSPSite(); ShimSPSite.AllInstances.OpenWebGuid = (_, _1) => spWeb; ShimSPContext.CurrentGet = () => new ShimSPContext() { SiteGet = () => spSite, WebGet = () => spWeb }; ShimSqlCommand.AllInstances.ExecuteReader = _ => dataReader; ShimSqlCommand.AllInstances.ExecuteNonQuery = _ => 1; ShimSqlCommand.ConstructorStringSqlConnection = (_, commandString, connection) => commandsList.Add(commandString); ShimSqlConnection.ConstructorString = (_, __) => new ShimSqlConnection(); ShimSqlConnection.AllInstances.Open = _ => { }; ShimSqlConnection.AllInstances.Close = _ => { }; ShimSqlParameterCollection.AllInstances.AddWithValueStringObject = (_, parameterName, parameterObject) => { parameterList.Add(parameterName); return(null); }; }
public void ConfigureColumns_WhenCalled_ConfiguresColumns() { // Arrange var actual = default(XElement); var headerElement = new XElement("headerElement"); var colsElement = new XElement("colsElement"); var defaultColumns = new List <string>() { "1" }; var fields = new List <string>() { "1", "2" }; ShimUtils.GetRelatedGridTypeSPField = _ => "Icon"; ShimUtils.GetFormatSPField = _ => DummyString; ShimUtils.ToGridSafeFieldNameString = (input) => input; ShimMyWork.GetRelatedGridFormatStringStringSPFieldSPWeb = (_, _1, _2, _3) => DummyString; ShimExtensionMethods.ContainsFieldWithInternalNameSPFieldCollectionString = (_, __) => true; ShimSPFieldCollection.AllInstances.GetFieldByInternalNameString = (_, __) => new ShimSPField() { InternalNameGet = () => DummyString, TypeGet = () => SPFieldType.Lookup, TitleGet = () => DummyString }; ShimXContainer.AllInstances.AddObject = (instance, input) => { if (instance.NodeType == XmlNodeType.Element) { if (colsElement.Name.LocalName.Equals(((XElement)instance).Name.LocalName)) { actual = (XElement)input; } } ShimsContext.ExecuteWithoutShims(() => { instance.Add(input); }); }; // Act privateObject.Invoke( ConfigureColumnsMethodName, BindingFlags.Static | BindingFlags.NonPublic, new object[] { spWeb.Instance, string.Empty, headerElement, colsElement, string.Empty, defaultColumns, fields, spList.Instance }); // Assert actual.ShouldSatisfyAllConditions( () => actual.Attribute("Name").Value.ShouldBe($"{DummyString}Text"), () => actual.Attribute("Type").Value.ShouldBe("Icon"), () => actual.Attribute("IconAlign").Value.ShouldBe("Center"), () => actual.Attribute("Format").Value.ShouldBe("DummyString"), () => actual.Attribute("Visible").Value.ShouldBe("0")); }
public void ConfigureDefaultColumns_WhenCalled_ConfiguresDefaultColumns() { // Arrange const short startHour = 10; const short endHour = 20; const string ganttExclude = "ganttExclude"; const string layoutXmlString = @" <xmlcfg> <RightCols> <C Name=""ColName""/> </RightCols> </xmlcfg>"; var actual = default(XElement); var layoutXml = XDocument.Parse(layoutXmlString); var defaultColumns = new List <string>(); ShimUtils.GetRelatedGridTypeSPField = _ => "Icon"; ShimUtils.GetFormatSPField = _ => DummyString; ShimUtils.ToGridSafeFieldNameString = (input) => input; ShimMyWork.GetRelatedGridFormatStringStringSPFieldSPWeb = (_, _1, _2, _3) => DummyString; ShimExtensionMethods.ContainsFieldWithInternalNameSPFieldCollectionString = (_, __) => true; ShimSPFieldCollection.AllInstances.GetFieldByInternalNameString = (_, __) => new ShimSPField() { InternalNameGet = () => DummyString, TypeGet = () => SPFieldType.Lookup, TitleGet = () => DummyString }; ShimXContainer.AllInstances.AddObject = (instance, input) => { if (instance.NodeType == XmlNodeType.Element) { if (((XElement)instance).Name.LocalName.Equals("RightCols")) { actual = (XElement)input; } } ShimsContext.ExecuteWithoutShims(() => { instance.Add(input); }); }; // Act privateObject.Invoke( ConfigureDefaultColumnsMethodName, BindingFlags.Static | BindingFlags.NonPublic, new object[] { spList.Instance, string.Empty, string.Empty, spWeb.Instance, startHour, endHour, ganttExclude, layoutXml, defaultColumns }); // Assert actual.ShouldSatisfyAllConditions( () => actual.Attribute("Name").Value.ShouldBe("G"), () => actual.Attribute("GanttExclude").Value.ShouldBe(ganttExclude), () => actual.Attribute("GanttNewStart").Value.ShouldBe("1/1/2000 10:00"), () => actual.Attribute("GanttNewEnd").Value.ShouldBe("1/1/2000 20:00")); }
public void GetDataFromLists_WhenCalled_GetsData() { // Arrange const string query = "query"; const string expectedType = "expectedType"; const string expectedFormat = "expectedFormat"; var actualCount = 0; GetMyWorkParams.FieldTypes = new Dictionary <string, SPField>(); GetMyWorkParams.SelectedLists = new List <string>() { DummyString }; GetMyWorkParams.SelectedFields = new List <string>() { DummyString }; var actual = default(XElement); var result = new XDocument(); ShimsContext.ExecuteWithoutShims(() => { result.Add(new XElement("MyWork")); }); var dTable = new DataTable(); dTable.Columns.Add(ListIdColumn); dTable.Columns.Add(ItemIdColumn); var row = dTable.NewRow(); row[ListIdColumn] = guid.ToString().ToUpper(); row[ItemIdColumn] = 1.ToString(CultureInfo.InvariantCulture); dTable.Rows.Add(row); ShimMyWork.GetArchivedWebsGuid = _ => new List <Guid>() { Guid.NewGuid() }; ShimMyWork.GetWorkingOnSPWeb = _ => dTable; ShimMyWork.GetTypeAndFormatIDictionaryOfStringSPFieldStringStringOutStringOut = (IDictionary <string, SPField> fieldTypesParam, string selectedField, out string type, out string format) => { type = expectedType; format = expectedFormat; }; ShimXContainer.AllInstances.AddObject = (instance, element) => { if (instance.NodeType == XmlNodeType.Element) { if (((XElement)instance).Name.LocalName.Equals("MyWork")) { actual = (XElement)element; actualCount = actualCount + 1; return; } } ShimsContext.ExecuteWithoutShims(() => { instance.Add(element); }); }; // Act privateObj.Invoke( GetDataFromListsMethodName, BindingFlags.Static | BindingFlags.NonPublic, new object[] { result, query, spSite.Instance, spWeb.Instance }); // Assert actual.ShouldSatisfyAllConditions( () => actualCount.ShouldBe(1), () => actual.Name.ShouldBe("Item"), () => actual.Attribute("ID").Value.ShouldBe(DummyString), () => actual.Attribute("ListID").Value.ShouldBe(guid.ToString().ToUpper()), () => actual.Attribute("WorkingOn").Value.ToLower().ShouldBe("true")); }
public void PerformPostRegistrationSteps_WhenCalled_Updates() { // Arrange const bool updateExpected = true; var updateActual = false; var dataTableCount = 1; var data = CreateDataObject(); data.Add(CommentersColumn, Commenters); data.Add(IsMassOperation, true); data.Add(ActivityValue, new Activity() { Id = guid }); data.Add(AssociatedListItems, $"{guid.ToString()}|1,{guid.ToString()}|2"); data.Add(ThreadValue, new Thread() { Id = guid }); var userTable = new DataTable(); userTable.Columns.Add(UserIdColumn, typeof(int)); userTable.Columns.Add(RoleColumn, typeof(UserRole)); var row = userTable.NewRow(); row[UserIdColumn] = 1; row[RoleColumn] = UserRole.Commenter; userTable.Rows.Add(row); ShimSqlCommand.AllInstances.ExecuteScalar = sqlCommand => { if (sqlCommand.CommandText.StartsWith("SELECT Id FROM SS_Streams")) { return(guid); } else if (sqlCommand.CommandText.StartsWith("SELECT TOP (1) Role FROM SS_ThreadUsers")) { return(UserRole.Commenter); } return(UserRole.Commenter); }; ShimSqlCommand.AllInstances.ExecuteReader = sqlCommand => { var reader = new ShimSqlDataReader() { Close = () => { } }; return(reader); }; ShimDataTableExtensions.AsEnumerableDataTable = _ => { EnumerableRowCollection <DataRow> result = null; ShimsContext.ExecuteWithoutShims(() => { if (dataTableCount == 1) { dataTableCount++; result = CreateActivityTable().AsEnumerable(); } else { dataTableCount++; result = userTable.AsEnumerable(); } }); return(result); }; ShimDataRowCollection.AllInstances.CountGet = _ => 1; var args = new ProcessActivityEventArgs(ObjectKind.List, ActivityKind.CommentAdded, data, spWeb, streamManager, threadManager, activityManager); ShimSqlCommand.AllInstances.ExecuteNonQuery = sqlCommand => { if (sqlCommand.CommandText.Contains("INSERT INTO SS_AssociatedThreads") && sqlCommand.CommandText.Contains("UPDATE SS_AssociatedThreads")) { updateActual = true; } return(1); }; // Act privateObj.Invoke( PerformPostRegistrationStepsMethod, BindingFlags.Instance | BindingFlags.NonPublic, new object[] { args }); // Assert updateActual.ShouldBe(updateExpected); }
public void ProcessMyWork_WhenCalled_ProcessesWork() { // Arrange const string selectedField = "Author"; const string expectedType = "Boolean"; const string expectedFormat = "format"; const string expectedUniqueIdValue = "UniqueIdValue"; const string myWorkString = "MyWork"; var inputElement = new XDocument(); inputElement.Add(new XElement(myWorkString)); GetMyWorkParams.SelectedFields = new List <string>() { selectedField }; GetMyWorkParams.WorkTypes = new Dictionary <string, string>(); GetMyWorkParams.WorkSpaces = new Dictionary <string, string>(); var actual = new XElement(selectedField); var actualCount = 0; var dTable = new DataTable(); dTable.Columns.Add(IDColumn); dTable.Columns.Add(ListIdColumn); dTable.Columns.Add(selectedField); dTable.Columns.Add(WebIdColumn); dTable.Columns.Add(WorkingOnColumn); var row = dTable.NewRow(); row[IDColumn] = guid.ToString(); row[ListIdColumn] = guid.ToString().ToUpper(); row[selectedField] = true.ToString(); row[WebIdColumn] = guid.ToString(); row[WorkingOnColumn] = WorkingOnColumn; dTable.Rows.Add(row); ShimMyWork.GetListNameFromDbGuidGuidSPWeb = (_, _1, _2) => expectedUniqueIdValue; ShimMyWork.GetWorkspaceNameFromDbGuidString = (_, _1) => expectedUniqueIdValue; ShimMyWork.GetTypeAndFormatIDictionaryOfStringSPFieldStringStringOutStringOut = (IDictionary <string, SPField> fieldTypesParam, string selectedFieldParam, out string type, out string format) => { type = expectedType; format = expectedFormat; }; ShimXContainer.AllInstances.AddObject = (instance, element) => { if (instance.NodeType == XmlNodeType.Element) { if (((XElement)instance).Name.LocalName.Equals(myWorkString)) { actual = (XElement)element; actualCount = actualCount + 1; } } ShimsContext.ExecuteWithoutShims(() => { instance.Add(element); }); }; // Act privateObj.Invoke( ProcessMyWorkMethodName, BindingFlags.Static | BindingFlags.NonPublic, new object[] { dTable, spSite.Instance, spWeb.Instance, inputElement }); // Assert actual.ShouldSatisfyAllConditions( () => actualCount.ShouldBe(1), () => actual.Name.ShouldBe("Item"), () => actual.Attribute("ID").Value.ShouldBe(guid.ToString().ToUpper()), () => actual.Attribute("ListID").Value.ShouldBe(guid.ToString().ToUpper()), () => actual.Attribute("WorkingOn").Value.ShouldBe(WorkingOnColumn), () => actual.Element("Fields").Elements("Field").ElementAt(0).Attribute("Name").Value.ShouldBe("AuthorID"), () => actual.Element("Fields").Elements("Field").ElementAt(1).Attribute("Name").Value.ShouldBe(selectedField)); }
public void CreateChildControls_OnValidCall_UpdateFields() { // Arrange SetupShimsForHttpRequest(); SetupShimsForSqlClient(); SetupShimsForSharePoint(); _cookies.Add(new HttpCookie("EPMLiveTSPeriod")); ShimCoreFunctions.getConfigSettingSPWebString = (_, name) => { if (name.Equals("EPMLiveTSAllowNotes")) { return(bool.TrueString); } if (name.Equals("EPMLiveDaySettings")) { return(string.Join("|", Enumerable.Repeat <string>(bool.TrueString, 30))); } return(DummyString); }; ShimAct.AllInstances.CheckOnlineFeatureLicenseActFeatureStringSPSite = (_, _2, _3, _4) => 0; ShimStringDictionary.AllInstances.ContainsKeyString = (sd, key) => { if (key.Equals("EPMLiveResourceURL")) { return(true); } return(ShimsContext.ExecuteWithoutShims(() => sd.ContainsKey(key))); }; ShimStringDictionary.AllInstances.ItemGetString = (sd, key) => { if (key.Equals("EPMLiveResourceURL")) { return(DummyString); } return(ShimsContext.ExecuteWithoutShims(() => sd[key])); }; ShimTemplateControl.AllInstances.LoadControlString = (_, name) => new ToolBarFake(); ShimPeopleEditor.Constructor = _ => { }; var firstTimeCall = true; ShimTemplateBasedControl.AllInstances.ControlsGet = _ => { if (firstTimeCall) { firstTimeCall = false; return(new ControlCollection(new Control()) { new Control { Controls = { new HyperLink { ID = "hlGanttScrollTo" }, new NewMenu(), new ActionsMenu(), new Label { ID = "lblFilter" } } } }); } return(new ControlCollection(new Control())); }; ShimToolBarMenuButton.AllInstances.AddMenuItemStringStringStringStringStringString = (_, _2, _3, _4, _5, _6, _7) => new MenuItemTemplate(); ShimToolBarMenuButton.AllInstances.AddMenuItemSeparator = _ => { }; ShimToolBarMenuButton.AllInstances.GetMenuItemString = (_, __) => new MenuItemTemplate(); ShimPage.AllInstances.IsPostBackGet = _ => true; ShimPart.AllInstances.ControlsGet = _ => new ControlCollection(new Control()); ShimControlCollection.AllInstances.ItemGetInt32 = (_, __) => new Control(); ShimToolBarMenuButton.AllInstances.MenuControlGet = _ => new ShimMenu().Instance; ShimControlCollection.AllInstances.AddAtInt32Control = (_, _2, _3) => { }; // Act PrivateObject.Invoke("CreateChildControls"); var arrPeriods = Get <SortedList>(Periods); // Assert this.ShouldSatisfyAllConditions( () => { var timesheetMenu = Get <TimesheetMenu>("_timeSheetMenu"); timesheetMenu.Text.ShouldContain("Actions"); timesheetMenu.TemplateName.ShouldContain("ToolbarPMMenu"); }, () => arrPeriods.Count.ShouldBe(1), () => arrPeriods.ContainsKey(DummyInt).ShouldBeTrue()); }