Exemple #1
0
        public async Task CollectionActorRemove_ExpectsNewStateWithoutRemovedItems()
        {
            var stateManager = new Mock <IActorStateManager>();
            var list         = new List <string> {
                Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()
            };
            var state = new HashSet <string>(list);

            stateManager.Setup(manager => manager.GetStateAsync <HashSet <string> >(_stateName, It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(state))
            .Verifiable();
            stateManager.Setup(manager => manager.SetStateAsync(_stateName, state, It.IsAny <CancellationToken>()))
            .Verifiable();
            CollectionActor testDemoActor = await CreateActor(stateManager.Object, "Test Collection");

            await testDemoActor.Remove(list[2]);

            await testDemoActor.Remove(list[0]);

            list.Remove(list[2]);
            list.Remove(list[0]);
            state.Should().HaveCount(3);
            state.Should().Contain(list);

            stateManager.VerifyAll();
        }
        public void TestAddRangeAddsElements()
        {
            var elementsToBeAdded = new List <int> {
                1, 3, 5
            };

            HashSet <int> hash = new HashSet <int>();

            hash.AddRange(elementsToBeAdded);

            foreach (int elementToBeAdded in elementsToBeAdded)
            {
                hash.Should().Contain(elementToBeAdded);
            }

            var moreElementsToBeAdded = new List <int> {
                5, 7, 9
            };

            hash.AddRange(moreElementsToBeAdded);

            foreach (int elementToBeAdded in moreElementsToBeAdded)
            {
                hash.Should().Contain(elementToBeAdded);
            }

            hash.Count.Should().Be(5);
        }
Exemple #3
0
        public void CreateNew_ShouldReturnNewGuid_WithoutCollisions_WhenTypeIsBinaryEnd()
        {
            // Arrange
            const int numberOfChars = SequentialGuidFactory.NumberOfSequentialBytes * 2;              // 2 chars per byte

            var uniqueResults  = new HashSet <Guid>();
            var sequentialData = new string[TestIterations];
            var subject        = new SequentialGuidFactory(SequentialGuidType.BinaryEnd);

            for (var i = 0; i < TestIterations; i++)
            {
                // Act
                var result = subject.CreateNew();

                // Assert
                uniqueResults.Add(result).Should().BeTrue();
                var guidString = result.ToString();
                sequentialData[i] = guidString.Substring(guidString.Length - numberOfChars, numberOfChars);
            }

            uniqueResults.Should().HaveCount(TestIterations);
            uniqueResults.Should().NotContain(Guid.Empty);

            sequentialData.Should().BeInAscendingOrder();
        }
Exemple #4
0
        public async Task CollectionActorAdd_ExpectsNewStateWithNewItems()
        {
            var stateManager = new Mock <IActorStateManager>();
            var state1       = new HashSet <string> {
                Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()
            };
            var state2 = new List <string> {
                Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()
            };

            stateManager.Setup(manager => manager.GetStateAsync <HashSet <string> >(_stateName, It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(state1))
            .Verifiable();
            stateManager.Setup(manager => manager.SetStateAsync(_stateName, state1, It.IsAny <CancellationToken>()))
            .Verifiable();
            CollectionActor testDemoActor = await CreateActor(stateManager.Object, "Test Collection");

            await testDemoActor.Add(state2[0]);

            await testDemoActor.Add(state2[1]);

            await testDemoActor.Add(state2[2]);

            state1.Should().HaveCount(8);
            state1.Should().Contain(state2);

            stateManager.VerifyAll();
        }
Exemple #5
0
        public void BigTest_WithLimitedDepth(int depth, double ans, int evaluationsCount)
        {
            var root = GetTreeFromWikipediaSample();

            alphaBeta.Search(root, depth).Score
            .Should().Be(ans);
            evaluations.Should().HaveCount(evaluationsCount);
        }
        public void Clean_EmptyRootFolder_EmptyFileRegistry()
        {
            _folderNamesGenerator = path => Enumerable.Empty <string>();
            _fileNamesGenerator   = path => Enumerable.Empty <string>();

            _cleaner.Clean("root");

            _uniqueNames.Should().BeEmpty();
            _backedUpNames.Should().BeEmpty();
        }
Exemple #7
0
        public void GetNeighbours_Coordinates_For_TopRight_Cell()
        {
            var cell = new NotAliveCell(new Coordinate(x: 99, y: 1));

            var neighbours = new HashSet <Coordinate>(cell.GetNeighbours());

            neighbours.Count.Should().Be(3);
            neighbours.Should().Contain(new Coordinate(98, 1));
            neighbours.Should().Contain(new Coordinate(98, 2));
            neighbours.Should().Contain(new Coordinate(99, 2));
        }
Exemple #8
0
        public void GetNeighbours_Coordinates_For_BottomLeft_Cell()
        {
            var cell = new NotAliveCell(new Coordinate(x: 1, y: 99));

            var neighbours = new HashSet <Coordinate>(cell.GetNeighbours());

            neighbours.Count.Should().Be(3);
            neighbours.Should().Contain(new Coordinate(1, 98));
            neighbours.Should().Contain(new Coordinate(2, 98));
            neighbours.Should().Contain(new Coordinate(2, 99));
        }
Exemple #9
0
        public void GetNeighbours_Coordinates_For_LeftSide_Cell()
        {
            var cell = new NotAliveCell(new Coordinate(x: 1, y: 2));

            var neighbours = new HashSet <Coordinate>(cell.GetNeighbours());

            neighbours.Count.Should().Be(5);
            neighbours.Should().Contain(new Coordinate(1, 1));
            neighbours.Should().Contain(new Coordinate(2, 1));
            neighbours.Should().Contain(new Coordinate(2, 2));
            neighbours.Should().Contain(new Coordinate(1, 3));
            neighbours.Should().Contain(new Coordinate(2, 3));
        }
        public void CheckLoadOfSuppressionFile(string fileName)
        {
            const int expectedCount = 3629;

            var    messagesToCheck     = GetSuppressionMessagesToCheck();
            string suppressionFilePath = GetFileFullPath(fileName);

            HashSet <SuppressMessage> messages = SuppressionFile.LoadMessages(_fileService, suppressionFilePath);

            messages.Should().NotBeNull();
            messages.Should().HaveCount(expectedCount);
            messages.Should().ContainInOrder(messagesToCheck);
        }
        public void Visit_EventDelegateTypesInluded()
        {
            //-- arrange

            var type1 = new TypeMember(new TypeGeneratorInfo(this.GetType()), "NS1", MemberVisibility.Public, TypeMemberKind.Class, "ClassOne");
            var type2 = new TypeMember(new TypeGeneratorInfo(this.GetType()), "NS2", MemberVisibility.Public, TypeMemberKind.Class, "ClassTwo");

            type1.Members.Add(new EventMember(
                                  MemberVisibility.Public, MemberModifier.None, typeof(Action <DateTime>), "E1"));
            type1.Members.Add(new EventMember(
                                  MemberVisibility.Public, MemberModifier.Static, ((TypeMember)typeof(Action <>)).MakeGenericType(type2), "E2"));


            var foundTypes       = new HashSet <TypeMember>();
            var visitorUnderTest = new TypeReferenceMemberVisitor(foundTypes);

            //-- act

            type1.AcceptVisitor(visitorUnderTest);

            //-- assert

            foundTypes.Should().BeEquivalentTo(new TypeMember[] {
                type1, typeof(Action <>), typeof(DateTime), type2
            });
        }
        public void Visit_GenericTypeDefinitionsAndArgumentsIncluded()
        {
            //-- arrange

            var type1 = new TypeMember(new TypeGeneratorInfo(this.GetType()), "NS1", MemberVisibility.Public, TypeMemberKind.Class, "ClassOne");
            var type2 = new TypeMember(new TypeGeneratorInfo(this.GetType()), "NS2", MemberVisibility.Public, TypeMemberKind.Class, "ClassTwo");
            var type3 = new TypeMember(new TypeGeneratorInfo(this.GetType()), "NS3", MemberVisibility.Public, TypeMemberKind.Class, "ClassThree");

            type1.Members.Add(new PropertyMember(
                                  type1, MemberVisibility.Public, MemberModifier.None, ((TypeMember)typeof(IList <>)).MakeGenericType(type2), "Twos"));

            type1.Members.Add(new PropertyMember(
                                  type1, MemberVisibility.Public, MemberModifier.Static, ((TypeMember)typeof(IDictionary <,>)).MakeGenericType(type2, type3), "ThreeByTwo"));

            var foundTypes       = new HashSet <TypeMember>();
            var visitorUnderTest = new TypeReferenceMemberVisitor(foundTypes);

            //-- act

            type1.AcceptVisitor(visitorUnderTest);

            //-- assert

            foundTypes.Should().BeEquivalentTo(new TypeMember[] {
                type1, typeof(IList <>), typeof(IDictionary <,>), type2, type3
            });
        }
Exemple #13
0
        public void MergePrioritized_must_stream_data_from_all_sources()
        {
            var source1 = Source.From(Enumerable.Range(1, 3));
            var source2 = Source.From(Enumerable.Range(4, 3));
            var source3 = Source.From(Enumerable.Range(7, 3));

            var priorities = new List <int> {
                6, 3, 1
            };
            var probe = this.CreateManualSubscriberProbe <int>();

            ThreeSourceMerge(source1, source2, source3, priorities, probe).Run(Materializer);

            var subscription = probe.ExpectSubscription();

            var collected = new HashSet <int>();

            for (int i = 1; i <= 9; i++)
            {
                subscription.Request(1);
                collected.Add(probe.ExpectNext());
            }

            collected.Should().BeEquivalentTo(new HashSet <int> {
                1, 2, 3, 4, 5, 6, 7, 8, 9
            });
            probe.ExpectComplete();
        }
        public void Visit_MethodSignatureTypesIncluded()
        {
            //-- arrange

            var type1 = new TypeMember(new TypeGeneratorInfo(this.GetType()), "NS1", MemberVisibility.Public, TypeMemberKind.Class, "ClassOne");

            type1.Members.Add(new MethodMember(MemberVisibility.Public, MemberModifier.None, "M1", new MethodSignature(
                                                   new[] { new MethodParameter("x", 1, typeof(int)), new MethodParameter("y", 2, typeof(string)) },
                                                   returnValue: null,
                                                   isAsync: false
                                                   )));
            type1.Members.Add(new MethodMember(MemberVisibility.Public, MemberModifier.Static, "M2", new MethodSignature(
                                                   new MethodParameter[0],
                                                   returnValue: new MethodParameter(null, -1, typeof(TimeSpan)),
                                                   isAsync: false
                                                   )));

            var foundTypes       = new HashSet <TypeMember>();
            var visitorUnderTest = new TypeReferenceMemberVisitor(foundTypes);

            //-- act

            type1.AcceptVisitor(visitorUnderTest);

            //-- assert

            foundTypes.Should().BeEquivalentTo(new TypeMember[] {
                type1, typeof(int), typeof(string), typeof(TimeSpan)
            });
        }
Exemple #15
0
        public void BuildExpressionTree_Should_Create_ExpressionTree_From_PrefixExpression(List <int> minterms)
        {
            GC.Collect();
            Stopwatch s2 = Stopwatch.StartNew();
            var       externalLibraryResult = QuineMcCluskeySolver.QMC_Solve(minterms, new int[] { });

            s2.Stop();

            TruthTable table = TruthTableHelpers.GenerateTruthTable(minterms);
            Stopwatch  s1    = Stopwatch.StartNew();
            var        customLibraryResult = logic.ExpressionService.Common.QMC.QuineMcCluskey.SimplifyTable(table.Value);

            s1.Stop();

            TestContext.Out.WriteLine(s1.ElapsedTicks);
            TestContext.Out.WriteLine(s2.ElapsedTicks);

            var helperSet = new HashSet <string>();

            foreach (var pr in customLibraryResult)
            {
                helperSet.Add(pr.RowData);
            }

            foreach (var item in externalLibraryResult)
            {
                helperSet.Should().Contain(item.ToString());
            }
        }
Exemple #16
0
        public void ShouldReportEventsWhenStateIsModified()
        {
            var expected = new HashSet <string>()
            {
                "resized",
                "deactivated",
                "activated",
                "closed",
                "disposed"
            };
            var actual = new HashSet <string>();

            app.Window.Show();
            app.Window.Raise();
            Window.OverrideCurrentWith(app.Window);
            app.IsActive.Should().BeTrue();
            // it gets called when the initial size of window is set too
            app.Resized     += (s, e) => actual.Add("resized");
            app.Deactivated += (s, e) => actual.Add("deactivated");
            app.Activated   += (s, e) => actual.Add("activated");
            app.Exiting     += (s, e) => { actual.Add("closed"); e.Cancel = true; };
            app.Disposed    += (s, e) => actual.Add("disposed");

            app.Window.Hide(); app.Tick();
            app.Window.Raise(); app.Tick();
            app.RequestExit(); app.Tick();

            Window.OverrideCurrentWith(app.Window);
            app.Dispose();
            actual.Should().BeEquivalentTo(expected);
        }
Exemple #17
0
        public void Group_Send_AllClientsShouldBeReceiveEvent()
        {
            var group = new FlowGroup(server);

            group.Add(destinationClients[0]);
            group.Add(destinationClients[2]);
            var transferString = "Hello client under index 0 & 2";
            var expected       = new HashSet <int> {
                0, 2
            };

            var receivedOn = new HashSet <int>();

            for (var i = 0; i < clients.Length; i++)
            {
                var index = i;
                clients[i].Bind <string>(1, value =>
                {
                    receivedOn.Add(index);
                });
            }

            group.Send(1, transferString);

            Thread.Sleep(MillisecondsToWaitForTransfer);

            receivedOn.Should().BeEquivalentTo(expected);
        }
        public void DocumentMappableTestDiscoversAllTypes()
        {
            //Arrange
            var assemblies = new HashSet <Assembly> {
                this.GetType().Assembly
            };
            var seenTypes = new HashSet <Type>();

            var expectedTypes = new HashSet <Type>
            {
                typeof(Guid),
                typeof(string),
                typeof(ClassWithDifferentMappableName),
                typeof(ChildClassWithDifferentMappableName),
                typeof(List <ChildClassWithDifferentMappableName>),
                typeof(IReadOnlyList <ChildClassWithDifferentMappableName>),
                typeof(IChildClassWithDifferentMappableName),
                typeof(List <IChildClassWithDifferentMappableName>),
                typeof(ChildClassWithDifferentMappableNameBase),
                typeof(IList <ChildClassWithDifferentMappableNameBase>),
                typeof(IReadOnlyDictionary <string, ChildClassWithDifferentMappableNameBase>),
                typeof(ChildClassWithDifferentMappableNameBase[])
            };

            //Act
            CheckForDocumentMappableAttribute(typeof(ClassWithDifferentMappableName), assemblies, seenTypes);

            //Assert
            seenTypes.Should().BeEquivalentTo(expectedTypes);
        }
        public void ExplodedGraph_BothBranchesVisited_NonCondition()
        {
            var testInput    = "var str = this?.ToString();";
            var method       = ControlFlowGraphTest.CompileWithMethodBody(string.Format(TestInput, testInput), "Bar", out var semanticModel);
            var methodSymbol = semanticModel.GetDeclaredSymbol(method);

            var cfg = CSharpControlFlowGraph.Create(method.Body, semanticModel);
            var lva = CSharpLiveVariableAnalysis.Analyze(cfg, methodSymbol, semanticModel);

            var explodedGraph    = new CSharpExplodedGraph(cfg, methodSymbol, semanticModel, lva);
            var explorationEnded = false;

            explodedGraph.ExplorationEnded += (sender, args) => { explorationEnded = true; };

            var countConditionEvaluated = 0;

            explodedGraph.ConditionEvaluated += (sender, args) => { countConditionEvaluated++; };

            var visitedBlocks = new HashSet <Block>();

            explodedGraph.InstructionProcessed +=
                (sender, args) =>
            {
                visitedBlocks.Add(args.ProgramPoint.Block);
            };

            explodedGraph.Walk();

            explorationEnded.Should().BeTrue();
            visitedBlocks.Should().HaveCount(cfg.Blocks.Count() - 1 /* Exit block */);
            countConditionEvaluated.Should().Be(0);
        }
        public void Visit_ConstructorBodyStatementsIncluded()
        {
            //-- arrange

            var type1        = new TypeMember(new TypeGeneratorInfo(this.GetType()), "NS1", MemberVisibility.Public, TypeMemberKind.Class, "ClassOne");
            var constructor1 = new ConstructorMember(MemberVisibility.Public, MemberModifier.None, "ClassOne", new MethodSignature());
            var variable1    = new LocalVariable {
                Name = "x", Type = typeof(TimeSpan)
            };

            constructor1.Body = new BlockStatement(
                new VariableDeclarationStatement {
                Variable = variable1
            }
                );

            type1.Members.Add(constructor1);

            var foundTypes       = new HashSet <TypeMember>();
            var visitorUnderTest = new TypeReferenceMemberVisitor(foundTypes);

            //-- act

            type1.AcceptVisitor(visitorUnderTest);

            //-- assert

            foundTypes.Should().BeEquivalentTo(new TypeMember[] {
                type1, typeof(TimeSpan)
            });
        }
        public void ItComputesExcludeFromPublishList()
        {
            LockFile       lockFile       = TestLockFiles.GetLockFile("dependencies.withgraphs");
            ProjectContext projectContext = lockFile.CreateProjectContext(
                FrameworkConstants.CommonFrameworks.NetStandard16,
                runtime: null,
                Constants.DefaultPlatformLibrary,
                runtimeFrameworks: null,
                isSelfContained: false);

            IEnumerable <string> excludeFromPublishPackageIds         = new[] { "Microsoft.Extensions.Logging.Abstractions" };
            IDictionary <string, LockFileTargetLibrary> libraryLookup =
                projectContext
                .LockFileTarget
                .Libraries
                .ToDictionary(e => e.Name, StringComparer.OrdinalIgnoreCase);

            HashSet <string> exclusionList =
                projectContext.GetExcludeFromPublishList(excludeFromPublishPackageIds, libraryLookup);

            HashSet <string> expectedExclusions = new HashSet <string>()
            {
                "Microsoft.Extensions.Logging.Abstractions",
                "System.Collections.Concurrent",
                "System.Diagnostics.Tracing",
            };

            exclusionList.Should().BeEquivalentTo(expectedExclusions);
        }
Exemple #22
0
        private void ExecuteRandomDurationsTest(int nrOfTests, int maxRandomDuration, int nrOfThreads)
        {
            IDictionary <Model.TestCase, int> durations = CreateRandomTestResults(nrOfTests, maxRandomDuration);

            MockOptions.Setup(o => o.MaxNrOfThreads).Returns(nrOfThreads);

            ITestsSplitter splitter = new DurationBasedTestsSplitter(durations, TestEnvironment.Options);
            List <List <Model.TestCase> > result = splitter.SplitTestcases();

            result.Should().HaveCount(nrOfThreads);
            result.Select(l => l.Count).Sum().Should().Be(nrOfTests);

            int sumOfAllDurations = durations.Select(kvp => kvp.Value).Sum();
            int maxDuration       = durations.Select(kvp => kvp.Value).Max();

            int targetDuration = sumOfAllDurations / nrOfThreads;

            HashSet <Model.TestCase> foundTestcases = new HashSet <Model.TestCase>();

            foreach (List <Model.TestCase> testcases in result)
            {
                int sum = testcases.Select(tc => durations[tc]).Sum();
                sum.Should().BeLessThan(targetDuration + maxDuration / 2);
                sum.Should().BeGreaterThan(targetDuration - maxDuration / 2);

                foundTestcases.UnionWith(testcases);
            }

            foundTestcases.Should().HaveCount(nrOfTests);
        }
Exemple #23
0
        public void DiagnosticBuilder_CodesAreUnique()
        {
            var diagnosticMethods = typeof(DiagnosticBuilder.DiagnosticBuilderInternal)
                                    .GetMethods(BindingFlags.Instance | BindingFlags.Public)
                                    .Where(m => typeof(Diagnostic).IsAssignableFrom(m.ReturnType));

            // verify the above Linq is actually working
            diagnosticMethods.Should().HaveCountGreaterThan(40);

            var builder = DiagnosticBuilder.ForPosition(new TextSpan(0, 10));

            var definedCodes = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            foreach (var diagnosticMethod in diagnosticMethods)
            {
                var mockParams = diagnosticMethod.GetParameters().Select(CreateMockParameter);

                var diagnostic = diagnosticMethod.Invoke(builder, mockParams.ToArray()) as Diagnostic;

                if (mockParams.Any())
                {
                    // verify that all the params are actually being written in the message
                    diagnostic !.Message.Should().ContainAll(CollectExpectedStrings(mockParams), $"method {diagnosticMethod.Name} should use all of its parameters in the format string.");
                }

                // verify that the Code is unique
                definedCodes.Should().NotContain(diagnostic !.Code, $"Method {diagnosticMethod.Name} should be assigned a unique error code.");
                definedCodes.Add(diagnostic !.Code);
            }
        }
Exemple #24
0
        public async Task SubscribeAndUnsubcribe_MultipleSubscription()
        {
            var customResizeOptioons = new ResizeOptions();

            var feedbackCallerCount = 0;

            Action <ListenForResizeCallbackInfo> feedbackCaller = (x) =>
            {
                if (x.ListenerId == default)
                {
                    throw new ArgumentException();
                }

                feedbackCallerCount++;
            };

            SetupJsMockForSubscription(customResizeOptioons, true, feedbackCaller);

            HashSet <Guid> subscriptionIds = new HashSet <Guid>();

            for (int i = 0; i < 10; i++)
            {
                var subscritionResult = await _service.Subscribe((Breakpoint size) => { });

                subscriptionIds.Add(subscritionResult.SubscriptionId);
            }

            feedbackCallerCount.Should().Be(1);
            subscriptionIds.Should().HaveCount(10);

            _jsruntimeMock.Verify();
            _browserWindowSizeProvider.Verify(x => x.GetBrowserWindowSize(), Times.Once());
        }
        public void VisitBlockStatement_TypeofConstantsIncluded()
        {
            //-- arrange

            var block = new BlockStatement(
                new ReturnStatement {
                Expression = new ConstantExpression {
                    Value = typeof(IDisposable)
                }
            },
                new ReturnStatement {
                Expression = new ConstantExpression {
                    Value = (TypeMember)typeof(IFormattable)
                }
            }
                );

            var foundTypes = new HashSet <TypeMember>();
            var visitor    = new TypeReferenceStatementVisitor(foundTypes);

            //-- act

            block.AcceptVisitor(visitor);

            //-- assert

            foundTypes.Should().BeEquivalentTo(new TypeMember[] { typeof(IDisposable), typeof(IFormattable) });
        }
 public void ThenTheFollowingTimeseriesWillBeNonPrioritized(Table timeseries)
 {
     foreach (var row in timeseries.Rows)
     {
         _nonPrioritizedTimeseries.Should().Contain(Guid.Parse(row["timeseries"]));
     }
 }
Exemple #27
0
        public void ExplodedGraph_BothBranchesVisited()
        {
            const string testInput                     = "var a = false; bool b; if (inParameter) { b = inParameter; } else { b = !inParameter; } a = b;";
            var          context                       = new ExplodedGraphContext(testInput);
            var          aSymbol                       = context.GetSymbol("a");
            var          bSymbol                       = context.GetSymbol("b");
            var          parameters                    = context.MainMethod.DescendantNodes().OfType <ParameterSyntax>();
            var          inParameterSymbol             = context.SemanticModel.GetDeclaredSymbol(parameters.First(d => d.Identifier.ToString() == "inParameter"));
            var          numberOfLastInstructionVisits = 0;
            var          visitedBlocks                 = new HashSet <Block>();
            var          branchesVisited               = 0;

            context.ExplodedGraph.InstructionProcessed +=
                (sender, args) =>
            {
                visitedBlocks.Add(args.ProgramPoint.Block);

                if (args.Instruction.ToString() == "a = false")
                {
                    branchesVisited++;

                    args.ProgramState.GetSymbolValue(aSymbol).Should().Be(SymbolicValue.False);
                }
                if (args.Instruction.ToString() == "b = inParameter")
                {
                    branchesVisited++;

                    bSymbol.HasConstraint(BoolConstraint.True, args.ProgramState).Should().BeTrue();
                    inParameterSymbol.HasConstraint(BoolConstraint.True, args.ProgramState).Should().BeTrue();
                }
                if (args.Instruction.ToString() == "b = !inParameter")
                {
                    branchesVisited++;

                    // b has value, but not true or false
                    args.ProgramState.GetSymbolValue(bSymbol).Should().NotBeNull();
                    bSymbol.HasConstraint(BoolConstraint.False, args.ProgramState).Should().BeFalse();
                    bSymbol.HasConstraint(BoolConstraint.True, args.ProgramState).Should().BeFalse();

                    inParameterSymbol.HasConstraint(BoolConstraint.False, args.ProgramState).Should().BeTrue();
                }
                if (args.Instruction.ToString() == "a = b")
                {
                    branchesVisited++;

                    args.ProgramState.GetSymbolValue(inParameterSymbol).Should().BeNull();     // not out/ref parameter and LVA says dead
                    numberOfLastInstructionVisits++;
                }
            };

            // Number of ExitBlocks is still 1 in this case:
            // All variables are dead at the ExitBlock, so whenever we get there,
            // the ExplodedGraph nodes should be the same, and thus should be processed only once.
            context.WalkWithInstructions(13);

            branchesVisited.Should().Be(4 + 1);
            numberOfLastInstructionVisits.Should().Be(2);
            visitedBlocks.Should().HaveCount(context.ControlFlowGraph.Blocks.Count() - 1 /* Exit block*/);
        }
Exemple #28
0
        public void EqualityComparer_List_VB()
        {
            var comparer = new VisualBasicSyntaxNodeEqualityComparer <VisualBasic.StatementSyntax>();

            var result = comparer.Equals(vbMethods.Method1, vbMethods.Method2);

            result.Should().BeTrue();

            result = comparer.Equals(vbMethods.Method1, vbMethods.Method3);
            result.Should().BeFalse();

            var hashSet = new HashSet <SyntaxList <VisualBasic.StatementSyntax> >(new[] { vbMethods.Method1, vbMethods.Method2, vbMethods.Method3 }, comparer);

            hashSet.Should().HaveCount(2);
            hashSet.Should().Contain(vbMethods.Method1);
            hashSet.Should().NotContain(vbMethods.Method4);
        }
Exemple #29
0
        public void EqualityComparer_Node_VB()
        {
            var comparer = new VisualBasicSyntaxNodeEqualityComparer <VisualBasic.StatementSyntax>();

            var result = comparer.Equals(vbMethods.Method1.First(), vbMethods.Method2.First());

            result.Should().BeTrue();

            result = comparer.Equals(vbMethods.Method1.First(), vbMethods.Method3.First());
            result.Should().BeFalse();

            var hashSet = new HashSet <VisualBasic.StatementSyntax>(new[] { vbMethods.Method1.First(), vbMethods.Method2.First(), vbMethods.Method3.First() }, comparer);

            hashSet.Should().HaveCount(2);
            hashSet.Should().Contain(vbMethods.Method1.First());
            hashSet.Should().NotContain(vbMethods.Method4.First());
        }
        public static void RandomSelect_SelectsAllElementsEventually()
        {
            var outputValues = new HashSet <string>();

            for (int numberOfSelections = 0; numberOfSelections < 1000; numberOfSelections++)
            {
                var selector = new Selector <string>();
                selector.TryAddItem("jen").Should().BeTrue();
                selector.TryAddItem("michael").Should().BeTrue();
                selector.TryAddItem("staci").Should().BeTrue();
                outputValues.Add(selector.RandomSelect(1).First().Value);
            }

            outputValues.Should().Contain("jen");
            outputValues.Should().Contain("michael");
            outputValues.Should().Contain("staci");
        }
        public void When_getting_a_new_identifier_multiple_times_they_should_all_be_unique()
        {
            var generator = new BasicGuidGenerator();
            var identifiers = new HashSet<Guid>();

            for (int i = 0; i < 500; i++)
            {
                var newId = generator.GenerateNewId();

                identifiers.Should().NotContain(newId);

                identifiers.Add(newId);
            }
        }
		/**
		* Request and Response class names should be one to one in *most* cases.
		* e.g. ValidateRequest => ValidateResponse, and not ValidateQueryRequest => ValidateResponse
		*/
		//[U]
		public void ParityBetweenRequestsAndResponses()
		{
			var types = Assembly.Load("Nest").GetTypes();

			var requests = new HashSet<string>(types
				.Where(t => t.IsClass && !t.IsAbstract && typeof(IRequest).IsAssignableFrom(t) && !(t.Name.EndsWith("Descriptor")))
				.Select(t => t.Name.Split('`')[0].Replace("Request", ""))
			);

			var responses = types
				.Where(t => t.IsClass && !t.IsAbstract && typeof(IResponse).IsAssignableFrom(t))
				.Select(t => t.Name.Split('`')[0].Replace("Response", ""));

			// Add any exceptions to the rule here
			var exceptions = new string[] { "Cat" };

			responses = responses.Where(r => !exceptions.Contains(r)).ToList();

			foreach (var response in responses)
				requests.Should().Contain(response);
		}
        public void PartialDelete()
        {
            using (var tmp = new TempDirectory())
            {
                var dir = new LocalFileSystemDirectory(tmp);

                Directory.CreateDirectory(Path.Combine(tmp, "dir1"));
                Directory.CreateDirectory(Path.Combine(tmp, "dir1", "dir2"));
                using (var f = File.CreateText(Path.Combine(tmp, "dir1", "file.delete")))
                    f.WriteLine("test");
                using (var f = File.CreateText(Path.Combine(tmp, "dir1", "file.keep")))
                    f.WriteLine("test");
                using (var f = File.CreateText(Path.Combine(tmp, "dir1", "dir2", "file.delete")))
                    f.WriteLine("test");

                var paths = new HashSet<string>();

                dir.Delete(p =>
                {
                    paths.Add(p);
                    return false;
                });

                paths.Should().HaveCount(3);
                paths.Should().Contain(Path.Combine("dir1", "file.delete"));
                paths.Should().Contain(Path.Combine("dir1", "file.keep"));
                paths.Should().Contain(Path.Combine("dir1", "dir2", "file.delete"));

                Directory.Exists(tmp).Should().BeTrue();
                Directory.Exists(Path.Combine(tmp, "dir1")).Should().BeTrue();
                Directory.Exists(Path.Combine(tmp, "dir1", "dir2")).Should().BeTrue();
                File.Exists(Path.Combine(tmp, "dir1", "file.delete")).Should().BeTrue();
                File.Exists(Path.Combine(tmp, "dir1", "file.keep")).Should().BeTrue();
                File.Exists(Path.Combine(tmp, "dir1", "dir2", "file.delete")).Should().BeTrue();

                paths.Clear();
                dir.Delete(p =>
                {
                    paths.Add(p);
                    return !p.EndsWith(".keep", System.StringComparison.InvariantCulture);
                });

                paths.Should().HaveCount(4);
                paths.Should().Contain(Path.Combine("dir1", "file.delete"));
                paths.Should().Contain(Path.Combine("dir1", "file.keep"));
                paths.Should().Contain(Path.Combine("dir1", "dir2"));
                paths.Should().Contain(Path.Combine("dir1", "dir2", "file.delete"));

                Directory.Exists(tmp).Should().BeTrue();
                Directory.Exists(Path.Combine(tmp, "dir1")).Should().BeTrue();
                Directory.Exists(Path.Combine(tmp, "dir1", "dir2")).Should().BeFalse();
                File.Exists(Path.Combine(tmp, "dir1", "file.delete")).Should().BeFalse();
                File.Exists(Path.Combine(tmp, "dir1", "file.keep")).Should().BeTrue();
                File.Exists(Path.Combine(tmp, "dir1", "dir2", "file.delete")).Should().BeFalse();

                paths.Clear();
                dir.Delete(p =>
                {
                    paths.Add(p);
                    return true;
                });

                paths.Should().HaveCount(3);
                paths.Should().Contain(Path.Combine("dir1", "file.keep"));
                paths.Should().Contain("dir1");
                paths.Should().Contain("");

                Directory.Exists(tmp).Should().BeFalse();
            }
        }
        public void GetCommandLines_ManyTestsWithSuites_BreaksUpLongCommandLinesCorrectly()
        {
            List<string> allTests = new List<string>();
            List<string> testsToExecute = new List<string>();
            for (int i = 0; i < 1000; i++)
            {
                allTests.Add("MyTestSuite" + i + ".MyTest");
                testsToExecute.Add("MyTestSuite" + i + ".MyTest");
                allTests.Add("MyTestSuite" + i + ".MyTest2");
            }
            testsToExecute.Add("MyTestSuite1.MyTest2");
            testsToExecute.Add("MyTestSuite5.MyTest2");

            IEnumerable<Model.TestCase> allTestCases = allTests.Select(TestDataCreator.ToTestCase).ToList();
            IEnumerable<Model.TestCase> testCases = testsToExecute.Select(TestDataCreator.ToTestCase).ToList();

            List<CommandLineGenerator.Args> commands = new CommandLineGenerator(allTestCases, testCases, TestDataCreator.DummyExecutable.Length, "", "", TestEnvironment)
                .GetCommandLines().ToList();

            commands.Count.Should().Be(3);

            int lengthOfLongestTestname = allTests.Max(s => s.Length);
            int maxLength = CommandLineGenerator.MaxCommandLength - TestDataCreator.DummyExecutable.Length;
            int minLength = CommandLineGenerator.MaxCommandLength - lengthOfLongestTestname - TestDataCreator.DummyExecutable.Length - 1;

            string commandLine = commands[0].CommandLine;
            commandLine.Length.Should().BeLessThan(maxLength);
            commandLine.Length.Should().BeGreaterOrEqualTo(minLength);
            commandLine.Should().StartWith($@"--gtest_output=""xml:""{DefaultArgs} --gtest_filter=MyTestSuite1.*:MyTestSuite5.*:MyTestSuite0.MyTest:");

            commandLine = commands[1].CommandLine;
            commandLine.Length.Should().BeLessThan(maxLength);
            commandLine.Length.Should().BeGreaterOrEqualTo(minLength);
            commandLine.Should().NotStartWith(@"--gtest_output=""xml:"" --gtest_filter=MyTestSuite1.*:MyTestSuite5.*:");
            commandLine.Should().StartWith($@"--gtest_output=""xml:""{DefaultArgs} --gtest_filter=");

            commandLine = commands[2].CommandLine;
            commandLine.Length.Should().BeLessThan(maxLength);
            commandLine.Should()
                .NotStartWith($@"--gtest_output=""xml:""{DefaultArgs} --gtest_filter=MyTestSuite1.*:MyTestSuite5.*:");
            commandLine.Should().StartWith($@"--gtest_output=""xml:""{DefaultArgs} --gtest_filter=");

            HashSet<Model.TestCase> testsAsSet = new HashSet<Model.TestCase>(testCases);
            HashSet<Model.TestCase> splittedTestsAsSet = new HashSet<Model.TestCase>(commands[0].TestCases.Union(commands[1].TestCases).Union(commands[2].TestCases));

            splittedTestsAsSet.Should().BeEquivalentTo(testsAsSet);
        }
 public void RemoteRouter_must_deploy_its_children_on_remote_host_driven_by_configuration()
 {
     var probe = CreateTestProbe(masterSystem);
     var router = masterSystem.ActorOf(new RoundRobinPool(2).Props(EchoActorProps), "blub");
     var replies = CollectRouteePaths(probe, router, 5);
     var childred = new HashSet<ActorPath>(replies);
     childred.Should().HaveCount(2);
     childred.Select(x => x.Parent).Distinct().Should().HaveCount(1);
     childred.ForEach(x => x.Address.Should().Be(intendedRemoteAddress));
     masterSystem.Stop(router);
 }
 public void RemoteRouter_must_deploy_its_children_on_remote_host_driven_by_programmatic_definition()
 {
     var probe = CreateTestProbe(masterSystem);
     var router = masterSystem.ActorOf(new RemoteRouterConfig(
         new RoundRobinPool(2),
         new[] { new Address("akka.tcp", sysName, "127.0.0.1", port) })
         .Props(EchoActorProps), "blub2");
     var replies = CollectRouteePaths(probe, router, 5);
     var childred = new HashSet<ActorPath>(replies);
     childred.Should().HaveCount(2);
     childred.Select(x => x.Parent).Distinct().Should().HaveCount(1);
     childred.ForEach(x => x.Address.Should().Be(intendedRemoteAddress));
     masterSystem.Stop(router);
 }
 public void RemoteRouter_must_deploy_dynamic_resizable_number_of_children_on_remote_host_driven_by_configuration()
 {
     var probe = CreateTestProbe(masterSystem);
     var router = masterSystem.ActorOf(FromConfig.Instance.Props(EchoActorProps), "elastic-blub");
     var replies = CollectRouteePaths(probe, router, 5);
     var childred = new HashSet<ActorPath>(replies);
     childred.Should().HaveCount(2);
     childred.Select(x => x.Parent).Distinct().Should().HaveCount(1);
     childred.ForEach(x => x.Address.Should().Be(intendedRemoteAddress));
     masterSystem.Stop(router);
 }
        public void RemoteRouter_must_deploy_remote_routers_based_on_configuration()
        {
            var probe = CreateTestProbe(masterSystem);
            var router = masterSystem.ActorOf(FromConfig.Instance.Props(EchoActorProps), "remote-blub");
            router.Path.Address.Should().Be(intendedRemoteAddress);

            var replies = CollectRouteePaths(probe, router, 5);
            var childred = new HashSet<ActorPath>(replies);
            childred.Should().HaveCount(2);

            var parents = childred.Select(x => x.Parent).Distinct().ToList();
            parents.Should().HaveCount(1);
            parents.Head().Should().Be(router.Path);

            childred.ForEach(x => x.Address.Should().Be(intendedRemoteAddress));
            masterSystem.Stop(router);
        }
        public void RemoteRouter_must_let_remote_deployment_be_overridden_by_local_configuration()
        {
            var probe = CreateTestProbe(masterSystem);
            var router = masterSystem.ActorOf(
                new RoundRobinPool(2)
                .Props(EchoActorProps)
                .WithDeploy(new Deploy(new RemoteScope(intendedRemoteAddress))), "local-blub");
            router.Path.Address.ToString().Should().Be(string.Format("akka://{0}", masterSystem.Name));

            var replies = CollectRouteePaths(probe, router, 5);
            var childred = new HashSet<ActorPath>(replies);
            childred.Should().HaveCount(2);

            var parents = childred.Select(x => x.Parent).Distinct().ToList();
            parents.Should().HaveCount(1);
            parents.Head().Address.Should().Be(new Address("akka.tcp", sysName, "127.0.0.1", port));

            childred.ForEach(x => x.Address.Should().Be(intendedRemoteAddress));
            masterSystem.Stop(router);
        }
        public void RemoteRouter_must_let_remote_deployment_be_overridden_by_remote_configuration()
        {
            var probe = CreateTestProbe(masterSystem);
            var router = masterSystem.ActorOf(
                new RoundRobinPool(2)
                .Props(EchoActorProps)
                .WithDeploy(new Deploy(new RemoteScope(intendedRemoteAddress))), "remote-override");

            router.Path.Address.Should().Be(intendedRemoteAddress);

            var replies = CollectRouteePaths(probe, router, 5);
            var childred = new HashSet<ActorPath>(replies);
            childred.Should().HaveCount(4);

            var parents = childred.Select(x => x.Parent).Distinct().ToList();
            parents.Should().HaveCount(1);
            parents.Head().Address.Should().Be(router.Path.Address);

            childred.ForEach(x => x.Address.Should().Be(intendedRemoteAddress));
            masterSystem.Stop(router);
        }
 public void RemoteRouter_must_load_settings_from_config_for_local_router()
 {
     var probe = CreateTestProbe(masterSystem);
     var router = masterSystem.ActorOf(FromConfig.Instance.Props(EchoActorProps), "round");
     var replies = CollectRouteePaths(probe, router, 10);
     var childred = new HashSet<ActorPath>(replies);
     childred.Should().HaveCount(5);
     masterSystem.Stop(router);
 }
 public void RemoteRouter_must_load_settings_from_config_for_local_child_router_of_system_actor()
 {
     // we don't really support deployment configuration of system actors, but
     // it's used for the pool of the SimpleDnsManager "/IO-DNS/inet-address"
     var probe = CreateTestProbe(masterSystem);
     var parent = ((ExtendedActorSystem)masterSystem).SystemActorOf(FromConfig.Instance.Props(Props.Create<Parent>()), "sys-parent");
     parent.Tell(Tuple.Create(FromConfig.Instance.Props(EchoActorProps), "round"), probe);
     var router = probe.ExpectMsg<IActorRef>();
     var replies = CollectRouteePaths(probe, router, 10);
     var childred = new HashSet<ActorPath>(replies);
     childred.Should().HaveCount(6);
     masterSystem.Stop(router);
 }