public async Task ValidateMetrics() { CancellationToken token = this.TestToken; await this.DeployAsync(token); var agent = new EdgeAgent(this.runtime.DeviceId, this.IotHub); await agent.PingAsync(token); // This method can take a long time to process in the nested case. // So have a long response timeout but short connection timeout. var result = await this.IotHub.InvokeMethodAsync( this.runtime.DeviceId, ModuleName, new CloudToDeviceMethod("ValidateMetrics", TimeSpan.FromSeconds(120), TimeSpan.FromSeconds(60)), token); Assert.AreEqual(result.Status, (int)HttpStatusCode.OK); string body = result.GetPayloadAsJson(); Report report = JsonConvert.DeserializeObject <Report>(body, new JsonSerializerSettings() { DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate }); Assert.Zero(report.Failed, report.ToString()); }
public async Task ManuallyProvisionEdgeAsync() { await Profiler.Run( async() => { using (var cts = new CancellationTokenSource(Context.Current.SetupTimeout)) { // NUnit's [Timeout] attribute isn't supported in .NET Standard // and even if it were, it doesn't run the teardown method when // a test times out. We need teardown to run, to remove the // device registration from IoT Hub and stop the daemon. So // we have our own timeout mechanism. DateTime startTime = DateTime.Now; CancellationToken token = cts.Token; EdgeDevice device = await EdgeDevice.GetOrCreateIdentityAsync( Context.Current.DeviceId, this.iotHub, token); Context.Current.DeleteList.TryAdd(device.Id, device); IotHubConnectionStringBuilder builder = IotHubConnectionStringBuilder.Create(device.ConnectionString); await this.daemon.ConfigureAsync( config => { config.SetDeviceConnectionString(device.ConnectionString); config.Update(); return(Task.FromResult(( "with connection string for device '{Identity}'", new object[] { builder.DeviceId }))); }, token); try { await this.daemon.WaitForStatusAsync(EdgeDaemonStatus.Running, token); var agent = new EdgeAgent(device.Id, this.iotHub); await agent.WaitForStatusAsync(EdgeModuleStatus.Running, token); await agent.PingAsync(token); } // ReSharper disable once RedundantCatchClause catch { throw; } finally { await NUnitLogs.CollectAsync(startTime, token); } } }, "Completed edge manual provisioning"); }
public async Task DpsX509() { (string, string, string)rootCa = Context.Current.RootCaKeys.Expect(() => new InvalidOperationException("Missing root CA keys")); string caCertScriptPath = Context.Current.CaCertScriptPath.Expect(() => new InvalidOperationException("Missing CA cert script path")); string idScope = Context.Current.DpsIdScope.Expect(() => new InvalidOperationException("Missing DPS ID scope")); string registrationId = DeviceId.Current.Generate(); CancellationToken token = this.TestToken; CertificateAuthority ca = await CertificateAuthority.CreateAsync( registrationId, rootCa, caCertScriptPath, token); IdCertificates idCert = await ca.GenerateIdentityCertificatesAsync(registrationId, token); // The trust bundle for this test isn't used. It can be any arbitrary existing certificate. string trustBundle = Path.Combine( caCertScriptPath, "certs", "azure-iot-test-only.intermediate-full-chain.cert.pem"); await this.daemon.ConfigureAsync( config => { config.SetDpsX509(idScope, registrationId, idCert, trustBundle); config.Update(); return(Task.FromResult(( "with DPS X509 attestation for '{Identity}'", new object[] { registrationId }))); }, token); await this.daemon.WaitForStatusAsync(EdgeDaemonStatus.Running, token); var agent = new EdgeAgent(registrationId, this.iotHub); await agent.WaitForStatusAsync(EdgeModuleStatus.Running, token); await agent.PingAsync(token); Option <EdgeDevice> device = await EdgeDevice.GetIdentityAsync( registrationId, Context.Current.ParentDeviceId, this.iotHub, token, takeOwnership : true); Context.Current.DeleteList.TryAdd( registrationId, device.Expect(() => new InvalidOperationException( $"Device '{registrationId}' should have been created by DPS, but was not found in '{this.iotHub.Hostname}'"))); }
public async Task DpsSymmetricKey() { string idScope = Context.Current.DpsIdScope.Expect(() => new InvalidOperationException("Missing DPS ID scope")); string groupKey = Context.Current.DpsGroupKey.Expect(() => new InvalidOperationException("Missing DPS enrollment group key")); string registrationId = DeviceId.Current.Generate(); string deviceKey = this.DeriveDeviceKey(Convert.FromBase64String(groupKey), registrationId); CancellationToken token = this.TestToken; (TestCertificates testCerts, _) = await TestCertificates.GenerateCertsAsync(registrationId, token); await this.daemon.ConfigureAsync( config => { testCerts.AddCertsToConfig(config); config.SetDpsSymmetricKey(idScope, registrationId, deviceKey); config.Update(); return(Task.FromResult(( "with DPS symmetric key attestation for '{Identity}'", new object[] { registrationId }))); }, token); await this.daemon.WaitForStatusAsync(EdgeDaemonStatus.Running, token); var agent = new EdgeAgent(registrationId, this.iotHub); await agent.WaitForStatusAsync(EdgeModuleStatus.Running, token); await agent.PingAsync(token); Option <EdgeDevice> device = await EdgeDevice.GetIdentityAsync( registrationId, Context.Current.ParentDeviceId, this.iotHub, token, takeOwnership : true); Context.Current.DeleteList.TryAdd( registrationId, device.Expect(() => new InvalidOperationException( $"Device '{registrationId}' should have been created by DPS, but was not found in '{this.iotHub.Hostname}'"))); }
private async Task WaitForConfiguredStatusAsync(EdgeDevice device, DateTime startTime, CancellationToken token) { try { await this.daemon.WaitForStatusAsync(EdgeDaemonStatus.Running, token); var agent = new EdgeAgent(device.Id, this.iotHub); await agent.WaitForStatusAsync(EdgeModuleStatus.Running, token); await agent.PingAsync(token); } // ReSharper disable once RedundantCatchClause catch { throw; } finally { await NUnitLogs.CollectAsync(startTime, token); } }
public async Task BeforeAllAsync() { await Profiler.Run( async() => { // Set up logging LogEventLevel consoleLevel = Context.Current.Verbose ? LogEventLevel.Verbose : LogEventLevel.Information; var loggerConfig = new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.NUnit(consoleLevel); Context.Current.LogFile.ForEach(f => loggerConfig.WriteTo.File(f)); Log.Logger = loggerConfig.CreateLogger(); // Install IoT Edge using (var cts = new CancellationTokenSource(Context.Current.SetupTimeout)) { // NUnit's [Timeout] attribute isn't supported in .NET Standard // and even if it were, it doesn't run the teardown method when // a test times out. We need teardown to run, to remove the // device registration from IoT Hub and stop the daemon. So // we have our own timeout mechanism. DateTime startTime = DateTime.Now; CancellationToken token = cts.Token; Assert.IsNull(this.device); this.device = await EdgeDevice.GetOrCreateIdentityAsync( Context.Current.DeviceId, this.iotHub, token); await this.daemon.UninstallAsync(token); await this.daemon.InstallAsync( this.device.ConnectionString, Context.Current.PackagePath, Context.Current.Proxy, token); try { await this.daemon.WaitForStatusAsync(EdgeDaemonStatus.Running, token); var agent = new EdgeAgent(this.device.Id, this.iotHub); await agent.WaitForStatusAsync(EdgeModuleStatus.Running, token); await agent.PingAsync(token); } // ReSharper disable once RedundantCatchClause catch { throw; } finally { await NUnitLogs.CollectAsync(startTime, token); } } }, "Completed end-to-end test setup"); }
public async Task DpsX509() { (string, string, string)rootCa = Context.Current.RootCaKeys.Expect(() => new InvalidOperationException("Missing DPS ID scope (check rootCaPrivateKeyPath in context.json)")); string caCertScriptPath = Context.Current.CaCertScriptPath.Expect(() => new InvalidOperationException("Missing CA cert script path (check caCertScriptPath in context.json)")); string idScope = Context.Current.DpsIdScope.Expect(() => new InvalidOperationException("Missing DPS ID scope (check dpsIdScope in context.json)")); string registrationId = DeviceId.Current.Generate(); CancellationToken token = this.TestToken; CertificateAuthority ca = await CertificateAuthority.CreateAsync( registrationId, rootCa, caCertScriptPath, token); IdCertificates idCert = await ca.GenerateIdentityCertificatesAsync(registrationId, token); (TestCertificates testCerts, _) = await TestCertificates.GenerateCertsAsync(registrationId, token); // Generated credentials need to be copied out of the script path because future runs // of the script will overwrite them. string path = Path.Combine(FixedPaths.E2E_TEST_DIR, registrationId); string certPath = Path.Combine(path, "device_id_cert.pem"); string keyPath = Path.Combine(path, "device_id_cert_key.pem"); Directory.CreateDirectory(path); File.Copy(idCert.CertificatePath, certPath); OsPlatform.Current.SetOwner(certPath, "aziotcs", "644"); File.Copy(idCert.KeyPath, keyPath); OsPlatform.Current.SetOwner(keyPath, "aziotks", "600"); await this.daemon.ConfigureAsync( config => { testCerts.AddCertsToConfig(config); config.SetDpsX509(idScope, registrationId, certPath, keyPath); config.Update(); return(Task.FromResult(( "with DPS X509 attestation for '{Identity}'", new object[] { registrationId }))); }, token); await this.daemon.WaitForStatusAsync(EdgeDaemonStatus.Running, token); var agent = new EdgeAgent(registrationId, this.iotHub); await agent.WaitForStatusAsync(EdgeModuleStatus.Running, token); await agent.PingAsync(token); Option <EdgeDevice> device = await EdgeDevice.GetIdentityAsync( registrationId, this.iotHub, token, takeOwnership : true); Context.Current.DeleteList.TryAdd( registrationId, device.Expect(() => new InvalidOperationException( $"Device '{registrationId}' should have been created by DPS, but was not found in '{this.iotHub.Hostname}'"))); }
public async Task <int> RunAsync(Args args) { LogEventLevel consoleLevel = args.Verbose ? LogEventLevel.Verbose : LogEventLevel.Information; var loggerConfig = new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.Console(consoleLevel); args.LogFile.ForEach(f => loggerConfig.WriteTo.File(f)); Log.Logger = loggerConfig.CreateLogger(); try { using (var cts = new CancellationTokenSource(args.Timeout)) { Log.Information("Running tempSensor test"); await Profiler.Run( async() => { CancellationToken token = cts.Token; // ** setup var iotHub = new IotHub(args.ConnectionString, args.Endpoint, args.Proxy); EdgeDevice device = await EdgeDevice.GetOrCreateIdentityAsync( args.DeviceId, iotHub, token); var daemon = Platform.CreateEdgeDaemon(args.InstallerPath); await daemon.UninstallAsync(token); await daemon.InstallAsync( device.ConnectionString, args.PackagesPath, args.Proxy, token); await daemon.WaitForStatusAsync(EdgeDaemonStatus.Running, token); var agent = new EdgeAgent(device.Id, iotHub); await agent.WaitForStatusAsync(EdgeModuleStatus.Running, token); await agent.PingAsync(token); // ** test var config = new EdgeConfiguration(device.Id, args.AgentImage, iotHub); args.Registry.ForEach( r => config.AddRegistryCredentials(r.address, r.username, r.password)); config.AddEdgeHub(args.HubImage); args.Proxy.ForEach(p => config.AddProxy(p)); config.AddTempSensor(args.SensorImage); await config.DeployAsync(token); var hub = new EdgeModule("edgeHub", device.Id, iotHub); var sensor = new EdgeModule("tempSensor", device.Id, iotHub); await EdgeModule.WaitForStatusAsync( new[] { hub, sensor }, EdgeModuleStatus.Running, token); await sensor.WaitForEventsReceivedAsync(token); var sensorTwin = new ModuleTwin(sensor.Id, device.Id, iotHub); await sensorTwin.UpdateDesiredPropertiesAsync( new { properties = new { desired = new { SendData = true, SendInterval = 10 } } }, token); await sensorTwin.WaitForReportedPropertyUpdatesAsync( new { properties = new { reported = new { SendData = true, SendInterval = 10 } } }, token); // ** teardown await daemon.StopAsync(token); await device.MaybeDeleteIdentityAsync(token); }, "Completed tempSensor test"); } } catch (OperationCanceledException e) { Log.Error(e, "Cancelled tempSensor test after {Timeout} minutes", args.Timeout.TotalMinutes); } catch (Exception e) { Log.Error(e, "Failed tempSensor test"); return(1); } finally { Log.CloseAndFlush(); } return(0); }
public Task <int> RunAsync(Args args) => Profiler.Run( "Running tempSensor test", async() => { using (var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5))) { CancellationToken token = cts.Token; // ** setup var iotHub = new IotHub(args.ConnectionString, args.Endpoint, args.Proxy); var device = await EdgeDevice.GetOrCreateIdentityAsync( args.DeviceId, iotHub, token); var daemon = new EdgeDaemon(args.InstallerPath); await daemon.UninstallAsync(token); await daemon.InstallAsync( device.ConnectionString, args.PackagesPath, args.Proxy, token); await args.Proxy.Match( async p => { await daemon.StopAsync(token); var yaml = new DaemonConfiguration(); yaml.AddHttpsProxy(p); yaml.Update(); await daemon.StartAsync(token); }, () => daemon.WaitForStatusAsync(EdgeDaemonStatus.Running, token)); var agent = new EdgeAgent(device.Id, iotHub); await agent.WaitForStatusAsync(EdgeModuleStatus.Running, token); await agent.PingAsync(token); // ** test var config = new EdgeConfiguration(device.Id, args.AgentImage, iotHub); args.Registry.ForEach( r => config.AddRegistryCredentials(r.address, r.username, r.password)); config.AddEdgeHub(args.HubImage); args.Proxy.ForEach(p => config.AddProxy(p)); config.AddTempSensor(args.SensorImage); await config.DeployAsync(token); var hub = new EdgeModule("edgeHub", device.Id, iotHub); var sensor = new EdgeModule("tempSensor", device.Id, iotHub); await EdgeModule.WaitForStatusAsync( new[] { hub, sensor }, EdgeModuleStatus.Running, token); await sensor.WaitForEventsReceivedAsync(token); var sensorTwin = new ModuleTwin(sensor.Id, device.Id, iotHub); await sensorTwin.UpdateDesiredPropertiesAsync( new { properties = new { desired = new { SendData = true, SendInterval = 10 } } }, token); await sensorTwin.WaitForReportedPropertyUpdatesAsync( new { properties = new { reported = new { SendData = true, SendInterval = 10 } } }, token); // ** teardown await daemon.StopAsync(token); await device.MaybeDeleteIdentityAsync(token); } return(0); }, "Completed tempSensor test");