protected void SetUp() { this.excelRowParser = MockRepository.GenerateStub <IExcelRowParser>(); this.excelRowParser .Stub(rowParser => rowParser.ParseRows(Arg <List <ExcelColumn> > .Is.Anything, Arg <ISheet> .Is.Anything, Arg <CellRangeAddress> .Is.Anything)) .Return(new List <ExcelRow>() { new ExcelRow() { }, new ExcelRow(), new ExcelRow() }); this.excelTableParser = new ExcelTableParser(this.excelRowParser); var excelBytes = TestUtility.RetrieveMockExcelBytes("MockExcel1.xlsx"); MemoryStream tableStream = new MemoryStream(excelBytes); this.workbook = new XSSFWorkbook(tableStream); this.name = workbook.GetName("TableId_Table1"); }
public async Task SystemReader_ForResponseWithIncompleteExtendedProperties_CreatesCorrectObject() { ISystem result = await TestUtility.ExecuteObjectReaderByTypeAsync <ISystem>(SYSTEM_RESPONSE_WITH_MINIMALEXTENDEDDATA); ExtendedDataConfiguration secondDataConfig = result.ExtendedDataConfig[1]; ExtendedDataConfiguration thirdDataConfig = result.ExtendedDataConfig[2]; Assert.Multiple(() => { Assert.That(result.ExtendedDataConfig, Has.Exactly(4).Items); Assert.That(result.ExtendedDataConfig.First().Label, Is.EqualTo("DC-1 Voltage")); Assert.That(result.ExtendedDataConfig.First().Unit, Is.EqualTo("V")); Assert.That(secondDataConfig.Label, Is.EqualTo("DC-2 Voltage")); Assert.That(secondDataConfig.Unit, Is.Empty); Assert.That(thirdDataConfig.Label, Is.Empty); Assert.That(thirdDataConfig.Unit, Is.EqualTo("°C")); Assert.That(result.ExtendedDataConfig.Last().Label, Is.EqualTo("DC-1 Power (2x13x290Wp)")); Assert.That(result.ExtendedDataConfig.Last().Unit, Is.EqualTo("W")); Assert.That(result.MonthlyGenerationEstimates[PVMonth.October], Is.EqualTo(159)); Assert.That(result.MonthlyGenerationEstimates[PVMonth.August], Is.EqualTo(354)); Assert.That(result.MonthlyConsumptionEstimates[PVMonth.February], Is.EqualTo(350)); Assert.That(result.MonthlyConsumptionEstimates[PVMonth.August], Is.EqualTo(175)); }); }
public void Dependant_FKConstraintUpdate() { using (var container = new RhetosTestContainer()) { var repository = container.Resolve <Common.DomRepository>(); var s1 = new TestPolymorphic.Simple1 { ID = Guid.NewGuid(), Name = "a", Days = 1 }; repository.TestPolymorphic.Simple1.Insert(new[] { s1 }); var dep = new TestPolymorphic.Dependant { ID = Guid.NewGuid(), Name = "dep", SimpleBaseID = s1.ID }; repository.TestPolymorphic.Dependant.Insert(new[] { dep }); dep.SimpleBaseID = Guid.NewGuid(); var ex = TestUtility.ShouldFail <Rhetos.UserException>( () => repository.TestPolymorphic.Dependant.Update(new[] { dep }), "It is not allowed to edit the record."); TestUtility.AssertContains(ex.ToString(), new[] { "Dependant", "FOREIGN KEY", "SimpleBase" }, "Expected inner SQL exception"); } }
public void SplitBatches() { var tests = new Dictionary <string, string[]> { { "111\r\nGO\r\n222", new[] { "111", "222" } }, // Simple { "111\nGO\n222", new[] { "111", "222" } }, // UNIX EOL { "111\r\ngo\r\n222", new[] { "111", "222" } }, // Case insensitive { "111\r\n GO\t\t\t\r\n222", new[] { "111", "222" } }, // Spaces and tabs { "GO\r\n111\r\nGO\r\n222\r\nGO", new[] { "111", "222" } }, // Beginning and ending with GO { "111\r\nGO\r\n222\r\nGO ", new[] { "111", "222" } }, // Beginning and ending with GO { "\r\n GO \r\n\r\n111\r\nGO\r\n222\r\nGO \r\nGO \r\n\r\n", new[] { "111", "222" } }, // Beginning and ending with GO { "111\r\n222\r\nGO\r\n333\r\n444", new[] { "111\r\n222", "333\r\n444" } }, // Multi-line batches { "111\n222\nGO\n333\n444", new[] { "111\n222", "333\n444" } }, // Multi-line batches, UNIX EOL { "111\r\nGO GO\r\n GO \r\n go \r\n222\r\ngoo\r\ngo", new[] { "111\r\nGO GO", "222\r\ngoo" } }, // Complex { "", new string[] { } }, // Empty batches { "GO", new string[] { } }, // Empty batches { "\r\n \r\n GO \r\n \r\n", new string[] { } } // Empty batches }; foreach (var test in tests) { Assert.AreEqual(TestUtility.Dump(test.Value), TestUtility.Dump(SqlUtility.SplitBatches(test.Key)), "Input: " + test.Key); } }
public void SortAndPaginateKeepsOriginalQueryableType() { var readCommand = new ReadCommandInfo { OrderByProperties = new[] { new OrderByProperty { Property = "Name", Descending = true } }, Skip = 1, Top = 2, }; IQueryable <object> query = new[] { "a", "b", "c", "d" }.AsQueryable().Select(name => new C { Name = name }); Console.WriteLine(query.GetType()); Assert.IsTrue(query is IQueryable <C>); var result = GenericFilterHelper.SortAndPaginate <object>(query, readCommand); Assert.AreEqual("c, b", TestUtility.Dump(result, item => ((C)item).Name)); Console.WriteLine(result.GetType()); Assert.IsTrue(result is IQueryable <C>); }
public void ExecuteSql_SimpleSqlError() { TestUtility.ShouldFail(() => NewSqlExecuter().ExecuteSql(new[] { "raiserror('aaa', 16, 100)" }), "aaa", "16", "100"); }
public void InheritingRowPermissions() { InsertCurrentPrincipal(); // Not related to row permissions. // Insert the test data (server code bypasses row permissions): using (var scope = TestScope.Create()) { var repository = scope.Resolve <Common.DomRepository>(); var context = scope.Resolve <Common.ExecutionContext>(); repository.DemoRowPermissions2.DocumentApproval.Delete(repository.DemoRowPermissions2.DocumentApproval.Query()); repository.DemoRowPermissions2.DocumentComment.Delete(repository.DemoRowPermissions2.DocumentComment.Query()); repository.DemoRowPermissions2.Document.Delete(repository.DemoRowPermissions2.Document.Query()); repository.DemoRowPermissions2.RegionSupervisor.Delete(repository.DemoRowPermissions2.RegionSupervisor.Query()); repository.DemoRowPermissions2.Employee.Delete(repository.DemoRowPermissions2.Employee.Query()); repository.DemoRowPermissions2.Division.Delete(repository.DemoRowPermissions2.Division.Query()); repository.DemoRowPermissions2.Region.Delete(repository.DemoRowPermissions2.Region.Query()); var reg3 = new DemoRowPermissions2.Region { Name = "reg3" }; repository.DemoRowPermissions2.Region.Insert(new[] { reg3 }); var div1 = new DemoRowPermissions2.Division { Name = "div1" }; var div2 = new DemoRowPermissions2.Division { Name = "div2" }; var div3 = new DemoRowPermissions2.Division { Name = "div3", RegionID = reg3.ID }; repository.DemoRowPermissions2.Division.Insert(new[] { div1, div2, div3 }); // The current user: var emp1 = new DemoRowPermissions2.Employee { UserName = context.UserInfo.UserName, DivisionID = div1.ID }; var emp2 = new DemoRowPermissions2.Employee { UserName = "******" }; repository.DemoRowPermissions2.Employee.Insert(new[] { emp1, emp2 }); var sup3 = new DemoRowPermissions2.RegionSupervisor { EmployeeID = emp1.ID, RegionID = reg3.ID }; repository.DemoRowPermissions2.RegionSupervisor.Insert(new[] { sup3 }); // The current user can access doc1, because it's in the same division: var doc1 = new DemoRowPermissions2.Document { Title = "doc1", DivisionID = div1.ID }; // The current user cannot access doc2: var doc2 = new DemoRowPermissions2.Document { Title = "doc2", DivisionID = div2.ID }; // The current user can access doc3, because it's in the region he supervises: var doc3 = new DemoRowPermissions2.Document { Title = "doc3", DivisionID = div3.ID }; repository.DemoRowPermissions2.Document.Insert(new[] { doc1, doc2, doc3 }); // The current user can access com1, because it is related to his document: var com1 = new DemoRowPermissions2.DocumentComment { DocumentID = doc1.ID, Comment = "com1" }; // The current user cannot access com2: var com2 = new DemoRowPermissions2.DocumentComment { DocumentID = doc2.ID, Comment = "com2" }; repository.DemoRowPermissions2.DocumentComment.Insert(new[] { com1, com2 }); // The current user can access app1, because it is related to his document: var app1 = new DemoRowPermissions2.DocumentApproval { ID = doc1.ID, ApprovedByID = emp1.ID, Note = "app1" }; // The current user cannot access app2: var app2 = new DemoRowPermissions2.DocumentApproval { ID = doc2.ID, ApprovedByID = emp1.ID, Note = "app2" }; // The current user can read app3, but cannot write it, because it is approved by a different user: var app3 = new DemoRowPermissions2.DocumentApproval { ID = doc3.ID, ApprovedByID = emp2.ID, Note = "app3" }; repository.DemoRowPermissions2.DocumentApproval.Insert(new[] { app1, app2, app3 }); scope.CommitAndClose(); } // Test the current user's row permissions: // The test will not execute client requests, but simply directly check the row permissions filters. using (var scope = TestScope.Create()) { var allowedReadBrowse = scope.Resolve <GenericRepository <DemoRowPermissions2.DocumentBrowse> >() .Load <Common.RowPermissionsReadItems>(); Assert.AreEqual("doc1, doc3", TestUtility.DumpSorted(allowedReadBrowse, browse => browse.Title)); var allowedReadComment = scope.Resolve <GenericRepository <DemoRowPermissions2.DocumentComment> >() .Load <Common.RowPermissionsReadItems>(); Assert.AreEqual("com1", TestUtility.DumpSorted(allowedReadComment, comment => comment.Comment)); var allowedReadApproval = scope.Resolve <GenericRepository <DemoRowPermissions2.DocumentApproval> >() .Load <Common.RowPermissionsReadItems>(); Assert.AreEqual("app1, app3", TestUtility.DumpSorted(allowedReadApproval, approval => approval.Note)); var allowedWriteApproval = scope.Resolve <GenericRepository <DemoRowPermissions2.DocumentApproval> >() .Load <Common.RowPermissionsWriteItems>(); Assert.AreEqual("app1", TestUtility.DumpSorted(allowedWriteApproval, approval => approval.Note)); var allowedReadInfo = scope.Resolve <GenericRepository <DemoRowPermissions2.DocumentInfo> >() .Load <Common.RowPermissionsReadItems>(); Assert.AreEqual("doc1_2, doc3_2", TestUtility.DumpSorted(allowedReadInfo, info => info.Title2)); } }
public void ReadGenericFilter_QueryVsEnum() { var entityRepos = new GenericFilterRepository(); var genericRepos = NewRepos(entityRepos); Assert.AreEqual("IQ: ql1, ql2", TypeAndNames(genericRepos.Read(new[] { new FilterCriteria { Filter = typeof(QueryLoaderFilter).FullName } }, preferQuery: true))); Assert.AreEqual("QP", entityRepos.Log); entityRepos._log.Clear(); // For a single filter, loader is preferred: Assert.AreEqual("IL: ql1, ql2", TypeAndNames(genericRepos.Load(new[] { new FilterCriteria { Filter = typeof(QueryLoaderFilter).FullName } }))); Assert.AreEqual("LP", entityRepos.Log); entityRepos._log.Clear(); // For multiple filters, queryable loader (QP) is preferred: Assert.AreEqual("IL: ql1", TypeAndNames(genericRepos.Load(new[] { new FilterCriteria { Filter = typeof(QueryLoaderFilter).FullName }, new FilterCriteria { Property = "Name", Operation = "Contains", Value = "1" } }))); Assert.AreEqual("QP", entityRepos.Log); entityRepos._log.Clear(); // Using given order of filters. There is no loader for property filter (expression). Assert.AreEqual("IL: a1_qf, b1_qf", TypeAndNames(genericRepos.Load(new[] { new FilterCriteria { Property = "Name", Operation = "Contains", Value = "1" }, new FilterCriteria { Filter = typeof(QueryLoaderFilter).FullName }, }))); Assert.AreEqual("Q, QF, X", entityRepos.Log); entityRepos._log.Clear(); // When only enumerable loader is available, use enumerable filter: Assert.AreEqual("IL: lp1_ef, lp2_ef", TypeAndNames(genericRepos.Load(new[] { new FilterCriteria { Filter = typeof(LoaderParameter).FullName }, new FilterCriteria { Filter = typeof(QueryLoaderFilter).FullName }, }))); Assert.AreEqual("LP, EF", entityRepos.Log); entityRepos._log.Clear(); // Trying to use queryable filter (property filter) on enumerable filtered items: Assert.AreEqual("IL: lp1_ef", TypeAndNames(genericRepos.Load(new[] { new FilterCriteria { Filter = typeof(LoaderParameter).FullName }, new FilterCriteria { Filter = typeof(QueryLoaderFilter).FullName }, new FilterCriteria { Property = "Name", Operation = "Contains", Value = "1" } })), "This is not a required feature. Property filter (as navigable queryable filter) does not need to work (and maybe it shouldn't) on materialized lists!"); Assert.AreEqual("LP, EF", entityRepos.Log); entityRepos._log.Clear(); // Trying to use a loader after the first position in generic filter should fail. // REMOVE THIS TEST after (if ever) automatic FilterCriteria reordering is implemented. TestUtility.ShouldFail(() => TypeAndNames(genericRepos.Load(new[] { new FilterCriteria { Filter = typeof(QueryLoaderFilter).FullName }, new FilterCriteria { Filter = typeof(LoaderParameter).FullName }, })), "SimpleEntity", "does not implement a filter", "LoaderParameter", "Try reordering"); // Since there is a loader implemented, reordering parameters might help. entityRepos._log.Clear(); // Enumerable filter after enumerable loader Assert.AreEqual("IL: lp1_ef, lp2_ef", TypeAndNames(genericRepos.Load(new[] { new FilterCriteria { Filter = typeof(LoaderParameter).FullName }, new FilterCriteria { Filter = typeof(EnumerableFilter).FullName }, }))); Assert.AreEqual("LP, EF", entityRepos.Log); entityRepos._log.Clear(); // Enumerable filter without a parametrized loader (inefficient) Assert.AreEqual("IL: a1_ef, a2_ef, b1_ef, b2_ef", TypeAndNames(genericRepos.Load(new[] { new FilterCriteria { Filter = typeof(EnumerableFilter).FullName }, }))); Assert.AreEqual("Q, X, EF", entityRepos.Log); entityRepos._log.Clear(); // Enumerable filter on a query (inefficient) Assert.AreEqual("IL: ql1_ef, ql2_ef", TypeAndNames(genericRepos.Load(new[] { new FilterCriteria { Filter = typeof(QueryLoaderFilter).FullName }, new FilterCriteria { Filter = typeof(EnumerableFilter).FullName }, }))); Assert.AreEqual("QP, EF", entityRepos.Log); entityRepos._log.Clear(); }
public void CanRoundtripW3dFiles() { InstalledFilesTestData.ReadFiles(".w3d", _output, entry => { switch (Path.GetFileName(entry.FilePath)) { case "UISabotr_idel.w3d": case "UISabotr_Jump.w3d": case "UISabotr_Left.w3d": case "UISabotr_Right.w3d": case "UISabotr_Up.w3d": case "cusheep_grza.w3d": case "gbmtwalld.w3d": case "gbmtwalldramp.w3d": case "gbmtwalle.w3d": case "bbbags.w3d": case "cuwyrm_cld_skl.w3d": case "cuwyrm_cld_skn.w3d": case "gugandalfcrstl.w3d": case "guhbtshfb_cinb.w3d": case "guhbtshfb_cinc.w3d": case "kbpostgaten_al.w3d": case "kbpostgaten_am.w3d": case "lwbanhfllbst.w3d": case "lwbanhnazgul.w3d": case "lwbanhwtchkng.w3d": case "psupplies04.w3d": case "readonly-0-rev-2-lwbanhwitchk.w3d": case "wbcave_d2a.w3d": case "wbcave_d2c.w3d": return; // Corrupt, or unreferenced and contain chunks that don't exist elsewhere. } var w3dFile = TestUtility.DoRoundtripTest( () => entry.Open(), stream => W3dFile.FromStream(stream, entry.FilePath), (w3d, stream) => w3d.WriteTo(stream), true); foreach (var mesh in w3dFile.GetMeshes()) { Assert.Equal((int)mesh.Header.NumVertices, mesh.Vertices.Items.Length); Assert.Equal((int)mesh.Header.NumTris, mesh.Triangles.Items.Length); if (mesh.Influences != null) { Assert.Equal(mesh.Vertices.Items.Length, mesh.Influences.Items.Length); } Assert.Equal((int)mesh.MaterialInfo.PassCount, mesh.MaterialPasses.Count); Assert.Equal((int)mesh.MaterialInfo.ShaderCount, mesh.Shaders?.Items.Count ?? 0); Assert.Equal(mesh.Vertices.Items.Length, mesh.ShadeIndices.Items.Length); if (mesh.VertexMaterials != null) { Assert.True(mesh.VertexMaterials.Items.Count <= 16); foreach (var material in mesh.VertexMaterials.Items) { Assert.Equal(W3dVertexMaterialFlags.None, material.Info.Attributes); Assert.Equal(0, material.Info.Translucency); } } Assert.True(mesh.MaterialPasses.Count <= 3); Assert.True(mesh.ShaderMaterials == null || mesh.ShaderMaterials.Items.Count == 1); if (mesh.ShaderMaterials != null) { Assert.Null(mesh.VertexMaterials); Assert.Single(mesh.MaterialPasses); } foreach (var materialPass in mesh.MaterialPasses) { Assert.True(materialPass.Dcg == null || materialPass.Dcg.Items.Length == mesh.Vertices.Items.Length); Assert.Null(materialPass.Dig); Assert.Null(materialPass.Scg); Assert.True(materialPass.TextureStages.Count <= 2); foreach (var textureStage in materialPass.TextureStages) { Assert.True(textureStage.TexCoords == null || textureStage.TexCoords.Items.Length == mesh.Header.NumVertices); Assert.Null(textureStage.PerFaceTexCoordIds); var numTextureIds = textureStage.TextureIds.Items.Count; Assert.True(numTextureIds == 1 || numTextureIds == mesh.Header.NumTris); } Assert.True((materialPass.ShaderIds != null && materialPass.VertexMaterialIds != null && materialPass.TexCoords == null) || materialPass.ShaderMaterialIds != null); if (materialPass.ShaderIds != null) { var numShaderIds = materialPass.ShaderIds.Items.Length; Assert.True(numShaderIds == 1 || numShaderIds == mesh.Header.NumTris); } if (materialPass.VertexMaterialIds != null) { var numVertexMaterialIds = materialPass.VertexMaterialIds.Items.Length; Assert.True(numVertexMaterialIds == 1 || numVertexMaterialIds == mesh.Header.NumVertices); } Assert.True(materialPass.ShaderMaterialIds == null || materialPass.ShaderMaterialIds.Items[0] == 0); } if (mesh.Textures != null) { Assert.True(mesh.Textures.Items.Count <= 29); } } foreach (var animation in w3dFile.GetCompressedAnimations()) { foreach (var channel in animation.TimeCodedChannels) { switch (channel.ChannelType) { case W3dAnimationChannelType.UnknownBfme: Assert.Equal(1, channel.VectorLength); break; } } } }); }
private static void AssertData(Common.DomRepository repository, string expected) { Assert.AreEqual(expected, TestUtility.DumpSorted(repository.TestInvalidData.Simple.Query(), item => item.Name)); }
public void AutoFilter_Where() { using (var container = new RhetosTestContainer()) { var repository = container.Resolve <Common.DomRepository>(); repository.TestFilter.AutoFilter3.Delete(repository.TestFilter.AutoFilter3.Query()); repository.TestFilter.AutoFilter3.Insert( new[] { "a1", "a2", "b1", "b2" } .Select(name => new TestFilter.AutoFilter3 { Name = name })); var readAll = new ReadCommandInfo { ReadRecords = true, OrderByProperties = new[] { new OrderByProperty { Property = "Name" } }, }; var read10 = new ReadCommandInfo { ReadRecords = true, OrderByProperties = new[] { new OrderByProperty { Property = "Name" } }, Top = 10, }; var readFiltered = new ReadCommandInfo { ReadRecords = true, OrderByProperties = new[] { new OrderByProperty { Property = "Name" } }, Filters = new[] { new FilterCriteria { Filter = "TestFilter.WithA" } }, }; var readFiltered10 = new ReadCommandInfo { ReadRecords = true, OrderByProperties = new[] { new OrderByProperty { Property = "Name" } }, Top = 10, Filters = new[] { new FilterCriteria { Filter = "TestFilter.WithA" } }, }; TestClientRead <TestFilter.AutoFilter3>(container, "a1, a2, b1, b2", item => item.Name, readAll); TestClientRead <TestFilter.AutoFilter3>(container, "a1, a2", item => item.Name, read10); TestClientRead <TestFilter.AutoFilter3>(container, "a1, a2", item => item.Name, readFiltered); TestClientRead <TestFilter.AutoFilter3>(container, "a1, a2", item => item.Name, readFiltered10); Assert.AreEqual("", TestUtility.Dump(readAll.Filters.Select(f => f.Filter))); Assert.AreEqual("TestFilter.WithA", TestUtility.Dump(read10.Filters.Select(f => f.Filter))); Assert.AreEqual("TestFilter.WithA", TestUtility.Dump(readFiltered.Filters.Select(f => f.Filter))); Assert.AreEqual("TestFilter.WithA", TestUtility.Dump(readFiltered10.Filters.Select(f => f.Filter))); // To make sure the filter is not duplicated. } }
public void InheritFrom() { using (var container = new RhetosTestContainer()) { Parent pReadAllow = new Parent() { ID = Guid.NewGuid(), value = 190 }, pReadDeny = new Parent() { ID = Guid.NewGuid(), value = 90 }, pWriteAllow = new Parent() { ID = Guid.NewGuid(), value = 60 }, pWriteDeny = new Parent() { ID = Guid.NewGuid(), value = 160 }; Child cParentReadAllow = new Child() { ID = Guid.NewGuid(), MyParentID = pReadAllow.ID, value = 5 }, cParentReadDeny = new Child() { ID = Guid.NewGuid(), MyParentID = pReadDeny.ID, value = 6 }, cParentWriteAllow = new Child() { ID = Guid.NewGuid(), MyParentID = pWriteAllow.ID, value = 7 }, cParentWriteDeny = new Child() { ID = Guid.NewGuid(), MyParentID = pWriteDeny.ID, value = 8 }; var repositories = container.Resolve <Common.DomRepository>(); var parentRepo = repositories.TestRowPermissions.Parent; var childRepo = repositories.TestRowPermissions.Child; var babyRepo = repositories.TestRowPermissions.Baby; var browseRepo = repositories.TestRowPermissions.ParentBrowse; babyRepo.Delete(babyRepo.All()); childRepo.Delete(childRepo.All()); parentRepo.Delete(parentRepo.All()); parentRepo.Insert(new Parent[] { pReadAllow, pReadDeny, pWriteAllow, pWriteDeny }); childRepo.Insert(new Child[] { cParentReadAllow, cParentReadDeny, cParentWriteAllow, cParentWriteDeny }); { var childAllowRead = childRepo.Filter(childRepo.Query(), new Common.RowPermissionsReadItems()).ToList(); Assert.AreEqual("5, 8", TestUtility.DumpSorted(childAllowRead, a => a.value.ToString())); } { var childAllowWrite = childRepo.Filter(childRepo.Query(), new Common.RowPermissionsWriteItems()).ToList(); Assert.AreEqual("6, 7", TestUtility.DumpSorted(childAllowWrite, a => a.value.ToString())); } // Test combination with rule on child Child cCombo = new Child() { ID = Guid.NewGuid(), MyParentID = pReadAllow.ID, value = 3 }; childRepo.Insert(new Child[] { cCombo }); { var childAllowRead = childRepo.Filter(childRepo.Query(), new Common.RowPermissionsReadItems()).ToList(); Assert.IsTrue(!childAllowRead.Select(a => a.value).Contains(3)); } // Test double inheritance, only write deny case Baby bDenyWrite = new Baby() { ID = Guid.NewGuid(), MyParentID = cParentWriteDeny.ID }; babyRepo.Insert(new Baby[] { bDenyWrite }); { Assert.AreEqual(1, babyRepo.Query().Count()); var babyDenyWrite = babyRepo.Filter(babyRepo.Query(), new Common.RowPermissionsWriteItems()).ToList(); Assert.AreEqual(0, babyDenyWrite.Count()); } // Test inheritance form base data structure { var allowedRead = browseRepo.Filter(browseRepo.Query(), new Common.RowPermissionsReadItems()).ToList(); Assert.AreEqual("160, 190", TestUtility.DumpSorted(allowedRead, item => item.Value2)); var allowedWrite = browseRepo.Filter(browseRepo.Query(), new Common.RowPermissionsWriteItems()).ToList(); Assert.AreEqual("60, 90", TestUtility.DumpSorted(allowedWrite, item => item.Value2)); } } }
protected async Task SendWithEventDataBatch(string partitionKey = null) { const int MinimumNumberOfMessagesToSend = 1000; var receivers = new List <PartitionReceiver>(); // Create partition receivers starting from the end of the stream. TestUtility.Log("Discovering end of stream on each partition."); foreach (var partitionId in this.PartitionIds) { var lastEvent = await this.EventHubClient.GetPartitionRuntimeInformationAsync(partitionId); receivers.Add(this.EventHubClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, partitionId, EventPosition.FromOffset(lastEvent.LastEnqueuedOffset))); } try { // Start receicing messages now. var receiverTasks = new List <Task <List <EventData> > >(); foreach (var receiver in receivers) { receiverTasks.Add(ReceiveAllMessages(receiver)); } // Create initial batcher. EventDataBatch batcher = null; // Exercise both CreateBatch overloads. if (partitionKey != null) { batcher = this.EventHubClient.CreateBatch(new BatchOptions() { PartitionKey = partitionKey }); } else { batcher = this.EventHubClient.CreateBatch(); } // We will send a thousand messages where each message is 1K. var totalSent = 0; var rnd = new Random(); TestUtility.Log($"Starting to send."); do { // Send random body size. var ed = new EventData(new byte[rnd.Next(0, 1024)]); if (!batcher.TryAdd(ed)) { await this.EventHubClient.SendAsync(batcher); totalSent += batcher.Count; TestUtility.Log($"Sent {batcher.Count} messages in the batch."); // Create new batcher. // Exercise CreateBatch with partition key only where PartitionKey might be null. batcher = this.EventHubClient.CreateBatch(new BatchOptions() { PartitionKey = partitionKey }); } } while (totalSent < MinimumNumberOfMessagesToSend); // Send the rest of the batch if any. if (batcher.Count > 0) { await this.EventHubClient.SendAsync(batcher); totalSent += batcher.Count; TestUtility.Log($"Sent {batcher.Count} messages in the batch."); } TestUtility.Log($"{totalSent} messages sent in total."); var pReceived = await Task.WhenAll(receiverTasks); var totalReceived = pReceived.Sum(p => p.Count); TestUtility.Log($"{totalReceived} messages received in total."); // All messages received? Assert.True(totalReceived == totalSent, $"Sent {totalSent}, but received {totalReceived} messages."); if (partitionKey != null) { // Partition key is set then we expect all messages from the same partition. Assert.True(pReceived.Count(p => p.Count > 0) == 1, "Received messsages from multiple partitions."); // Find target partition. var targetPartition = pReceived.Single(p => p.Count > 0); // Validate partition key is delivered on all messages. Assert.True(!targetPartition.Any(p => p.SystemProperties.PartitionKey != partitionKey), "Identified at least one event with a different partition key value."); } } finally { await Task.WhenAll(receivers.Select(r => r.CloseAsync())); } }
public void Can_Generate_SelectSql_With_Foreign_Tables() { const string expectedSql = @" SELECT j.[Id], j.[OrganizationId], j.[JobStatusId], j.[JobCategoryId], j.[Code], j.[CustomerId], j.[StartDate], j.[EndDate], j.[DueDate], j.[Version], j.[UtcCreated], j.[UtcUpdated], j.[Uid], js.[Name] AS [JobStatus], c.[CustomerTypeId] AS [CustomerTypeId], c.[LastName] AS [LastName], c.[FirstName] AS [FirstName], c.[OtherName] AS [OtherName] ,[TotalCount] FROM [dbo].[Job] j JOIN [dbo].[JobStatus] js ON j.[JobStatusId] = js.[Id] JOIN [dbo].[Customer] c ON j.[CustomerId] = c.[Id] CROSS APPLY( SELECT COUNT(*) TotalCount FROM [dbo].[Job] j JOIN [dbo].[JobStatus] js ON j.[JobStatusId] = js.[Id] JOIN [dbo].[Customer] c ON j.[CustomerId] = c.[Id] WHERE (j.[OrganizationId] = @orgid) )[Count] WHERE (j.[OrganizationId] = @orgid) ORDER BY 17 OFFSET @offset ROWS FETCH NEXT @pageSize ROWS ONLY "; var sqlTemplate = $@" SELECT {SqlPatterns.Columns} ,[TotalCount] FROM {SqlPatterns.FromTable} {SqlPatterns.Join} CROSS APPLY( SELECT COUNT(*) TotalCount FROM {SqlPatterns.FromTable} {SqlPatterns.Join} WHERE {SqlPatterns.Where} )[Count] WHERE {SqlPatterns.Where} ORDER BY {SqlPatterns.OrderBy} OFFSET @offset ROWS FETCH NEXT @pageSize ROWS ONLY "; var builder = new SelectSqlBuilder(); var orgId = 1000; builder.AddTemplate(sqlTemplate); builder.AddColumns <JobWithCustomerAndStatusPoco>(); builder.AddJoin <JobWithCustomerAndStatusPoco>(); builder.AddConditions <JobWithCustomerAndStatusPoco>(i => i.OrganizationId == orgId); builder.AddOrderBy <JobWithCustomerAndStatusPoco>("FirstName", false); builder.AddContains <JobWithCustomerAndStatusPoco>("test"); var sql = builder.GetSql(); Assert.Equal(TestUtility.NeutralizeString(sql), TestUtility.NeutralizeString(expectedSql)); }
public async Task Test_TraktShowsModule_GetShowCollectionProgress_With_Hidden() { TraktClient client = TestUtility.GetOAuthMockClient( $"{GET_SHOW_COLLECTION_PROGRESS_URI}?hidden={ProgressHidden}", SHOW_COLLECTION_PROGRESS_JSON); TraktResponse <ITraktShowCollectionProgress> response = await client.Shows.GetShowCollectionProgressAsync(SHOW_ID, PROGRESS_HIDDEN); response.Should().NotBeNull(); response.IsSuccess.Should().BeTrue(); response.HasValue.Should().BeTrue(); response.Value.Should().NotBeNull(); ITraktShowCollectionProgress responseValue = response.Value; responseValue.Aired.Should().Be(6); responseValue.Completed.Should().Be(6); responseValue.LastCollectedAt.Should().Be(DateTime.Parse("2015-03-21T19:03:58.000Z").ToUniversalTime()); responseValue.Seasons.Should().NotBeNull(); responseValue.Seasons.Should().HaveCount(1); ITraktSeasonCollectionProgress[] seasons = responseValue.Seasons.ToArray(); seasons[0].Number.Should().Be(1); seasons[0].Aired.Should().Be(6); seasons[0].Completed.Should().Be(6); seasons[0].Episodes.Should().NotBeNull(); seasons[0].Episodes.Should().HaveCount(6); ITraktEpisodeCollectionProgress[] episodes = seasons[0].Episodes.ToArray(); episodes[0].Number.Should().Be(1); episodes[0].Completed.Should().BeTrue(); episodes[0].CollectedAt.Should().Be(DateTime.Parse("2015-03-21T19:03:58.000Z").ToUniversalTime()); episodes[1].Number.Should().Be(2); episodes[1].Completed.Should().BeTrue(); episodes[1].CollectedAt.Should().Be(DateTime.Parse("2015-03-21T19:03:58.000Z").ToUniversalTime()); episodes[2].Number.Should().Be(3); episodes[2].Completed.Should().BeTrue(); episodes[2].CollectedAt.Should().Be(DateTime.Parse("2015-03-21T19:03:58.000Z").ToUniversalTime()); episodes[3].Number.Should().Be(4); episodes[3].Completed.Should().BeTrue(); episodes[3].CollectedAt.Should().Be(DateTime.Parse("2015-03-21T19:03:58.000Z").ToUniversalTime()); episodes[4].Number.Should().Be(5); episodes[4].Completed.Should().BeTrue(); episodes[4].CollectedAt.Should().Be(DateTime.Parse("2015-03-21T19:03:58.000Z").ToUniversalTime()); episodes[5].Number.Should().Be(6); episodes[5].Completed.Should().BeTrue(); episodes[5].CollectedAt.Should().Be(DateTime.Parse("2015-03-21T19:03:58.000Z").ToUniversalTime()); responseValue.HiddenSeasons.Should().NotBeNull(); responseValue.HiddenSeasons.Should().HaveCount(1); ITraktSeason[] hiddenSeasons = responseValue.HiddenSeasons.ToArray(); hiddenSeasons[0].Number.Should().Be(2); hiddenSeasons[0].Ids.Should().NotBeNull(); hiddenSeasons[0].Ids.Trakt.Should().Be(3051U); hiddenSeasons[0].Ids.Tvdb.Should().Be(498968U); hiddenSeasons[0].Ids.Tmdb.Should().Be(53334U); hiddenSeasons[0].Ids.TvRage.Should().BeNull(); responseValue.NextEpisode.Should().BeNull(); }
public void Setup() { _provider = TestUtility.InitDI(); _service = new SettingsService(_provider); }
public async Task SendBatchWithPartitionKey() { string targetPartitionKey = "this is the partition key"; await using (var scope = await EventHubScope.CreateAsync(1)) { var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName); var ehClient = EventHubClient.CreateFromConnectionString(connectionString); var receiver = default(PartitionReceiver); try { // Mark end of each partition so that we can start reading from there. var partitionIds = await this.GetPartitionsAsync(ehClient); var partitions = await TestUtility.DiscoverEndOfStreamForPartitionsAsync(ehClient, partitionIds); // Send a batch of 2 messages. using (var eventData1 = new EventData(Guid.NewGuid().ToByteArray())) using (var eventData2 = new EventData(Guid.NewGuid().ToByteArray())) { await ehClient.SendAsync(new[] { eventData1, eventData2 }, targetPartitionKey); } // Now find out the partition where our messages landed. var targetPartition = ""; foreach (var pId in partitionIds) { var pInfo = await ehClient.GetPartitionRuntimeInformationAsync(pId); if (pInfo.LastEnqueuedOffset != partitions[pId]) { targetPartition = pId; TestUtility.Log($"Batch landed on partition {targetPartition}"); } } // Confirm that we identified the partition with our messages. Assert.True(targetPartition != "", "None of the partition offsets moved."); // Receive all messages from target partition. receiver = ehClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, targetPartition, EventPosition.FromOffset(partitions[targetPartition])); var messages = await ReceiveAllMessagesAsync(receiver); // Validate 2 messages received. Assert.True(messages.Count == 2, $"Received {messages.Count} messages instead of 2."); // Validate both messages carry correct partition id. Assert.True(messages[0].SystemProperties.PartitionKey == targetPartitionKey, $"First message returned partition key value '{messages[0].SystemProperties.PartitionKey}'"); Assert.True(messages[1].SystemProperties.PartitionKey == targetPartitionKey, $"Second message returned partition key value '{messages[1].SystemProperties.PartitionKey}'"); } finally { await Task.WhenAll( receiver?.CloseAsync(), ehClient.CloseAsync()); } } }
public void RulesWrite() { using (var container = new RhetosTestContainer()) { var repositories = container.Resolve <Common.DomRepository>(); var emptyRP = repositories.TestRowPermissions.RPWriteRulesEmpty; var writeRP = repositories.TestRowPermissions.RPWriteRules; var commandImplementations = container.Resolve <IPluginsContainer <ICommandImplementation> >(); var saveCommand = commandImplementations.GetImplementations(typeof(SaveEntityCommandInfo)).Single(); { emptyRP.Delete(emptyRP.All()); var saveInfo = new SaveEntityCommandInfo() { Entity = "TestRowPermissions.RPWriteRulesEmpty" }; saveInfo.DataToInsert = new[] { new RPWriteRulesEmpty() }; TestUtility.ShouldFail(() => saveCommand.Execute(saveInfo), _writeException); } { writeRP.Delete(writeRP.All()); var saveInfo = new SaveEntityCommandInfo() { Entity = "TestRowPermissions.RPWriteRules" }; saveInfo.DataToInsert = (new[] { 10 }).Select(item => new RPWriteRules() { value = item }).ToArray(); TestUtility.ShouldFail(() => saveCommand.Execute(saveInfo), _writeException); } { writeRP.Delete(writeRP.All()); var saveInfo = new SaveEntityCommandInfo() { Entity = "TestRowPermissions.RPWriteRules" }; saveInfo.DataToInsert = (new[] { 5 }).Select(item => new RPWriteRules() { value = item }).ToArray(); TestUtility.ShouldFail(() => saveCommand.Execute(saveInfo), _writeException); } { writeRP.Delete(writeRP.All()); var saveInfo = new SaveEntityCommandInfo() { Entity = "TestRowPermissions.RPWriteRules" }; saveInfo.DataToInsert = (new[] { 1, 2, 8 }).Select(item => new RPWriteRules() { value = item }).ToArray(); TestUtility.ShouldFail(() => saveCommand.Execute(saveInfo), _writeException); } { writeRP.Delete(writeRP.All()); var saveInfo = new SaveEntityCommandInfo() { Entity = "TestRowPermissions.RPWriteRules" }; saveInfo.DataToDelete = (new[] { 7 }).Select(item => new RPWriteRules() { value = item, ID = Guid.NewGuid() }).ToArray(); writeRP.Insert((RPWriteRules[])saveInfo.DataToDelete); TestUtility.ShouldFail(() => saveCommand.Execute(saveInfo), _writeException); } { writeRP.Delete(writeRP.All()); var saveInfo = new SaveEntityCommandInfo() { Entity = "TestRowPermissions.RPWriteRules" }; saveInfo.DataToInsert = (new[] { 1, 2, 3, 4, 6, 9 }).Select(item => new RPWriteRules() { value = item, ID = Guid.NewGuid() }).ToArray(); saveCommand.Execute(saveInfo); saveInfo.DataToDelete = saveInfo.DataToInsert; saveInfo.DataToInsert = null; saveCommand.Execute(saveInfo); Assert.AreEqual(0, writeRP.All().Count()); } // update to legal { writeRP.Delete(writeRP.All()); var saveInfo = new SaveEntityCommandInfo() { Entity = "TestRowPermissions.RPWriteRules" }; var items = (new[] { 12 }).Select(item => new RPWriteRules() { value = item, ID = Guid.NewGuid() }).ToArray(); writeRP.Insert(items); items[0].value = 1; saveInfo.DataToUpdate = items; TestUtility.ShouldFail(() => saveCommand.Execute(saveInfo), _writeException); } // update from legal { writeRP.Delete(writeRP.All()); var saveInfo = new SaveEntityCommandInfo() { Entity = "TestRowPermissions.RPWriteRules" }; var items = (new[] { 1 }).Select(item => new RPWriteRules() { value = item, ID = Guid.NewGuid() }).ToArray(); writeRP.Insert(items); items[0].value = 12; saveInfo.DataToUpdate = items; TestUtility.ShouldFail(() => saveCommand.Execute(saveInfo), _writeException); } { writeRP.Delete(writeRP.All()); var saveInfo = new SaveEntityCommandInfo() { Entity = "TestRowPermissions.RPWriteRules" }; var items = (new[] { 1 }).Select(item => new RPWriteRules() { value = item, ID = Guid.NewGuid() }).ToArray(); writeRP.Insert(items); items[0].value = 2; saveInfo.DataToUpdate = items; saveCommand.Execute(saveInfo); } { writeRP.Delete(writeRP.All()); var saveInfo = new SaveEntityCommandInfo() { Entity = "TestRowPermissions.RPWriteRules" }; saveInfo.DataToInsert = (new[] { 20 }).Select(item => new RPWriteRules() { value = item, ID = Guid.NewGuid() }).ToArray(); saveCommand.Execute(saveInfo); } } }
private static void FilterEntityByIdentifiers(int n) { int oldFilterIds; Guid commitCheckId = Guid.NewGuid(); using (var container = new RhetosTestContainer(true)) { var context = container.Resolve <Common.ExecutionContext>(); var filterIdRepos = container.Resolve <GenericRepository <Common.FilterId> >(); oldFilterIds = filterIdRepos.Query().Count(); var guids = Enumerable.Range(0, n).Select(x => Guid.NewGuid()).ToList(); List <string> commands = new List <string>(); commands.Add("DELETE FROM Test10.Simple;"); for (int j = 0; j < (n + 999) / 1000; j++) { var sql = new StringBuilder(); for (int i = 0; i < 1000 && j * 1000 + i < n; i++) { sql.AppendFormat("INSERT INTO Test10.Simple (ID, i) SELECT '{0}', {1};\r\n", guids[j * 1000 + i], j * 1000 + i); } commands.Add(sql.ToString()); } container.Resolve <ISqlExecuter>().ExecuteSql(commands); var repository = container.Resolve <Common.DomRepository>(); var loaded = repository.Test10.Simple.Load(new[] { guids[0] }); Assert.AreEqual("0", TestUtility.DumpSorted(loaded, item => item.i.ToString())); try { var loadedByIds = repository.Test10.Simple.Load(guids); Assert.AreEqual(n, loadedByIds.Count()); var queriedByIds = container.Resolve <GenericRepository <Test10.Simple> >().Query(guids); Assert.AreEqual(n, queriedByIds.Count()); } catch (Exception ex) { var limitedLengthReport = new StringBuilder(); do { string message = ex.GetType().Name + ": " + ex.Message; if (message.Length > 1000) { message = message.Substring(0, 1000); } limitedLengthReport.AppendLine(message); ex = ex.InnerException; } while (ex != null); throw new Exception(limitedLengthReport.ToString()); } context.EntityFrameworkContext.Database.ExecuteSqlCommand("DELETE FROM Test10.Simple"); repository.Test10.Simple.Insert(new[] { new Test10.Simple { ID = commitCheckId } }); } using (var container = new RhetosTestContainer()) { var testRepos = container.Resolve <GenericRepository <Test10.Simple> >(); if (testRepos.Query(new[] { commitCheckId }).Count() == 0) { Assert.Fail("Transaction did not commit. Cannot test for remaining temporary data."); } var filterIdRepos = container.Resolve <GenericRepository <Common.FilterId> >(); Assert.AreEqual(0, filterIdRepos.Query().Count() - oldFilterIds, "Temporary data used for filtering should be cleaned."); } }
public void CombinedRules() { using (var container = new RhetosTestContainer()) { var settingsRepos = container.Resolve <GenericRepository <RPCombinedRulesSettings> >(); var itemsRepos = container.Resolve <GenericRepository <RPCombinedRulesItems> >(); var items = "a a1 a2 ab ab1 ab2 b b1 b2 r w" .Split(' ') .Select(name => new RPCombinedRulesItems { Name = name }) .ToList(); itemsRepos.Save(items, null, itemsRepos.Load()); { // Test read allow/deny without conditional rules: var settings = new RPCombinedRulesSettings { Settings = "no conditional rules" }; settingsRepos.Save(new[] { settings }, null, settingsRepos.Load()); var allowRead = itemsRepos.Query <Common.RowPermissionsReadItems>().Select(item => item.Name).ToList(); Assert.AreEqual("a, a2, ab, ab2, r", TestUtility.DumpSorted(allowRead)); } { // Test read allow/deny with conditional rules: var settings = new RPCombinedRulesSettings { Settings = "add conditional rules" }; settingsRepos.Save(new[] { settings }, null, settingsRepos.Load()); var allowRead = itemsRepos.Query <Common.RowPermissionsReadItems>().Select(item => item.Name).ToList(); Assert.AreEqual("a, ab, b, r", TestUtility.DumpSorted(allowRead)); } { // Test write allow/deny without conditional rules: var settings = new RPCombinedRulesSettings { Settings = "no conditional rules" }; settingsRepos.Save(new[] { settings }, null, settingsRepos.Load()); var allowWrite = itemsRepos.Query <Common.RowPermissionsWriteItems>().Select(item => item.Name).ToList(); Assert.AreEqual("a, a2, ab, ab2, w", TestUtility.DumpSorted(allowWrite)); } { // Test write allow/deny with conditional rules: var settings = new RPCombinedRulesSettings { Settings = "add conditional rules" }; settingsRepos.Save(new[] { settings }, null, settingsRepos.Load()); var allowWrite = itemsRepos.Query <Common.RowPermissionsWriteItems>().Select(item => item.Name).ToList(); Assert.AreEqual("a, ab, b, w", TestUtility.DumpSorted(allowWrite)); } } }
public void Test_TraktAuthenticationModule_RevokeAuthorization_ArgumentExceptions() { TraktClient client = TestUtility.GetAuthenticationMockClient(); client.Authorization = null; Func <Task <TraktNoContentResponse> > act = () => client.Authentication.RevokeAuthorizationAsync(); act.Should().Throw <ArgumentException>(); client.Authorization = new TraktAuthorization { CreatedAtTimestamp = TestUtility.CalculateTimestamp(TestConstants.CREATED_AT), TokenType = TraktAccessTokenType.Bearer, ExpiresInSeconds = 7200, Scope = TraktAccessScope.Public }; act = () => client.Authentication.RevokeAuthorizationAsync(); act.Should().Throw <ArgumentException>(); client.Authorization = new TraktAuthorization { CreatedAtTimestamp = TestUtility.CalculateTimestamp(TestConstants.CREATED_AT), AccessToken = null, TokenType = TraktAccessTokenType.Bearer, ExpiresInSeconds = 7200, RefreshToken = TestConstants.MOCK_REFRESH_TOKEN, Scope = TraktAccessScope.Public }; act = () => client.Authentication.RevokeAuthorizationAsync(); act.Should().Throw <ArgumentException>(); client.Authorization = new TraktAuthorization { CreatedAtTimestamp = TestUtility.CalculateTimestamp(TestConstants.CREATED_AT), AccessToken = string.Empty, TokenType = TraktAccessTokenType.Bearer, ExpiresInSeconds = 7200, RefreshToken = TestConstants.MOCK_REFRESH_TOKEN, Scope = TraktAccessScope.Public }; act = () => client.Authentication.RevokeAuthorizationAsync(); act.Should().Throw <ArgumentException>(); client.Authorization = new TraktAuthorization { CreatedAtTimestamp = TestUtility.CalculateTimestamp(TestConstants.CREATED_AT), AccessToken = "mock access token", TokenType = TraktAccessTokenType.Bearer, ExpiresInSeconds = 7200, RefreshToken = TestConstants.MOCK_REFRESH_TOKEN, Scope = TraktAccessScope.Public }; act = () => client.Authentication.RevokeAuthorizationAsync(); act.Should().Throw <ArgumentException>(); client.Authorization = MockAuthorization; client.ClientId = null; act = () => client.Authentication.RevokeAuthorizationAsync(); act.Should().Throw <ArgumentException>(); client.ClientId = string.Empty; act = () => client.Authentication.RevokeAuthorizationAsync(); act.Should().Throw <ArgumentException>(); client.ClientId = "client id"; act = () => client.Authentication.RevokeAuthorizationAsync(); act.Should().Throw <ArgumentException>(); client.ClientId = TraktClientId; client.ClientSecret = null; act = () => client.Authentication.RevokeAuthorizationAsync(); act.Should().Throw <ArgumentException>(); client.ClientSecret = string.Empty; act = () => client.Authentication.RevokeAuthorizationAsync(); act.Should().Throw <ArgumentException>(); client.ClientSecret = "client secret"; act = () => client.Authentication.RevokeAuthorizationAsync(); act.Should().Throw <ArgumentException>(); }
public async Task Test_TraktCommentsModule_PostMovieComment_ArgumentExceptions() { ITraktMovie movie = new TraktMovie { Title = "Guardians of the Galaxy", Year = 2014, Ids = new TraktMovieIds { Trakt = 28, Slug = "guardians-of-the-galaxy-2014", Imdb = "tt2015381", Tmdb = 118340 } }; ITraktMovieCommentPost movieCommentPost = new TraktMovieCommentPost { Movie = movie, Comment = COMMENT_TEXT }; string postJson = await TestUtility.SerializeObject(movieCommentPost); postJson.Should().NotBeNullOrEmpty(); TraktClient client = TestUtility.GetOAuthMockClient(POST_MOVIE_COMMENT_URI, postJson, COMMENT_POST_RESPONSE_JSON); Func <Task <TraktResponse <ITraktCommentPostResponse> > > act = () => client.Comments.PostMovieCommentAsync(null, COMMENT_TEXT); await act.Should().ThrowAsync <ArgumentNullException>(); movie.Title = string.Empty; act = () => client.Comments.PostMovieCommentAsync(movie, COMMENT_TEXT); await act.Should().ThrowAsync <ArgumentException>(); movie.Title = "Guardians of the Galaxy"; movie.Year = 0; act = () => client.Comments.PostMovieCommentAsync(movie, COMMENT_TEXT); await act.Should().ThrowAsync <ArgumentOutOfRangeException>(); movie.Year = 123; act = () => client.Comments.PostMovieCommentAsync(movie, COMMENT_TEXT); await act.Should().ThrowAsync <ArgumentOutOfRangeException>(); movie.Year = 12345; act = () => client.Comments.PostMovieCommentAsync(movie, COMMENT_TEXT); await act.Should().ThrowAsync <ArgumentOutOfRangeException>(); movie.Year = 2014; movie.Ids = null; act = () => client.Comments.PostMovieCommentAsync(movie, COMMENT_TEXT); await act.Should().ThrowAsync <ArgumentNullException>(); movie.Ids = new TraktMovieIds(); act = () => client.Comments.PostMovieCommentAsync(movie, COMMENT_TEXT); await act.Should().ThrowAsync <ArgumentException>(); movie.Ids = new TraktMovieIds { Trakt = 28, Slug = "guardians-of-the-galaxy-2014", Imdb = "tt2015381", Tmdb = 118340 }; act = () => client.Comments.PostMovieCommentAsync(movie, null); await act.Should().ThrowAsync <ArgumentException>(); act = () => client.Comments.PostMovieCommentAsync(movie, string.Empty); await act.Should().ThrowAsync <ArgumentException>(); const string comment = "one two three four"; act = () => client.Comments.PostMovieCommentAsync(movie, comment); await act.Should().ThrowAsync <ArgumentOutOfRangeException>(); }
string TypeAndNames(IEnumerable <ISimpleEntity> items) { return(TestIListIQueryable(items) + ": " + TestUtility.Dump(items)); }
async Task SendAndHandlerFireExceptionEvents() { this.queueClient = new QueueClient(TestUtility.NamespaceConnectionString, TestConstants.NonPartitionedQueueName, ReceiveMode.PeekLock); bool exceptionCalled = false; ManualResetEvent processingDone = new ManualResetEvent(false); await TestUtility.SendMessagesAsync(this.queueClient.InnerSender, 1); this.listener.Enable((name, queueName, arg) => !name.EndsWith(".Start") && !name.Contains("Receive")); int count = 0; this.queueClient.RegisterMessageHandler((msg, ct) => { if (count++ == 0) { throw new Exception("123"); } processingDone.Set(); return(Task.CompletedTask); }, exArgs => { exceptionCalled = true; return(Task.CompletedTask); }); processingDone.WaitOne(TimeSpan.FromSeconds(maxWaitSec)); Assert.True(exceptionCalled); // message is processed, but abandon happens after that // let's spin until Complete call starts and ends int wait = 0; while (wait++ < maxWaitSec && this.events.Count < 3) { await Task.Delay(TimeSpan.FromSeconds(1)); } Assert.True(this.events.TryDequeue(out var abandonStop)); AssertAbandonStop(abandonStop.eventName, abandonStop.payload, abandonStop.activity, null); Assert.True(this.events.TryDequeue(out var exception)); AssertException(exception.eventName, exception.payload, exception.activity, null); Assert.True(this.events.TryDequeue(out var processStop)); AssertProcessStop(processStop.eventName, processStop.payload, processStop.activity, null); Assert.Equal(processStop.activity, abandonStop.activity.Parent); Assert.Equal(processStop.activity, exception.activity); // message will be processed and compelted again wait = 0; while (wait++ < maxWaitSec && this.events.Count < 2) { await Task.Delay(TimeSpan.FromSeconds(1)); } Assert.True(this.events.TryDequeue(out var completeStop)); AssertCompleteStop(completeStop.eventName, completeStop.payload, completeStop.activity, null, null); Assert.True(this.events.TryDequeue(out processStop)); AssertProcessStop(processStop.eventName, processStop.payload, processStop.activity, null); Assert.True(this.events.IsEmpty); }
public void Initialize() { TestUtility.SetCulture("en-US"); }
async Task SendAndHandlerFireEvents() { this.queueClient = new QueueClient(TestUtility.NamespaceConnectionString, TestConstants.NonPartitionedQueueName, ReceiveMode.PeekLock); Activity parentActivity = new Activity("test").AddBaggage("k1", "v1").AddBaggage("k2", "v2"); Activity processActivity = null; bool exceptionCalled = false; ManualResetEvent processingDone = new ManualResetEvent(false); this.listener.Enable((name, queueName, arg) => !name.Contains("Receive") && !name.Contains("Exception")); parentActivity.Start(); await TestUtility.SendSessionMessagesAsync(this.queueClient.InnerSender, 1, 1); parentActivity.Stop(); this.queueClient.RegisterMessageHandler((msg, ct) => { processActivity = Activity.Current; processingDone.Set(); return(Task.CompletedTask); }, exArgs => { exceptionCalled = true; return(Task.CompletedTask); }); processingDone.WaitOne(TimeSpan.FromSeconds(maxWaitSec)); Assert.True(this.events.TryDequeue(out var sendStart)); AssertSendStart(sendStart.eventName, sendStart.payload, sendStart.activity, parentActivity); Assert.True(this.events.TryDequeue(out var sendStop)); AssertSendStop(sendStop.eventName, sendStop.payload, sendStop.activity, sendStart.activity); Assert.True(this.events.TryDequeue(out var processStart)); AssertProcessStart(processStart.eventName, processStart.payload, processStart.activity, sendStart.activity); // message is processed, but complete happens after that // let's wat until Complete starts and ends and Process ends int wait = 0; while (wait++ < maxWaitSec && this.events.Count < 3) { await Task.Delay(TimeSpan.FromSeconds(1)); } Assert.True(this.events.TryDequeue(out var completeStart)); AssertCompleteStart(completeStart.eventName, completeStart.payload, completeStart.activity, processStart.activity); Assert.True(this.events.TryDequeue(out var completeStop)); AssertCompleteStop(completeStop.eventName, completeStop.payload, completeStop.activity, completeStart.activity, processStart.activity); Assert.True(this.events.TryDequeue(out var processStop)); AssertProcessStop(processStop.eventName, processStop.payload, processStop.activity, processStart.activity); Assert.False(this.events.TryDequeue(out var evnt)); Assert.Equal(processStop.activity, processActivity); Assert.False(exceptionCalled); }
public void ChecklDatabaseAvailability() { TestUtility.CheckDatabaseAvailability("MsSql"); }
static void RunWebTest(string[] args) { //params 1 = test assembly string testAssembly = string.Empty; if (args.Length > 1) { testAssembly = args[1]; } else { Console.WriteLine("You need to specify an assembly."); return; } //params 2 = test name string testName = string.Empty; if (args.Length > 2) { testName = args[2]; } else { Console.WriteLine("You need to specify a test."); return; } //params 3 = environments Dictionary <int, TestEnvironment> Environments = new Dictionary <int, TestEnvironment>(); if (args.Length > 3) { IEnumerable <TestEnvironment> prEnv = EnvironmentProvider.GetEnvironments(); foreach (string s in GetStrings(args[3])) { foreach (TestEnvironment fenv in prEnv.Where(a => a.ID.Equals(int.Parse(s)))) { if (!Environments.ContainsKey(fenv.ID)) { Console.WriteLine(string.Format("Adding '{0}' Environment.", fenv.Name)); Environments.Add(fenv.ID, fenv); } } } } // params 4 = systems // params 5 = sites // will look for sites by system unless systems is an empty string then it looks for them by site Dictionary <int, TestSite> Sites = new Dictionary <int, TestSite>(); IEnumerable <TestSite> prSites = SiteProvider.GetEnabledSites(); if (args.Length > 4 && !string.IsNullOrEmpty(args[4])) { foreach (string s in GetStrings(args[4])) { foreach (TestSite fsite in prSites.Where(a => a.SystemID.Equals(int.Parse(s)))) { if (!Sites.ContainsKey(fsite.ID)) { Console.WriteLine(string.Format("Adding '{0}' Site.", fsite.Name)); Sites.Add(fsite.ID, fsite); } } } } if (args.Length > 5) { foreach (string s in GetStrings(args[5])) { foreach (TestSite fsite in prSites.Where(a => a.ID.Equals(int.Parse(s)))) { if (!Sites.ContainsKey(fsite.ID)) { Console.WriteLine(string.Format("Adding '{0}' Site.", fsite.Name)); Sites.Add(fsite.ID, fsite); } } } } //setup for testing CoreExtensions.Host.InitializeService(); //get the test suite TestSuite suite = TestUtility.GetTestSuite(testAssembly); IEnumerable <TestFixture> Fixtures = suite.GetFixtures().Where(a => a.ClassName.EndsWith(string.Format(".{0}", testName))); if (!Fixtures.Any()) { Console.WriteLine("There were no Test Fixtures found. Make sure the class has the [TestFixture] attribute."); return; } TestFixture tf = Fixtures.First(); WebTestManager manager = new WebTestManager(new WebConsoleTestHandler()); manager.RunTest(tf, Environments.Values, Sites.Values); }
public static void Initialize(TestContext context) { TestUtility.LaunchWindowsCalc(); }
static void RunUnitTest(string[] args) { //params 1 = test assembly string testAssembly = string.Empty; if (args.Length > 1) { testAssembly = args[1]; } else { Console.WriteLine("You need to specify an assembly."); return; } //params 2 = test category List <string> categories = new List <string>(); if (args.Length > 2) { foreach (string s in GetStrings(args[2])) { if (!categories.Contains(s)) { Console.WriteLine(string.Format("Caught '{0}' Category.", s)); categories.Add(s); } } } //params 3 = test method List <string> names = new List <string>(); if (args.Length > 3) { foreach (string n in GetStrings(args[3])) { if (!names.Contains(n)) { Console.WriteLine(string.Format("Caught '{0}' Method.", n)); names.Add(n); } } } //setup for testing CoreExtensions.Host.InitializeService(); //get the test suite TestSuite suite = TestUtility.GetTestSuite(testAssembly); Dictionary <string, TestMethod> Methods = new Dictionary <string, TestMethod>(); IEnumerable <TestMethod> allMethods = suite.GetMethods(); if (!categories.Any() && !names.Any()) // if nothing selected add all { Methods = allMethods.ToDictionary(a => a.MethodName); } else // add one at a time { IEnumerable <TestFixture> Fixtures = suite.GetFixtures(); foreach (string c in categories) { foreach (TestFixture tf in Fixtures) { bool fixtHasCat = (tf.Categories().Any(b => b.Equals(c))); foreach (TestMethod tm in tf.Tests) { //if fixture or the method has the selected category then add if (fixtHasCat || tm.Categories().Any(b => b.Equals(c))) { Console.WriteLine(string.Format("Adding '{0}' Method.", tm.MethodName)); Methods.Add(tm.MethodName, tm); } } } } foreach (string n in names) { foreach (TestMethod ctm in allMethods.Where(a => a.MethodName.Equals(n))) { if (!Methods.ContainsKey(ctm.MethodName)) { Console.WriteLine(string.Format("Adding '{0}' Method.", ctm.MethodName)); Methods.Add(ctm.MethodName, ctm); } } } } if (!Methods.Any()) { Console.WriteLine("There are no Test Methods found. Make sure the class method has the [Test] attribute."); return; } UnitTestManager manager = new UnitTestManager(new UnitConsoleTestHandler()); foreach (TestMethod tm in Methods.Values) { manager.RunTest(tm); } }