예제 #1
0
        public async Task List_LastNameIsChen_ReturnsChen()
        {
            // Arrange
            var client = _factory.CreateClient();

            // Act
            var response = await client.GetAsync("/api/randomusers?lastName=Chen");

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Contains("application/json", response.Content.Headers.ContentType.ToString());
            var content = await response.Content.ReadAsStringAsync();

            Assert.False(string.IsNullOrWhiteSpace(content));

            var users = JsonSerializer.Deserialize <IList <RandomUserDto> >(content, new JsonSerializerOptions {
                PropertyNameCaseInsensitive = true
            });

            Assert.All(users, user => Assert.Equal("Chen", user.Name.Last));
        }
예제 #2
0
        public async Task ShouldEnumerateTopLevelDirectories()
        {
            // Arrange
            var expectedDirectories = new[] { "A", "B", "C" };
            var actualDirectories   = new List <string>();
            var actualExists        = new List <bool>();

            // Act
            await foreach (var directory in root.EnumerateDirectoriesAsync().ConfigureAwait(false))
            {
                actualDirectories.Add(directory.Name);

                var exists = await directory.ExistsAsync().ConfigureAwait(false);

                actualExists.Add(exists);
            }

            // Assert
            AssertEx.Equivalence(expectedDirectories, actualDirectories);
            Assert.All(actualExists, Assert.True);
        }
예제 #3
0
        public void Validate_ShouldReturnCombinedPropertyName_WhenFailurePropertyNameIsNotNull()
        {
            // Arrange
            var model = _fixture.Create <PostFigureModel>();

            ValidationFailure[] failures = _fixture.CreateMany <ValidationFailure>().ToArray();

            _figureDescriptorMock
            .Setup(descriptor => descriptor.ValidateProps(It.IsAny <IDictionary <string, double> >()))
            .Returns(new ValidationResult(failures));

            // Act
            ValidationResult validationResult = _validator.Validate(model);

            // Assert
            Assert.NotNull(validationResult);
            Assert.False(validationResult.IsValid);

            Assert.All(validationResult.Errors,
                       error => Assert.Contains(failures, failure => error.PropertyName == $"{nameof(PostFigureModel.FigureProps)}.{failure.PropertyName}"));
        }
예제 #4
0
        public void SubsetInvariants()
        {
            // Arrange
            var set1 = new Set <int> {
                1, 2
            };
            var set2 = new Set <int> {
                1, 2, 3, 4, 5
            };

            // Act

            // Assert
            Assert.True(set1.Subset(set2));

            // A \ B = {0}
            Assert.True(!set1.Difference(set2).Any());

            // A intersect B = {A}
            Assert.All(set1.Intersect(set2), i => Assert.True(set1.Contains(i)));
        }
예제 #5
0
    public async Task Shared_inventory_can_be_found()
    {
        await using Composer services = new();
        var sut         = services.Resolve <Gw2Client>();
        var accessToken = services.Resolve <ApiKey>();

        var actual = await sut.Inventory.GetSharedInventory(accessToken.Key);

        Assert.NotEmpty(actual.Value);
        Assert.All(
            actual.Value,
            slot =>
        {
            if (slot is not null)
            {
                Assert.True(slot.Id > 0);
                Assert.True(slot.Count > 0);
            }
        }
            );
    }
예제 #6
0
        public static void OfType_SomeValidNull(Labeled <ParallelQuery <int> > labeled, int count)
        {
            ParallelQuery <int> query = labeled.Item;
            int nullCount             = 0;
            int seen = count / 2;

            Assert.All(query.Select(x => x >= count / 2 ? (object)(x.ToString()) : (object)(string)null).OfType <string>(),
                       x =>
            {
                if (string.IsNullOrEmpty(x))
                {
                    nullCount++;
                }
                else
                {
                    Assert.Equal(seen++, int.Parse(x));
                }
            });
            Assert.Equal(count, seen);
            Assert.Equal(0, nullCount);
        }
예제 #7
0
        public void ReplacingInstructionInInstructionExpression()
        {
            var ast = ConstructAst(new[]
            {
                DummyInstruction.Push(0, 1),
                DummyInstruction.Pop(1, 1),
                DummyInstruction.Ret(2)
            });

            Assert.Single(ast.Nodes);
            var block = ast.Entrypoint.Contents.Instructions;

            Assert.Equal(3, block.Count);
            Assert.All(block, node => Assert.Null(node.Parent));

            var instruction = DummyInstruction.Jmp(0, 69);
            var asmt        = Assert.IsType <AssignmentStatement <DummyInstruction> >(block[0]);
            var expr        = Assert.IsType <InstructionExpression <DummyInstruction> >(asmt.Expression);

            Assert.Equal(instruction, expr.WithInstruction(instruction).Instruction);
        }
예제 #8
0
        public void ResolvesPublicClassFieldsAndProperties()
        {
            var resolution = Resolver.ResolveType <VisibilityClass>() as RecordResolution;

            Assert.NotNull(resolution);
            Assert.False(resolution.IsNullable);
            Assert.Equal(typeof(VisibilityClass), resolution.Type);

            Assert.False(resolution.Name.IsSetExplicitly);
            Assert.Equal(typeof(VisibilityClass).Name, resolution.Name.Value);

            Assert.False(resolution.Namespace.IsSetExplicitly);
            Assert.Equal(typeof(VisibilityClass).Namespace, resolution.Namespace.Value);

            Assert.All(resolution.Fields, f => Assert.False(f.Name.IsSetExplicitly));
            Assert.All(resolution.Fields, f => Assert.Equal(typeof(int), f.Type));
            Assert.Collection(resolution.Fields,
                              f => Assert.Equal(nameof(VisibilityClass.PublicField), f.Name.Value),
                              f => Assert.Equal(nameof(VisibilityClass.PublicProperty), f.Name.Value)
                              );
        }
예제 #9
0
        public async Task GetAll_BasicSearchByEssFileNumber_MatchedElementReturned()
        {
            var fromCommunity = await GetRandomSeededCommunity();

            var toCommunity = await GetRandomSeededCommunity();

            var incidentTaskId = await SeedIncident(fromCommunity.Id);

            var registrationId = await di.CreateEvacueeRegistrationAsync(RegistrationGenerator.GenerateCompleted(incidentTaskId, toCommunity.Id));

            var registration = await di.GetEvacueeRegistrationAsync(registrationId);

            var incidentCommunityName = fromCommunity.Name;

            var result = await di.GetEvacueesPaginatedAsync(new EvacueeSearchQueryParameters()
            {
                Query = registrationId
            });

            Assert.All(result.Items, e => Assert.Equal(registrationId, e.RegistrationId));
        }
예제 #10
0
        public async Task LoadCertsAsync()
        {
            var certs = await Certificates.ReceiverCertificates.Load();

            Assert.NotEmpty(certs.Certificates);
            Assert.NotEmpty(certs.RootCertificates);
            Assert.NotEmpty(certs.IntermediateCertificates);

            foreach (var certItem in certs.Certificates)
            {
                Assert.NotNull(certItem.Key);
                Assert.NotNull(certItem.Value);
                Assert.Equal(8, certItem.Key.Length);

                var chain = certs.GetCertificateChain(certItem.Value);
                Assert.NotNull(chain);
                Assert.Same(certItem.Value, chain.Certificate);
                Assert.Contains(chain.RootCertificate, certs.RootCertificates);
                Assert.All(chain.IntermediateCertificates, immedCert => Assert.Contains(immedCert, certs.IntermediateCertificates));
            }
        }
예제 #11
0
        public async Task RuleForEach_async_RunsTasksSynchronously()
        {
            var validator = new InlineValidator <Person>();
            var result    = new List <bool>();

            validator.RuleForEach(x => x.Children).MustAsync(async(person, token) =>
                                                             await ExclusiveDelay(1)
                                                             .ContinueWith(t => result.Add(t.Result), token)
                                                             .ContinueWith(t => true, token)
                                                             );

            await validator.ValidateAsync(new Person()
            {
                Children = new List <Person> {
                    new Person(), new Person()
                }
            });

            Assert.NotEmpty(result);
            Assert.All(result, Assert.True);
        }
        public async Task CanRegisterAndOverrideSingletonServiceIsPerTenant_WhenUseMultitenancy()
        {
            // Act
            string responseFirstTenant = await ClientOverrideSingleton.GetStringAsync(UrlTenant1).ConfigureAwait(false);

            string responseSecondTenant = await ClientOverrideSingleton.GetStringAsync(UrlTenant2).ConfigureAwait(false);

            // Assert
            string[] col = new[] { responseFirstTenant, responseFirstTenant };
            Assert.All(col, x => Assert.NotNull(x));
            Assert.All(col, x => Assert.NotEqual(string.Empty, x));

            // Begin with tenant1.
            Assert.StartsWith("Tenant 1", responseFirstTenant);

            // Begin with tenant2.
            Assert.StartsWith("Tenant 2", responseSecondTenant);

            Assert.Equal("Tenant 1::ValueSingletonService_Override_Tenant1", responseFirstTenant);
            Assert.Equal("Tenant 2::ValueSingletonService_Override_Tenant2", responseSecondTenant);
        }
        public void SequenceModel_values_null_for_default_min_max_start()
        {
            var sql     = @"CREATE SEQUENCE [TinyIntSequence_defaults]
    AS tinyint;
CREATE SEQUENCE [SmallIntSequence_defaults]
    AS smallint;
CREATE SEQUENCE [IntSequence_defaults]
    AS int;
CREATE SEQUENCE [DecimalSequence_defaults]
    AS decimal;
CREATE SEQUENCE [NumericSequence_defaults]
    AS numeric;";
            var dbModel = CreateModel(sql);

            Assert.All(dbModel.Sequences.Where(s => s.Name.EndsWith("_defaults")), s =>
            {
                Assert.Null(s.Start);
                Assert.Null(s.Min);
                Assert.Null(s.Max);
            });
        }
예제 #14
0
        public void LoopReversed()
        {
            // Artificially construct a looping construct.
            var graph = TestGraphs.CreateLoop();
            var n1    = graph.GetNodeById(1);
            var n2    = graph.GetNodeById(2);
            var n3    = graph.GetNodeById(3);
            var n4    = graph.GetNodeById(4);

            // Record a depth first traversal.
            var traversal = new DepthFirstTraversal(true);
            var recorder  = new TraversalOrderRecorder(traversal);

            traversal.Run(n4);

            // Check if n1 is before any node in the traversal.
            Assert.All(graph.GetNodes(),
                       n => Assert.True(n4 == n || recorder.GetIndex(n4) < recorder.GetIndex(n)));

            Assert.True(recorder.GetIndex(n1) > recorder.GetIndex(n3));
        }
예제 #15
0
        public async Task Convert_should_return_values_when_source_and_rate_service_returns_rates()
        {
            const decimal rate            = 100m;
            var           rateServiceMock = new Mock <IRateService>();

            rateServiceMock.Setup(m => m.Get(It.IsAny <Currencies>(), It.IsAny <Currencies>()))
            .ReturnsAsync(Result.Success <decimal, ProblemDetails>(rate));

            var service = new ConversionService(new NullLoggerFactory(), rateServiceMock.Object, _fixture.Factory);

            var(isSuccess, _, values, _) = await service.Convert(Currencies.USD, Currencies.AED, _values);

            Assert.True(isSuccess);
            Assert.Equal(_values.Count, values.Count);
            Assert.All(values, pair =>
            {
                var(k, v) = pair;
                Assert.Equal(k.Amount * rate, v.Amount);
                Assert.Contains(k.Amount, _values);
            });
        }
예제 #16
0
        public async Task GetAll_BasicSearchByHOHLastNamePartial_MatchedElementReturned()
        {
            var fromCommunity = await GetRandomSeededCommunity();

            var toCommunity = await GetRandomSeededCommunity();

            var incidentTaskId = await SeedIncident(fromCommunity.Id);

            var registrationId = await di.CreateEvacueeRegistrationAsync(RegistrationGenerator.GenerateCompleted(incidentTaskId, toCommunity.Id));

            var registration = await di.GetEvacueeRegistrationAsync(registrationId);

            var lastName = registration.HeadOfHousehold.LastName.Substring(1, 3);

            var result = await di.GetEvacueesPaginatedAsync(new EvacueeSearchQueryParameters()
            {
                Query = lastName
            });

            Assert.All(result.Items, e => Assert.Contains(lastName, e.LastName));
        }
예제 #17
0
        public static void Union_SecondOrdered_NotPipelined(Labeled <ParallelQuery <int> > left, int leftCount, Labeled <ParallelQuery <int> > right, int rightCount)
        {
            ParallelQuery <int> leftQuery     = left.Item;
            ParallelQuery <int> rightQuery    = right.Item;
            IntegerRangeSet     seenUnordered = new IntegerRangeSet(0, leftCount);
            int seen = leftCount;

            Assert.All(leftQuery.Union(rightQuery).ToList(), x =>
            {
                if (x >= leftCount)
                {
                    Assert.Equal(seen++, x);
                }
                else
                {
                    seenUnordered.Add(x);
                }
            });
            Assert.Equal(leftCount + rightCount, seen);
            seenUnordered.AssertComplete();
        }
예제 #18
0
        public void TryCreateSignature_UsesCreateSignature()
        {
            var input = new byte[1024];

            new Random(42).NextBytes(input);
            int bytesWritten = 0;

            using (var wrapperDsa = new OverrideAbstractDSA(DSA.Create(1024)))
            {
                byte[] initialSig = wrapperDsa.CreateSignature(input);
                byte[] actualSig  = new byte[initialSig.Length];

                Assert.False(wrapperDsa.TryCreateSignature(input, new Span <byte>(actualSig, 0, actualSig.Length - 1), out bytesWritten));
                Assert.Equal(0, bytesWritten);
                Assert.All(actualSig, b => Assert.Equal(0, b));

                Assert.True(wrapperDsa.TryCreateSignature(input, actualSig, out bytesWritten));
                Assert.Equal(initialSig.Length, bytesWritten);
                Assert.Contains(actualSig, b => b != 0);
            }
        }
예제 #19
0
        public static void OfType_SomeNull(Labeled <ParallelQuery <int> > labeled, int count)
        {
            ParallelQuery <int> query = labeled.Item;
            int nullCount             = 0;
            int seen = count / 2;

            Assert.All(query.Select(x => x >= count / 2 ? (object)(int?)x : (int?)null).OfType <int?>(),
                       x =>
            {
                if (!x.HasValue)
                {
                    nullCount++;
                }
                else
                {
                    Assert.Equal(seen++, x.Value);
                }
            });
            Assert.Equal(count, seen);
            Assert.Equal(0, nullCount);
        }
예제 #20
0
        public void DirectoryLongerThanMaxLongPathWithExtendedSyntax_ThrowsException()
        {
            var paths = IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath(), useExtendedSyntax: true);

            // Long directory path with extended syntax throws PathTooLongException on Desktop.
            // Everywhere else, it may be either PathTooLongException or DirectoryNotFoundException
            if (PlatformDetection.IsFullFramework)
            {
                Assert.All(paths, path => { Assert.Throws <PathTooLongException>(() => Create(path)); });
            }
            else
            {
                Assert.All(paths,
                           path =>
                {
                    AssertExtensions
                    .ThrowsAny <PathTooLongException, DirectoryNotFoundException>(
                        () => Create(path));
                });
            }
        }
예제 #21
0
        private void VerifyEventWaitHandleSecurity(EventWaitHandleSecurity expectedSecurity, EventWaitHandleSecurity actualSecurity)
        {
            Assert.Equal(typeof(EventWaitHandleRights), expectedSecurity.AccessRightType);
            Assert.Equal(typeof(EventWaitHandleRights), actualSecurity.AccessRightType);

            List <EventWaitHandleAccessRule> expectedAccessRules = expectedSecurity.GetAccessRules(includeExplicit: true, includeInherited: false, typeof(SecurityIdentifier))
                                                                   .Cast <EventWaitHandleAccessRule>().ToList();

            List <EventWaitHandleAccessRule> actualAccessRules = actualSecurity.GetAccessRules(includeExplicit: true, includeInherited: false, typeof(SecurityIdentifier))
                                                                 .Cast <EventWaitHandleAccessRule>().ToList();

            Assert.Equal(expectedAccessRules.Count, actualAccessRules.Count);
            if (expectedAccessRules.Count > 0)
            {
                Assert.All(expectedAccessRules, actualAccessRule =>
                {
                    int count = expectedAccessRules.Count(expectedAccessRule => AreAccessRulesEqual(expectedAccessRule, actualAccessRule));
                    Assert.True(count > 0);
                });
            }
        }
예제 #22
0
        public async Task GetAllValidJobs()
        {
            _client.DefaultRequestHeaders.Add(TenantModel.DomainField, BoschTenants.BoschBlueDomain);
            var response = await _client.GetAsync($"/api/jobs");

            _logger.LogDebug("HTTP GET of Jobs returned status code: " + response.StatusCode);
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.True(response.Headers.Contains("X-Pagination"));
            Assert.NotNull(response.Content);
            var jsonContent = await response.Content.ReadAsStringAsync();

            _logger.LogDebug("HTTP GET of Jobs returned contents: " + jsonContent);
            Assert.False(string.IsNullOrWhiteSpace(jsonContent));
            var jobs = JsonConvert.DeserializeObject <JobModel[]>(jsonContent);

            Assert.NotNull(jobs);
            _logger.LogDebug("HTTP GET of Jobs returned a count of N jobs: " + jobs.Length);
            Assert.True(jobs.Length > 0);
            Assert.All(jobs, j => Assert.False(string.IsNullOrWhiteSpace(j.Name)));
            Assert.All(jobs, j => Assert.False(j.JobId <= 0));
        }
예제 #23
0
        [PlatformSpecific(TestPlatforms.Windows)] // In Windows, trailing whitespace in a path is trimmed appropriately
        public void TrailingWhitespaceExistence()
        {
            // This test relies on \\?\ support

            DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());

            Assert.All(IOInputs.GetWhiteSpace(), (component) =>
            {
                string path = testDir.FullName + component;
                Assert.True(Exists(path), path); // string concat in case Path.Combine() trims whitespace before Exists gets to it
                Assert.False(Exists(IOInputs.ExtendedPrefix + path), path);
            });

            Assert.All(IOInputs.GetSimpleWhiteSpace(), (component) =>
            {
                string path = GetTestFilePath(memberName: "Extended") + component;
                testDir     = Directory.CreateDirectory(IOInputs.ExtendedPrefix + path);
                Assert.False(Exists(path), path);
                Assert.True(Exists(testDir.FullName));
            });
        }
예제 #24
0
        public async Task TestExceptions()
        {
            var tb1 = new TransformBlock <int, int>((Func <int, int>)(i => { throw new InvalidCastException(); }));
            var tb2 = new TransformBlock <int, int>((Func <int, Task <int> >)(i => { throw new InvalidProgramException(); }));
            var tb3 = new TransformBlock <int, int>((Func <int, Task <int> >)(i => Task.Run((Func <int>)(() => { throw new InvalidTimeZoneException(); }))));

            for (int i = 0; i < 3; i++)
            {
                tb1.Post(i);
                tb2.Post(i);
                tb3.Post(i);
            }

            await Assert.ThrowsAsync <InvalidCastException>(() => tb1.Completion);

            await Assert.ThrowsAsync <InvalidProgramException>(() => tb2.Completion);

            await Assert.ThrowsAsync <InvalidTimeZoneException>(() => tb3.Completion);

            Assert.All(new[] { tb1, tb2, tb3 }, tb => Assert.True(tb.InputCount == 0 && tb.OutputCount == 0));
        }
예제 #25
0
        public void InsertWithByteArray()
        {
            var fauxImagebytes = new byte[] { 0x1, 0x3, 0x3, 0x7 };
            var query          = new Query("Books")
                                 .AsInsert(
                new[] { "Id", "CoverImageBytes" },
                new object[]
            {
                1,
                fauxImagebytes
            });

            var c = Compilers.Compile(query);

            Assert.All(c.Values, a => Assert.Equal(2, a.NamedBindings.Count));

            var exemplar = c[EngineCodes.SqlServer];

            Assert.Equal("INSERT INTO [Books] ([Id], [CoverImageBytes]) VALUES (?, ?)", exemplar.RawSql);
            Assert.Equal("INSERT INTO [Books] ([Id], [CoverImageBytes]) VALUES (@p0, @p1)", exemplar.Sql);
        }
예제 #26
0
        /// <summary>
        /// Verifies whether the <see cref="EnumerationType"/> Has the Method corresponding
        /// with the <paramref name="expectedMethodName"/>. We also know the methods in question
        /// to be <see cref="MethodInfo.IsStatic"/>, <see cref="MethodBase.IsPublic"/>, and to
        /// have parameters aligned with <see cref="paramPredicates"/>, for starters.
        /// </summary>
        /// <param name="expectedMethodName"></param>
        /// <param name="expectedReturnType"></param>
        /// <param name="allParamsPredicate"></param>
        /// <param name="paramPredicates"></param>
        private static void VerifyHasMethod(string expectedMethodName, Type expectedReturnType
                                            , Action <ParameterInfo> allParamsPredicate, params Action <ParameterInfo>[] paramPredicates)
        {
            // Do a bit of vetting of the parameters themselves.
            Assert.NotNull(expectedReturnType);
            Assert.NotNull(allParamsPredicate);
            Assert.NotEmpty(paramPredicates);
            Assert.All(paramPredicates, Assert.NotNull);

            var methodInfo = EnumerationType.GetMethods().SingleOrDefault(
                m => m.IsStatic && m.IsPublic && m.Name == expectedMethodName &&
                m.GetParameters().Length == paramPredicates.Length);

            Assert.NotNull(methodInfo);

            var parameters = methodInfo.GetParameters();

            Assert.All(parameters, allParamsPredicate);
            Assert.Collection(parameters, paramPredicates);
            Assert.Equal(expectedReturnType, methodInfo.ReturnType);
        }
예제 #27
0
        public void ShouldGetTagNamesFromFilePath(string documentPath, int tagsNumber)
        {
            // Arrange
            var expectedTags = new List <string>()
            {
                "Title",
                "Subtitle"
            };
            IEnumerable <string> actualTagsToReplace;

            // Act
            using (var document = new OpenXmlDocument(documentPath))
            {
                actualTagsToReplace = document.GetTagNames();
            }

            // Assert
            Assert.NotEmpty(actualTagsToReplace);
            Assert.Equal(tagsNumber, actualTagsToReplace.Count());
            Assert.All(expectedTags, expectedTag => Assert.Contains(expectedTag, actualTagsToReplace));
        }
예제 #28
0
        public void Check_prime_numbers(IEnumerable <int> primeNumbers)
        {
            Assert.NotNull(primeNumbers);
            primeNumbers = primeNumbers.ToArray();

            bool IsPrime(int value)
            {
                for (var i = 2; i *i <= value; i++)
                {
                    if (value % i == 0)
                    {
                        return(false);
                    }
                }
                return(true);
            }

            Assert.All(primeNumbers, x => Assert.True(IsPrime(x), $"Value '{x}' was not a Prime Number."));

            OutputHelper.WriteLine($"Prime Numbers are: {Join(", ", primeNumbers.Select(x => $"{x}"))}");
        }
예제 #29
0
        public void FireOnInvadersDecreasesInvadersHealth()
        {
            var map    = new Map(3, 3);
            var target = new Tower(new MapLocation(0, 0, map));

            var invaders = new InvaderMock[]
            {
                new InvaderMock()
                {
                    Location = new MapLocation(0, 0, map)
                },
                new InvaderMock()
                {
                    Location = new MapLocation(0, 0, map)
                }
            };

            target.FireOnInvaders(invaders);

            Assert.All(invaders, i => Assert.Equal(1, i.Health));
        }
        public static void GroupJoin_Unordered_NotPipelined(int leftCount, int rightCount)
        {
            ParallelQuery <int> leftQuery  = UnorderedSources.Default(leftCount);
            ParallelQuery <int> rightQuery = UnorderedSources.Default(rightCount);
            IntegerRangeSet     seen       = new IntegerRangeSet(0, leftCount);

            Assert.All(leftQuery.GroupJoin(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)).ToList(),
                       p =>
            {
                seen.Add(p.Key);
                if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor)
                {
                    Assert.Equal(p.Key * KeyFactor, Assert.Single(p.Value));
                }
                else
                {
                    Assert.Empty(p.Value);
                }
            });
            seen.AssertComplete();
        }