io.opentracing.noop.NoopSpan Java Examples

The following examples show how to use io.opentracing.noop.NoopSpan. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FileBasedRegistrationServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the <em>modificationEnabled</em> property prevents updating an existing entry.
 */
@Test
public void testUpdateDeviceFailsIfModificationIsDisabled() {

    // GIVEN a registry that has been configured to not allow modification of entries
    // which contains a device
    registrationConfig.setModificationEnabled(false);
    registrationService.createDevice(TENANT, Optional.of(DEVICE), new Device().putExtension("value", "1"),
            NoopSpan.INSTANCE);

    // WHEN trying to update the device
    final OperationResult<Id> result = registrationService
            .processUpdateDevice(TENANT, DEVICE, new Device().putExtension("value", "2"), Optional.empty(),
                    NoopSpan.INSTANCE);

    // THEN the result contains a FORBIDDEN status code and the device has not been updated
    assertEquals(HttpURLConnection.HTTP_FORBIDDEN, result.getStatus());
    final var device = registrationService.processReadDevice(TENANT, DEVICE, NoopSpan.INSTANCE);
    assertNotNull(device);
    assertNotNull(device.getPayload());
    assertNotNull(device.getPayload().getExtensions());
    Assertions.assertEquals("1", device.getPayload().getExtensions().get("value"));
}
 
Example #2
Source File: AbstractTenantServiceTest.java    From enmasse with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testBetweenBeforeAndAfter() throws Exception {

    var project = new ObjectMapper().readValue(AbstractTenantServiceTest.class.getResourceAsStream("/test-with-cert.json"), IoTProject.class);

    var input = (List<?>) ((Map<String, Object>) project.getStatus().getAccepted().getConfiguration()).get(TenantConstants.FIELD_PAYLOAD_TRUSTED_CA);

    assertNotNull(input);
    assertThat(input, iterableWithSize(1));

    var result = AbstractTenantService.stripInvalidTrustAnchors(
            OffsetDateTime.of(2021, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC).toInstant(),
            new JsonArray(input),
            NoopSpan.INSTANCE);

    assertNotNull(result);
    assertThat(result, iterableWithSize(1));
}
 
Example #3
Source File: OpenCensusTracerAdapter.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public Span activeSpan() {
  io.opencensus.trace.Span inner = ocTracer.getCurrentSpan();
  if (inner == null) {
    return null;
  }

  // An open census blank span is never sampled.
  // Moreover, gRPC creates non-blank spans even though it doesn't want to sample them.
  // The default policy is to inherit the sampling policy from the parent span.
  // Therefore, gRPC spans will not be sampled when we create blank parents.
  // Further reading:
  // https://github.com/census-instrumentation/opencensus-specs/blob/master/trace/Sampling.md
  final boolean shouldNotSample = !inner.getContext().getTraceOptions().isSampled();

  // Our traces will not sample if we use a noop.
  return shouldNotSample ? NoopSpan.INSTANCE : new OpenCensusSpanAdapter(inner);
}
 
Example #4
Source File: AutoProvisioningEnabledDeviceBackendTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a device is created and credentials are set for it when auto-provisioning a device.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testProvisionDeviceSucceeds(final VertxTestContext ctx) {

    // GIVEN an AutoProvisioningEnabledDeviceBackend instance with "happy path" answers
    final AutoProvisioningEnabledDeviceBackend underTest = mock(AutoProvisioningEnabledDeviceBackend.class);
    when(underTest.provisionDevice(anyString(), any(), any())).thenCallRealMethod();

    when(underTest.createDevice(any(), any(), any(), any()))
            .thenReturn(Future.succeededFuture(
                    OperationResult.ok(201, Id.of(DEVICE_ID), Optional.empty(), Optional.empty())));

    when(underTest.updateCredentials(any(), any(), any(), any(), any()))
            .thenReturn(Future.succeededFuture(OperationResult.empty(204)));
    // WHEN provisioning a device from a certificate
    final Future<OperationResult<String>> result = underTest.provisionDevice(TENANT_ID, cert, NoopSpan.INSTANCE);

    // THEN the device is created and credentials are set
    result.onComplete(ctx.succeeding(ok -> {
        ctx.verify(() -> {
            verify(underTest).createDevice(eq(TENANT_ID), any(), any(), any());
            verify(underTest).updateCredentials(eq(TENANT_ID), eq(DEVICE_ID), any(), any(), any());
        });
        ctx.completeNow();
    }));
}
 
Example #5
Source File: AbstractTenantServiceTest.java    From enmasse with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testNotBefore() throws Exception {

    var project = new ObjectMapper().readValue(AbstractTenantServiceTest.class.getResourceAsStream("/test-with-cert.json"), IoTProject.class);

    var input = (List<?>) ((Map<String, Object>) project.getStatus().getAccepted().getConfiguration()).get(TenantConstants.FIELD_PAYLOAD_TRUSTED_CA);

    assertNotNull(input);
    assertThat(input, iterableWithSize(1));

    var result = AbstractTenantService.stripInvalidTrustAnchors(
            OffsetDateTime.of(2000, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC).toInstant(),
            new JsonArray(input),
            NoopSpan.INSTANCE);

    assertNull(result);
}
 
Example #6
Source File: AbstractTenantServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a tenant can be added with a non specified tenant ID in request and that it receive a random
 * identifier.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testAddTenantSucceedsWithGeneratedTenantId(final VertxTestContext ctx) {

    getTenantManagementService().createTenant(
            Optional.empty(),
            buildTenantPayload(),
            NoopSpan.INSTANCE)
            .onComplete(ctx.succeeding(s -> {
                ctx.verify(() -> {
                    final String id = s.getPayload().getId();
                    assertNotNull(id);
                    assertEquals(HttpURLConnection.HTTP_CREATED, s.getStatus());
                });
                ctx.completeNow();
            }));
}
 
Example #7
Source File: AbstractTenantServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a created tenant is associated a resource version.
 * @param ctx The vert.x test context.
 */
@Test
public void testAddTenantSucceedsAndContainResourceVersion(final VertxTestContext ctx) {

    getTenantManagementService().createTenant(
            Optional.of("tenant"),
            buildTenantPayload(),
            NoopSpan.INSTANCE)
            .onComplete(ctx.succeeding(s -> {
                ctx.verify(() -> {
                    final String id = s.getPayload().getId();
                    final String version = s.getResourceVersion().orElse(null);
                    assertNotNull(version);
                    assertEquals("tenant", id);
                    assertEquals(HttpURLConnection.HTTP_CREATED, s.getStatus());
                });
                ctx.completeNow();
            })
    );
}
 
Example #8
Source File: AbstractTenantServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a deleting a tenant with an empty resource version succeeds.
 * @param ctx The vert.x test context.
 */
@Test
public void testDeleteTenantWithEmptyResourceVersionSucceed(final VertxTestContext ctx) {

    addTenant("tenant")
    .map(ok -> {
        getTenantManagementService().deleteTenant(
                "tenant",
                Optional.empty(),
                NoopSpan.INSTANCE)
                .onComplete(ctx.succeeding(s -> {
                    ctx.verify(() -> assertEquals(HttpURLConnection.HTTP_NO_CONTENT, s.getStatus()));
                    ctx.completeNow();
                })
        );
        return null;
    });
}
 
Example #9
Source File: AbstractTenantServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a deleting a tenant with the correct resource version succeeds.
 * @param ctx The vert.x test context.
 */
@Test
public void testDeleteTenantWithMatchingResourceVersionSucceed(final VertxTestContext ctx) {

    addTenant("tenant")
    .map(cr -> {
        final String version = cr.getResourceVersion().orElse(null);
        ctx.verify(() -> assertNotNull(version));
        getTenantManagementService().deleteTenant(
                "tenant",
                Optional.of(version),
                NoopSpan.INSTANCE)
                .onComplete(ctx.succeeding(s -> {
                    ctx.verify(() -> assertEquals(HttpURLConnection.HTTP_NO_CONTENT, s.getStatus()));
                    ctx.completeNow();
                })
        );
        return null;
    });
}
 
Example #10
Source File: AbstractTenantServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a updating a tenant with the matching resource version succeeds.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testUpdateTenantWithMatchingResourceVersionSucceeds(final VertxTestContext ctx) {

    addTenant("tenant")
    .map(cr -> {
        final String version = cr.getResourceVersion().orElse(null);
        ctx.verify(() -> assertNotNull(version));
        getTenantManagementService().updateTenant(
                "tenant",
                buildTenantPayload(),
                Optional.of(version),
                NoopSpan.INSTANCE)
                .onComplete(ctx.succeeding(s -> {
                    ctx.verify(() -> assertEquals(HttpURLConnection.HTTP_NO_CONTENT, s.getStatus()));
                    ctx.completeNow();
                })
        );
        return null;
    });
}
 
Example #11
Source File: AbstractTenantServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a updating a tenant with an empty resource version succeed.
 * @param ctx The vert.x test context.
 */
@Test
public void testUpdateTenantWithEmptyResourceVersionSucceed(final VertxTestContext ctx) {

    addTenant("tenant")
    .map(cr -> {
        getTenantManagementService().updateTenant(
                "tenant",
                buildTenantPayload(),
                Optional.empty(),
                NoopSpan.INSTANCE)
                .onComplete(ctx.succeeding(s -> {
                    ctx.verify(() -> assertEquals(HttpURLConnection.HTTP_NO_CONTENT, s.getStatus()));
                    ctx.completeNow();
                })
        );
        return null;
    });
}
 
Example #12
Source File: AbstractTenantServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a tenant cannot be added if it uses a trusted certificate authority
 * with the same subject DN as an already existing tenant.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testAddTenantFailsForDuplicateCa(final VertxTestContext ctx) {

    final TrustedCertificateAuthority trustedCa = new TrustedCertificateAuthority()
            .setSubjectDn("CN=taken")
            .setPublicKey("NOTAKEY".getBytes(StandardCharsets.UTF_8));

    final Tenant tenant = new Tenant()
            .setEnabled(true)
            .setTrustedCertificateAuthorities(Collections.singletonList(trustedCa));

    addTenant("tenant", tenant)
        .map(ok -> {
            getTenantManagementService().createTenant(
                    Optional.of("newTenant"),
                    tenant,
                    NoopSpan.INSTANCE)
                    .onComplete(ctx.succeeding(s -> {
                        ctx.verify(() -> assertEquals(HttpURLConnection.HTTP_CONFLICT, s.getStatus()));
                        ctx.completeNow();
                    }));
            return null;
        });
}
 
Example #13
Source File: AbstractTenantServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the service does not find any tenant for an unknown subject DN.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testGetForCertificateAuthorityFailsForUnknownSubjectDn(final VertxTestContext ctx) {

    final X500Principal unknownSubjectDn = new X500Principal("O=Eclipse, OU=NotHono, CN=ca");
    final X500Principal subjectDn = new X500Principal("O=Eclipse, OU=Hono, CN=ca");
    final TrustedCertificateAuthority trustedCa = new TrustedCertificateAuthority()
            .setSubjectDn(subjectDn.getName(X500Principal.RFC2253))
            .setPublicKey("NOTAPUBLICKEY".getBytes(StandardCharsets.UTF_8));
    final Tenant tenant = buildTenantPayload()
            .setTrustedCertificateAuthorities(Collections.singletonList(trustedCa));

    addTenant("tenant", tenant)
            .map(ok -> {
                getTenantService().get(unknownSubjectDn, NoopSpan.INSTANCE)
                        .onComplete(ctx.succeeding(s -> ctx.verify(() -> {
                            assertEquals(HttpURLConnection.HTTP_NOT_FOUND, s.getStatus());
                            ctx.completeNow();
                        })));
                return null;
            });
}
 
Example #14
Source File: RegistrationServiceTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a request to create a device using an existing identifier fails with a 409.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testCreateDeviceFailsForExistingDeviceId(final VertxTestContext ctx) {

    final String deviceId = randomDeviceId();

    createDevice(deviceId, new Device())
        .compose(ok -> getDeviceManagementService()
                .createDevice(TENANT, Optional.of(deviceId), new Device(), NoopSpan.INSTANCE))
        .onComplete(ctx.succeeding(response -> {
            ctx.verify(() -> {
                assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_CONFLICT);
            });
            ctx.completeNow();
        }));
}
 
Example #15
Source File: RegistrationServiceTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a request to create a device with a given identifier succeeds.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testCreateDeviceWithIdSucceeds(final VertxTestContext ctx) {

    final String deviceId = randomDeviceId();

    getDeviceManagementService().createDevice(TENANT, Optional.of(deviceId), new Device(), NoopSpan.INSTANCE)
            .onComplete(ctx.succeeding(response -> {
                ctx.verify(() -> {
                    assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_CREATED);
                    assertThat(response.getResourceVersion().orElse(null)).isNotNull();
                    assertThat(response.getPayload().getId()).isEqualTo(deviceId);
                });
                ctx.completeNow();
            }));
}
 
Example #16
Source File: RegistrationServiceTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a request to read an existing device succeeds.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testReadDeviceSucceedsForExistingDevice(final VertxTestContext ctx) {

    final String deviceId = randomDeviceId();
    final Device device = new Device()
            .setVia(List.of("a", "b", "c"))
            .setViaGroups(List.of("group1", "group2"))
            .setMapper("mapper");

    createDevices(Map.of(deviceId, device))
        .compose(ok -> getDeviceManagementService().readDevice(TENANT, deviceId, NoopSpan.INSTANCE))
        .onComplete(ctx.succeeding(s -> {
            ctx.verify(() -> {
                assertThat(s.isOk());
                assertThat(s.getPayload()).isNotNull();
                assertThat(s.getPayload().getVia()).contains("a", "b", "c");
                assertThat(s.getPayload().getViaGroups()).contains("group1", "group2");
                assertThat(s.getPayload().getMapper()).isEqualTo("mapper");
            });
            ctx.completeNow();
        }));
}
 
Example #17
Source File: RegistrationServiceTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that deleting a device succeeds when the request does not contain a resource version.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testDeleteDeviceSucceeds(final VertxTestContext ctx) {

    final String deviceId = randomDeviceId();
    final Checkpoint register = ctx.checkpoint(2);

    getDeviceManagementService().createDevice(TENANT, Optional.of(deviceId), new Device(), NoopSpan.INSTANCE)
            .map(response -> {
                ctx.verify(() -> assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_CREATED));
                register.flag();
                return response;
            }).compose(rr -> getDeviceManagementService()
                    .deleteDevice(TENANT, deviceId, Optional.empty(), NoopSpan.INSTANCE))
            .onComplete(ctx.succeeding(response -> {
                ctx.verify(() -> {
                    assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT);
                });
                register.flag();
            }));
}
 
Example #18
Source File: RegistrationServiceTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that deleting a device succeeds when the request contains a resource version that matches
 * the one of the device on record.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testDeleteDeviceSucceedsForMatchingResourceVersion(final VertxTestContext ctx) {

    final String deviceId = randomDeviceId();
    final Checkpoint register = ctx.checkpoint(2);

    getDeviceManagementService().createDevice(TENANT, Optional.of(deviceId), new Device(), NoopSpan.INSTANCE)
            .map(response -> {
                ctx.verify(() -> assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_CREATED));
                register.flag();
                return response;
            }).compose(rr -> {
                final String resourceVersion = rr.getResourceVersion().orElse(null);
                return getDeviceManagementService()
                        .deleteDevice(TENANT, deviceId, Optional.of(resourceVersion), NoopSpan.INSTANCE);
            }).onComplete(ctx.succeeding(response -> {
                ctx.verify(() -> {
                    assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT);
                });
                register.flag();
            }));
}
 
Example #19
Source File: RegistrationServiceTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Helps asserting device data.
 *
 * @param tenant The tenant.
 * @param deviceId The device ID.
 * @param gatewayId The optional gateway ID
 * @param managementAssertions assertions for the management data.
 * @param adapterAssertions assertions for the adapter data.
 * @return A new future that will succeed when the read/get operations succeed and the assertions are valid.
 *         Otherwise the future must fail.
 */
protected Future<?> assertDevice(final String tenant, final String deviceId, final Optional<String> gatewayId,
        final Handler<OperationResult<Device>> managementAssertions,
        final Handler<RegistrationResult> adapterAssertions) {

    // read management data

    final Future<OperationResult<Device>> f1 = getDeviceManagementService()
            .readDevice(tenant, deviceId, NoopSpan.INSTANCE);

    // read adapter data

    final Future<RegistrationResult> f2 = gatewayId
            .map(id -> getRegistrationService().assertRegistration(tenant, deviceId, id))
            .orElseGet(() -> getRegistrationService().assertRegistration(tenant, deviceId));
    return CompositeFuture.all(
            f1.map(r -> {
                managementAssertions.handle(r);
                return null;
            }),
            f2.map(r -> {
                adapterAssertions.handle(r);
                return null;
            }));
}
 
Example #20
Source File: RegistrationServiceTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates a set of devices.
 *
 * @param devices The devices to create.
 * @return A succeeded future if all devices have been created successfully.
 */
protected Future<?> createDevices(final Map<String, Device> devices) {

    Future<?> current = Future.succeededFuture();
    for (final Map.Entry<String, Device> entry : devices.entrySet()) {

        current = current.compose(ok -> getDeviceManagementService()
                .createDevice(TENANT, Optional.of(entry.getKey()), entry.getValue(), NoopSpan.INSTANCE)
                .map(r -> {
                    assertThat(r.getStatus()).isEqualTo(HttpURLConnection.HTTP_CREATED);
                    return null;
                }));

    }

    return current;

}
 
Example #21
Source File: AbstractCredentialsServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the service returns credentials for an existing device.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testGetCredentialsSucceedsForExistingDevice(final VertxTestContext ctx) {

    final var tenantId = "tenant";
    final var deviceId = UUID.randomUUID().toString();
    final var authId = UUID.randomUUID().toString();

    assertGetMissing(ctx, tenantId, deviceId, authId, CredentialsConstants.SECRETS_TYPE_HASHED_PASSWORD,
            () -> getDeviceManagementService()
                    .createDevice(tenantId, Optional.of(deviceId), new Device(), NoopSpan.INSTANCE)
                    .onComplete(ctx.succeeding(s -> assertGet(ctx, tenantId, deviceId, authId,
                            CredentialsConstants.SECRETS_TYPE_HASHED_PASSWORD,
                            r -> {
                                assertEquals(HttpURLConnection.HTTP_OK, r.getStatus());
                                assertNotNull(r.getPayload());
                                assertTrue(r.getPayload().isEmpty());
                            },
                            r -> assertEquals(HttpURLConnection.HTTP_NOT_FOUND, r.getStatus()),
                            ctx::completeNow))));
}
 
Example #22
Source File: AbstractCredentialsServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Registers a set of credentials for a device.
 *
 * @param svc The service to register the credentials with.
 * @param tenantId The tenant that the device belongs to.
 * @param deviceId The ID of the device.
 * @param secrets The secrets to register.
 * @return A succeeded future if the credentials have been registered successfully.
 */
protected static Future<OperationResult<Void>> setCredentials(
        final CredentialsManagementService svc,
        final String tenantId,
        final String deviceId,
        final List<CommonCredential> secrets) {

    return svc.updateCredentials(tenantId, deviceId, secrets, Optional.empty(), NoopSpan.INSTANCE)
            .compose(r -> {
                if (HttpURLConnection.HTTP_NO_CONTENT == r.getStatus()) {
                    return Future.succeededFuture(r);
                } else {
                    return Future.failedFuture(new ClientErrorException(r.getStatus()));
                }
            });
}
 
Example #23
Source File: FileBasedTenantServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the <em>modificationEnabled</em> property prevents removing a tenant.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testRemoveTenantsFailsIfModificationIsDisabled(final VertxTestContext ctx) {

    // GIVEN a service containing a set of tenants
    // that has been configured to not allow modification of entries
    props.setModificationEnabled(false);

    // WHEN trying to update the tenant
    svc.deleteTenant(
            "tenant",
            Optional.empty(),
            NoopSpan.INSTANCE)
            .onComplete(ctx.succeeding(s -> {
                ctx.verify(() -> {
                    // THEN the update fails
                    assertThat(s.getStatus()).isEqualTo(HttpURLConnection.HTTP_FORBIDDEN);
                });
                ctx.completeNow();
            }));
}
 
Example #24
Source File: FileBasedTenantServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the <em>modificationEnabled</em> property prevents updating an existing entry.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testUpdateTenantsFailsIfModificationIsDisabled(final VertxTestContext ctx) {

    // GIVEN a service containing a set of tenants
    // that has been configured to not allow modification of entries
    props.setModificationEnabled(false);

    // WHEN trying to update the tenant
    svc.updateTenant(
            "tenant",
            new Tenant(),
            null,
            NoopSpan.INSTANCE)
            .onComplete(ctx.succeeding(s -> {
                ctx.verify(() -> {
                    // THEN the update fails
                    assertThat(s.getStatus()).isEqualTo(HttpURLConnection.HTTP_FORBIDDEN);
                });
                ctx.completeNow();
            }));
}
 
Example #25
Source File: FileBasedTenantServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that autowired {@link org.eclipse.hono.deviceregistry.service.tenant.TenantInformationService} works correctly.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testTenantInformationService(final VertxTestContext ctx) {
    final AutowiredTenantInformationService informationService = new AutowiredTenantInformationService();
    informationService.setService(svc);

    informationService.tenantExists(Constants.DEFAULT_TENANT, NoopSpan.INSTANCE)
            .onComplete(ctx.succeeding(t -> {
                            ctx.verify(() -> assertThat(t.getStatus()).isEqualTo(HttpURLConnection.HTTP_NOT_FOUND));
                        }));

    addTenant(Constants.DEFAULT_TENANT)
            .map(ok -> {
                informationService.tenantExists(Constants.DEFAULT_TENANT, NoopSpan.INSTANCE)
                        .onComplete(ctx.succeeding(s -> {
                            ctx.verify(() -> {
                                assertThat(s.getPayload().getTenantId()).isEqualTo(Constants.DEFAULT_TENANT);
                                ctx.completeNow();
                            });
                        }));
                return null;
            });
}
 
Example #26
Source File: FileBasedRegistrationServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the registry enforces the maximum devices per tenant limit.
 */
@Test
public void testCreateDeviceFailsIfDeviceLimitIsReached() {

    // GIVEN a registry whose devices-per-tenant limit has been reached
    registrationConfig.setMaxDevicesPerTenant(1);
    registrationService.createDevice(TENANT, Optional.of(DEVICE), new Device(), NoopSpan.INSTANCE);

    // WHEN registering an additional device for the tenant
    final OperationResult<Id> result = registrationService.processCreateDevice(TENANT, Optional.of("newDevice"),
            new Device(), NoopSpan.INSTANCE);

    // THEN the result contains a FORBIDDEN status code and the device has not been added to the registry
    assertEquals(HttpURLConnection.HTTP_FORBIDDEN, result.getStatus());
    assertEquals(HttpURLConnection.HTTP_NOT_FOUND,
            registrationService.processReadDevice(TENANT, "newDevice", NoopSpan.INSTANCE).getStatus());
}
 
Example #27
Source File: FileBasedCredentialsServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the <em>modificationEnabled</em> property prevents updating an existing entry.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testUpdateCredentialsFailsIfModificationIsDisabled(final VertxTestContext ctx) {

    // GIVEN a registry that has been configured to not allow modification of entries
    credentialsConfig.setModificationEnabled(false);

    final CommonCredential secret = createPasswordCredential("myId", "bar", OptionalInt.empty());

    // containing a set of credentials
    setCredentials(getCredentialsManagementService(), "tenant", "device", Collections.singletonList(secret))
            .compose(ok -> {
                // WHEN trying to update the credentials
                final PasswordCredential newSecret = createPasswordCredential("myId", "baz", OptionalInt.empty());
                return svc.updateCredentials("tenant", "device",
                        Collections.singletonList(newSecret),
                        Optional.empty(),
                        NoopSpan.INSTANCE);
            })
            .onComplete(ctx.succeeding(s -> ctx.verify(() -> {
                // THEN the update fails with a 403
                assertThat(s.getStatus()).isEqualTo(HttpURLConnection.HTTP_FORBIDDEN);
                ctx.completeNow();
            })));
}
 
Example #28
Source File: RegistrationServiceTests.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that updating a device succeeds when the request contains a resource version that matches
 * the one of the device on record.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testUpdateDeviceSucceedsForMatchingResourceVersion(final VertxTestContext ctx) {

    final String deviceId = randomDeviceId();
    final Checkpoint register = ctx.checkpoint(2);
    final AtomicReference<String> resourceVersion = new AtomicReference<>();

    getDeviceManagementService().createDevice(TENANT, Optional.of(deviceId), new Device(), NoopSpan.INSTANCE)
            .map(response -> {
                ctx.verify(() -> assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_CREATED));
                resourceVersion.set(response.getResourceVersion().get());
                register.flag();
                return response;
            }).compose(rr -> getDeviceManagementService().updateDevice(
                    TENANT,
                    deviceId,
                    new Device().putExtension("customKey", "customValue"),
                    Optional.of(resourceVersion.get()),
                    NoopSpan.INSTANCE))
            .onComplete(ctx.succeeding(response -> {
                ctx.verify(() -> {
                    assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT);
                    assertThat(response.getResourceVersion().get()).isNotEqualTo(resourceVersion.get());
                });
                register.flag();
            }));
}
 
Example #29
Source File: RegistrationServiceTests.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that updating a device succeeds when the request does not contain a resource version.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testUpdateDeviceSucceeds(final VertxTestContext ctx) {

    final String deviceId = randomDeviceId();
    final Checkpoint register = ctx.checkpoint(2);
    final AtomicReference<String> resourceVersion = new AtomicReference<>();

    getDeviceManagementService().createDevice(TENANT, Optional.of(deviceId), new Device(), NoopSpan.INSTANCE)
            .map(response -> {
                ctx.verify(() -> assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_CREATED));
                resourceVersion.set(response.getResourceVersion().get());
                register.flag();
                return response;
            }).compose(rr -> getDeviceManagementService().updateDevice(
                    TENANT,
                    deviceId,
                    new Device().putExtension("customKey", "customValue"),
                    Optional.empty(),
                    NoopSpan.INSTANCE))
            .onComplete(ctx.succeeding(response -> {
                ctx.verify(() -> {
                    assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT);
                    assertThat(response.getResourceVersion().get()).isNotEqualTo(resourceVersion.get());
                });
                register.flag();
            }));
}
 
Example #30
Source File: RegistrationServiceTests.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that a request to update a device fails if the given resource version doesn't
 * match the one of the device on record.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testUpdateDeviceFailsForNonMatchingResourceVersion(final VertxTestContext ctx) {

    final String deviceId = randomDeviceId();
    final Checkpoint register = ctx.checkpoint(2);

    getDeviceManagementService().createDevice(TENANT, Optional.of(deviceId), new Device(), NoopSpan.INSTANCE)
            .map(response -> {
                ctx.verify(() -> assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_CREATED));
                register.flag();
                return response;
            }).compose(rr -> {
                final String resourceVersion = rr.getResourceVersion().orElse(null);
                return getDeviceManagementService().updateDevice(
                        TENANT,
                        deviceId,
                        new Device().putExtension("customKey", "customValue"),
                        Optional.of("not- " + resourceVersion),
                        NoopSpan.INSTANCE);
            }).onComplete(ctx.succeeding(response -> {
                ctx.verify(() -> {
                    assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_PRECON_FAILED);
                });
                register.flag();
            }));
}