コード例 #1
0
        public void FilterMutantsWithNoChangedFilesAndNoCoverage()
        {
            // Arrange
            var diffProvider = new Mock <IDiffProvider>(MockBehavior.Strict);

            var options = new StrykerOptions();

            diffProvider.Setup(x => x.ScanDiff()).Returns(new DiffResult
            {
                ChangedSourceFiles = new List <string>()
            });

            diffProvider.SetupGet(x => x.Tests).Returns(new TestSet());

            var target = new SinceMutantFilter(diffProvider.Object);

            var mutants = new List <Mutant>
            {
                new Mutant()
                {
                    Id           = 1,
                    Mutation     = new Mutation(),
                    ResultStatus = MutantStatus.NoCoverage
                },
                new Mutant()
                {
                    Id           = 2,
                    Mutation     = new Mutation(),
                    ResultStatus = MutantStatus.NoCoverage
                },
                new Mutant()
                {
                    Id           = 3,
                    Mutation     = new Mutation(),
                    ResultStatus = MutantStatus.NoCoverage
                }
            };

            // Act
            var results = target.FilterMutants(mutants, new CsharpFileLeaf()
            {
                RelativePath = "src/1/SomeFile0.cs"
            }, options);

            // Assert
            results.Count().ShouldBe(0);
            mutants.ShouldAllBe(m => m.ResultStatus == MutantStatus.Ignored);
            mutants.ShouldAllBe(m => m.ResultStatusReason == "Mutant not changed compared to target commit");
        }
コード例 #2
0
        public void TypeBinaryExpressionScenarioShouldFail()
        {
            var objects = new List <object> {
                "1", 1
            };

            Verify.ShouldFail(() =>
                              objects.ShouldAllBe(x => x is string, "Some additional context"),

                              errorWithSource:
                              @"objects
    should satisfy the condition
(x Is String)
    but
[1]
    do not

Additional Info:
    Some additional context",

                              errorWithoutSource:
                              @"[""1"", 1]
    should satisfy the condition
(x Is String)
    but
[1]
    do not

Additional Info:
    Some additional context");
        }
コード例 #3
0
        public void TypeBinaryExpressionScenarioShouldFail()
        {
            List<object> objects = new List<object> { "1", 1 };

            Verify.ShouldFail(() =>
            objects.ShouldAllBe(x => x is string, "Some additional context"),

            errorWithSource:
            @"objects
            should satisfy the condition
            (x Is String)
            but
            [1]
            do not

            Additional Info:
            Some additional context",

            errorWithoutSource:
            @"[""1"", 1]
            should satisfy the condition
            (x Is String)
            but
            [1]
            do not

            Additional Info:
            Some additional context");
        }
コード例 #4
0
        public async Task AddEstablishedHandler_MultipleHandlers_ShouldExecuteHandlers()
        {
            // Arrange
            _transport.Setup(t => t.IsConnected).Returns(true);
            var handlerClientChannels     = new List <IClientChannel>();
            var handlerCancellationTokens = new List <CancellationToken>();
            var target = GetTarget();

            // Act
            var count = Dummy.CreateRandomInt(100);

            for (int i = 0; i < count; i++)
            {
                Func <IClientChannel, CancellationToken, Task> establishedHandler = (clientChannel, cancellationToken) =>
                {
                    handlerClientChannels.Add(clientChannel);
                    handlerCancellationTokens.Add(cancellationToken);
                    return(TaskUtil.CompletedTask);
                };
                target.AddEstablishedHandler(establishedHandler);
            }
            var channel = await target.BuildAndEstablishAsync(_cancellationToken);

            // Assert
            handlerClientChannels.Count.ShouldBe(count);
            handlerCancellationTokens.Count.ShouldBe(count);
            handlerClientChannels.ShouldAllBe(c => c == channel);
            handlerCancellationTokens.ShouldAllBe(t => t == _cancellationToken);
        }
コード例 #5
0
        public void Generates_random_sequence(IList <int> collection)
        {
            List <int> random = collection.Random(10).ToList();

            random.Count.ShouldBe(10);
            random.ShouldAllBe(n => collection.Any(element => element == n));
        }
コード例 #6
0
        public void DuplexStreamingCall()
        {
            RunWith10SecTimeout(async() =>
            {
                Console.WriteLine("Starting test");

                async Task HandleAsync(
                    IReadableChannel <EchoRequest> requestStream,
                    IWriteOnlyChannel <EchoRequest> responseStream,
                    MethodCallContext context)
                {
                    while (await requestStream.WaitForNextSafeAsync())
                    {
                        while (requestStream.TryReadSafe(out var item))
                        {
                            await responseStream.WriteAsync(item);
                        }
                    }
                }

                using (await StartTestBrokerAsync())
                {
                    var client = ConnectEchoClient();
                    ConnectEchoServer(x => x
                                      .WithProvidedService(
                                          "plexus.interop.testing.EchoService",
                                          s => s.WithDuplexStreamingMethod <EchoRequest, EchoRequest>("DuplexStreaming", HandleAsync)
                                          )
                                      );
                    var sentRequest = CreateTestRequest();
                    Console.WriteLine("Starting call");
                    var responses = new List <EchoRequest>();
                    var call      = client.Call(EchoDuplexStreamingMethod);
                    for (var i = 0; i < 3; i++)
                    {
                        await call.RequestStream.WriteAsync(sentRequest);
                        var response = await call.ResponseStream.ReadAsync();
                        responses.Add(response);
                    }
                    await call.RequestStream.CompleteAsync();
                    Console.WriteLine("Requests sent");

                    while (await call.ResponseStream.WaitForNextSafeAsync())
                    {
                        while (call.ResponseStream.TryReadSafe(out var item))
                        {
                            responses.Add(item);
                        }
                    }
                    Console.WriteLine("Responses received");

                    await call.Completion;

                    Console.WriteLine("Call completed");

                    responses.ShouldAllBe(x => x.Equals(sentRequest));
                }
            });
        }
コード例 #7
0
        public void When_generating_a_object_person_list_should_be_equal_to_habitants_list()
        {
            var bfo = DataGenerator.GetBFO();
            var mergedHabbitants = new List <Person>();

            bfo.Houses.ForEach(x => mergedHabbitants.AddRange(x.Habitants));

            mergedHabbitants.ShouldAllBe(item => bfo.Persons.Contains(item));
        }
コード例 #8
0
        public void FilterMutantsWithNoChangedFilesReturnsEmptyList()
        {
            // Arrange
            var diffProvider = new Mock <IDiffProvider>(MockBehavior.Strict);

            var options = new StrykerOptions();

            diffProvider.Setup(x => x.ScanDiff()).Returns(new DiffResult
            {
                ChangedSourceFiles = new List <string>()
            });

            var target = new DiffMutantFilter(options, diffProvider.Object, new Mock <IBaselineProvider>().Object, new Mock <IGitInfoProvider>().Object);

            var mutants = new List <Mutant>
            {
                new Mutant()
                {
                    Id       = 1,
                    Mutation = new Mutation()
                },
                new Mutant()
                {
                    Id       = 2,
                    Mutation = new Mutation()
                },
                new Mutant()
                {
                    Id       = 3,
                    Mutation = new Mutation()
                }
            };

            // Act
            var results = target.FilterMutants(mutants, new CsharpFileLeaf()
            {
                RelativePath = "src/1/SomeFile0.cs"
            }.ToReadOnly(), options);

            // Assert
            results.Count().ShouldBe(0);
            mutants.ShouldAllBe(m => m.ResultStatus == MutantStatus.Ignored);
            mutants.ShouldAllBe(m => m.ResultStatusReason == "Mutant not changed compared to target commit");
        }
コード例 #9
0
        public void Returns_random_bytes(int count, byte min, byte max)
        {
            List <byte> bytes = EnumerableHelpers.CreateRandomBytes(count, min, max).ToList();

            bytes.ShouldNotBeNull();
            bytes.Count.ShouldBe(count);
            bytes.ShouldAllBe(b => b >= min && b <= max);

            _output.WriteLine(bytes.ToString(", "));
        }
コード例 #10
0
        public void Returns_random_ints(int count, int min, int max)
        {
            List <int> bytes = EnumerableHelpers.CreateRandomInts(count, min, max).ToList();

            bytes.ShouldNotBeNull();
            bytes.Count.ShouldBe(count);
            bytes.ShouldAllBe(i => i >= min && i <= max);

            _output.WriteLine(bytes.ToString(", "));
        }
コード例 #11
0
        public void Removes_all_matching_elements()
        {
            IList <int> collection = new List <int> {
                1, 2, 3, 4, 5, 6
            };

            int removedCount = collection.RemoveAll(n => n % 2 == 0);

            removedCount.ShouldBe(3);
            collection.Count.ShouldBe(3);
            collection.ShouldAllBe(n => n % 2 != 0);
        }
コード例 #12
0
        public void ShouldAllBe()
        {
            DocExampleWriter.Document(() =>
            {
                var mrBurns = new Person() { Name = "Mr.Burns", Salary = 3000000 };
                var kentBrockman = new Person() { Name = "Homer", Salary = 3000000 };
                var homer = new Person() { Name = "Homer", Salary = 30000 };
                var millionares = new List<Person>() { mrBurns, kentBrockman, homer };

                millionares.ShouldAllBe(m => m.Salary > 1000000);
            }, _testOutputHelper);
        }
コード例 #13
0
        public void ClientStreamingCall()
        {
            RunWith10SecTimeout(async() =>
            {
                Console.WriteLine("Starting test");
                var receivedRequests = new List <EchoRequest>();

                async Task <EchoRequest> HandleAsync(IReadableChannel <EchoRequest> requestStream,
                                                     MethodCallContext context)
                {
                    while (await requestStream.WaitReadAvailableAsync().ConfigureAwait(false))
                    {
                        while (requestStream.TryRead(out var item))
                        {
                            receivedRequests.Add(item);
                        }
                    }

                    Console.WriteLine("Received {0} requests", receivedRequests.Count);
                    return(receivedRequests.Last());
                }

                var client = ConnectEchoClient();
                ConnectEchoServer(x => x
                                  .WithProvidedService(
                                      "plexus.interop.testing.EchoService",
                                      s => s.WithClientStreamingMethod <EchoRequest, EchoRequest>("ClientStreaming", HandleAsync)
                                      )
                                  );
                var sentRequest = CreateTestRequest();
                Console.WriteLine("Starting call");
                var call = client.CallInvoker.Call(EchoClientStreamingMethod);
                for (var i = 0; i < 3; i++)
                {
                    await call.RequestStream.WriteAsync(sentRequest).ConfigureAwait(false);
                }

                await call.RequestStream.CompleteAsync();
                Console.WriteLine("Requests sent");
                var response = await call.ResponseAsync;
                Console.WriteLine("Response received");

                await call.Completion;

                Console.WriteLine("Call completed");

                receivedRequests.ShouldAllBe(r => r.Equals(sentRequest));
                response.ShouldBe(sentRequest);
            });
        }
コード例 #14
0
        public async Task OnAuthorizeAsync_Is_Called_Twice_If_Request_Contains_A_Body(string uploadConcatHeader)
        {
            var shouldUseConcatenation = !string.IsNullOrEmpty(uploadConcatHeader);

            var fileId   = Guid.NewGuid().ToString("n");
            var tusStore = MockStoreHelper.CreateWithExtensions <ITusCreationStore, ITusConcatenationStore>();

            var tusCreationStore = (ITusCreationStore)tusStore;

            tusCreationStore.CreateFileAsync(1, null, CancellationToken.None).ReturnsForAnyArgs(fileId);

            var tusConcatenationStore = (ITusConcatenationStore)tusStore;

            tusConcatenationStore.CreatePartialFileAsync(1, null, CancellationToken.None).ReturnsForAnyArgs(fileId);

            tusStore.WithExistingFile(fileId);

            var intents = new List <IntentType>(2);
            var authorizeEventFileConcatenations = new List <FileConcat>(2);
            var events = new Events
            {
                OnAuthorizeAsync = authorizeContext =>
                {
                    intents.Add(authorizeContext.Intent);
                    authorizeEventFileConcatenations.Add(authorizeContext.FileConcatenation);
                    return(Task.FromResult(0));
                }
            };

            using (var server = TestServerFactory.Create(tusStore, events))
            {
                var response = await server
                               .CreateTusResumableRequest("/files")
                               .AddHeader("Upload-Length", "100")
                               .AddHeaderIfNotEmpty("Upload-Concat", uploadConcatHeader)
                               .AddBody()
                               .PostAsync();

                response.StatusCode.ShouldBe(HttpStatusCode.Created);

                var authorizeIntentToCreateFile = shouldUseConcatenation ? IntentType.ConcatenateFiles : IntentType.CreateFile;

                intents.Count.ShouldBe(2);
                intents[0].ShouldBe(authorizeIntentToCreateFile);
                intents[1].ShouldBe(IntentType.WriteFile);

                authorizeEventFileConcatenations.Count.ShouldBe(2);
                authorizeEventFileConcatenations.ShouldAllBe(fc => shouldUseConcatenation ? fc is FileConcatPartial : fc == null);
            }
        }
コード例 #15
0
        public static void Access_Tokens_Are_Randomly_Generated()
        {
            // Arrange
            var tokens = new List <string>();

            // Act
            for (int i = 0; i < 512; i++)
            {
                tokens.Add(AlexaController.GenerateAccessToken());
            }

            // Assert
            tokens.Distinct().Count().ShouldBe(tokens.Count);
            tokens.ShouldAllBe((p) => p.Length >= 64);
        }
コード例 #16
0
ファイル: XmlPoke_Tests.cs プロジェクト: Nirmal4G/msbuild
        public void PokeNoNamespace()
        {
            const string query = "//variable/@Name";
            const string value = "Mert";

            XmlDocument xmlDocument = ExecuteXmlPoke(query: query, value: value);

            List <XmlAttribute> nodes = xmlDocument.SelectNodes(query)?.Cast <XmlAttribute>().ToList();

            nodes.ShouldNotBeNull($"There should be <variable /> elements with a Name attribute {Environment.NewLine}{xmlDocument.OuterXml}");

            nodes.Count.ShouldBe(3, $"There should be 3 <variable /> elements with a Name attribute {Environment.NewLine}{xmlDocument.OuterXml}");

            nodes.ShouldAllBe(i => i.Value.Equals(value), $"All <variable /> elements should have Name=\"{value}\" {Environment.NewLine}{xmlDocument.OuterXml}");
        }
コード例 #17
0
        public void ShouldMainFieldGetSquareCombinations()
        {
            var fieldSetting     = CreateDefaultFieldSetting();
            var firstCombination = new List <TestMainFieldSquare>()
            {
                TSA(2, 4, color: Color.Blue),
                TSA(2, 5, color: Color.Blue),
                TSA(2, 6, color: Color.Blue),
                TSA(3, 5, color: Color.Blue),
                TSA(3, 6, color: Color.Blue),
                TSA(3, 7, color: Color.Blue),
            };

            var secondCombination = new List <TestMainFieldSquare>()
            {
                TSA(3, 3, color: Color.Red),
                TSA(4, 3, color: Color.Red),
                TSA(5, 3, color: Color.Red),
            };

            var thirdNotCompleteCombination = new List <TestMainFieldSquare>()
            {
                TSA(4, 4, color: Color.Green),
                TSA(5, 4, color: Color.Green),
                TSA(7, 4, color: Color.Green),
            };

            var testValues = new List <TestMainFieldSquare>();

            testValues.AddRange(firstCombination);
            testValues.AddRange(secondCombination);
            testValues.AddRange(thirdNotCompleteCombination);

            var mainField    = TestMainField.Create(fieldSetting, testValues);
            var combinations = mainField.GetSquareCombinations();

            combinations.Count().ShouldBe(2);
            var result1 = combinations.ElementAt(0);

            result1.Count().ShouldBe(6);
            firstCombination.ShouldAllBe(item => result1.Any(resItem => item.X == resItem.X && item.Y == resItem.Y));

            var result2 = combinations.ElementAt(1);

            result2.Count().ShouldBe(3);
            secondCombination.ShouldAllBe(item => result2.Any(resItem => item.X == resItem.X && item.Y == resItem.Y));
        }
コード例 #18
0
        public async Task GetChallenges_ShouldGetChallengesForEachIdentifier()
        {
            //SETUP
            AcmeRestApi api = new AcmeRestApi(ProtoacmeContants.LETSENCRYPT_STAGING_ENDPOINT);
            AcmeApiResponse <AcmeDirectory> directory;
            AcmeApiResponse nonceResponse = null;
            AcmeApiResponse <AcmeAccount> accountResponse = null;
            AcmeApiResponse <AcmeCertificateFulfillmentPromise> certificateFulfillmentPromise = null;
            List <AcmeApiResponse <AcmeAuthorization> >         authorizations = null;

            AcmeCertificateRequest certifcateRequest = new AcmeCertificateRequest()
            {
                Identifiers = new List <DnsCertificateIdentifier>()
                {
                    new DnsCertificateIdentifier()
                    {
                        Value = "taco.com"
                    },
                    new DnsCertificateIdentifier()
                    {
                        Value = "www.taco.com"
                    }
                }
            };

            //EXECUTE
            directory = await api.GetDirectoryAsync();

            nonceResponse = await api.GetNonceAsync(directory.Data);

            accountResponse = await api.CreateAccountAsync(directory.Data, nonceResponse.Nonce, new AcmeCreateAccount()
            {
                Contact = new List <string>()
                {
                    "mailto:[email protected]"
                }, TermsOfServiceAgreed = true
            });

            certificateFulfillmentPromise = await api.RequestCertificateAsync(directory.Data, accountResponse.Nonce, accountResponse.Data, certifcateRequest);

            authorizations = await api.GetChallengesAsync(certificateFulfillmentPromise.Data);

            //ASSERT
            authorizations.ShouldNotBeNull();
            authorizations.Count.ShouldBe(2);
            authorizations.ShouldAllBe(auth => auth.Status == AcmeApiResponseStatus.Success);
        }
コード例 #19
0
        public void Can_replace_tokens()
        {
            // Arrange
            const string value = "changed", format = "value: {{0}}";

            var tokens  = ReplacementToken.Create();
            var results = new List <string>();

            // Act
            foreach (var item in tokens.Keys)
            {
                results.Add(ReplacementToken.Expand(string.Format(format, value), tokens));
            }

            // Assert
            results.ShouldNotBeEmpty();
            results.ShouldAllBe(x => x == string.Format(format, x));
        }
コード例 #20
0
        public void Should_log_unsupported_tokens()
        {
            var messages = new List <string>();

            SelfLog.Enable(x => messages.Add(x));

            const string input  = "/my/path/{Myergen:yyyy}/{Meh:MM}";
            var          result = TokenExpander.Expand(input);

            // Result should be the unchanged input
            result.ShouldBe(input);

            // Ensure we wrote diagnostic logs
            messages.Count.ShouldBe(2);
            messages.ShouldAllBe(x => x.Contains("Unsupported token"));
            messages.ShouldContain(x => x.EndsWith("Myergen"));
            messages.ShouldContain(x => x.EndsWith("Meh"));
        }
コード例 #21
0
        public void ServerStreamingCall()
        {
            RunWith10SecTimeout(async() =>
            {
                Console.WriteLine("Starting test");
                EchoRequest receivedRequest = null;
                var responses   = new List <EchoRequest>();
                var sentRequest = CreateTestRequest();

                async Task HandleAsync(EchoRequest request, IWriteOnlyChannel <EchoRequest> responseStream, MethodCallContext context)
                {
                    Console.WriteLine("Handling invocation");
                    receivedRequest = request;
                    await responseStream.WriteAsync(request).ConfigureAwait(false);
                    await Task.Yield();
                    await responseStream.WriteAsync(request).ConfigureAwait(false);
                    await responseStream.WriteAsync(request).ConfigureAwait(false);
                    Console.WriteLine("Responses sent");
                }

                using (await StartTestBrokerAsync())
                {
                    var client = ConnectEchoClient();
                    ConnectEchoServer(x => x
                                      .WithProvidedService(
                                          "plexus.interop.testing.EchoService",
                                          s => s.WithServerStreamingMethod <EchoRequest, EchoRequest>("ServerStreaming", HandleAsync)
                                          )
                                      );
                    Console.WriteLine("Starting call");
                    var call = client.Call(EchoServerStreamingMethod, sentRequest);
                    while (await call.ResponseStream.WaitForNextSafeAsync())
                    {
                        while (call.ResponseStream.TryReadSafe(out var item))
                        {
                            responses.Add(item);
                        }
                    }
                    Console.WriteLine("Responses received");
                }
                receivedRequest.ShouldBe(sentRequest);
                responses.ShouldAllBe(r => r.Equals(sentRequest));
            });
        }
コード例 #22
0
        public void GivenListOfBuildersWithARangeOfCustomisationMethods_WhenBuildingEntitiesImplicitly_ThenThenTheListIsBuiltAndModifiedCorrectly()
        {
            var             i         = 0;
            List <Customer> customers = CustomerBuilder.CreateListOfSize(5)
                                        .TheFirst(1).WithFirstName("First")
                                        .TheNext(1).WithLastName("Next Last")
                                        .TheLast(1).WithLastName("Last Last")
                                        .ThePrevious(2).With(b => b.WithLastName("last" + (++i).ToString()))
                                        .All().WhoJoinedIn(1999);

            customers.ShouldBeAssignableTo <IList <Customer> >();
            customers.Count.ShouldBe(5);
            customers[0].FirstName.ShouldBe("First");
            customers[1].LastName.ShouldBe("Next Last");
            customers[2].LastName.ShouldBe("last1");
            customers[3].LastName.ShouldBe("last2");
            customers[4].LastName.ShouldBe("Last Last");
            customers.ShouldAllBe(c => c.YearJoined == 1999);
        }
コード例 #23
0
        public void AsManyAsBurstTokensAreAvailableRightAway(int burst)
        {
            // arrange
            var clock   = new FakeSystemClock();
            var limiter = new Limiter(new Limit(10), burst, clock);

            // act
            var allowed = new List <bool>();

            foreach (var index in Enumerable.Range(1, burst))
            {
                allowed.Add(limiter.Allow());
            }
            var notAllowed = limiter.Allow();

            // assert
            allowed.ShouldAllBe(item => item == true);
            notAllowed.ShouldBeFalse();
        }
コード例 #24
0
ファイル: StreamsDemo.cs プロジェクト: riezebosch/minor
        public void KanIkStreamsInElkaarVouwen()
        {
            // Arrange
            var inputPaths = new List <string> {
                "temp1.txt", "temp2.txt"
            };
            var outputPath = "output.txt";

            var data = CreateInputFiles(inputPaths);

            // Act
            CopyFilesToOutput(inputPaths, outputPath);

            // Assert
            inputPaths.ShouldAllBe(file => File.Exists(file));
            Assert.True(File.Exists(outputPath));

            CompareInputsToExtractedOutput(inputPaths, outputPath);
        }
コード例 #25
0
        public void WhenGettingAnyIntegerExceptASetOfIntegers_ThenReturnDifferentIntegersExceptTheGivenIntegersEveryTime()
        {
            var generated = new List <int>();

            for (var i = 0; i < 1000; i++)
            {
                var integer = Any.IntegerExcept(1, 5, 200, 356, 4, 53);
                generated.Add(integer);
            }

            generated.ShouldAllBe(i => i != 1 &&
                                  i != 5 &&
                                  i != 200 &&
                                  i != 356 &&
                                  i != 4 &&
                                  i != 53);
            generated.Distinct().Count()
            .ShouldBe(generated.Count);
        }
コード例 #26
0
        public void GivenListOfBuildersWithComplexCustomisations_WhenBuildingObjectsImplicitly_ThenThenTheListIsBuiltAndModifiedCorrectly()
        {
            var i = 0;
            List <StudentViewModel> studentViewModels = Builder <StudentViewModel> .CreateListOfSize(5)
                                                        .TheFirst(1).Set(x => x.FirstName, "First")
                                                        .TheNext(1).Set(x => x.LastName, "Next Last")
                                                        .TheLast(1).Set(x => x.LastName, "Last Last")
                                                        .ThePrevious(2).With(b => b.Set(x => x.LastName, "last" + (++i).ToString()))
                                                        .All().Set(x => x.EnrollmentDate, _enrollmentDate);

            studentViewModels.ShouldBeAssignableTo <IList <StudentViewModel> >();
            studentViewModels.Count.ShouldBe(5);
            studentViewModels[0].FirstName.ShouldBe("First");
            studentViewModels[1].LastName.ShouldBe("Next Last");
            studentViewModels[2].LastName.ShouldBe("last1");
            studentViewModels[3].LastName.ShouldBe("last2");
            studentViewModels[4].LastName.ShouldBe("Last Last");
            studentViewModels.ShouldAllBe(c => c.EnrollmentDate == _enrollmentDate);
        }
コード例 #27
0
        public void WhenGettingAnyIntegerExceptASetOfIntegers_ThenReturnDifferentIntegersExceptTheGivenIntegersEveryTime()
        {
            var generated = new List<int>();

            for (var i = 0; i < 1000; i++)
            {
                var integer = Any.IntegerExcept(1, 5, 200, 356, 4, 53);
                generated.Add(integer);
            }

            generated.ShouldAllBe(i => i != 1
                && i != 5
                && i != 200
                && i != 356
                && i != 4
                && i != 53);
            generated.Distinct().Count()
                .ShouldBe(generated.Count);
        }
コード例 #28
0
        public void ShouldAllBe()
        {
            DocExampleWriter.Document(() =>
            {
                var mrBurns = new Person {
                    Name = "Mr.Burns", Salary = 3000000
                };
                var kentBrockman = new Person {
                    Name = "Homer", Salary = 3000000
                };
                var homer = new Person {
                    Name = "Homer", Salary = 30000
                };
                var millionaires = new List <Person> {
                    mrBurns, kentBrockman, homer
                };

                millionaires.ShouldAllBe(m => m.Salary > 1000000);
            }, _testOutputHelper);
        }
コード例 #29
0
ファイル: XmlPoke_Tests.cs プロジェクト: Nirmal4G/msbuild
        public void PokeWithNamespace()
        {
            const string query = "//s:variable/@Name";

            XmlDocument xmlDocument = ExecuteXmlPoke(
                query: query,
                useNamespace: true,
                value: "Mert");

            XmlNamespaceManager ns = new XmlNamespaceManager(xmlDocument.NameTable);

            ns.AddNamespace("s", XmlNamespaceUsedByTests);

            List <XmlAttribute> nodes = xmlDocument.SelectNodes(query, ns)?.Cast <XmlAttribute>().ToList();

            nodes.ShouldNotBeNull($"There should be <variable /> elements with a Name attribute {Environment.NewLine}{xmlDocument.OuterXml}");

            nodes.Count.ShouldBe(3, $"There should be 3 <variable /> elements with a Name attribute {Environment.NewLine}{xmlDocument.OuterXml}");

            nodes.ShouldAllBe(i => i.Value.Equals("Mert"), $"All <variable /> elements should have Name=\"Mert\" {Environment.NewLine}{xmlDocument.OuterXml}");
        }
コード例 #30
0
        public void Shouldly_ShouldReturnAListOfEmployeesWithAHireDateGreaterThan2005()
        {
            //arrange
            List <Employee> employees = new EmployeeRepository().GetEmployeesWithHireDates();

            //act
            //IEnumerable<Employee> query = from e in employees
            //                              where e.HireDate.Year < 2005
            //                              orderby e.Name
            //                              select e;

            List <Employee> employeesHiredBefore2005 = employees
                                                       .Where(e => e.HireDate.Year < 2005)
                                                       .OrderBy(e => e.Name).ToList();

            //assert
            employeesHiredBefore2005.ShouldNotBeNull();
            employeesHiredBefore2005.Count.ShouldBe(2);
            employeesHiredBefore2005.ShouldAllBe(e => e.HireDate.Year < 2005);
            employeesHiredBefore2005[0].Name.ShouldBe("Poonam");
            employeesHiredBefore2005[1].Name.ShouldBe("Scott");
        }
コード例 #31
0
 public void Should_not_return_added_items_after_next_cache_expiration()
 {
     _actualGetResultsForCacheMiss.ShouldAllBe(x => x == false);
     _actualEntriesForCacheMiss.ShouldAllBe(x => x == null);
 }
コード例 #32
0
 public void Should_return_added_items_before_next_cache_expiration()
 {
     _actualGetResultsForCacheHit.ShouldAllBe(x => x == true);
     _actualEntriesForCacheHit.ShouldAllBe(x => _suppliedEntries.Contains(x));
 }
コード例 #33
0
        public void can_query_document_with_noda_time_types()
        {
            StoreOptions(_ =>
            {
                _.UseNodaTime();
                _.DatabaseSchemaName = "NodaTime";
            });

            var dateTime      = DateTime.UtcNow;
            var localDateTime = LocalDateTime.FromDateTime(dateTime);
            var instantUTC    = Instant.FromDateTimeUtc(dateTime.ToUniversalTime());
            var testDoc       = TargetWithDates.Generate(dateTime);

            using (var session = theStore.OpenSession())
            {
                session.Insert(testDoc);
                session.SaveChanges();
            }

            using (var query = theStore.QuerySession())
            {
                var results = new List <TargetWithDates>
                {
                    // LocalDate
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.LocalDate == localDateTime.Date),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.LocalDate < localDateTime.Date.PlusDays(1)),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.LocalDate <= localDateTime.Date.PlusDays(1)),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.LocalDate > localDateTime.Date.PlusDays(-1)),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.LocalDate >= localDateTime.Date.PlusDays(-1)),

                    //// Nullable LocalDate
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.NullableLocalDate == localDateTime.Date),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.NullableLocalDate < localDateTime.Date.PlusDays(1)),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.NullableLocalDate <= localDateTime.Date.PlusDays(1)),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.NullableLocalDate > localDateTime.Date.PlusDays(-1)),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.NullableLocalDate >= localDateTime.Date.PlusDays(-1)),

                    //// LocalDateTime
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.LocalDateTime == localDateTime),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.LocalDateTime < localDateTime.PlusSeconds(1)),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.LocalDateTime <= localDateTime.PlusSeconds(1)),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.LocalDateTime > localDateTime.PlusSeconds(-1)),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.LocalDateTime >= localDateTime.PlusSeconds(-1)),

                    //// Nullable LocalDateTime
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.NullableLocalDateTime == localDateTime),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.NullableLocalDateTime < localDateTime.PlusSeconds(1)),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.NullableLocalDateTime <= localDateTime.PlusSeconds(1)),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.NullableLocalDateTime > localDateTime.PlusSeconds(-1)),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.NullableLocalDateTime >= localDateTime.PlusSeconds(-1)),

                    //// Instant UTC
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.InstantUTC == instantUTC),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.InstantUTC < instantUTC.PlusTicks(1000)),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.InstantUTC <= instantUTC.PlusTicks(1000)),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.InstantUTC > instantUTC.PlusTicks(-1000)),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.InstantUTC >= instantUTC.PlusTicks(-1000)),

                    // Nullable Instant UTC
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.NullableInstantUTC == instantUTC),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.NullableInstantUTC < instantUTC.PlusTicks(1000)),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.NullableInstantUTC <= instantUTC.PlusTicks(1000)),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.NullableInstantUTC > instantUTC.PlusTicks(-1000)),
                    query.Query <TargetWithDates>().FirstOrDefault(d => d.NullableInstantUTC >= instantUTC.PlusTicks(-1000))
                };

                results.ShouldAllBe(x => x.Equals(testDoc));
            }
        }