下面列出了org.junit.jupiter.api.Tag#org.assertj.core.api.Assertions 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void incomingConnection_deduplicatedWhenAlreadyConnected_peerWithLowerValueNodeId()
throws ExecutionException, InterruptedException {
final Bytes localNodeId = Bytes.fromHexString("0x02", EnodeURL.NODE_ID_SIZE);
final Bytes remoteNodeId = Bytes.fromHexString("0x01", EnodeURL.NODE_ID_SIZE);
startAgent(localNodeId);
final Peer peer = createPeer(remoteNodeId);
final CompletableFuture<PeerConnection> existingConnection = agent.connect(peer);
final PeerConnection incomingConnection = connection(peer);
connectionInitializer.simulateIncomingConnection(incomingConnection);
// New connection should be kept
Assertions.assertThat(agent.getPeerConnection(peer).get().get()).isEqualTo(incomingConnection);
assertThat(agent.getConnectionCount()).isEqualTo(1);
assertThat(existingConnection.get().isDisconnected()).isTrue();
assertThat(((MockPeerConnection) existingConnection.get()).getDisconnectReason())
.contains(DisconnectReason.ALREADY_CONNECTED);
}
@Test
public void setToolTipBuilderWithOneParam_hasToolTip() {
//given
ToolTipBuilder toolTipBuilder = new ToolTipBuilder() {
@Override
public Object call(Object x) {
return "x=" + x;
}
@Override
public int getMaximumNumberOfParameters() {
return 1;
}
};
//when
xyGraphics.setToolTip(toolTipBuilder);
//then
Assertions.assertThat(xyGraphics.getToolTips().get(0)).isEqualTo("x=10");
}
@Test(groups = STORAGE_FORMATS)
public void testCreateTable()
throws SQLException
{
onPresto().executeQuery("CREATE TABLE test_create_table(a bigint, b varchar, c smallint) WITH (format='ORC')");
onPresto().executeQuery("INSERT INTO test_create_table(a, b, c) VALUES " +
"(NULL, NULL, NULL), " +
"(-42, 'abc', SMALLINT '-127'), " +
"(9223372036854775807, 'abcdefghijklmnopqrstuvwxyz', SMALLINT '32767')");
assertThat(onPresto().executeQuery("SELECT * FROM test_create_table"))
.containsOnly(
row(null, null, null),
row(-42, "abc", -127),
row(9223372036854775807L, "abcdefghijklmnopqrstuvwxyz", 32767));
Assertions.assertThat(getTableProperty("test_create_table", "transactional"))
// Hive 3 removes "transactional" table property when it has value "false"
.isIn(Optional.empty(), Optional.of("false"));
onPresto().executeQuery("DROP TABLE test_create_table");
}
@Test
public void testTakeSnapshot() throws InterruptedException, ReaperException, ClassNotFoundException, IOException {
JmxProxy proxy = (JmxProxy) mock(Class.forName("io.cassandrareaper.jmx.JmxProxyImpl"));
StorageServiceMBean storageMBean = Mockito.mock(StorageServiceMBean.class);
JmxProxyTest.mockGetStorageServiceMBean(proxy, storageMBean);
AppContext cxt = new AppContext();
cxt.config = TestRepairConfiguration.defaultConfig();
cxt.jmxConnectionFactory = mock(JmxConnectionFactory.class);
when(cxt.jmxConnectionFactory.connectAny(any(Collection.class))).thenReturn(proxy);
Pair<Node,String> result = SnapshotService
.create(cxt, SNAPSHOT_MANAGER_EXECUTOR)
.takeSnapshot("Test", Node.builder().withHostname("127.0.0.1").build());
Assertions.assertThat(result.getLeft().getHostname()).isEqualTo("127.0.0.1");
Assertions.assertThat(result.getRight()).isEqualTo("Test");
verify(storageMBean, times(1)).takeSnapshot("Test");
}
@Test
@Description("Weight is validated and saved to the Rollout.")
public void weightValidatedAndSaved() {
final String targetPrefix = UUID.randomUUID().toString();
testdataFactory.createTargets(4, targetPrefix);
enableMultiAssignments();
Assertions.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> createTestRolloutWithTargetsAndDistributionSet(4, 2, "50", "80",
UUID.randomUUID().toString(), UUID.randomUUID().toString(), Action.WEIGHT_MAX + 1));
Assertions.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> createTestRolloutWithTargetsAndDistributionSet(4, 2, "50", "80",
UUID.randomUUID().toString(), UUID.randomUUID().toString(), Action.WEIGHT_MIN - 1));
final Rollout createdRollout1 = createTestRolloutWithTargetsAndDistributionSet(4, 2, "50", "80",
UUID.randomUUID().toString(), UUID.randomUUID().toString(), Action.WEIGHT_MAX);
final Rollout createdRollout2 = createTestRolloutWithTargetsAndDistributionSet(4, 2, "50", "80",
UUID.randomUUID().toString(), UUID.randomUUID().toString(), Action.WEIGHT_MIN);
assertThat(rolloutRepository.findById(createdRollout1.getId()).get().getWeight()).get()
.isEqualTo(Action.WEIGHT_MAX);
assertThat(rolloutRepository.findById(createdRollout2.getId()).get().getWeight()).get()
.isEqualTo(Action.WEIGHT_MIN);
}
public void testPropagatingAlgorithmException() {
// The query should result in an error.
try {
// Out of allowed range (should cause an exception).
Map<String,Object> attrs = new HashMap<>();
attrs.put("ignoreWordIfInHigherDocsPercent", Double.MAX_VALUE);
new ClusteringActionRequestBuilder(client)
.setQueryHint("")
.addSourceFieldMapping("title", LogicalField.TITLE)
.addSourceFieldMapping("content", LogicalField.CONTENT)
.setAlgorithm(STCClusteringAlgorithm.NAME)
.addAttributes(attrs)
.setSearchRequest(
client.prepareSearch()
.setIndices(INDEX_TEST)
.setSize(100)
.setQuery(QueryBuilders.termQuery("content", "data"))
.setFetchSource(new String[] {"title", "content"}, null))
.execute().actionGet();
throw Preconditions.unreachable();
} catch (ElasticsearchException e) {
Assertions.assertThat(e)
.hasMessageContaining("Clustering error:");
}
}
@Test
public void scanSingleSubscriber() {
CoreSubscriber<Integer> actual = new LambdaSubscriber<>(null, e -> {}, null, null);
FluxZip.ZipSingleCoordinator<Integer, Integer> main =
new FluxZip.ZipSingleCoordinator<Integer, Integer>(actual, new Object[1], 1, i -> 5);
FluxZip.ZipSingleSubscriber<Integer> test = new FluxZip.ZipSingleSubscriber<>(main, 0);
Subscription parent = Operators.emptySubscription();
test.onSubscribe(parent);
Assertions.assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent);
Assertions.assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(main);
test.onNext(7);
Assertions.assertThat(test.scan(Scannable.Attr.BUFFERED)).isEqualTo(1);
Assertions.assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue();
Assertions.assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue();
}
@Test
public void buildTestNoOutboundInternetTrafficBothVpcCidrsAndPrefixListsAreGiven() {
//GIVEN
//WHEN
modelContext = new ModelContext()
.withAuthenticatedContext(authenticatedContext)
.withStack(cloudStack)
.withExistingVpc(true)
.withExistingIGW(true)
.withExistingSubnetCidr(singletonList(existingSubnetCidr))
.mapPublicIpOnLaunch(true)
.withEnableInstanceProfile(true)
.withInstanceProfileAvailable(true)
.withOutboundInternetTraffic(OutboundInternetTraffic.DISABLED)
.withVpcCidrs(List.of("vpccidr1", "vpccidr2"))
.withPrefixListIds(List.of("prefix1", "prefix2"))
.withTemplate(awsCloudFormationTemplate);
String templateString = cloudFormationTemplateBuilder.build(modelContext);
//THEN
Assertions.assertThat(JsonUtil.isValid(templateString)).overridingErrorMessage("Invalid JSON: " + templateString).isTrue();
assertThat(templateString, stringContainsInOrder("SecurityGroupEgress", "vpccidr1", "vpccidr2", "prefix1", "prefix2"));
}
@Test
@SuppressWarnings("unchecked")
public void testHandlerBean() throws Exception {
ConfigurableApplicationContext context = SpringApplication.run(this.configClass,
"--spring.cloud.stream.bindings.output.contentType=application/json",
"--server.port=0");
MessageCollector collector = context.getBean(MessageCollector.class);
Processor processor = context.getBean(Processor.class);
String id = UUID.randomUUID().toString();
processor.input()
.send(MessageBuilder.withPayload("{\"foo\":\"barbar" + id + "\"}")
.setHeader("contentType", "application/json").build());
HandlerBean handlerBean = context.getBean(HandlerBean.class);
Assertions.assertThat(handlerBean.receivedPojos).hasSize(1);
Assertions.assertThat(handlerBean.receivedPojos.get(0))
.hasFieldOrPropertyWithValue("foo", "barbar" + id);
Message<String> message = (Message<String>) collector
.forChannel(processor.output()).poll(1, TimeUnit.SECONDS);
assertThat(message).isNotNull();
assertThat(message.getPayload()).isEqualTo("{\"bar\":\"barbar" + id + "\"}");
assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)
.includes(MimeTypeUtils.APPLICATION_JSON));
context.close();
}
@Test
public void shouldSetInvocationsPerBatchType() {
// given
configuration.getInvocationsPerBatchJobByBatchType()
.put(Batch.TYPE_HISTORIC_DECISION_INSTANCE_DELETION, 42);
HistoricDecisionInstanceQuery query = historyService.createHistoricDecisionInstanceQuery()
.decisionDefinitionKey(DECISION);
// when
Batch batch = historyService.deleteHistoricDecisionInstancesAsync(query, null);
// then
Assertions.assertThat(batch.getInvocationsPerBatchJob()).isEqualTo(42);
// clear
configuration.setInvocationsPerBatchJobByBatchType(new HashMap<>());
}
@Test
public void newCharge_whenDoesNotExist() {
existingCharge = null;
context.checking(new Expectations() {
{
oneOf(mockServiceRegistry2).injectServicesInto(with(any(Charge.class)));
oneOf(mockRepositoryService).persistAndFlush(with(any(Charge.class)));
}
});
final Charge newCharge = chargeRepository.upsert("CG-REF", "CG-Name", "CG-Description",
newApplicationTenancy("/it"), Applicability.IN_AND_OUT, tax, chargeGroup
);
Assertions.assertThat(newCharge.getReference()).isEqualTo("CG-REF");
Assertions.assertThat(newCharge.getName()).isEqualTo("CG-Name");
Assertions.assertThat(newCharge.getDescription()).isEqualTo("CG-Description");
Assertions.assertThat(newCharge.getTax()).isEqualTo(tax);
Assertions.assertThat(newCharge.getGroup()).isEqualTo(chargeGroup);
}
@Test
public void rxObservableIntFallback() {
server.enqueue(new MockResponse().setResponseCode(500));
final TestInterface api = target();
final Observable<Integer> observable = api.intObservable();
assertThat(observable).isNotNull();
assertThat(server.getRequestCount()).isEqualTo(0);
final TestSubscriber<Integer> testSubscriber = new TestSubscriber<Integer>();
observable.subscribe(testSubscriber);
testSubscriber.awaitTerminalEvent();
Assertions.assertThat(testSubscriber.getOnNextEvents().get(0)).isEqualTo(new Integer(0));
}
@Test
public void concatRemittanceInformation_works() throws Exception {
// given
PaymentBatch paymentBatch = new PaymentBatch();
// when
List<PaymentLine> lines = new ArrayList<>();
// then
Assertions.assertThat(paymentBatch.concatRemittanceInformationAndTruncateIfNeeded(lines)).isEqualTo("");
// and when
final PaymentLine line1 = new PaymentLine();
line1.setRemittanceInformation("info1");
lines.add(line1);
// then
Assertions.assertThat(paymentBatch.concatRemittanceInformationAndTruncateIfNeeded(lines)).isEqualTo("info1");
// and when
final PaymentLine line2 = new PaymentLine();
line2.setRemittanceInformation("info2");
lines.add(line2);
// then
Assertions.assertThat(paymentBatch.concatRemittanceInformationAndTruncateIfNeeded(lines)).isEqualTo("info1;info2");
}
@Test
public void testOrFailOK() {
Mockito.when(repository.get("1"))
.thenReturn(Optional.of(order));
AggregateRoot<?> aggregateRoot = null;
try {
aggregateRoot = underTest.fromRepository()
.orFail();
} catch (AggregateNotFoundException e) {
fail();
}
Assertions.assertThat(aggregateRoot)
.isNotNull();
Assertions.assertThat(aggregateRoot)
.isEqualTo(order);
Assertions.assertThat(((Order) aggregateRoot).getProduct())
.isEqualTo("lightsaber");
}
@Test
public void testCreate_4() {
Cluster cluster = Cluster.builder()
.withName("test")
.withSeedHosts(ImmutableSet.of("127.0.0.1", "127.0.0.2"))
.withPartitioner("murmur3")
.withJmxPort(9999)
.withState(Cluster.State.ACTIVE)
.build();
Assertions.assertThat(cluster.getName()).isEqualTo("test");
Assertions.assertThat(cluster.getSeedHosts()).hasSize(2);
Assertions.assertThat(cluster.getSeedHosts()).contains("127.0.0.1", "127.0.0.2");
Assertions.assertThat(cluster.getPartitioner()).isPresent();
Assertions.assertThat(cluster.getPartitioner().get()).isEqualTo("murmur3");
Assertions.assertThat(cluster.getJmxPort()).isEqualTo(9999);
Assertions.assertThat(cluster.getState()).isEqualTo(Cluster.State.ACTIVE);
Assertions.assertThat(cluster.getLastContact()).isEqualTo(LocalDate.MIN);
}
@Test
public void testToDtos() {
underTest2 = new AssembleMultipleImpl<>(context, Stream.of(new Order("lightsaber"), new Order("death star")),
null);
List<OrderDto> orderDtos = underTest2.toListOf(OrderDto.class);
Assertions.assertThat(orderDtos)
.isNotNull();
Assertions.assertThat(orderDtos)
.isNotEmpty();
Assertions.assertThat(orderDtos.get(0)
.getProduct())
.isEqualTo("lightsaber");
Assertions.assertThat(orderDtos.get(1)
.getProduct())
.isEqualTo("death star");
}
public DirectoryAssert hasSameContentAs(Path path) {
FileAssert fileAssert = new FileAssert(actual.toFile());
fileAssert.exists().isDirectory();
Arrays
.stream(path.toFile().listFiles())
.map(File::toPath)
.forEach(expectedFile -> {
Path actualFile = actual.resolve(expectedFile.getFileName());
if (expectedFile.toFile().isDirectory()) {
assertThatDirectory(actualFile).hasSameContentAs(expectedFile);
} else {
Assertions.assertThat(actualFile).exists().isRegularFile().hasSameContentAs(expectedFile);
}
});
return this;
}
/**
* Test equals.
*/
@Test
void canFindEquality() {
final Cluster.Builder builder = new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP);
builder.withConfigs(null);
builder.withDependencies(null);
builder.withCreated(null);
builder.withDescription(null);
builder.withId(UUID.randomUUID().toString());
builder.withTags(null);
builder.withUpdated(null);
final Cluster cluster1 = builder.build();
final Cluster cluster2 = builder.build();
builder.withDescription(UUID.randomUUID().toString());
final Cluster cluster3 = builder.build();
builder.withId(UUID.randomUUID().toString());
final Cluster cluster4 = builder.build();
Assertions.assertThat(cluster1).isEqualTo(cluster2);
Assertions.assertThat(cluster1).isEqualTo(cluster3);
Assertions.assertThat(cluster1).isNotEqualTo(cluster4);
}
@Before
public void before() {
new Expectations() {
{
restConfig.getPath();
result = REST_PATH;
restConfig.getBaseRel();
result = BASE_REL;
restConfig.getBaseParam();
result = BASE_PARAM;
}
};
ResourceScanner resourceScanner = new ResourceScanner(restConfig, SERVLET_CONTEXT_PATH);
resourceScanner.scan(Lists.newArrayList(
MethodResource.class,
ClassResource.class,
ClassAndMethodResource.class,
ClassAndMethodResource2.class,
ClassAndMethodResource3.class
));
resourceMap = resourceScanner.jsonHomeResources();
Assertions.assertThat(resourceMap).isNotNull();
}
@Test
public void seoFinished_shouldSetPayload() throws Exception {
//given
Object payload = new Object();
//when
seo.finished(payload);
//then
Assertions.assertThat(seo.getPayload()).isEqualTo(payload);
}
@Test
public void buildTestWithVPCAndRoleWithoutIGWAndPublicIpOnLaunchAndInstanceProfile() {
CloudStack cloudStack = initCloudStackWithInstanceProfile();
//WHEN
modelContext = new ModelContext()
.withAuthenticatedContext(authenticatedContext)
.withStack(cloudStack)
.withExistingVpc(true)
.withExistingIGW(false)
.withExistingSubnetCidr(singletonList(existingSubnetCidr))
.mapPublicIpOnLaunch(false)
.withEnableInstanceProfile(false)
.withInstanceProfileAvailable(true)
.withOutboundInternetTraffic(OutboundInternetTraffic.ENABLED)
.withTemplate(awsCloudFormationTemplate);
String templateString = cloudFormationTemplateBuilder.build(modelContext);
//THEN
Assertions.assertThat(JsonUtil.isValid(templateString)).overridingErrorMessage("Invalid JSON: " + templateString).isTrue();
assertThat(templateString, containsString("InstanceProfile"));
assertThat(templateString, containsString("VPCId"));
assertThat(templateString, not(containsString("SubnetCIDR")));
assertThat(templateString, containsString("SubnetId"));
assertThat(templateString, not(containsString("SubnetConfig")));
assertThat(templateString, not(containsString("\"AttachGateway\"")));
assertThat(templateString, not(containsString("\"InternetGateway\"")));
assertThat(templateString, containsString("AvailabilitySet"));
assertThat(templateString, not(containsString("EIP")));
}
public AbstractGridItemViewAssert hasSecondaryTextView() {
isNotNull();
Assertions.assertThat(actual.findViewById(R.id.grid_list_label_line_2))
.overridingErrorMessage("Expected secondary text view to be present but it is not.")
.isNotNull();
return myself;
}
/**
* Make sure a tag can't be validated if the value is blank.
*/
@Test
void cantCreateTagEntityDueToNoTag() {
final TagEntity tagEntity = new TagEntity();
final String tag = "";
tagEntity.setTag(tag);
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.validate(tagEntity));
}
@Test
public void using_predicates() throws Exception {
final ReasonBuffer2 buf = ReasonBuffer2.forAll("Cannot change");
buf.append(() -> false, "reason #1");
buf.append(false, "reason #2");
buf.append(true, "reason #3");
buf.append(() -> true, "reason #4");
Assertions.assertThat(buf.getReason()).isEqualTo("Cannot change: reason #3; reason #4");
}
@Test
public void failsOnUnknownProvider() {
String nonExistingProvider = UUID.randomUUID().toString();
Assertions
.assertThatThrownBy(() -> {
ConnectionFactories.get(String.format("r2dbc:tc:%s:///db", nonExistingProvider));
})
.hasMessageContaining("Missing provider")
.hasMessageContaining(nonExistingProvider);
}
/**
* Test to get a {@link Service} with a qualifier from the {@link DomainRegistry}.
*/
@Test
public void testServiceWithQualifierAndComposite() {
Type type = new TypeLiteral<RebateService<Composite<Long>>>() {}.getType();
RebateService<Composite<Long>> service = this.domainRegistry.getService(type, ServiceQualifier.class);
Assertions.assertThat(service)
.isInstanceOf(RebateServiceInternalWithQualifierComposite.class);
}
@Test
void shouldThrowExceptionOnMalformedMetadata_wellknowninstead() {
Assertions.assertThatThrownBy(
() ->
AuthMetadataFlyweight.decodeCustomAuthType(
AuthMetadataFlyweight.encodeMetadata(
ByteBufAllocator.DEFAULT,
WellKnownAuthType.BEARER,
Unpooled.copiedBuffer(new byte[] {'a', 'b'}))))
.hasMessage("Unable to decode custom Auth type. Incorrect auth type length");
}
@Test
void updateTelegrafConfig() {
Telegraf telegrafConfig = telegrafsApi
.createTelegraf(generateName("tc"), "test-config", organization, Arrays.asList(newOutputPlugin(), newKernelPlugin()));
Assertions.assertThat(telegrafConfig.getConfig()).isNotEqualTo("my-updated-config");
telegrafConfig.setDescription("updated");
telegrafConfig.setConfig("my-updated-config");
telegrafConfig = telegrafsApi.updateTelegraf(telegrafConfig);
Assertions.assertThat(telegrafConfig.getDescription()).isEqualTo("updated");
Assertions.assertThat(telegrafConfig.getConfig()).isEqualTo("my-updated-config");
}
@Test
public void testWithUrlAndReadContent() throws IOException {
YamlToJson res = YamlToJson.builder()
.withYamlInputPath(
"https://raw.githubusercontent.com/zalando/nakadi/nakadi-jvm/api/nakadi-event-bus-api.yaml")
.build();
String yamlFilename = res.getYamlFilename();
Assertions.assertThat(yamlFilename).isNotNull();
String json = res.getYamlFileContentAsJson();
Assertions.assertThat(json).isNotNull();
Assertions.assertThat(json).isNotEmpty();
Assertions.assertThat(json).startsWith("{").endsWith("}");
}
@Test
public void givenNoExplicitContructor_whenUsed_thenFails() {
BankAccount account = new BankAccount();
Assertions.assertThatThrownBy(() -> {
account.toString();
}).isInstanceOf(Exception.class);
}