public void FlowElementCached_Process_CheckCacheGet()
        {
            // Arrange

            var evidence = new Dictionary <string, object>()
            {
                { "user-agent", "1234" }
            };
            var             mockData   = MockFlowData.CreateFromEvidence(evidence, false);
            IFlowData       data       = mockData.Object;
            EmptyEngineData cachedData = new EmptyEngineData(
                _loggerFactory.CreateLogger <EmptyEngineData>(),
                data.Pipeline,
                _engine,
                new Mock <IMissingPropertyService>().Object);

            cachedData.ValueOne = 2;
            _cache.Setup(c => c[It.IsAny <IFlowData>()])
            .Returns(cachedData);

            // Act
            _engine.Process(data);

            // Assert
            // Verify that the cached result was added to the flow data.
            mockData.Verify(d => d.GetOrAdd(
                                It.IsAny <ITypedKey <EmptyEngineData> >(),
                                It.Is <Func <IPipeline, EmptyEngineData> >(f => f(mockData.Object.Pipeline) == cachedData)), Times.Once());
            // Verify that the cache was checked once.
            _cache.Verify(c => c[It.Is <IFlowData>(d => d == data)], Times.Once);
            // Verify that the Put method of the cache was not called.
            _cache.Verify(c => c.Put(It.IsAny <IFlowData>(), It.IsAny <IElementData>()), Times.Never);
            // Verify the CacheHit flag is true.
            Assert.IsTrue(cachedData.CacheHit);
        }
        public void ShareUsageTracker_Session_DoNotTrack()
        {
            var evidenceKeyFilter = new EvidenceKeyFilterShareUsage(
                _blockedHttpHeaders, _includedQueryStringParameters, false, _aspSessionCookieName);
            var shareUsageTracker = new ShareUsageTracker(new CacheConfiguration()
            {
                Builder = new LruPutCacheBuilder(),
                Size    = 1000
            },
                                                          _interval,
                                                          evidenceKeyFilter);

            int trackedEvents = 0;

            for (var i = 0; i < 2; i++)
            {
                var evidenceData = new Dictionary <string, object>()
                {
                    { Core.Constants.EVIDENCE_HTTPHEADER_PREFIX + Core.Constants.EVIDENCE_SEPERATOR + "user-agent", "iPhone" },
                    { Core.Constants.EVIDENCE_COOKIE_PREFIX + Core.Constants.EVIDENCE_SEPERATOR + Engines.Constants.DEFAULT_ASP_COOKIE_NAME, i }
                };
                var data = MockFlowData.CreateFromEvidence(_evidenceData, true);
                data.Setup(d => d.GenerateKey(It.IsAny <IEvidenceKeyFilter>())).Returns(
                    (IEvidenceKeyFilter filter) =>
                {
                    return(GenerateKey(filter, evidenceData));
                });
                if (shareUsageTracker.Track(data.Object))
                {
                    trackedEvents++;
                }
            }
            Assert.IsTrue(trackedEvents == 1);
        }
        public void Init()
        {
            _blockedHttpHeaders = new List <string>()
            {
            };
            _includedQueryStringParameters = new List <string>();
            _aspSessionCookieName          = Engines.Constants.DEFAULT_ASP_COOKIE_NAME;

            _interval          = new TimeSpan(0, 0, 0, 0, 50);
            _evidenceKeyFilter = new EvidenceKeyFilterShareUsage(
                _blockedHttpHeaders, _includedQueryStringParameters, true, _aspSessionCookieName);
            _shareUsageTracker = new ShareUsageTracker(new CacheConfiguration()
            {
                Builder = new LruPutCacheBuilder(),
                Size    = 1000
            },
                                                       _interval,
                                                       _evidenceKeyFilter);

            _evidenceData = new Dictionary <string, object>()
            {
                { Core.Constants.EVIDENCE_HTTPHEADER_PREFIX + Core.Constants.EVIDENCE_SEPERATOR + "user-agent", "iPhone" }
            };

            var dataKeyBuilder = new DataKeyBuilder();

            foreach (var evidence in _evidenceData)
            {
                dataKeyBuilder.Add(100, evidence.Key, evidence.Value);
            }

            _data = MockFlowData.CreateFromEvidence(_evidenceData, false);
            _data.Setup(d => d.GenerateKey(It.IsAny <IEvidenceKeyFilter>())).Returns(dataKeyBuilder.Build());
        }
        public void ShareUsageElement_BadSchema()
        {
            // Arrange
            CreateShareUsage(1, 1, 1, new List <string>(), new List <string>(), new List <KeyValuePair <string, string> >());

            Dictionary <string, object> evidenceData = new Dictionary <string, object>()
            {
                // Contains hidden character at the end of the string.
                // (0x0018) - Cancel control character
                { Core.Constants.EVIDENCE_HEADER_USERAGENT_KEY, "iPhone" },
            };
            var data = MockFlowData.CreateFromEvidence(evidenceData, false);

            // Act
            _shareUsageElement.Process(data.Object);
            // Wait for the consumer task to finish.
            Assert.IsNotNull(_shareUsageElement.SendDataTask);
            _shareUsageElement.SendDataTask.Wait();

            // Assert
            // Check that one and only one HTTP message was sent.
            _httpHandler.Verify(h => h.Send(It.IsAny <HttpRequestMessage>()), Times.Once);
            Assert.AreEqual(1, _xmlContent.Count);

            // Validate that the XML is well formed by passing it through a reader
            using (XmlReader xr = XmlReader.Create(new StringReader(_xmlContent[0])))
            {
                while (xr.Read())
                {
                }
            }
            // Check that the expected values are populated.
            Assert.IsTrue(_xmlContent[0].Contains(@"iPhone\x0018"));
            Assert.IsTrue(_xmlContent[0].Contains("<BadSchema>true</BadSchema>"));
        }
Exemple #5
0
        public void AspectEngineLazyLoad_ProcessCancelled()
        {
            // Arrange
            // Set the process time to the configured timeout
            _engine.SetProcessCost(TimeSpan.TicksPerMillisecond * _timeoutMS);

            // Act
            var evidence = new Dictionary <string, object>()
            {
                { "user-agent", "1234" }
            };
            // Use the mock flow data to populate this variable with the
            // engine data from the call to process.
            var             mockData   = MockFlowData.CreateFromEvidence(evidence, false);
            EmptyEngineData engineData = null;

            mockData.Setup(d => d.GetOrAdd(It.IsAny <ITypedKey <EmptyEngineData> >(),
                                           It.IsAny <Func <IPipeline, EmptyEngineData> >()))
            .Callback((ITypedKey <EmptyEngineData> k, Func <IPipeline, EmptyEngineData> f) =>
            {
                engineData = f(mockData.Object.Pipeline);
            })
            .Returns((ITypedKey <EmptyEngineData> k, Func <IPipeline, EmptyEngineData> f) =>
            {
                return(engineData);
            });
            var data = mockData.Object;

            // Process the data
            _engine.Process(data);

            // Ideally, start a new task that will wait a short time and
            // then trigger the cancellation token.
            // If we've only got one core to work with then this approach
            // can cause the test to fail as the cancellation task may
            // not get run in time.
            // If we only have one core then just trigger cancellation
            // up-front.
            if (Environment.ProcessorCount > 1)
            {
                Task.Run(() =>
                {
                    Task.Delay(_timeoutMS / 10);
                    _cancellationTokenSource.Cancel();
                });
            }
            else
            {
                _cancellationTokenSource.Cancel();
            }

            // Attempt to get the value.
            var result = engineData.ValueTwo;

            // These asserts are not really needed but can help work out
            // what is happening if the test fails to throw the expected
            // exception.
            Assert.IsTrue(_cancellationTokenSource.IsCancellationRequested);
            Assert.IsNull(result);
        }
        public void ShareUsageElement_CancelOnServerError()
        {
            // Arrange
            _httpHandler.Setup(h => h.Send(It.IsAny <HttpRequestMessage>()))
            .Returns(new HttpResponseMessage(
                         System.Net.HttpStatusCode.InternalServerError));
            CreateShareUsage(1, 1, 1, new List <string>(), new List <string>(), new List <KeyValuePair <string, string> >());

            Dictionary <string, object> evidenceData = new Dictionary <string, object>()
            {
                { Core.Constants.EVIDENCE_CLIENTIP_KEY, "1.2.3.4" },
            };
            var data = MockFlowData.CreateFromEvidence(evidenceData, false);

            // Act
            _shareUsageElement.Process(data.Object);
            // Wait for the consumer task to finish.
            Assert.IsNotNull(_shareUsageElement.SendDataTask);
            _shareUsageElement.SendDataTask.Wait();

            // Assert
            // Check that no HTTP messages were sent.
            _httpHandler.Verify(h => h.Send(It.IsAny <HttpRequestMessage>()), Times.Once);
            Assert.IsTrue(_shareUsageElement.IsCanceled);
        }
        public void ShareUsageElement_IgnoreOnEvidence()
        {
            // Arrange
            _httpHandler.Setup(h => h.Send(It.IsAny <HttpRequestMessage>()))
            .Returns(new HttpResponseMessage(
                         System.Net.HttpStatusCode.OK));
            CreateShareUsage(1, 1, 1, new List <string>(), new List <string>(),
                             new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("header.User-Agent", "Azure Traffic Manager Endpoint Monitor")
            });

            Dictionary <string, object> evidenceData = new Dictionary <string, object>()
            {
                { Core.Constants.EVIDENCE_CLIENTIP_KEY, "1.2.3.4" },
                { "header.User-Agent", "Azure Traffic Manager Endpoint Monitor" }
            };
            var data = MockFlowData.CreateFromEvidence(evidenceData, false);

            // Act
            _shareUsageElement.Process(data.Object);
            // Check that the consumer task did not start.
            Assert.IsNull(_shareUsageElement.SendDataTask);

            // Assert
            // Check that no HTTP messages were sent.
            _httpHandler.Verify(h => h.Send(It.IsAny <HttpRequestMessage>()), Times.Never);
        }
        public void FlowElementCached_Process_CheckCachePut()
        {
            // Arrange
            var evidence = new Dictionary <string, object>()
            {
                { "user-agent", "1234" }
            };
            Mock <IFlowData> data       = MockFlowData.CreateFromEvidence(evidence, false);
            EmptyEngineData  aspectData = new EmptyEngineData(
                _loggerFactory.CreateLogger <EmptyEngineData>(),
                data.Object.Pipeline,
                _engine,
                MissingPropertyService.Instance);

            data.Setup(d => d.GetOrAdd(
                           It.IsAny <TypedKey <EmptyEngineData> >(),
                           It.IsAny <Func <IPipeline, EmptyEngineData> >()))
            .Returns(aspectData);

            _cache.Setup(c => c[It.IsAny <IFlowData>()])
            .Returns <IDictionary <string, object> >(null);

            // Act
            _engine.Process(data.Object);

            // Assert
            // Verify that the cache was checked to see if there was an
            // existing result for this key.
            _cache.Verify(c => c[It.Is <IFlowData>(d => d == data.Object)], Times.Once);
            // Verify that the result was added to the cache.
            _cache.Verify(c => c.Put(It.Is <IFlowData>(d => d == data.Object),
                                     It.IsAny <EmptyEngineData>()), Times.Once);
            // Verify the CacheHit flag is false.
            Assert.IsFalse(aspectData.CacheHit);
        }
        public void ShareUsageElement_SendOnCleanup()
        {
            // Arrange
            CreateShareUsage(1, 2, 1, new List <string>(), new List <string>(), new List <KeyValuePair <string, string> >());

            Dictionary <string, object> evidenceData = new Dictionary <string, object>()
            {
                { Core.Constants.EVIDENCE_CLIENTIP_KEY, "1.2.3.4" },
            };
            var data = MockFlowData.CreateFromEvidence(evidenceData, false);

            // Act
            _shareUsageElement.Process(data.Object);

            // No data should be being sending yet.
            Assert.IsNull(_shareUsageElement.SendDataTask);
            _httpHandler.Verify(h => h.Send(It.IsAny <HttpRequestMessage>()), Times.Never);

            // Dispose of the element.
            _shareUsageElement.Dispose();

            // Assert
            // Check that no HTTP messages were sent.
            _httpHandler.Verify(h => h.Send(It.IsAny <HttpRequestMessage>()), Times.Once);
        }
        public void ShareUsageElement_NullQueryWhitelist()
        {
            // Arrange
            CreateShareUsage(1, 1, 1,
                             new List <string>(), null,
                             new List <KeyValuePair <string, string> >());

            Dictionary <string, object> evidenceData = new Dictionary <string, object>()
            {
                { Core.Constants.EVIDENCE_QUERY_PREFIX + Core.Constants.EVIDENCE_SEPERATOR + "somevalue", "123" },
            };
            var data = MockFlowData.CreateFromEvidence(evidenceData, false);

            // Act
            _shareUsageElement.Process(data.Object);
            // Wait for the consumer task to finish.
            Assert.IsNotNull(_shareUsageElement.SendDataTask);
            _shareUsageElement.SendDataTask.Wait();

            // Assert
            // Check that one and only one HTTP message was sent
            _httpHandler.Verify(h => h.Send(It.IsAny <HttpRequestMessage>()), Times.Once);
            Assert.AreEqual(1, _xmlContent.Count);

            // Validate that the XML is well formed by passing it through a reader
            using (XmlReader xr = XmlReader.Create(new StringReader(_xmlContent[0])))
            {
                while (xr.Read())
                {
                }
            }
            // Check that the expected values are populated.
            Assert.IsTrue(_xmlContent[0].Contains("<query Name=\"somevalue\"><![CDATA[123]]></query>"));
        }
Exemple #11
0
        public void AspectEngineLazyLoad_ProcessMultipleErrored()
        {
            // Arrange
            // Set the engine to throw an exception while processing
            var exceptionMessage = "an exception message";
            var engine2          = new EmptyEngineBuilder(_loggerFactory)
                                   .SetLazyLoading(new LazyLoadingConfiguration(_timeoutMS,
                                                                                _cancellationTokenSource.Token))
                                   .Build();

            _engine.SetException(new Exception(exceptionMessage));
            engine2.SetException(new Exception(exceptionMessage));
            // Act
            var evidence = new Dictionary <string, object>()
            {
                { "user-agent", "1234" }
            };
            // Use the mock flow data to populate this variable with the
            // engine data from the call to process.
            var             mockData   = MockFlowData.CreateFromEvidence(evidence, false);
            EmptyEngineData engineData = null;

            mockData.Setup(d => d.GetOrAdd(It.IsAny <ITypedKey <EmptyEngineData> >(),
                                           It.IsAny <Func <IPipeline, EmptyEngineData> >()))
            .Callback((ITypedKey <EmptyEngineData> k, Func <IPipeline, EmptyEngineData> f) =>
            {
                if (engineData == null)
                {
                    engineData = f(mockData.Object.Pipeline);
                }
            })
            .Returns((ITypedKey <EmptyEngineData> k, Func <IPipeline, EmptyEngineData> f) =>
            {
                return(engineData);
            });
            var data = mockData.Object;

            // Process the data twice
            _engine.Process(data);
            engine2.Process(data);

            // Attempt to get the value.
            try
            {
                var result = engineData.ValueOne;
            }
            catch (Exception e)
            {
                Assert.IsTrue(e is AggregateException);
                Assert.IsNotNull(((AggregateException)e).InnerExceptions);
                Assert.AreEqual(2, ((AggregateException)e).InnerExceptions.Count);
                Assert.AreEqual(
                    $"One or more errors occurred. ({exceptionMessage})",
                    ((AggregateException)e).InnerExceptions[0].Message);
                Assert.AreEqual(
                    $"One or more errors occurred. ({exceptionMessage})",
                    ((AggregateException)e).InnerExceptions[1].Message);
            }
        }
Exemple #12
0
        public void AspectEngineLazyLoad_ProcessErrored()
        {
            // Arrange
            // Set the engine to throw an exception while processing
            var exceptionMessage = "an exception message";

            _engine.SetException(new Exception(exceptionMessage));
            // Act
            var evidence = new Dictionary <string, object>()
            {
                { "user-agent", "1234" }
            };
            // Use the mock flow data to populate this variable with the
            // engine data from the call to process.
            var             mockData   = MockFlowData.CreateFromEvidence(evidence, false);
            EmptyEngineData engineData = null;

            mockData.Setup(d => d.GetOrAdd(It.IsAny <ITypedKey <EmptyEngineData> >(),
                                           It.IsAny <Func <IPipeline, EmptyEngineData> >()))
            .Callback((ITypedKey <EmptyEngineData> k, Func <IPipeline, EmptyEngineData> f) =>
            {
                engineData = f(mockData.Object.Pipeline);
            })
            .Returns((ITypedKey <EmptyEngineData> k, Func <IPipeline, EmptyEngineData> f) =>
            {
                return(engineData);
            });
            var data = mockData.Object;

            // Process the data
            _engine.Process(data);


            // Attempt to get the value.
            try
            {
                var result = engineData.ValueOne;
            }
            catch (Exception e)
            {
                Assert.IsTrue(e is Exception);
                Assert.IsNotNull(e.InnerException);
                Assert.AreEqual(
                    $"One or more errors occurred. ({exceptionMessage})",
                    e.InnerException.Message);
            }
        }
        public void ShareUsageElement_TwoEvents_SecondEvent()
        {
            // Arrange
            CreateShareUsage(1, 2, 1, new List <string>(), new List <string>(), new List <KeyValuePair <string, string> >());

            Dictionary <string, object> evidenceData = new Dictionary <string, object>()
            {
                { Core.Constants.EVIDENCE_CLIENTIP_KEY, "1.2.3.4" },
            };
            var data = MockFlowData.CreateFromEvidence(evidenceData, false);

            // Act
            _shareUsageElement.Process(data.Object);
            _shareUsageElement.Process(data.Object);

            // Wait for the consumer task to finish.
            Assert.IsNotNull(_shareUsageElement.SendDataTask);
            _shareUsageElement.SendDataTask.Wait();

            // Assert
            // Check that one and only one HTTP message was sent.
            _httpHandler.Verify(h => h.Send(It.IsAny <HttpRequestMessage>()), Times.Once);
            Assert.AreEqual(1, _xmlContent.Count);

            // Validate that the XML is well formed by passing it through a reader
            using (XmlReader xr = XmlReader.Create(new StringReader(_xmlContent[0])))
            {
                while (xr.Read())
                {
                }
            }
            // Make sure there are 2 'Device' nodes
            int count = 0;
            int index = 0;

            while (index >= 0)
            {
                index = _xmlContent[0].IndexOf("<Device>", index + 1);
                if (index > 0)
                {
                    count++;
                }
            }
            Assert.AreEqual(2, count);
        }
        public void ShareUsageElement_TwoEvents_FirstEvent()
        {
            // Arrange
            CreateShareUsage(1, 2, 1, new List <string>(), new List <string>(), new List <KeyValuePair <string, string> >());

            Dictionary <string, object> evidenceData = new Dictionary <string, object>()
            {
                { Core.Constants.EVIDENCE_CLIENTIP_KEY, "1.2.3.4" },
            };
            var data = MockFlowData.CreateFromEvidence(evidenceData, false);

            // Act
            _shareUsageElement.Process(data.Object);

            // Assert
            // Check that no HTTP messages were sent.
            _httpHandler.Verify(h => h.Send(It.IsAny <HttpRequestMessage>()), Times.Never);
        }
Exemple #15
0
        public void AspectEngineLazyLoad_Process()
        {
            // Arrange
            // Set the process time to half of the configured timeout
            _engine.SetProcessCost(TimeSpan.TicksPerMillisecond * (_timeoutMS / 2));

            // Act
            var evidence = new Dictionary <string, object>()
            {
                { "user-agent", "1234" }
            };
            var mockData = MockFlowData.CreateFromEvidence(evidence, false);
            // Use the mock flow data to populate this variable with the
            // engine data from the call to process.
            EmptyEngineData engineData = null;

            mockData.Setup(d => d.GetOrAdd(It.IsAny <ITypedKey <EmptyEngineData> >(),
                                           It.IsAny <Func <IPipeline, EmptyEngineData> >()))
            .Callback((ITypedKey <EmptyEngineData> k, Func <IPipeline, EmptyEngineData> f) =>
            {
                engineData = f(mockData.Object.Pipeline);
            })
            .Returns((ITypedKey <EmptyEngineData> k, Func <IPipeline, EmptyEngineData> f) =>
            {
                return(engineData);
            });
            var data = mockData.Object;

            // Process the data.
            _engine.Process(data);
            // Check that the task is not complete when process returns.
            bool processReturnedBeforeTaskComplete =
                engineData.ProcessTask.IsCompleted == false;

            // Assert
            Assert.AreEqual(2, engineData.ValueTwo);
            // Check that the task is now complete (because the code to get
            // the property value will wait until it is complete)
            bool valueReturnedAfterTaskComplete =
                engineData.ProcessTask.IsCompleted == true;

            Assert.IsTrue(processReturnedBeforeTaskComplete);
            Assert.IsTrue(valueReturnedAfterTaskComplete);
        }
Exemple #16
0
        public void TrackerBase_Track()
        {
            TestTracker tracker = new TestTracker(new CacheConfiguration()
            {
                Builder = new LruPutCacheBuilder(),
                Size    = 100
            }, 1);

            Dictionary <string, object> keyDictionary = new Dictionary <string, object>()
            {
                { "test.field1", "1.2.3.4" },
                { "test.field2", "abcd" },
            };
            var data1 = MockFlowData.CreateFromEvidence(keyDictionary, true);
            var data2 = MockFlowData.CreateFromEvidence(keyDictionary, true);

            Assert.IsTrue(tracker.Track(data1.Object));
            Assert.IsFalse(tracker.Track(data2.Object));
        }
        public void ShareUsageElement_RestrictedHeaders()
        {
            // Arrange
            CreateShareUsage(1, 1, 1, new List <string>()
            {
                "x-forwarded-for", "forwarded-for"
            }, new List <string>(), new List <KeyValuePair <string, string> >());

            string useragent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0 Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/42.0.";
            Dictionary <string, object> evidenceData = new Dictionary <string, object>()
            {
                { Core.Constants.EVIDENCE_CLIENTIP_KEY, "1.2.3.4" },
                { Core.Constants.EVIDENCE_HTTPHEADER_PREFIX + Core.Constants.EVIDENCE_SEPERATOR + "x-forwarded-for", "5.6.7.8" },
                { Core.Constants.EVIDENCE_HTTPHEADER_PREFIX + Core.Constants.EVIDENCE_SEPERATOR + "forwarded-for", "2001::" },
                { Core.Constants.EVIDENCE_HTTPHEADER_PREFIX + Core.Constants.EVIDENCE_SEPERATOR + "user-agent", useragent },
            };
            var data = MockFlowData.CreateFromEvidence(evidenceData, false);

            // Act
            _shareUsageElement.Process(data.Object);
            // Wait for the consumer task to finish.
            Assert.IsNotNull(_shareUsageElement.SendDataTask);
            _shareUsageElement.SendDataTask.Wait();

            // Assert
            // Check that one and only one HTTP message was sent.
            _httpHandler.Verify(h => h.Send(It.IsAny <HttpRequestMessage>()), Times.Once);
            Assert.AreEqual(1, _xmlContent.Count);

            // Validate that the XML is well formed by passing it through a reader
            using (XmlReader xr = XmlReader.Create(new StringReader(_xmlContent[0])))
            {
                while (xr.Read())
                {
                }
            }
            // Check that the expected values are populated.
            Assert.IsTrue(_xmlContent[0].Contains("<ClientIP>1.2.3.4</ClientIP>"));
            Assert.IsTrue(_xmlContent[0].Contains($"<header Name=\"user-agent\"><![CDATA[{useragent}]]></header>"));
            Assert.IsFalse(_xmlContent[0].Contains("<header Name=\"x-forwarded-for\">"));
            Assert.IsFalse(_xmlContent[0].Contains("<header Name=\"forwarded-for\">"));
        }
        public void ShareUsageElement_SingleEvent_ClientIPAndHeader()
        {
            // Arrange
            CreateShareUsage(1, 1, 1, new List <string>(), new List <string>(), new List <KeyValuePair <string, string> >());

            Dictionary <string, object> evidenceData = new Dictionary <string, object>()
            {
                { Core.Constants.EVIDENCE_CLIENTIP_KEY, "1.2.3.4" },
                { Core.Constants.EVIDENCE_HTTPHEADER_PREFIX + Core.Constants.EVIDENCE_SEPERATOR + "x-forwarded-for", "5.6.7.8" },
                { Core.Constants.EVIDENCE_HTTPHEADER_PREFIX + Core.Constants.EVIDENCE_SEPERATOR + "forwarded-for", "2001::" },
                { Core.Constants.EVIDENCE_COOKIE_PREFIX + Core.Constants.EVIDENCE_SEPERATOR + Engines.Constants.FIFTYONE_COOKIE_PREFIX + "Profile", "123456" },
                { Core.Constants.EVIDENCE_COOKIE_PREFIX + Core.Constants.EVIDENCE_SEPERATOR + "RemoveMe", "123456" }
            };
            var data = MockFlowData.CreateFromEvidence(evidenceData, false);

            // Act
            _shareUsageElement.Process(data.Object);
            // Wait for the consumer task to finish.
            Assert.IsNotNull(_shareUsageElement.SendDataTask);
            _shareUsageElement.SendDataTask.Wait();

            // Assert
            // Check that one and only one HTTP message was sent
            _httpHandler.Verify(h => h.Send(It.IsAny <HttpRequestMessage>()), Times.Once);
            Assert.AreEqual(1, _xmlContent.Count);

            // Validate that the XML is well formed by passing it through a reader
            using (XmlReader xr = XmlReader.Create(new StringReader(_xmlContent[0])))
            {
                while (xr.Read())
                {
                }
            }
            // Check that the expected values are populated.
            Assert.IsTrue(_xmlContent[0].Contains("<ClientIP>1.2.3.4</ClientIP>"));
            Assert.IsTrue(_xmlContent[0].Contains("<header Name=\"x-forwarded-for\"><![CDATA[5.6.7.8]]></header>"));
            Assert.IsTrue(_xmlContent[0].Contains("<header Name=\"forwarded-for\"><![CDATA[2001::]]></header>"));
            Assert.IsTrue(_xmlContent[0].Contains($"<cookie Name=\"{Engines.Constants.FIFTYONE_COOKIE_PREFIX}Profile\"><![CDATA[123456]]></cookie>"));
            Assert.IsFalse(_xmlContent[0].Contains("<cookie Name=\"RemoveMe\">"));
        }
        public void ShareUsageElement_LowPercentage()
        {
            // Arrange
            CreateShareUsage(0.001, 100, 1, new List <string>(), new List <string>(), new List <KeyValuePair <string, string> >());

            Dictionary <string, object> evidenceData = new Dictionary <string, object>()
            {
                { Core.Constants.EVIDENCE_CLIENTIP_KEY, "1.2.3.4" },
            };
            var data = MockFlowData.CreateFromEvidence(evidenceData, false);

            // Act
            int requiredEvents = 0;

            while (_xmlContent.Count == 0 &&
                   requiredEvents <= 1000000)
            {
                _shareUsageElement.Process(data.Object);
                requiredEvents++;
            }
            // Wait for the consumer task to finish.
            Assert.IsNotNull(_shareUsageElement.SendDataTask);
            _shareUsageElement.SendDataTask.Wait();

            // Assert
            // On average, the number of required events should be around
            // 100,000. However, as it's chance based it can vary
            // significantly. We only want to catch any gross errors so just
            // make sure the value is of the expected order of magnitude.
            Assert.IsTrue(requiredEvents > 10000, $"Expected the number of required " +
                          $"events to be at least 10,000, but was actually '{requiredEvents}'");
            Assert.IsTrue(requiredEvents < 1000000, $"Expected the number of required " +
                          $"events to be less than 1,000,000, but was actually '{requiredEvents}'");
            // Check that one and only one HTTP message was sent.
            _httpHandler.Verify(h => h.Send(It.IsAny <HttpRequestMessage>()), Times.Once);
            Assert.AreEqual(1, _xmlContent.Count);
        }
Exemple #20
0
        public void AspectEngineLazyLoad_PropertyTimeout()
        {
            // Arrange
            // Set the process time to double the configured timeout
            _engine.SetProcessCost(TimeSpan.TicksPerMillisecond * (_timeoutMS * 2));

            // Act
            var evidence = new Dictionary <string, object>()
            {
                { "user-agent", "1234" }
            };
            // Use the mock flow data to populate this variable with the
            // engine data from the call to process.
            var             mockData   = MockFlowData.CreateFromEvidence(evidence, false);
            EmptyEngineData engineData = null;

            mockData.Setup(d => d.GetOrAdd(It.IsAny <ITypedKey <EmptyEngineData> >(),
                                           It.IsAny <Func <IPipeline, EmptyEngineData> >()))
            .Callback((ITypedKey <EmptyEngineData> k, Func <IPipeline, EmptyEngineData> f) =>
            {
                engineData = f(mockData.Object.Pipeline);
            })
            .Returns((ITypedKey <EmptyEngineData> k, Func <IPipeline, EmptyEngineData> f) =>
            {
                return(engineData);
            });
            var data = mockData.Object;

            // Process the data
            _engine.Process(data);
            // Attempt to get the value. This should cause the timeout
            // to be triggered.
            var result = engineData.ValueTwo;

            // No asserts needed. Just the ExpectedException attribute
            // on the method.
        }