Exemple #1
0
        public async Task Read_HasNetworkUtilization()
        {
            var collector = MockCollector <VolatileDeviceCollector> .Mock <INetworkCollector, NetworkUtilization[]>(
                c => c.ReadNetworkUtilization(),
                new NetworkUtilization[]
            {
                new NetworkUtilization
                {
                    Name = "wifi",
                    ReceivedBytesPerSecond = 1,
                    SentBytesPerSecond     = 2
                },
                new NetworkUtilization
                {
                    Name = "lan",
                    ReceivedBytesPerSecond = 1,
                    SentBytesPerSecond     = 2
                }
            });

            var info = await collector.Read();

            Assert.Equal(2, info.Net.Length);
            Assert.Equal(3, info.Net[0].GetPublicPropertyCount());

            Assert.Equal("wifi", info.Net[0].Name);
            Assert.Equal(1UL, info.Net[0].ReceivedBytesPerSecond);
            Assert.Equal(2UL, info.Net[0].SentBytesPerSecond);
            Assert.Equal("lan", info.Net[1].Name);
            Assert.Equal(1UL, info.Net[1].ReceivedBytesPerSecond);
            Assert.Equal(2UL, info.Net[1].SentBytesPerSecond);
        }
        public async Task Read_HasOsInfo()
        {
            var collector = MockCollector <StableDeviceCollector> .Mock <IOsCollector, OsInfo>(
                c => c.ReadOsInfo(),
                new OsInfo
            {
                Bitness = 32,
                Edition = "Windows 10",
                EnvironmentVariables = new Dictionary <string, object> {
                    { "foo", "bar" }
                },
                InstalledUICulture = "de-DE",
                MachineName        = "baz",
                Version            = "10.0.0.0"
            });

            var info = await collector.Read();

            Assert.Equal(6, info.Os.GetPublicPropertyCount());

            Assert.Equal(32, info.Os.Bitness);
            Assert.Equal("Windows 10", info.Os.Edition);
            Assert.Equal("bar", info.Os.EnvironmentVariables["foo"]);
            Assert.Equal("de-DE", info.Os.InstalledUICulture);
            Assert.Equal("baz", info.Os.MachineName);
            Assert.Equal("10.0.0.0", info.Os.Version);
        }
Exemple #3
0
        public async Task Read_HasDriveUtilization()
        {
            var collector = MockCollector <VolatileDeviceCollector> .Mock <IDriveCollector, DriveUtilization[]>(
                c => c.ReadDriveUtilization(),
                new DriveUtilization[]
            {
                new DriveUtilization
                {
                    Name      = "C:",
                    FreeBytes = 1
                },
                new DriveUtilization
                {
                    Name = "D:"
                }
            });

            var info = await collector.Read();

            Assert.Equal(2, info.Drives.Length);
            Assert.Equal(2, info.Drives[0].GetPublicPropertyCount());

            Assert.Equal("C:", info.Drives[0].Name);
            Assert.Equal(1UL, info.Drives[0].FreeBytes);
            Assert.Equal("D:", info.Drives[1].Name);
            Assert.Null(info.Drives[1].FreeBytes);
        }
Exemple #4
0
        public async Task Read_HasOsUtilization()
        {
            var collector = MockCollector <VolatileDeviceCollector> .Mock <IOsCollector, OsUtilization>(
                c => c.ReadOsUtilization(),
                new OsUtilization
            {
                Processes = 1,
                Update    = new WindowsUpdateInfo
                {
                    LastUpdateInstalledAt = new DateTime(2000, 1, 1),
                    PendingUpdates        = 1
                },
                UpTime = TimeSpan.FromHours(1),
            });

            var info = await collector.Read();

            Assert.Equal(3, info.Os.GetPublicPropertyCount());
            Assert.Equal(2, info.Os.Update.GetPublicPropertyCount());

            Assert.Equal(1, info.Os.Processes);
            Assert.Equal(new DateTime(2000, 1, 1), info.Os.Update.LastUpdateInstalledAt);
            Assert.Equal(1, info.Os.Update.PendingUpdates);
            Assert.Equal(TimeSpan.FromHours(1), info.Os.UpTime);
        }
        public async System.Threading.Tasks.Task TestCheckGithubAsyncAsync()
        {
            var logger    = new MockLogger();
            var timerInfo = new TimerInfo(new MockSchedule(), null);
            var context   = new Microsoft.Azure.WebJobs.ExecutionContext()
            {
                InvocationId         = Guid.NewGuid(),
                FunctionAppDirectory = $@"C:\code\COVID19\COVID19_Azure_DataSync\COVI19_Timer_Function\bin\Debug\netcoreapp2.1"
            };


            IConfigurationRoot config = new ConfigurationBuilder()
                                        .SetBasePath(context.FunctionAppDirectory)
                                        .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                                        .AddEnvironmentVariables()
                                        .Build();

            var AzureWebJobsStorage = config.GetValue <string>("Values:AzureWebJobsStorage");

            var covidTable = Helper.GetCloudTable("Covid19", AzureWebJobsStorage, logger, context);
            var syncTable  = Helper.GetCloudTable("SyncStatus", AzureWebJobsStorage, logger, context);
            var errorTable = Helper.GetCloudTable("ErrorLogs", AzureWebJobsStorage, logger, context);

            ICollector <string> queue = new MockCollector <string>();


            var function = new COIVD19_Api(new COVIDService(new System.Net.Http.HttpClient()));
            await function.CheckGithubAsync(timerInfo, syncTable, queue, logger);
        }
Exemple #6
0
        public void VersionOneMapper_Map_Success()
        {
            var config = new ConverterConfiguration()
            {
                LeftSideMap = new Dictionary <string, List <string> >()
                {
                    { "ABC", new List <string>()
                      {
                          "XYZ"
                      } }
                },
                Properties = new Dictionary <string, string>()
            };
            var converter = new AllUpperCaseConverter();

            converter.Configure(config);

            var converters = new Dictionary <string, IConverter>();

            converters.Add("ABC", converter);


            var collector = new MockCollector(new MockLogger());

            collector.Configure(new CollectorConfiguration()
            {
                Id      = "1",
                Version = 1.0
            });

            var mapper = new VersionOneMapper();

            mapper.Configure("1", null, "2", converters);

            mapper.Id.Should().Be("1");
            mapper.TransformerId.Should().Be("2");

            var dataPoint = new KeyValuePair <string, object>("ABC", "foobar");
            var dataRow   = new EntityCollection();

            dataRow.Entities.Add(dataPoint.Key, dataPoint.Value);

            var data = new List <IEntityCollection>();

            data.Add(dataRow);

            var convertedData = mapper.Map(data);

            convertedData.Should().NotBeNull();
        }
        public async Task Read_HasNetworkInfo()
        {
            var collector = MockCollector <StableDeviceCollector> .Mock <INetworkCollector, NetworkInfo[]>(
                c => c.ReadNetworkInfo(),
                new NetworkInfo[]
            {
                new NetworkInfo
                {
                    DhcpServerAddresses = new[] { "foo" },
                    DnsAddresses        = new[] { "bar" },
                    MacAddress          = "aa:bb:cc:dd:ee:ff",
                    Model            = "intel",
                    Name             = "wifi",
                    Type             = NetworkInterfaceType.Wireless80211.ToString(),
                    UnicastAddresses = new[] { "1.1.1.1" }
                },
                new NetworkInfo
                {
                    DhcpServerAddresses = new[] { "foo", "bar" },
                    DnsAddresses        = new[] { "baz" },
                    MacAddress          = "00:11:22:33:44:55",
                    Model            = "intel",
                    Name             = "lan",
                    Type             = NetworkInterfaceType.Ethernet.ToString(),
                    UnicastAddresses = new[] { "1.1.1.1", "2.2.2.2" }
                }
            });

            var info = await collector.Read();

            Assert.Equal(2, info.Net.Length);

            Assert.Equal(7, info.Net[0].GetPublicPropertyCount());

            Assert.Equal(new[] { "foo" }, info.Net[0].DhcpServerAddresses);
            Assert.Equal(new[] { "bar" }, info.Net[0].DnsAddresses);
            Assert.Equal("aa:bb:cc:dd:ee:ff", info.Net[0].MacAddress);
            Assert.Equal("intel", info.Net[0].Model);
            Assert.Equal("wifi", info.Net[0].Name);
            Assert.Equal("Wireless80211", info.Net[0].Type);
            Assert.Equal(new[] { "1.1.1.1" }, info.Net[0].UnicastAddresses);

            Assert.Equal(new[] { "foo", "bar" }, info.Net[1].DhcpServerAddresses);
            Assert.Equal(new[] { "baz" }, info.Net[1].DnsAddresses);
            Assert.Equal("00:11:22:33:44:55", info.Net[1].MacAddress);
            Assert.Equal("intel", info.Net[1].Model);
            Assert.Equal("lan", info.Net[1].Name);
            Assert.Equal("Ethernet", info.Net[1].Type);
            Assert.Equal(new[] { "1.1.1.1", "2.2.2.2" }, info.Net[1].UnicastAddresses);
        }
        public async Task Read_HasMemoryInfo()
        {
            var collector = MockCollector <StableDeviceCollector> .Mock <IMemoryCollector, MemoryInfo>(
                c => c.ReadMemoryInfo(),
                new MemoryInfo
            {
                TotalBytes = 1
            });

            var info = await collector.Read();

            Assert.Equal(1, info.Mem.GetPublicPropertyCount());

            Assert.Equal(1UL, info.Mem.TotalBytes);
        }
Exemple #9
0
        public async Task Read_HasMemoryUtilization()
        {
            var collector = MockCollector <VolatileDeviceCollector> .Mock <IMemoryCollector, MemoryUtilization>(
                c => c.ReadMemoryUtilization(),
                new MemoryUtilization
            {
                FreeBytes = 1
            });

            var info = await collector.Read();

            Assert.Equal(1, info.Mem.GetPublicPropertyCount());

            Assert.Equal(1UL, info.Mem.FreeBytes);
        }
Exemple #10
0
        public async Task Read_HasCpuUtilization()
        {
            var collector = MockCollector <VolatileDeviceCollector> .Mock <ICpuCollector, CpuUtilization>(
                c => c.ReadCpuUtilization(),
                new CpuUtilization
            {
                SpeedMhz       = 1000,
                LoadPercentage = 1
            });

            var info = await collector.Read();

            Assert.Equal(2, info.Cpu.GetPublicPropertyCount());

            Assert.Equal(1000, info.Cpu.SpeedMhz);
            Assert.Equal(1.0f, info.Cpu.LoadPercentage);
        }
        public async Task Read_HasCpuInfo()
        {
            var collector = MockCollector <StableDeviceCollector> .Mock <ICpuCollector, CpuInfo>(
                c => c.ReadCpuInfo(),
                new CpuInfo
            {
                Cores    = 1,
                Name     = "foo",
                SpeedMhz = 1000,
                Threads  = 2
            });

            var info = await collector.Read();

            Assert.Equal(4, info.Cpu.GetPublicPropertyCount());

            Assert.Equal(1, info.Cpu.Cores);
            Assert.Equal("foo", info.Cpu.Name);
            Assert.Equal(1000, info.Cpu.SpeedMhz);
            Assert.Equal(2, info.Cpu.Threads);
        }
        public void SQLPrinterReader_Success()
        {
            var logger    = new MockLogger();
            var collector = new MockCollector(logger);
            var sqlReader = new MockSQLReader();
            var reader    = new SQLPrinterReader(sqlReader, logger, collector);
            var handler   = new MockHandler();
            var config    = new EndPointConfiguration()
            {
                Id       = "2",
                Password = "******",
                User     = "******",
            };

            config.Properties.Add("ServerName", "localhost");
            config.Properties.Add("Database", "MdmPrinter");
            config.Properties.Add("SqlCommand", "SELECT * FROM PRINTER");
            config.Properties.Add("Top", "100");

            reader.Configure("1", config, handler);
            reader.Run(new Dictionary <string, string>()).Wait();
            collector.GetTotalEventCount().Should().Be(1);
        }
        public async Task Read_HasDriveInfo()
        {
            var collector = MockCollector <StableDeviceCollector> .Mock <IDriveCollector, DriveInfo[]>(
                p => p.ReadDriveInfo(),
                new DriveInfo[]
            {
                new DriveInfo
                {
                    Name       = "C:",
                    Format     = "NTFS",
                    Label      = "foo",
                    TotalBytes = 1,
                    Type       = System.IO.DriveType.Fixed.ToString()
                },
                new DriveInfo
                {
                    Name = "D:",
                    Type = System.IO.DriveType.CDRom.ToString()
                }
            });

            var info = await collector.Read();

            Assert.Equal(2, info.Drives.Length);
            Assert.Equal(5, info.Drives[0].GetPublicPropertyCount());

            Assert.Equal("C:", info.Drives[0].Name);
            Assert.Equal("NTFS", info.Drives[0].Format);
            Assert.Equal("foo", info.Drives[0].Label);
            Assert.Equal(1UL, info.Drives[0].TotalBytes);
            Assert.Equal("Fixed", info.Drives[0].Type);
            Assert.Equal("D:", info.Drives[1].Name);
            Assert.Null(info.Drives[1].Format);
            Assert.Null(info.Drives[1].Label);
            Assert.Null(info.Drives[1].TotalBytes);
            Assert.Equal("CDRom", info.Drives[1].Type);
        }
Exemple #14
0
        public void DefaultMapper_NoPipeConverters_Map_Success()
        {
            // Use Case : I want to first combine a date and time field.  Then pipe
            // that result into the UTC converter along with the original data point.
            // Because PipedData is set to false then the end result should be two entries.
            // 1. Combined Date and Time
            // 2. Combined Date and Time converted to UTC.

            var converters = CreateConverters();

            var collector = new MockCollector(new MockLogger());

            collector.Configure(new CollectorConfiguration()
            {
                Id      = "1",
                Version = 2.0
            });

            var mapper = new DefaultMapper(new MockLogger(), collector);

            var leftSideMap1 = new Dictionary <string, List <string> >()
            {
                { "Date", new List <string>()
                  {
                      "DateTime"
                  } }
            };
            var leftSideMap2 = new Dictionary <string, List <string> >()
            {
                { "DateTime", new List <string>()
                  {
                      "DateTimeUTC"
                  } }
            };

            // Create the converters we are targeting
            var targetConverters = new List <SourceTargetConverter>();

            targetConverters.Add(new SourceTargetConverter()
            {
                Id = ID_CONVERTER_1, LeftSideMap = leftSideMap1, CombineInputOutput = false
            });
            targetConverters.Add(new SourceTargetConverter()
            {
                Id = ID_CONVERTER_2, LeftSideMap = leftSideMap2, CombineInputOutput = true
            });
            // Now create the targeted mapping
            var targetMappings = new List <SourceTargetMapping>();

            targetMappings.Add(new SourceTargetMapping()
            {
                PrimaryKey       = "Date",
                TargetConverters = targetConverters
            });
            // Finally create the mapper config and configure the mapper
            var mapperConfig = new MapperConfiguration()
            {
                Id                   = "1234",
                TransformerId        = "6678",
                SourceTargetMappings = targetMappings
            };

            mapper.Configure(mapperConfig, converters);

            mapper.Id.Should().Be("1234");
            mapper.TransformerId.Should().Be("6678");

            var dataRow = new EntityCollection();

            dataRow.Entities.Add("Date", "1/17/2018");
            dataRow.Entities.Add("Time", "15:46:07.000");

            var data = new List <IEntityCollection>();

            data.Add(dataRow);

            var convertedData = mapper.Map(data);

            convertedData.Should().NotBeNull();
            convertedData.Count.Should().Be(1);

            var entities = convertedData[0] as IEntityCollection;

            entities.Entities.Count.Should().Be(2);
            entities.Entities.ContainsKey("DateTimeUTC").Should().BeTrue();

            var dateTime         = DateTime.Parse(entities.Entities["DateTimeUTC"].ToString());
            var expectedDateTime = DateTime.Parse("1/17/2018 15:46:07.000");

            dateTime.Month.Should().Be(expectedDateTime.Month);
            dateTime.Day.Should().Be(expectedDateTime.Day);
            dateTime.Year.Should().Be(expectedDateTime.Year);
            dateTime.Hour.Should().Be(expectedDateTime.Hour);
            dateTime.Minute.Should().Be(expectedDateTime.Minute);
        }
        public void SubmitMetrics()
        {
            var collectorPort = TcpPortProvider.GetOpenPort();

            using var collector = new MockCollector(Output, collectorPort);

            const int expectedMetricRequests = 1;

            var testSettings = new TestSettings
            {
                MetricsSettings = new MetricsSettings {
                    Port = collectorPort
                },
                EnableStartupHook = true
            };

            using var processResult = RunTestApplicationAndWaitForExit(testSettings);
            Assert.True(processResult.ExitCode >= 0, $"Process exited with code {processResult.ExitCode} and exception: {processResult.StandardError}");
            var metricRequests = collector.WaitForMetrics(expectedMetricRequests, TimeSpan.FromSeconds(5));

            using (new AssertionScope())
            {
                metricRequests.Count.Should().Be(expectedMetricRequests);

                var resourceMetrics = metricRequests.Single().ResourceMetrics.Single();

                var expectedServiceNameAttribute = new KeyValue {
                    Key = "service.name", Value = new AnyValue {
                        StringValue = ServiceName
                    }
                };
                resourceMetrics.Resource.Attributes.Should().ContainEquivalentOf(expectedServiceNameAttribute);

                var httpclientScope = resourceMetrics.ScopeMetrics.Single(rm => rm.Scope.Name.Equals("OpenTelemetry.Instrumentation.Http", StringComparison.OrdinalIgnoreCase));
                var aspnetcoreScope = resourceMetrics.ScopeMetrics.Single(rm => rm.Scope.Name.Equals("OpenTelemetry.Instrumentation.AspNetCore", StringComparison.OrdinalIgnoreCase));

                var httpClientDurationMetric = httpclientScope.Metrics.FirstOrDefault(m => m.Name.Equals("http.client.duration", StringComparison.OrdinalIgnoreCase));
                var httpServerDurationMetric = aspnetcoreScope.Metrics.FirstOrDefault(m => m.Name.Equals("http.server.duration", StringComparison.OrdinalIgnoreCase));

                httpClientDurationMetric.Should().NotBeNull();
                httpServerDurationMetric.Should().NotBeNull();

                httpClientDurationMetric.DataCase.Should().Be(Opentelemetry.Proto.Metrics.V1.Metric.DataOneofCase.Histogram);
                httpServerDurationMetric.DataCase.Should().Be(Opentelemetry.Proto.Metrics.V1.Metric.DataOneofCase.Histogram);

                var httpClientDurationAttributes = httpClientDurationMetric.Histogram.DataPoints.Single().Attributes;
                var httpServerDurationAttributes = httpServerDurationMetric.Histogram.DataPoints.Single().Attributes;

                httpClientDurationAttributes.Count.Should().Be(4);
                httpClientDurationAttributes.Single(a => a.Key == "http.method").Value.StringValue.Should().Be("GET");
                httpClientDurationAttributes.Single(a => a.Key == "http.scheme").Value.StringValue.Should().Be("http");
                httpClientDurationAttributes.Single(a => a.Key == "http.flavor").Value.StringValue.Should().Be("1.1");
                httpClientDurationAttributes.Single(a => a.Key == "http.status_code").Value.IntValue.Should().Be(200);

                httpServerDurationAttributes.Count.Should().Be(5);
                httpServerDurationAttributes.Single(a => a.Key == "http.method").Value.StringValue.Should().Be("GET");
                httpClientDurationAttributes.Single(a => a.Key == "http.scheme").Value.StringValue.Should().Be("http");
                httpClientDurationAttributes.Single(a => a.Key == "http.flavor").Value.StringValue.Should().Be("1.1");
                httpServerDurationAttributes.Single(a => a.Key == "http.host").Value.StringValue.Should().StartWith("localhost");
                httpClientDurationAttributes.Single(a => a.Key == "http.status_code").Value.IntValue.Should().Be(200);
            }
        }