Esempio n. 1
0
        public void IncludingNavigationMethodQueryVariablesIncludesIncludedNavigationMethodArgument()
        {
            var agencyQuery = hslGraphContext.Agency("248798")
                              .Include(agency => agency.routes.Select(route => route.trips.Select(trip => trip.stoptimesForDate("20170427"))));

            Assert.That(agencyQuery.QueryVariables, Does.ContainKey("serviceDay1").With.ContainValue("20170427"));
        }
Esempio n. 2
0
        public void ToMappingDictionary_CheckValues(StandardEnumWithNull keyToCheck, string expectedValue)
        {
            var dict = EnumTranslator.ToMappingDictionary <StandardEnumWithNull>();

            Assert.That(dict, Does.ContainKey(keyToCheck));
            Assert.That(dict[keyToCheck], Is.EqualTo(expectedValue));
        }
        public void WhenApplyingCustomFormatThenItWillBuildResultFromFactory()
        {
            var options = new CustomPolicyOptions()
                          .AddPolicy("add hello", IsStringNamePropertyName, value => $"Hello {value}!")
                          .AddPolicy("add welcome", IsStringNamePropertyName, value => $"{value} Welcome home.");
            var events = new List <LogEvent>();
            var logger = new LoggerConfiguration()
                         .Destructure.With(new CustomRuleDestructuringPolicy(options))
                         .WriteTo.Sink(new DelegatingSink(events.Add))
                         .CreateLogger();

            var sut = new Test {
                Name = "world"
            };

            logger.Information("Hello {@Data}", sut);

            Assert.That(events.Count, Is.EqualTo(1));
            var logEvent = events[0];

            Assert.That(logEvent.Properties, Does.ContainKey("Data"));
            Assert.That(logEvent.Properties["Data"], Is.TypeOf <StructureValue>());
            var logProperties = ((StructureValue)logEvent.Properties["Data"]).Properties;
            var nameProperty  = logProperties.FirstOrDefault(p => p.Name == nameof(Test.Name));

            Assert.That(nameProperty, Is.Not.Null);
            Assert.That(nameProperty !.Value.ToString(), Is.EqualTo("\"Hello world! Welcome home.\""));
        }
Esempio n. 4
0
        public void TestGetConfigFromFile()
        {
            const string xmlSimple =
                "<coredistributedcache factory-class=\"factory1\" append-hashcode=\"false\">" +
                "<properties><property name=\"prop1\">Value1</property></properties>" +
                "<cache region=\"foo\" expiration=\"500\" sliding=\"true\" append-hashcode=\"true\" />" +
                "</coredistributedcache>";

            var handler = new CoreDistributedCacheSectionHandler();
            var section = GetConfigurationSection(xmlSimple);
            var result  = handler.Create(null, null, section);

            Assert.That(result, Is.Not.Null, "result");
            Assert.That(result, Is.InstanceOf <CacheConfig>());
            var config = (CacheConfig)result;

            Assert.That(config.FactoryClass, Is.EqualTo("factory1"));

            Assert.That(config.Properties, Is.Not.Null, "Properties");
            Assert.That(config.Properties.Count, Is.EqualTo(1), "Properties count");
            Assert.That(config.Properties, Does.ContainKey("prop1"));
            Assert.That(config.Properties["prop1"], Is.EqualTo("Value1"));

            Assert.That(config.Regions, Is.Not.Null, "Regions");
            Assert.That(config.Regions.Length, Is.EqualTo(1), "Regions count");
            Assert.That(config.Regions[0].Region, Is.EqualTo("foo"));
            Assert.That(config.Regions[0].Properties, Does.ContainKey("cache.use_sliding_expiration"));
            Assert.That(config.Regions[0].Properties["cache.use_sliding_expiration"], Is.EqualTo("true"));
            Assert.That(config.Regions[0].Properties, Does.ContainKey("expiration"));
            Assert.That(config.Regions[0].Properties["expiration"], Is.EqualTo("500"));
            Assert.That(config.Regions[0].Properties, Does.ContainKey("cache.use_sliding_expiration"));
            Assert.That(config.Regions[0].Properties["cache.use_sliding_expiration"], Is.EqualTo("true"));

            Assert.That(config.AppendHashcodeToKey, Is.False);
        }
        public void GetLinkingMetadata_IsHandled_DuplicateKeyInMessageTemplate()
        {
            // Arrange
            const string TestValue    = "TEST VALUE";
            const string TestTemplate = "TEMPLATE {newrelic.linkingmetadata}"; // matches our metadata property name

            var wasRun   = false;
            var testDict = new Dictionary <string, string> {
                { "message", "duplicate" }
            };                                                                            // must not be empty

            Mock.Arrange(() => _testAgent.GetLinkingMetadata())
            .DoInstead(() => { wasRun = true; })
            .Returns(testDict);
            var testEnricher = new NewRelicEnricher(() => _testAgent);
            var testLogger   = SerilogTestHelpers.GetLogger(_outputSink, testEnricher);

            // Act
            testLogger.Warning(TestTemplate, TestValue);

            // Assert
            Assert.That(wasRun, Is.True);
            Assert.That(_outputSink.LogEvents.Count, Is.EqualTo(1));
            Assert.That(_outputSink.LogEvents[0].MessageTemplate.Text, Is.EqualTo(TestTemplate));
            Assert.That(_testRunDebugLogs.Count, Is.EqualTo(0));
            Assert.That(_outputSink.LogEvents[0].Properties, Does.ContainKey(LinkingMetadataKey));
            Assert.That(_outputSink.LogEvents[0].Properties[LinkingMetadataKey].ToString(), Does.Not.Contain(TestValue));
        }
        public void ShouldCallContainsKeysMethodOnDictionary()
        {
            var dictionary = new TestDictionary(20);

            Assert.That(dictionary, Does.ContainKey(20));
            Assert.That(dictionary, !Does.ContainKey(10));
        }
        public void GetLinkingMetadata_IsHandled_MetadataPropertyAdded()
        {
            // Arrange
            var wasRun   = false;
            var testDict = new Dictionary <string, string>
            {
                { "trace.id", "trace-id" },
                { "span.id", "span-id" },
                { "entity.name", "entity-name" },
                { "entity.type", "entity-type" },
                { "entity.guid", "entity-guid" },
                { "hostname", "host-name" }
            };

            Mock.Arrange(() => _testAgent.GetLinkingMetadata())
            .DoInstead(() => { wasRun = true; })
            .Returns(testDict);
            var testEnricher = new NewRelicEnricher(() => _testAgent);
            var testLogger   = SerilogTestHelpers.GetLogger(_outputSink, testEnricher);

            // Act
            testLogger.Warning(WarningLogMessage);

            // Assert
            Assert.That(wasRun, Is.True);
            Assert.That(_outputSink.LogEvents.Count, Is.EqualTo(1));
            Assert.That(_outputSink.LogEvents[0].MessageTemplate.Text, Is.EqualTo(WarningLogMessage));
            Assert.That(_outputSink.LogEvents[0].Properties, Does.ContainKey(LinkingMetadataKey));
            Assert.That(_testRunDebugLogs.Count, Is.EqualTo(0));
        }
        public void WhenMaskedWithDefaultTextThenItWillBeReplacedByFiveAsterisks()
        {
            var events = new List <LogEvent>();
            var logger = new LoggerConfiguration()
                         .Destructure.ByCustomRules(rule => rule.Masking(new[] { nameof(Test.Name) }))
                         .WriteTo.Sink(new DelegatingSink(events.Add))
                         .CreateLogger();

            var sut = new Test {
                Name = "secret", Default = "world"
            };

            logger.Information("Hello {@Data}", sut);

            Assert.That(events.Count, Is.EqualTo(1));
            var logEvent = events[0];

            Assert.That(logEvent.Properties, Does.ContainKey("Data"));
            Assert.That(logEvent.Properties["Data"], Is.TypeOf <StructureValue>());
            var properties = ((StructureValue)logEvent.Properties["Data"]).Properties;

            AssertLogProperty(properties, nameof(Test.ReadOnly), "\"never changed\"");
            AssertLogProperty(properties, nameof(Test.Default), "\"world\"");
            AssertLogProperty(properties, nameof(Test.Name), "\"*****\"");
        }
        public void WhenManyFormattersDefinedThenItWillBeAppliedInOrder()
        {
            var options = new CustomPolicyOptions()
                          .AddPolicy("add hello", (p, value) =>
                                     p.Name == nameof(Test.Name) && value is string word && !string.IsNullOrWhiteSpace(word),
                                     value => $"Hello {value}!");
            var events = new List <LogEvent>();
            var logger = new LoggerConfiguration()
                         .Destructure.With(new CustomRuleDestructuringPolicy(options))
                         .WriteTo.Sink(new DelegatingSink(events.Add))
                         .CreateLogger();

            var sut = new Test {
                Name = "world"
            };

            logger.Information("Hello {@Data}", sut);

            Assert.That(events.Count, Is.EqualTo(1));
            var logEvent = events[0];

            Assert.That(logEvent.Properties, Does.ContainKey("Data"));
            Assert.That(logEvent.Properties["Data"], Is.TypeOf <StructureValue>());
            var logProperties = ((StructureValue)logEvent.Properties["Data"]).Properties;
            var nameProperty  = logProperties.FirstOrDefault(p => p.Name == nameof(Test.Name));

            Assert.That(nameProperty, Is.Not.Null);
            Assert.That(nameProperty !.Value.ToString(), Is.EqualTo("\"Hello world!\""));
        }
        public void WhenFilteredByOneOfExcludeCallbackThenItWillNotBeIncluded()
        {
            var options = new CustomPolicyOptions()
                          .AddPolicy("exclude non writable", isExcluded: p => !p.CanWrite)
                          .AddPolicy("exclude field", isExcluded: p => p.GetMethod == null);
            var events = new List <LogEvent>();
            var logger = new LoggerConfiguration()
                         .Destructure.With(new CustomRuleDestructuringPolicy(options))
                         .WriteTo.Sink(new DelegatingSink(events.Add))
                         .CreateLogger();

            var sut = new Test {
                Name = "my name"
            };

            logger.Information("Hello {@Data}", sut);

            Assert.That(events.Count, Is.EqualTo(1));
            var logEvent = events[0];

            Assert.That(logEvent.Properties, Does.ContainKey("Data"));
            Assert.That(logEvent.Properties["Data"], Is.TypeOf <StructureValue>());
            var logProperties = ((StructureValue)logEvent.Properties["Data"]).Properties;

            Assert.That(logProperties.Select(p => p.Name),
                        Is.Not.SupersetOf(new[] { nameof(Test.ReadOnly), nameof(Test.Default) }).And.Contain(nameof(Test.Name)));
            var property = logProperties.First(p => p.Name == nameof(Test.Name));

            Assert.That(property.Value.ToString(), Is.EqualTo($"\"{sut.Name}\""));
        }
Esempio n. 11
0
        public async Task ExecuteRuleAsyncShouldReturnErrorResultWithTimeoutIfRuleTakesTooLongToExecute([Frozen] IGetsRuleContext contextFactory,
                                                                                                        [RuleContext] RuleContext context,
                                                                                                        [ExecutableModel] ExecutableRule rule,
                                                                                                        SingleRuleExecutor sut)
        {
            var timeout = TimeSpan.FromMilliseconds(100);

            Mock.Get(rule.RuleLogic).Setup(x => x.GetTimeout()).Returns(timeout);
            Mock.Get(rule.RuleLogic)
            .Setup(x => x.GetResultAsync(It.IsAny <object>(), It.IsAny <object>(), It.IsAny <RuleContext>(), It.IsAny <CancellationToken>()))
            .Returns(() => Task.Run(async() => {
                await Task.Delay(200);
                return(CommonResults.Pass());
            }));
            Mock.Get(contextFactory).Setup(x => x.GetRuleContext(rule)).Returns(context);

            var result = await sut.ExecuteRuleAsync(rule);

            Assert.Multiple(() =>
            {
                Assert.That(result.Outcome, Is.EqualTo(RuleOutcome.Errored), "Result has error outcome");
                Assert.That(result.Data, Does.ContainKey(RuleResult.RuleTimeoutDataKey), "Result has a rule-timeout data key");

                if (result.Data.TryGetValue(RuleResult.RuleTimeoutDataKey, out var timeoutData))
                {
                    Assert.That(timeoutData, Is.EqualTo(timeout), "Timeout data is equal");
                }
            });
        }
Esempio n. 12
0
        public void TestStatusesMaps()
        {
            var(webClient, webClientFactory) = MockWebClientFactory(
                new Dictionary <string, object>
            {
                { requestUrl, data_statuses_1 }
            });

            var client = new TestRailApiClient(
                data_config,
                webClientFactory.Object);

            var statuses = client.Statuses;

            Assert.That(statuses, Has.Count.EqualTo(4));
            Assert.That(statuses, Does.ContainKey("status-1"));
            Assert.That(statuses, Does.ContainKey("status-2"));
            Assert.That(statuses, Does.ContainKey("STATUS"));
            Assert.That(statuses, Does.ContainKey("STATUS 3"));

            var statusesById = client.StatusesById;

            Assert.That(statusesById, Has.Count.EqualTo(3));
            Assert.That(statusesById, Does.ContainKey(1));
            Assert.That(statusesById, Does.ContainKey(2));
            Assert.That(statusesById, Does.ContainKey(3));
        }
Esempio n. 13
0
        public async Task RemoveUserFromAllProjectsAsync_DisassociatesUserAndProjects()
        {
            var    env                = new TestEnvironment();
            string requestingUser     = User02;
            string userToDisassociate = User01;

            Assert.That(env.GetProject(Project01).UserRoles[requestingUser] != TestProjectRole.Administrator,
                        "setup: user requesting deletion should not be a project administrator to demonstrate the " +
                        "functionality");
            Assert.That(env.GetProject(Project02).UserRoles[requestingUser] != TestProjectRole.Administrator,
                        "setup: user requesting deletion should not be a project administrator to demonstrate the " +
                        "functionality");
            Assert.That(requestingUser, Is.Not.EqualTo(userToDisassociate), "setup: not demonstrating functionality");

            Assert.That(env.GetProject(Project01).UserRoles, Does.ContainKey(userToDisassociate), "setup");
            Assert.That(env.GetUser(userToDisassociate).Sites[SiteId].Projects, Does.Contain(Project01), "setup");
            Assert.That(env.GetProject(Project02).UserRoles, Does.ContainKey(userToDisassociate), "setup");
            Assert.That(env.GetUser(userToDisassociate).Sites[SiteId].Projects, Does.Contain(Project02), "setup");
            // SUT
            await env.Service.RemoveUserFromAllProjectsAsync(requestingUser, userToDisassociate);

            Assert.That(env.GetProject(Project01).UserRoles, Does.Not.ContainKey(userToDisassociate));
            Assert.That(env.GetUser(userToDisassociate).Sites[SiteId].Projects, Does.Not.Contain(Project01));
            Assert.That(env.GetProject(Project02).UserRoles, Does.Not.ContainKey(userToDisassociate));
            Assert.That(env.GetUser(userToDisassociate).Sites[SiteId].Projects, Does.Not.Contain(Project02));
        }
        public void ShouldCallContainsKeysMethodOnLookupInterface()
        {
            var dictionary = new TestLookup(20);

            Assert.That(dictionary, Does.ContainKey(20));
            Assert.That(dictionary, !Does.ContainKey(43));
        }
        public void ShouldCallContainsKeysMethodOnReadOnlyInterface()
        {
            var dictionary = new TestReadOnlyDictionary("BOB");

            Assert.That(dictionary, Does.ContainKey("BOB"));
            Assert.That(dictionary, !Does.ContainKey("ALICE"));
        }
Esempio n. 16
0
        public void ShouldBeAbleToExecuteJavascriptAndReturnABasicObjectLiteral()
        {
            if (!(driver is IJavaScriptExecutor))
            {
                return;
            }

            driver.Url = javascriptPage;

            object result = ExecuteScript("return {abc: '123', tired: false};");

            Assert.That(result, Is.InstanceOf <Dictionary <string, object> >());
            Dictionary <string, object> map = (Dictionary <string, object>)result;

            Dictionary <string, object> expected = new Dictionary <string, object>();

            expected.Add("abc", "123");
            expected.Add("tired", false);

            Assert.AreEqual(expected.Count, map.Count, "Expected:<" + expected.Count + ">, but was:<" + map.Count + ">");
            foreach (string expectedKey in expected.Keys)
            {
                Assert.That(map, Does.ContainKey(expectedKey));
                Assert.That(map[expectedKey], Is.EqualTo(expected[expectedKey]));
            }
        }
Esempio n. 17
0
        public void ShouldCallContainsKeysMethodOnPlainDictionary()
        {
            var dictionary = new TestNonGenericDictionary(99);

            Assert.That(dictionary, Does.ContainKey(99));
            Assert.That(dictionary, !Does.ContainKey(35));
        }
        public void ShouldCallContainsKeysMethodWithTKeyParameterOnNewMethod()
        {
            var dictionary = new TestDictionaryGeneric <string, string> {
                { "ALICE", "BOB" }, { "CALUM", "DENNIS" }
            };

            Assert.That(dictionary, Does.ContainKey("BOB"));
        }
        public void SucceedsWhenKeyIsPresentUsingContainsKeyUsingHashtableDefaultComparer()
        {
            var table = new Hashtable {
                { "ALICE", "BOB" }, { "CALUM", "DENNIS" }
            };

            Assert.That(table, !Does.ContainKey("calum"));
        }
        public void SucceedsWhenKeyIsPresentUsingContainKey()
        {
            var dictionary = new Dictionary <string, string> {
                { "Hello", "World" }, { "Hola", "Mundo" }
            };

            Assert.That(dictionary, Does.ContainKey("Hola"));
        }
        public void KeyIsNotPresentUsingContainsKeyUsingKeyedCollectionDefaultComparer()
        {
            var list = new TestKeyedCollection {
                "ALICE", "BOB", "CALUM"
            };

            Assert.That(list, !Does.ContainKey("alice"));
        }
Esempio n. 22
0
        public void TestScriptObjectImport()
        {
            {
                var obj = new ScriptObject();
                obj.Import(typeof(MyStaticObject));

                Assert.That(obj, Does.ContainKey("static_field_a"));
                Assert.AreEqual("ValueStaticFieldA", obj["static_field_a"]);
                Assert.True(obj.ContainsKey("static_field_b"));
                Assert.AreEqual("ValueStaticFieldB", obj["static_field_b"]);
                Assert.True(obj.ContainsKey("static_property_a"));
                Assert.AreEqual("ValueStaticPropertyA", obj["static_property_a"]);
                Assert.True(obj.ContainsKey("static_property_b"));
                Assert.AreEqual("ValueStaticPropertyB", obj["static_property_b"]);
                Assert.True(obj.ContainsKey("static_yoyo"));
                Assert.False(obj.ContainsKey("invalid"));
            }

            // Test MemberFilterDelegate
            {
                var obj = new ScriptObject();
                obj.Import(typeof(MyStaticObject), filter: member => member.Name.Contains("Property"));

                Assert.That(obj, Does.Not.ContainKey("static_field_a"));
                Assert.That(obj, Does.Not.ContainKey("static_field_b"));
                Assert.That(obj, Does.ContainKey("static_property_a"));
                Assert.AreEqual("ValueStaticPropertyA", obj["static_property_a"]);
                Assert.That(obj, Does.ContainKey("static_property_b"));
                Assert.AreEqual("ValueStaticPropertyB", obj["static_property_b"]);
                Assert.That(obj, Does.Not.ContainKey("static_yoyo"));
                Assert.That(obj, Does.Not.ContainKey("invalid"));
            }

            // Test MemberRenamerDelegate
            {
                var obj = new ScriptObject();
                obj.Import(typeof(MyStaticObject), renamer: member => member.Name);

                Assert.That(obj, Does.ContainKey(nameof(MyStaticObject.StaticFieldA)));
                Assert.That(obj, Does.ContainKey(nameof(MyStaticObject.StaticFieldB)));
                Assert.That(obj, Does.ContainKey(nameof(MyStaticObject.StaticPropertyA)));
                Assert.AreEqual("ValueStaticPropertyA", obj[nameof(MyStaticObject.StaticPropertyA)]);
                Assert.That(obj, Does.ContainKey(nameof(MyStaticObject.StaticPropertyB)));
                Assert.AreEqual("ValueStaticPropertyB", obj[nameof(MyStaticObject.StaticPropertyB)]);
                Assert.That(obj, Does.ContainKey(nameof(MyStaticObject.StaticYoyo)));
                Assert.That(obj, Does.Not.ContainKey(nameof(MyStaticObject.Invalid)));
            }

            {
                var obj = new ScriptObject();
                obj.Import(new MyObject2(), renamer: member => member.Name);

                Assert.AreEqual(9, obj.Count);
                Assert.That(obj, Does.ContainKey(nameof(MyStaticObject.StaticFieldA)));
                Assert.That(obj, Does.ContainKey(nameof(MyObject.PropertyA)));
                Assert.That(obj, Does.ContainKey(nameof(MyObject2.PropertyC)));
            }
        }
        public void SucceedsWhenKeyIsPresentUsingContainsKeyUsingHashtableCustomComparer()
        {
            var table = new Hashtable(StringComparer.OrdinalIgnoreCase)
            {
                { "ALICE", "BOB" }, { "CALUM", "DENNIS" }
            };

            Assert.That(table, Does.ContainKey("alice"));
        }
        public void SucceedsWhenKeyIsPresentUsingContainsKeyWhenUsingKeyedCollectionCustomComparer()
        {
            var list = new TestKeyedCollection(StringComparer.OrdinalIgnoreCase)
            {
                "ALICE", "BOB", "CALUM"
            };

            Assert.That(list, Does.ContainKey("calum"));
        }
        public void SucceedsWhenKeyIsNotPresentUsingContainsKeyUsingLookupDefaultComparer()
        {
            var list = new List <string> {
                "ALICE", "BOB", "CATHERINE"
            };
            ILookup <string, string> lookup = list.ToLookup(x => x);

            Assert.That(lookup, !Does.ContainKey("alice"));
        }
        public void SucceedsWhenKeyIsPresentUsingContainsKeyWhenUsingLookupCustomComparer()
        {
            var list = new List <string> {
                "ALICE", "BOB", "CATHERINE"
            };
            ILookup <string, string> lookup = list.ToLookup(x => x, StringComparer.OrdinalIgnoreCase);

            Assert.That(lookup, Does.ContainKey("catherine"));
        }
        public void SucceedsWhenKeyIsPresentUsingContainsKeyWhenDictionaryUsingCustomComparer()
        {
            var dictionary = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
            {
                { "Hello", "World" }, { "Hola", "Mundo" }
            };

            Assert.That(dictionary, Does.ContainKey("hola"));
        }
Esempio n. 28
0
        public void Assert_does_contain_key_and_value()
        {
            var people = new Dictionary <string, int>()
            {
                ["carlos"] = 29, ["Jazzy"] = 9
            };

            Assert.That(people, Does.ContainKey("carlos"));
            Assert.That(people, Does.ContainValue(30));
        }
Esempio n. 29
0
        public async Task WhenNonExistingWebSiteIsDeletedThenThereShouldBeNotFoundErrorAndSaveChangesShouldNotBeCalled()
        {
            _webSiteManagerData.WebSiteRepository.Returns(_webSiteRepository);
            var serviceResult = await _webSiteService.DeleteAsync(1);

            await _webSiteManagerData.DidNotReceive().SaveChangesAsync();

            Assert.That(serviceResult.HasErrors, Is.True, "There should be no errors");
            Assert.That(serviceResult.Errors, Does.ContainKey(ErrorType.NotFound), "There should be not found error");
        }
Esempio n. 30
0
        public void AddNullableBoolean_FalseValue()
        {
            var  @params = new VkParameters();
            bool?nbool   = false;

            @params.Add(name: "NullableBoolean", nullableValue: nbool);
            Assert.That(actual: @params, expression: Does.ContainKey(expected: "NullableBoolean"));
            var val = @params[key : "NullableBoolean"];

            Assert.That(actual: val, expression: Is.EqualTo(expected: "0"));
        }